babylon.max.js 3.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addVector3 = function (otherVector) {
  412. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  413. };
  414. Vector2.prototype.subtract = function (otherVector) {
  415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  416. };
  417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  418. result.x = this.x - otherVector.x;
  419. result.y = this.y - otherVector.y;
  420. return this;
  421. };
  422. Vector2.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.multiplyInPlace = function (otherVector) {
  428. this.x *= otherVector.x;
  429. this.y *= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiply = function (otherVector) {
  433. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  434. };
  435. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  436. result.x = this.x * otherVector.x;
  437. result.y = this.y * otherVector.y;
  438. return this;
  439. };
  440. Vector2.prototype.multiplyByFloats = function (x, y) {
  441. return new Vector2(this.x * x, this.y * y);
  442. };
  443. Vector2.prototype.divide = function (otherVector) {
  444. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  445. };
  446. Vector2.prototype.divideToRef = function (otherVector, result) {
  447. result.x = this.x / otherVector.x;
  448. result.y = this.y / otherVector.y;
  449. return this;
  450. };
  451. Vector2.prototype.negate = function () {
  452. return new Vector2(-this.x, -this.y);
  453. };
  454. Vector2.prototype.scaleInPlace = function (scale) {
  455. this.x *= scale;
  456. this.y *= scale;
  457. return this;
  458. };
  459. Vector2.prototype.scale = function (scale) {
  460. return new Vector2(this.x * scale, this.y * scale);
  461. };
  462. Vector2.prototype.equals = function (otherVector) {
  463. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  464. };
  465. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  466. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  467. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  468. };
  469. // Properties
  470. Vector2.prototype.length = function () {
  471. return Math.sqrt(this.x * this.x + this.y * this.y);
  472. };
  473. Vector2.prototype.lengthSquared = function () {
  474. return (this.x * this.x + this.y * this.y);
  475. };
  476. // Methods
  477. Vector2.prototype.normalize = function () {
  478. var len = this.length();
  479. if (len === 0)
  480. return this;
  481. var num = 1.0 / len;
  482. this.x *= num;
  483. this.y *= num;
  484. return this;
  485. };
  486. Vector2.prototype.clone = function () {
  487. return new Vector2(this.x, this.y);
  488. };
  489. // Statics
  490. Vector2.Zero = function () {
  491. return new Vector2(0, 0);
  492. };
  493. Vector2.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Vector2(array[offset], array[offset + 1]);
  496. };
  497. Vector2.FromArrayToRef = function (array, offset, result) {
  498. result.x = array[offset];
  499. result.y = array[offset + 1];
  500. };
  501. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  502. var squared = amount * amount;
  503. var cubed = amount * squared;
  504. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  505. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  506. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  507. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  508. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  509. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  510. return new Vector2(x, y);
  511. };
  512. Vector2.Clamp = function (value, min, max) {
  513. var x = value.x;
  514. x = (x > max.x) ? max.x : x;
  515. x = (x < min.x) ? min.x : x;
  516. var y = value.y;
  517. y = (y > max.y) ? max.y : y;
  518. y = (y < min.y) ? min.y : y;
  519. return new Vector2(x, y);
  520. };
  521. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  522. var squared = amount * amount;
  523. var cubed = amount * squared;
  524. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  525. var part2 = (-2.0 * cubed) + (3.0 * squared);
  526. var part3 = (cubed - (2.0 * squared)) + amount;
  527. var part4 = cubed - squared;
  528. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  529. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  530. return new Vector2(x, y);
  531. };
  532. Vector2.Lerp = function (start, end, amount) {
  533. var x = start.x + ((end.x - start.x) * amount);
  534. var y = start.y + ((end.y - start.y) * amount);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Dot = function (left, right) {
  538. return left.x * right.x + left.y * right.y;
  539. };
  540. Vector2.Normalize = function (vector) {
  541. var newVector = vector.clone();
  542. newVector.normalize();
  543. return newVector;
  544. };
  545. Vector2.Minimize = function (left, right) {
  546. var x = (left.x < right.x) ? left.x : right.x;
  547. var y = (left.y < right.y) ? left.y : right.y;
  548. return new Vector2(x, y);
  549. };
  550. Vector2.Maximize = function (left, right) {
  551. var x = (left.x > right.x) ? left.x : right.x;
  552. var y = (left.y > right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Transform = function (vector, transformation) {
  556. var r = Vector2.Zero();
  557. Vector2.TransformToRef(vector, transformation, r);
  558. return r;
  559. };
  560. Vector2.TransformToRef = function (vector, transformation, result) {
  561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  563. result.x = x;
  564. result.y = y;
  565. };
  566. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  567. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  568. var sign = a < 0 ? -1 : 1;
  569. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  570. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  571. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  572. };
  573. Vector2.Distance = function (value1, value2) {
  574. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  575. };
  576. Vector2.DistanceSquared = function (value1, value2) {
  577. var x = value1.x - value2.x;
  578. var y = value1.y - value2.y;
  579. return (x * x) + (y * y);
  580. };
  581. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  582. var l2 = Vector2.DistanceSquared(segA, segB);
  583. if (l2 === 0.0) {
  584. return Vector2.Distance(p, segA);
  585. }
  586. var v = segB.subtract(segA);
  587. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  588. var proj = segA.add(v.multiplyByFloats(t, t));
  589. return Vector2.Distance(p, proj);
  590. };
  591. return Vector2;
  592. }());
  593. BABYLON.Vector2 = Vector2;
  594. var Vector3 = (function () {
  595. function Vector3(x, y, z) {
  596. this.x = x;
  597. this.y = y;
  598. this.z = z;
  599. }
  600. Vector3.prototype.toString = function () {
  601. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  602. };
  603. Vector3.prototype.getClassName = function () {
  604. return "Vector3";
  605. };
  606. Vector3.prototype.getHashCode = function () {
  607. var hash = this.x || 0;
  608. hash = (hash * 397) ^ (this.y || 0);
  609. hash = (hash * 397) ^ (this.z || 0);
  610. return hash;
  611. };
  612. // Operators
  613. Vector3.prototype.asArray = function () {
  614. var result = [];
  615. this.toArray(result, 0);
  616. return result;
  617. };
  618. Vector3.prototype.toArray = function (array, index) {
  619. if (index === void 0) { index = 0; }
  620. array[index] = this.x;
  621. array[index + 1] = this.y;
  622. array[index + 2] = this.z;
  623. return this;
  624. };
  625. Vector3.prototype.toQuaternion = function () {
  626. var result = new Quaternion(0, 0, 0, 1);
  627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  631. var cosy = Math.cos(this.y * 0.5);
  632. var siny = Math.sin(this.y * 0.5);
  633. result.x = coszMinusx * siny;
  634. result.y = -sinzMinusx * siny;
  635. result.z = sinxPlusz * cosy;
  636. result.w = cosxPlusz * cosy;
  637. return result;
  638. };
  639. Vector3.prototype.addInPlace = function (otherVector) {
  640. this.x += otherVector.x;
  641. this.y += otherVector.y;
  642. this.z += otherVector.z;
  643. return this;
  644. };
  645. Vector3.prototype.add = function (otherVector) {
  646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  647. };
  648. Vector3.prototype.addToRef = function (otherVector, result) {
  649. result.x = this.x + otherVector.x;
  650. result.y = this.y + otherVector.y;
  651. result.z = this.z + otherVector.z;
  652. return this;
  653. };
  654. Vector3.prototype.subtractInPlace = function (otherVector) {
  655. this.x -= otherVector.x;
  656. this.y -= otherVector.y;
  657. this.z -= otherVector.z;
  658. return this;
  659. };
  660. Vector3.prototype.subtract = function (otherVector) {
  661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  662. };
  663. Vector3.prototype.subtractToRef = function (otherVector, result) {
  664. result.x = this.x - otherVector.x;
  665. result.y = this.y - otherVector.y;
  666. result.z = this.z - otherVector.z;
  667. return this;
  668. };
  669. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  670. return new Vector3(this.x - x, this.y - y, this.z - z);
  671. };
  672. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  673. result.x = this.x - x;
  674. result.y = this.y - y;
  675. result.z = this.z - z;
  676. return this;
  677. };
  678. Vector3.prototype.negate = function () {
  679. return new Vector3(-this.x, -this.y, -this.z);
  680. };
  681. Vector3.prototype.scaleInPlace = function (scale) {
  682. this.x *= scale;
  683. this.y *= scale;
  684. this.z *= scale;
  685. return this;
  686. };
  687. Vector3.prototype.scale = function (scale) {
  688. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  689. };
  690. Vector3.prototype.scaleToRef = function (scale, result) {
  691. result.x = this.x * scale;
  692. result.y = this.y * scale;
  693. result.z = this.z * scale;
  694. };
  695. Vector3.prototype.equals = function (otherVector) {
  696. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  697. };
  698. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  699. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  700. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  701. };
  702. Vector3.prototype.equalsToFloats = function (x, y, z) {
  703. return this.x === x && this.y === y && this.z === z;
  704. };
  705. Vector3.prototype.multiplyInPlace = function (otherVector) {
  706. this.x *= otherVector.x;
  707. this.y *= otherVector.y;
  708. this.z *= otherVector.z;
  709. return this;
  710. };
  711. Vector3.prototype.multiply = function (otherVector) {
  712. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  713. };
  714. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  715. result.x = this.x * otherVector.x;
  716. result.y = this.y * otherVector.y;
  717. result.z = this.z * otherVector.z;
  718. return this;
  719. };
  720. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  721. return new Vector3(this.x * x, this.y * y, this.z * z);
  722. };
  723. Vector3.prototype.divide = function (otherVector) {
  724. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  725. };
  726. Vector3.prototype.divideToRef = function (otherVector, result) {
  727. result.x = this.x / otherVector.x;
  728. result.y = this.y / otherVector.y;
  729. result.z = this.z / otherVector.z;
  730. return this;
  731. };
  732. Vector3.prototype.MinimizeInPlace = function (other) {
  733. if (other.x < this.x)
  734. this.x = other.x;
  735. if (other.y < this.y)
  736. this.y = other.y;
  737. if (other.z < this.z)
  738. this.z = other.z;
  739. return this;
  740. };
  741. Vector3.prototype.MaximizeInPlace = function (other) {
  742. if (other.x > this.x)
  743. this.x = other.x;
  744. if (other.y > this.y)
  745. this.y = other.y;
  746. if (other.z > this.z)
  747. this.z = other.z;
  748. return this;
  749. };
  750. // Properties
  751. Vector3.prototype.length = function () {
  752. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  753. };
  754. Vector3.prototype.lengthSquared = function () {
  755. return (this.x * this.x + this.y * this.y + this.z * this.z);
  756. };
  757. // Methods
  758. Vector3.prototype.normalize = function () {
  759. var len = this.length();
  760. if (len === 0 || len === 1.0)
  761. return this;
  762. var num = 1.0 / len;
  763. this.x *= num;
  764. this.y *= num;
  765. this.z *= num;
  766. return this;
  767. };
  768. Vector3.prototype.clone = function () {
  769. return new Vector3(this.x, this.y, this.z);
  770. };
  771. Vector3.prototype.copyFrom = function (source) {
  772. this.x = source.x;
  773. this.y = source.y;
  774. this.z = source.z;
  775. return this;
  776. };
  777. Vector3.prototype.copyFromFloats = function (x, y, z) {
  778. this.x = x;
  779. this.y = y;
  780. this.z = z;
  781. return this;
  782. };
  783. // Statics
  784. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  785. var d0 = Vector3.Dot(vector0, axis) - size;
  786. var d1 = Vector3.Dot(vector1, axis) - size;
  787. var s = d0 / (d0 - d1);
  788. return s;
  789. };
  790. Vector3.FromArray = function (array, offset) {
  791. if (!offset) {
  792. offset = 0;
  793. }
  794. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  795. };
  796. Vector3.FromFloatArray = function (array, offset) {
  797. if (!offset) {
  798. offset = 0;
  799. }
  800. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  801. };
  802. Vector3.FromArrayToRef = function (array, offset, result) {
  803. result.x = array[offset];
  804. result.y = array[offset + 1];
  805. result.z = array[offset + 2];
  806. };
  807. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  808. result.x = array[offset];
  809. result.y = array[offset + 1];
  810. result.z = array[offset + 2];
  811. };
  812. Vector3.FromFloatsToRef = function (x, y, z, result) {
  813. result.x = x;
  814. result.y = y;
  815. result.z = z;
  816. };
  817. Vector3.Zero = function () {
  818. return new Vector3(0, 0, 0);
  819. };
  820. Vector3.Up = function () {
  821. return new Vector3(0, 1.0, 0);
  822. };
  823. Vector3.TransformCoordinates = function (vector, transformation) {
  824. var result = Vector3.Zero();
  825. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  826. return result;
  827. };
  828. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  829. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  830. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  831. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  832. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  833. result.x = x / w;
  834. result.y = y / w;
  835. result.z = z / w;
  836. };
  837. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  838. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  839. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  840. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  841. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  842. result.x = rx / rw;
  843. result.y = ry / rw;
  844. result.z = rz / rw;
  845. };
  846. Vector3.TransformNormal = function (vector, transformation) {
  847. var result = Vector3.Zero();
  848. Vector3.TransformNormalToRef(vector, transformation, result);
  849. return result;
  850. };
  851. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  852. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  853. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  854. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  855. };
  856. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  857. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  858. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  859. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  860. };
  861. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  865. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  866. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  867. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  868. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  869. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  870. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  871. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  872. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  873. return new Vector3(x, y, z);
  874. };
  875. Vector3.Clamp = function (value, min, max) {
  876. var x = value.x;
  877. x = (x > max.x) ? max.x : x;
  878. x = (x < min.x) ? min.x : x;
  879. var y = value.y;
  880. y = (y > max.y) ? max.y : y;
  881. y = (y < min.y) ? min.y : y;
  882. var z = value.z;
  883. z = (z > max.z) ? max.z : z;
  884. z = (z < min.z) ? min.z : z;
  885. return new Vector3(x, y, z);
  886. };
  887. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  888. var squared = amount * amount;
  889. var cubed = amount * squared;
  890. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  891. var part2 = (-2.0 * cubed) + (3.0 * squared);
  892. var part3 = (cubed - (2.0 * squared)) + amount;
  893. var part4 = cubed - squared;
  894. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  895. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  896. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  897. return new Vector3(x, y, z);
  898. };
  899. Vector3.Lerp = function (start, end, amount) {
  900. var x = start.x + ((end.x - start.x) * amount);
  901. var y = start.y + ((end.y - start.y) * amount);
  902. var z = start.z + ((end.z - start.z) * amount);
  903. return new Vector3(x, y, z);
  904. };
  905. Vector3.Dot = function (left, right) {
  906. return (left.x * right.x + left.y * right.y + left.z * right.z);
  907. };
  908. Vector3.Cross = function (left, right) {
  909. var result = Vector3.Zero();
  910. Vector3.CrossToRef(left, right, result);
  911. return result;
  912. };
  913. Vector3.CrossToRef = function (left, right, result) {
  914. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  915. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  916. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  917. result.copyFrom(Tmp.Vector3[0]);
  918. };
  919. Vector3.Normalize = function (vector) {
  920. var result = Vector3.Zero();
  921. Vector3.NormalizeToRef(vector, result);
  922. return result;
  923. };
  924. Vector3.NormalizeToRef = function (vector, result) {
  925. result.copyFrom(vector);
  926. result.normalize();
  927. };
  928. Vector3.Project = function (vector, world, transform, viewport) {
  929. var cw = viewport.width;
  930. var ch = viewport.height;
  931. var cx = viewport.x;
  932. var cy = viewport.y;
  933. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  934. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  935. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  936. world.multiplyToRef(transform, matrix);
  937. matrix.multiplyToRef(viewportMatrix, matrix);
  938. return Vector3.TransformCoordinates(vector, matrix);
  939. };
  940. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  941. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  942. world.multiplyToRef(transform, matrix);
  943. matrix.invert();
  944. source.x = source.x / viewportWidth * 2 - 1;
  945. source.y = -(source.y / viewportHeight * 2 - 1);
  946. var vector = Vector3.TransformCoordinates(source, matrix);
  947. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  948. if (MathTools.WithinEpsilon(num, 1.0)) {
  949. vector = vector.scale(1.0 / num);
  950. }
  951. return vector;
  952. };
  953. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  954. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  955. world.multiplyToRef(view, matrix);
  956. matrix.multiplyToRef(projection, matrix);
  957. matrix.invert();
  958. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  959. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  960. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  961. if (MathTools.WithinEpsilon(num, 1.0)) {
  962. vector = vector.scale(1.0 / num);
  963. }
  964. return vector;
  965. };
  966. Vector3.Minimize = function (left, right) {
  967. var min = left.clone();
  968. min.MinimizeInPlace(right);
  969. return min;
  970. };
  971. Vector3.Maximize = function (left, right) {
  972. var max = left.clone();
  973. max.MaximizeInPlace(right);
  974. return max;
  975. };
  976. Vector3.Distance = function (value1, value2) {
  977. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  978. };
  979. Vector3.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. var z = value1.z - value2.z;
  983. return (x * x) + (y * y) + (z * z);
  984. };
  985. Vector3.Center = function (value1, value2) {
  986. var center = value1.add(value2);
  987. center.scaleInPlace(0.5);
  988. return center;
  989. };
  990. /**
  991. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  992. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  993. * to something in order to rotate it from its local system to the given target system.
  994. */
  995. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  996. var rotation = Vector3.Zero();
  997. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  998. return rotation;
  999. };
  1000. /**
  1001. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1002. */
  1003. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1004. var u = axis1.normalize();
  1005. var w = axis3.normalize();
  1006. // world axis
  1007. var X = Axis.X;
  1008. var Y = Axis.Y;
  1009. // equation unknowns and vars
  1010. var yaw = 0.0;
  1011. var pitch = 0.0;
  1012. var roll = 0.0;
  1013. var x = 0.0;
  1014. var y = 0.0;
  1015. var z = 0.0;
  1016. var t = 0.0;
  1017. var sign = -1.0;
  1018. var nbRevert = 0;
  1019. var cross = Tmp.Vector3[0];
  1020. var dot = 0.0;
  1021. // step 1 : rotation around w
  1022. // Rv3(u) = u1, and u1 belongs to plane xOz
  1023. // Rv3(w) = w1 = w invariant
  1024. var u1 = Tmp.Vector3[1];
  1025. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1026. z = 1.0;
  1027. }
  1028. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1029. x = 1.0;
  1030. }
  1031. else {
  1032. t = w.z / w.x;
  1033. x = -t * Math.sqrt(1 / (1 + t * t));
  1034. z = Math.sqrt(1 / (1 + t * t));
  1035. }
  1036. u1.x = x;
  1037. u1.y = y;
  1038. u1.z = z;
  1039. u1.normalize();
  1040. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1041. cross.normalize();
  1042. if (Vector3.Dot(w, cross) < 0) {
  1043. sign = 1.0;
  1044. }
  1045. dot = Vector3.Dot(u, u1);
  1046. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1047. roll = Math.acos(dot) * sign;
  1048. if (Vector3.Dot(u1, X) < 0) {
  1049. roll = Math.PI + roll;
  1050. u1 = u1.scaleInPlace(-1);
  1051. nbRevert++;
  1052. }
  1053. // step 2 : rotate around u1
  1054. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1055. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1056. var w2 = Tmp.Vector3[2];
  1057. var v2 = Tmp.Vector3[3];
  1058. x = 0.0;
  1059. y = 0.0;
  1060. z = 0.0;
  1061. sign = -1.0;
  1062. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1063. x = 1.0;
  1064. }
  1065. else {
  1066. t = u1.z / u1.x;
  1067. x = -t * Math.sqrt(1 / (1 + t * t));
  1068. z = Math.sqrt(1 / (1 + t * t));
  1069. }
  1070. w2.x = x;
  1071. w2.y = y;
  1072. w2.z = z;
  1073. w2.normalize();
  1074. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1075. v2.normalize();
  1076. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1077. cross.normalize();
  1078. if (Vector3.Dot(u1, cross) < 0) {
  1079. sign = 1.0;
  1080. }
  1081. dot = Vector3.Dot(w, w2);
  1082. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1083. pitch = Math.acos(dot) * sign;
  1084. if (Vector3.Dot(v2, Y) < 0) {
  1085. pitch = Math.PI + pitch;
  1086. nbRevert++;
  1087. }
  1088. // step 3 : rotate around v2
  1089. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1090. sign = -1.0;
  1091. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1092. cross.normalize();
  1093. if (Vector3.Dot(cross, Y) < 0) {
  1094. sign = 1.0;
  1095. }
  1096. dot = Vector3.Dot(u1, X);
  1097. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1098. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1099. if (dot < 0 && nbRevert < 2) {
  1100. yaw = Math.PI + yaw;
  1101. }
  1102. ref.x = pitch;
  1103. ref.y = yaw;
  1104. ref.z = roll;
  1105. };
  1106. return Vector3;
  1107. }());
  1108. BABYLON.Vector3 = Vector3;
  1109. //Vector4 class created for EulerAngle class conversion to Quaternion
  1110. var Vector4 = (function () {
  1111. function Vector4(x, y, z, w) {
  1112. this.x = x;
  1113. this.y = y;
  1114. this.z = z;
  1115. this.w = w;
  1116. }
  1117. Vector4.prototype.toString = function () {
  1118. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1119. };
  1120. Vector4.prototype.getClassName = function () {
  1121. return "Vector4";
  1122. };
  1123. Vector4.prototype.getHashCode = function () {
  1124. var hash = this.x || 0;
  1125. hash = (hash * 397) ^ (this.y || 0);
  1126. hash = (hash * 397) ^ (this.z || 0);
  1127. hash = (hash * 397) ^ (this.w || 0);
  1128. return hash;
  1129. };
  1130. // Operators
  1131. Vector4.prototype.asArray = function () {
  1132. var result = [];
  1133. this.toArray(result, 0);
  1134. return result;
  1135. };
  1136. Vector4.prototype.toArray = function (array, index) {
  1137. if (index === undefined) {
  1138. index = 0;
  1139. }
  1140. array[index] = this.x;
  1141. array[index + 1] = this.y;
  1142. array[index + 2] = this.z;
  1143. array[index + 3] = this.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.addInPlace = function (otherVector) {
  1147. this.x += otherVector.x;
  1148. this.y += otherVector.y;
  1149. this.z += otherVector.z;
  1150. this.w += otherVector.w;
  1151. return this;
  1152. };
  1153. Vector4.prototype.add = function (otherVector) {
  1154. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1155. };
  1156. Vector4.prototype.addToRef = function (otherVector, result) {
  1157. result.x = this.x + otherVector.x;
  1158. result.y = this.y + otherVector.y;
  1159. result.z = this.z + otherVector.z;
  1160. result.w = this.w + otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.subtractInPlace = function (otherVector) {
  1164. this.x -= otherVector.x;
  1165. this.y -= otherVector.y;
  1166. this.z -= otherVector.z;
  1167. this.w -= otherVector.w;
  1168. return this;
  1169. };
  1170. Vector4.prototype.subtract = function (otherVector) {
  1171. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1172. };
  1173. Vector4.prototype.subtractToRef = 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. result.w = this.w - otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1181. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1182. };
  1183. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1184. result.x = this.x - x;
  1185. result.y = this.y - y;
  1186. result.z = this.z - z;
  1187. result.w = this.w - w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.negate = function () {
  1191. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1192. };
  1193. Vector4.prototype.scaleInPlace = function (scale) {
  1194. this.x *= scale;
  1195. this.y *= scale;
  1196. this.z *= scale;
  1197. this.w *= scale;
  1198. return this;
  1199. };
  1200. Vector4.prototype.scale = function (scale) {
  1201. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1202. };
  1203. Vector4.prototype.scaleToRef = function (scale, result) {
  1204. result.x = this.x * scale;
  1205. result.y = this.y * scale;
  1206. result.z = this.z * scale;
  1207. result.w = this.w * scale;
  1208. };
  1209. Vector4.prototype.equals = function (otherVector) {
  1210. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1211. };
  1212. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1213. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1214. return otherVector
  1215. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1216. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1217. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1218. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1219. };
  1220. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1221. return this.x === x && this.y === y && this.z === z && this.w === w;
  1222. };
  1223. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1224. this.x *= otherVector.x;
  1225. this.y *= otherVector.y;
  1226. this.z *= otherVector.z;
  1227. this.w *= otherVector.w;
  1228. return this;
  1229. };
  1230. Vector4.prototype.multiply = function (otherVector) {
  1231. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1232. };
  1233. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1234. result.x = this.x * otherVector.x;
  1235. result.y = this.y * otherVector.y;
  1236. result.z = this.z * otherVector.z;
  1237. result.w = this.w * otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1241. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1242. };
  1243. Vector4.prototype.divide = function (otherVector) {
  1244. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1245. };
  1246. Vector4.prototype.divideToRef = function (otherVector, result) {
  1247. result.x = this.x / otherVector.x;
  1248. result.y = this.y / otherVector.y;
  1249. result.z = this.z / otherVector.z;
  1250. result.w = this.w / otherVector.w;
  1251. return this;
  1252. };
  1253. Vector4.prototype.MinimizeInPlace = function (other) {
  1254. if (other.x < this.x)
  1255. this.x = other.x;
  1256. if (other.y < this.y)
  1257. this.y = other.y;
  1258. if (other.z < this.z)
  1259. this.z = other.z;
  1260. if (other.w < this.w)
  1261. this.w = other.w;
  1262. return this;
  1263. };
  1264. Vector4.prototype.MaximizeInPlace = function (other) {
  1265. if (other.x > this.x)
  1266. this.x = other.x;
  1267. if (other.y > this.y)
  1268. this.y = other.y;
  1269. if (other.z > this.z)
  1270. this.z = other.z;
  1271. if (other.w > this.w)
  1272. this.w = other.w;
  1273. return this;
  1274. };
  1275. // Properties
  1276. Vector4.prototype.length = function () {
  1277. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1278. };
  1279. Vector4.prototype.lengthSquared = function () {
  1280. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1281. };
  1282. // Methods
  1283. Vector4.prototype.normalize = function () {
  1284. var len = this.length();
  1285. if (len === 0)
  1286. return this;
  1287. var num = 1.0 / len;
  1288. this.x *= num;
  1289. this.y *= num;
  1290. this.z *= num;
  1291. this.w *= num;
  1292. return this;
  1293. };
  1294. Vector4.prototype.toVector3 = function () {
  1295. return new Vector3(this.x, this.y, this.z);
  1296. };
  1297. Vector4.prototype.clone = function () {
  1298. return new Vector4(this.x, this.y, this.z, this.w);
  1299. };
  1300. Vector4.prototype.copyFrom = function (source) {
  1301. this.x = source.x;
  1302. this.y = source.y;
  1303. this.z = source.z;
  1304. this.w = source.w;
  1305. return this;
  1306. };
  1307. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1308. this.x = x;
  1309. this.y = y;
  1310. this.z = z;
  1311. this.w = w;
  1312. return this;
  1313. };
  1314. // Statics
  1315. Vector4.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1320. };
  1321. Vector4.FromArrayToRef = function (array, offset, result) {
  1322. result.x = array[offset];
  1323. result.y = array[offset + 1];
  1324. result.z = array[offset + 2];
  1325. result.w = array[offset + 3];
  1326. };
  1327. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1328. result.x = array[offset];
  1329. result.y = array[offset + 1];
  1330. result.z = array[offset + 2];
  1331. result.w = array[offset + 3];
  1332. };
  1333. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1334. result.x = x;
  1335. result.y = y;
  1336. result.z = z;
  1337. result.w = w;
  1338. };
  1339. Vector4.Zero = function () {
  1340. return new Vector4(0, 0, 0, 0);
  1341. };
  1342. Vector4.Normalize = function (vector) {
  1343. var result = Vector4.Zero();
  1344. Vector4.NormalizeToRef(vector, result);
  1345. return result;
  1346. };
  1347. Vector4.NormalizeToRef = function (vector, result) {
  1348. result.copyFrom(vector);
  1349. result.normalize();
  1350. };
  1351. Vector4.Minimize = function (left, right) {
  1352. var min = left.clone();
  1353. min.MinimizeInPlace(right);
  1354. return min;
  1355. };
  1356. Vector4.Maximize = function (left, right) {
  1357. var max = left.clone();
  1358. max.MaximizeInPlace(right);
  1359. return max;
  1360. };
  1361. Vector4.Distance = function (value1, value2) {
  1362. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1363. };
  1364. Vector4.DistanceSquared = function (value1, value2) {
  1365. var x = value1.x - value2.x;
  1366. var y = value1.y - value2.y;
  1367. var z = value1.z - value2.z;
  1368. var w = value1.w - value2.w;
  1369. return (x * x) + (y * y) + (z * z) + (w * w);
  1370. };
  1371. Vector4.Center = function (value1, value2) {
  1372. var center = value1.add(value2);
  1373. center.scaleInPlace(0.5);
  1374. return center;
  1375. };
  1376. return Vector4;
  1377. }());
  1378. BABYLON.Vector4 = Vector4;
  1379. var Size = (function () {
  1380. function Size(width, height) {
  1381. this.width = width;
  1382. this.height = height;
  1383. }
  1384. Size.prototype.toString = function () {
  1385. return "{W: " + this.width + ", H: " + this.height + "}";
  1386. };
  1387. Size.prototype.getClassName = function () {
  1388. return "Size";
  1389. };
  1390. Size.prototype.getHashCode = function () {
  1391. var hash = this.width || 0;
  1392. hash = (hash * 397) ^ (this.height || 0);
  1393. return hash;
  1394. };
  1395. Size.prototype.copyFrom = function (src) {
  1396. this.width = src.width;
  1397. this.height = src.height;
  1398. };
  1399. Size.prototype.copyFromFloats = function (width, height) {
  1400. this.width = width;
  1401. this.height = height;
  1402. };
  1403. Size.prototype.multiplyByFloats = function (w, h) {
  1404. return new Size(this.width * w, this.height * h);
  1405. };
  1406. Size.prototype.clone = function () {
  1407. return new Size(this.width, this.height);
  1408. };
  1409. Size.prototype.equals = function (other) {
  1410. if (!other) {
  1411. return false;
  1412. }
  1413. return (this.width === other.width) && (this.height === other.height);
  1414. };
  1415. Object.defineProperty(Size.prototype, "surface", {
  1416. get: function () {
  1417. return this.width * this.height;
  1418. },
  1419. enumerable: true,
  1420. configurable: true
  1421. });
  1422. Size.Zero = function () {
  1423. return new Size(0, 0);
  1424. };
  1425. Size.prototype.add = function (otherSize) {
  1426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1427. return r;
  1428. };
  1429. Size.prototype.substract = function (otherSize) {
  1430. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1431. return r;
  1432. };
  1433. Size.Lerp = function (start, end, amount) {
  1434. var w = start.width + ((end.width - start.width) * amount);
  1435. var h = start.height + ((end.height - start.height) * amount);
  1436. return new Size(w, h);
  1437. };
  1438. return Size;
  1439. }());
  1440. BABYLON.Size = Size;
  1441. var Quaternion = (function () {
  1442. function Quaternion(x, y, z, w) {
  1443. if (x === void 0) { x = 0; }
  1444. if (y === void 0) { y = 0; }
  1445. if (z === void 0) { z = 0; }
  1446. if (w === void 0) { w = 1; }
  1447. this.x = x;
  1448. this.y = y;
  1449. this.z = z;
  1450. this.w = w;
  1451. }
  1452. Quaternion.prototype.toString = function () {
  1453. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1454. };
  1455. Quaternion.prototype.getClassName = function () {
  1456. return "Quaternion";
  1457. };
  1458. Quaternion.prototype.getHashCode = function () {
  1459. var hash = this.x || 0;
  1460. hash = (hash * 397) ^ (this.y || 0);
  1461. hash = (hash * 397) ^ (this.z || 0);
  1462. hash = (hash * 397) ^ (this.w || 0);
  1463. return hash;
  1464. };
  1465. Quaternion.prototype.asArray = function () {
  1466. return [this.x, this.y, this.z, this.w];
  1467. };
  1468. Quaternion.prototype.equals = function (otherQuaternion) {
  1469. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1470. };
  1471. Quaternion.prototype.clone = function () {
  1472. return new Quaternion(this.x, this.y, this.z, this.w);
  1473. };
  1474. Quaternion.prototype.copyFrom = function (other) {
  1475. this.x = other.x;
  1476. this.y = other.y;
  1477. this.z = other.z;
  1478. this.w = other.w;
  1479. return this;
  1480. };
  1481. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1482. this.x = x;
  1483. this.y = y;
  1484. this.z = z;
  1485. this.w = w;
  1486. return this;
  1487. };
  1488. Quaternion.prototype.add = function (other) {
  1489. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1490. };
  1491. Quaternion.prototype.subtract = function (other) {
  1492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1493. };
  1494. Quaternion.prototype.scale = function (value) {
  1495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1496. };
  1497. Quaternion.prototype.multiply = function (q1) {
  1498. var result = new Quaternion(0, 0, 0, 1.0);
  1499. this.multiplyToRef(q1, result);
  1500. return result;
  1501. };
  1502. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1503. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1504. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1505. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1506. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1507. result.copyFromFloats(x, y, z, w);
  1508. return this;
  1509. };
  1510. Quaternion.prototype.multiplyInPlace = function (q1) {
  1511. this.multiplyToRef(q1, this);
  1512. return this;
  1513. };
  1514. Quaternion.prototype.conjugateToRef = function (ref) {
  1515. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1516. return this;
  1517. };
  1518. Quaternion.prototype.conjugateInPlace = function () {
  1519. this.x *= -1;
  1520. this.y *= -1;
  1521. this.z *= -1;
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugate = function () {
  1525. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.length = function () {
  1529. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1530. };
  1531. Quaternion.prototype.normalize = function () {
  1532. var length = 1.0 / this.length();
  1533. this.x *= length;
  1534. this.y *= length;
  1535. this.z *= length;
  1536. this.w *= length;
  1537. return this;
  1538. };
  1539. Quaternion.prototype.toEulerAngles = function (order) {
  1540. if (order === void 0) { order = "YZX"; }
  1541. var result = Vector3.Zero();
  1542. this.toEulerAnglesToRef(result, order);
  1543. return result;
  1544. };
  1545. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1546. if (order === void 0) { order = "YZX"; }
  1547. var heading, attitude, bank;
  1548. var x = this.x, y = this.y, z = this.z, w = this.w;
  1549. switch (order) {
  1550. case "YZX":
  1551. var test = x * y + z * w;
  1552. if (test > 0.499) {
  1553. heading = 2 * Math.atan2(x, w);
  1554. attitude = Math.PI / 2;
  1555. bank = 0;
  1556. }
  1557. if (test < -0.499) {
  1558. heading = -2 * Math.atan2(x, w);
  1559. attitude = -Math.PI / 2;
  1560. bank = 0;
  1561. }
  1562. if (isNaN(heading)) {
  1563. var sqx = x * x;
  1564. var sqy = y * y;
  1565. var sqz = z * z;
  1566. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1567. attitude = Math.asin(2 * test); // attitude
  1568. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1569. }
  1570. break;
  1571. default:
  1572. throw new Error("Euler order " + order + " not supported yet.");
  1573. }
  1574. result.y = heading;
  1575. result.z = attitude;
  1576. result.x = bank;
  1577. return this;
  1578. };
  1579. ;
  1580. Quaternion.prototype.toRotationMatrix = function (result) {
  1581. var xx = this.x * this.x;
  1582. var yy = this.y * this.y;
  1583. var zz = this.z * this.z;
  1584. var xy = this.x * this.y;
  1585. var zw = this.z * this.w;
  1586. var zx = this.z * this.x;
  1587. var yw = this.y * this.w;
  1588. var yz = this.y * this.z;
  1589. var xw = this.x * this.w;
  1590. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1591. result.m[1] = 2.0 * (xy + zw);
  1592. result.m[2] = 2.0 * (zx - yw);
  1593. result.m[3] = 0;
  1594. result.m[4] = 2.0 * (xy - zw);
  1595. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1596. result.m[6] = 2.0 * (yz + xw);
  1597. result.m[7] = 0;
  1598. result.m[8] = 2.0 * (zx + yw);
  1599. result.m[9] = 2.0 * (yz - xw);
  1600. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1601. result.m[11] = 0;
  1602. result.m[12] = 0;
  1603. result.m[13] = 0;
  1604. result.m[14] = 0;
  1605. result.m[15] = 1.0;
  1606. return this;
  1607. };
  1608. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1609. Quaternion.FromRotationMatrixToRef(matrix, this);
  1610. return this;
  1611. };
  1612. // Statics
  1613. Quaternion.FromRotationMatrix = function (matrix) {
  1614. var result = new Quaternion();
  1615. Quaternion.FromRotationMatrixToRef(matrix, result);
  1616. return result;
  1617. };
  1618. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1619. var data = matrix.m;
  1620. var m11 = data[0], m12 = data[4], m13 = data[8];
  1621. var m21 = data[1], m22 = data[5], m23 = data[9];
  1622. var m31 = data[2], m32 = data[6], m33 = data[10];
  1623. var trace = m11 + m22 + m33;
  1624. var s;
  1625. if (trace > 0) {
  1626. s = 0.5 / Math.sqrt(trace + 1.0);
  1627. result.w = 0.25 / s;
  1628. result.x = (m32 - m23) * s;
  1629. result.y = (m13 - m31) * s;
  1630. result.z = (m21 - m12) * s;
  1631. }
  1632. else if (m11 > m22 && m11 > m33) {
  1633. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1634. result.w = (m32 - m23) / s;
  1635. result.x = 0.25 * s;
  1636. result.y = (m12 + m21) / s;
  1637. result.z = (m13 + m31) / s;
  1638. }
  1639. else if (m22 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1641. result.w = (m13 - m31) / s;
  1642. result.x = (m12 + m21) / s;
  1643. result.y = 0.25 * s;
  1644. result.z = (m23 + m32) / s;
  1645. }
  1646. else {
  1647. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1648. result.w = (m21 - m12) / s;
  1649. result.x = (m13 + m31) / s;
  1650. result.y = (m23 + m32) / s;
  1651. result.z = 0.25 * s;
  1652. }
  1653. };
  1654. Quaternion.Inverse = function (q) {
  1655. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1656. };
  1657. Quaternion.Identity = function () {
  1658. return new Quaternion(0, 0, 0, 1);
  1659. };
  1660. Quaternion.RotationAxis = function (axis, angle) {
  1661. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1662. };
  1663. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1664. var sin = Math.sin(angle / 2);
  1665. axis.normalize();
  1666. result.w = Math.cos(angle / 2);
  1667. result.x = axis.x * sin;
  1668. result.y = axis.y * sin;
  1669. result.z = axis.z * sin;
  1670. return result;
  1671. };
  1672. Quaternion.FromArray = function (array, offset) {
  1673. if (!offset) {
  1674. offset = 0;
  1675. }
  1676. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1677. };
  1678. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1679. var q = new Quaternion();
  1680. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1681. return q;
  1682. };
  1683. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1684. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1685. var halfRoll = roll * 0.5;
  1686. var halfPitch = pitch * 0.5;
  1687. var halfYaw = yaw * 0.5;
  1688. var sinRoll = Math.sin(halfRoll);
  1689. var cosRoll = Math.cos(halfRoll);
  1690. var sinPitch = Math.sin(halfPitch);
  1691. var cosPitch = Math.cos(halfPitch);
  1692. var sinYaw = Math.sin(halfYaw);
  1693. var cosYaw = Math.cos(halfYaw);
  1694. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1695. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1696. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1697. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1698. };
  1699. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1700. var result = new Quaternion();
  1701. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1702. return result;
  1703. };
  1704. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1705. // Produces a quaternion from Euler angles in the z-x-z orientation
  1706. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1707. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1708. var halfBeta = beta * 0.5;
  1709. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1710. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1711. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1712. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1713. };
  1714. Quaternion.Slerp = function (left, right, amount) {
  1715. var num2;
  1716. var num3;
  1717. var num = amount;
  1718. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1719. var flag = false;
  1720. if (num4 < 0) {
  1721. flag = true;
  1722. num4 = -num4;
  1723. }
  1724. if (num4 > 0.999999) {
  1725. num3 = 1 - num;
  1726. num2 = flag ? -num : num;
  1727. }
  1728. else {
  1729. var num5 = Math.acos(num4);
  1730. var num6 = (1.0 / Math.sin(num5));
  1731. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1732. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1733. }
  1734. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1735. };
  1736. return Quaternion;
  1737. }());
  1738. BABYLON.Quaternion = Quaternion;
  1739. var Matrix = (function () {
  1740. function Matrix() {
  1741. this.m = new Float32Array(16);
  1742. }
  1743. // Properties
  1744. Matrix.prototype.isIdentity = function () {
  1745. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1746. return false;
  1747. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1751. return false;
  1752. return true;
  1753. };
  1754. Matrix.prototype.determinant = function () {
  1755. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1756. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1757. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1758. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1759. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1760. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1761. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1762. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1763. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1764. };
  1765. // Methods
  1766. Matrix.prototype.toArray = function () {
  1767. return this.m;
  1768. };
  1769. Matrix.prototype.asArray = function () {
  1770. return this.toArray();
  1771. };
  1772. Matrix.prototype.invert = function () {
  1773. this.invertToRef(this);
  1774. return this;
  1775. };
  1776. Matrix.prototype.reset = function () {
  1777. for (var index = 0; index < 16; index++) {
  1778. this.m[index] = 0;
  1779. }
  1780. return this;
  1781. };
  1782. Matrix.prototype.add = function (other) {
  1783. var result = new Matrix();
  1784. this.addToRef(other, result);
  1785. return result;
  1786. };
  1787. Matrix.prototype.addToRef = function (other, result) {
  1788. for (var index = 0; index < 16; index++) {
  1789. result.m[index] = this.m[index] + other.m[index];
  1790. }
  1791. return this;
  1792. };
  1793. Matrix.prototype.addToSelf = function (other) {
  1794. for (var index = 0; index < 16; index++) {
  1795. this.m[index] += other.m[index];
  1796. }
  1797. return this;
  1798. };
  1799. Matrix.prototype.invertToRef = function (other) {
  1800. var l1 = this.m[0];
  1801. var l2 = this.m[1];
  1802. var l3 = this.m[2];
  1803. var l4 = this.m[3];
  1804. var l5 = this.m[4];
  1805. var l6 = this.m[5];
  1806. var l7 = this.m[6];
  1807. var l8 = this.m[7];
  1808. var l9 = this.m[8];
  1809. var l10 = this.m[9];
  1810. var l11 = this.m[10];
  1811. var l12 = this.m[11];
  1812. var l13 = this.m[12];
  1813. var l14 = this.m[13];
  1814. var l15 = this.m[14];
  1815. var l16 = this.m[15];
  1816. var l17 = (l11 * l16) - (l12 * l15);
  1817. var l18 = (l10 * l16) - (l12 * l14);
  1818. var l19 = (l10 * l15) - (l11 * l14);
  1819. var l20 = (l9 * l16) - (l12 * l13);
  1820. var l21 = (l9 * l15) - (l11 * l13);
  1821. var l22 = (l9 * l14) - (l10 * l13);
  1822. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1823. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1824. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1825. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1826. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1827. var l28 = (l7 * l16) - (l8 * l15);
  1828. var l29 = (l6 * l16) - (l8 * l14);
  1829. var l30 = (l6 * l15) - (l7 * l14);
  1830. var l31 = (l5 * l16) - (l8 * l13);
  1831. var l32 = (l5 * l15) - (l7 * l13);
  1832. var l33 = (l5 * l14) - (l6 * l13);
  1833. var l34 = (l7 * l12) - (l8 * l11);
  1834. var l35 = (l6 * l12) - (l8 * l10);
  1835. var l36 = (l6 * l11) - (l7 * l10);
  1836. var l37 = (l5 * l12) - (l8 * l9);
  1837. var l38 = (l5 * l11) - (l7 * l9);
  1838. var l39 = (l5 * l10) - (l6 * l9);
  1839. other.m[0] = l23 * l27;
  1840. other.m[4] = l24 * l27;
  1841. other.m[8] = l25 * l27;
  1842. other.m[12] = l26 * l27;
  1843. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1844. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1845. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1846. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1847. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1848. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1849. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1850. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1851. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1852. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1853. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1854. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1855. return this;
  1856. };
  1857. Matrix.prototype.setTranslation = function (vector3) {
  1858. this.m[12] = vector3.x;
  1859. this.m[13] = vector3.y;
  1860. this.m[14] = vector3.z;
  1861. return this;
  1862. };
  1863. Matrix.prototype.getTranslation = function () {
  1864. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1865. };
  1866. Matrix.prototype.multiply = function (other) {
  1867. var result = new Matrix();
  1868. this.multiplyToRef(other, result);
  1869. return result;
  1870. };
  1871. Matrix.prototype.copyFrom = function (other) {
  1872. for (var index = 0; index < 16; index++) {
  1873. this.m[index] = other.m[index];
  1874. }
  1875. return this;
  1876. };
  1877. Matrix.prototype.copyToArray = function (array, offset) {
  1878. if (offset === void 0) { offset = 0; }
  1879. for (var index = 0; index < 16; index++) {
  1880. array[offset + index] = this.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.multiplyToRef = function (other, result) {
  1885. this.multiplyToArray(other, result.m, 0);
  1886. return this;
  1887. };
  1888. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1889. var tm0 = this.m[0];
  1890. var tm1 = this.m[1];
  1891. var tm2 = this.m[2];
  1892. var tm3 = this.m[3];
  1893. var tm4 = this.m[4];
  1894. var tm5 = this.m[5];
  1895. var tm6 = this.m[6];
  1896. var tm7 = this.m[7];
  1897. var tm8 = this.m[8];
  1898. var tm9 = this.m[9];
  1899. var tm10 = this.m[10];
  1900. var tm11 = this.m[11];
  1901. var tm12 = this.m[12];
  1902. var tm13 = this.m[13];
  1903. var tm14 = this.m[14];
  1904. var tm15 = this.m[15];
  1905. var om0 = other.m[0];
  1906. var om1 = other.m[1];
  1907. var om2 = other.m[2];
  1908. var om3 = other.m[3];
  1909. var om4 = other.m[4];
  1910. var om5 = other.m[5];
  1911. var om6 = other.m[6];
  1912. var om7 = other.m[7];
  1913. var om8 = other.m[8];
  1914. var om9 = other.m[9];
  1915. var om10 = other.m[10];
  1916. var om11 = other.m[11];
  1917. var om12 = other.m[12];
  1918. var om13 = other.m[13];
  1919. var om14 = other.m[14];
  1920. var om15 = other.m[15];
  1921. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1922. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1923. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1924. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1925. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1926. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1927. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1928. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1929. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1930. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1931. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1932. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1933. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1934. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1935. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1936. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1937. return this;
  1938. };
  1939. Matrix.prototype.equals = function (value) {
  1940. return value &&
  1941. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1942. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1943. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1944. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1945. };
  1946. Matrix.prototype.clone = function () {
  1947. 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]);
  1948. };
  1949. Matrix.prototype.getClassName = function () {
  1950. return "Matrix";
  1951. };
  1952. Matrix.prototype.getHashCode = function () {
  1953. var hash = this.m[0] || 0;
  1954. for (var i = 1; i < 16; i++) {
  1955. hash = (hash * 397) ^ (this.m[i] || 0);
  1956. }
  1957. return hash;
  1958. };
  1959. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1960. translation.x = this.m[12];
  1961. translation.y = this.m[13];
  1962. translation.z = this.m[14];
  1963. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1964. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1965. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1966. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1967. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1968. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1969. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1970. rotation.x = 0;
  1971. rotation.y = 0;
  1972. rotation.z = 0;
  1973. rotation.w = 1;
  1974. return false;
  1975. }
  1976. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1977. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1978. return true;
  1979. };
  1980. // Statics
  1981. Matrix.FromArray = function (array, offset) {
  1982. var result = new Matrix();
  1983. if (!offset) {
  1984. offset = 0;
  1985. }
  1986. Matrix.FromArrayToRef(array, offset, result);
  1987. return result;
  1988. };
  1989. Matrix.FromArrayToRef = function (array, offset, result) {
  1990. for (var index = 0; index < 16; index++) {
  1991. result.m[index] = array[index + offset];
  1992. }
  1993. };
  1994. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1995. for (var index = 0; index < 16; index++) {
  1996. result.m[index] = array[index + offset] * scale;
  1997. }
  1998. };
  1999. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2000. result.m[0] = initialM11;
  2001. result.m[1] = initialM12;
  2002. result.m[2] = initialM13;
  2003. result.m[3] = initialM14;
  2004. result.m[4] = initialM21;
  2005. result.m[5] = initialM22;
  2006. result.m[6] = initialM23;
  2007. result.m[7] = initialM24;
  2008. result.m[8] = initialM31;
  2009. result.m[9] = initialM32;
  2010. result.m[10] = initialM33;
  2011. result.m[11] = initialM34;
  2012. result.m[12] = initialM41;
  2013. result.m[13] = initialM42;
  2014. result.m[14] = initialM43;
  2015. result.m[15] = initialM44;
  2016. };
  2017. Matrix.prototype.getRow = function (index) {
  2018. if (index < 0 || index > 3) {
  2019. return null;
  2020. }
  2021. var i = index * 4;
  2022. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2023. };
  2024. Matrix.prototype.setRow = function (index, row) {
  2025. if (index < 0 || index > 3) {
  2026. return this;
  2027. }
  2028. var i = index * 4;
  2029. this.m[i + 0] = row.x;
  2030. this.m[i + 1] = row.y;
  2031. this.m[i + 2] = row.z;
  2032. this.m[i + 3] = row.w;
  2033. return this;
  2034. };
  2035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2036. var result = new Matrix();
  2037. result.m[0] = initialM11;
  2038. result.m[1] = initialM12;
  2039. result.m[2] = initialM13;
  2040. result.m[3] = initialM14;
  2041. result.m[4] = initialM21;
  2042. result.m[5] = initialM22;
  2043. result.m[6] = initialM23;
  2044. result.m[7] = initialM24;
  2045. result.m[8] = initialM31;
  2046. result.m[9] = initialM32;
  2047. result.m[10] = initialM33;
  2048. result.m[11] = initialM34;
  2049. result.m[12] = initialM41;
  2050. result.m[13] = initialM42;
  2051. result.m[14] = initialM43;
  2052. result.m[15] = initialM44;
  2053. return result;
  2054. };
  2055. Matrix.Compose = function (scale, rotation, translation) {
  2056. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2057. var rotationMatrix = Matrix.Identity();
  2058. rotation.toRotationMatrix(rotationMatrix);
  2059. result = result.multiply(rotationMatrix);
  2060. result.setTranslation(translation);
  2061. return result;
  2062. };
  2063. Matrix.Identity = function () {
  2064. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2065. };
  2066. Matrix.IdentityToRef = function (result) {
  2067. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2068. };
  2069. Matrix.Zero = function () {
  2070. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2071. };
  2072. Matrix.RotationX = function (angle) {
  2073. var result = new Matrix();
  2074. Matrix.RotationXToRef(angle, result);
  2075. return result;
  2076. };
  2077. Matrix.Invert = function (source) {
  2078. var result = new Matrix();
  2079. source.invertToRef(result);
  2080. return result;
  2081. };
  2082. Matrix.RotationXToRef = function (angle, result) {
  2083. var s = Math.sin(angle);
  2084. var c = Math.cos(angle);
  2085. result.m[0] = 1.0;
  2086. result.m[15] = 1.0;
  2087. result.m[5] = c;
  2088. result.m[10] = c;
  2089. result.m[9] = -s;
  2090. result.m[6] = s;
  2091. result.m[1] = 0;
  2092. result.m[2] = 0;
  2093. result.m[3] = 0;
  2094. result.m[4] = 0;
  2095. result.m[7] = 0;
  2096. result.m[8] = 0;
  2097. result.m[11] = 0;
  2098. result.m[12] = 0;
  2099. result.m[13] = 0;
  2100. result.m[14] = 0;
  2101. };
  2102. Matrix.RotationY = function (angle) {
  2103. var result = new Matrix();
  2104. Matrix.RotationYToRef(angle, result);
  2105. return result;
  2106. };
  2107. Matrix.RotationYToRef = function (angle, result) {
  2108. var s = Math.sin(angle);
  2109. var c = Math.cos(angle);
  2110. result.m[5] = 1.0;
  2111. result.m[15] = 1.0;
  2112. result.m[0] = c;
  2113. result.m[2] = -s;
  2114. result.m[8] = s;
  2115. result.m[10] = c;
  2116. result.m[1] = 0;
  2117. result.m[3] = 0;
  2118. result.m[4] = 0;
  2119. result.m[6] = 0;
  2120. result.m[7] = 0;
  2121. result.m[9] = 0;
  2122. result.m[11] = 0;
  2123. result.m[12] = 0;
  2124. result.m[13] = 0;
  2125. result.m[14] = 0;
  2126. };
  2127. Matrix.RotationZ = function (angle) {
  2128. var result = new Matrix();
  2129. Matrix.RotationZToRef(angle, result);
  2130. return result;
  2131. };
  2132. Matrix.RotationZToRef = function (angle, result) {
  2133. var s = Math.sin(angle);
  2134. var c = Math.cos(angle);
  2135. result.m[10] = 1.0;
  2136. result.m[15] = 1.0;
  2137. result.m[0] = c;
  2138. result.m[1] = s;
  2139. result.m[4] = -s;
  2140. result.m[5] = c;
  2141. result.m[2] = 0;
  2142. result.m[3] = 0;
  2143. result.m[6] = 0;
  2144. result.m[7] = 0;
  2145. result.m[8] = 0;
  2146. result.m[9] = 0;
  2147. result.m[11] = 0;
  2148. result.m[12] = 0;
  2149. result.m[13] = 0;
  2150. result.m[14] = 0;
  2151. };
  2152. Matrix.RotationAxis = function (axis, angle) {
  2153. var result = Matrix.Zero();
  2154. Matrix.RotationAxisToRef(axis, angle, result);
  2155. return result;
  2156. };
  2157. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2158. var s = Math.sin(-angle);
  2159. var c = Math.cos(-angle);
  2160. var c1 = 1 - c;
  2161. axis.normalize();
  2162. result.m[0] = (axis.x * axis.x) * c1 + c;
  2163. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2164. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2165. result.m[3] = 0.0;
  2166. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2167. result.m[5] = (axis.y * axis.y) * c1 + c;
  2168. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2169. result.m[7] = 0.0;
  2170. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2171. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2172. result.m[10] = (axis.z * axis.z) * c1 + c;
  2173. result.m[11] = 0.0;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2177. var result = new Matrix();
  2178. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2179. return result;
  2180. };
  2181. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2183. this._tempQuaternion.toRotationMatrix(result);
  2184. };
  2185. Matrix.Scaling = function (x, y, z) {
  2186. var result = Matrix.Zero();
  2187. Matrix.ScalingToRef(x, y, z, result);
  2188. return result;
  2189. };
  2190. Matrix.ScalingToRef = function (x, y, z, result) {
  2191. result.m[0] = x;
  2192. result.m[1] = 0;
  2193. result.m[2] = 0;
  2194. result.m[3] = 0;
  2195. result.m[4] = 0;
  2196. result.m[5] = y;
  2197. result.m[6] = 0;
  2198. result.m[7] = 0;
  2199. result.m[8] = 0;
  2200. result.m[9] = 0;
  2201. result.m[10] = z;
  2202. result.m[11] = 0;
  2203. result.m[12] = 0;
  2204. result.m[13] = 0;
  2205. result.m[14] = 0;
  2206. result.m[15] = 1.0;
  2207. };
  2208. Matrix.Translation = function (x, y, z) {
  2209. var result = Matrix.Identity();
  2210. Matrix.TranslationToRef(x, y, z, result);
  2211. return result;
  2212. };
  2213. Matrix.TranslationToRef = function (x, y, z, result) {
  2214. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2215. };
  2216. Matrix.Lerp = function (startValue, endValue, gradient) {
  2217. var result = Matrix.Zero();
  2218. for (var index = 0; index < 16; index++) {
  2219. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2220. }
  2221. return result;
  2222. };
  2223. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2224. var startScale = new Vector3(0, 0, 0);
  2225. var startRotation = new Quaternion();
  2226. var startTranslation = new Vector3(0, 0, 0);
  2227. startValue.decompose(startScale, startRotation, startTranslation);
  2228. var endScale = new Vector3(0, 0, 0);
  2229. var endRotation = new Quaternion();
  2230. var endTranslation = new Vector3(0, 0, 0);
  2231. endValue.decompose(endScale, endRotation, endTranslation);
  2232. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2233. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2234. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2235. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2236. };
  2237. Matrix.LookAtLH = function (eye, target, up) {
  2238. var result = Matrix.Zero();
  2239. Matrix.LookAtLHToRef(eye, target, up, result);
  2240. return result;
  2241. };
  2242. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2243. // Z axis
  2244. target.subtractToRef(eye, this._zAxis);
  2245. this._zAxis.normalize();
  2246. // X axis
  2247. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2248. if (this._xAxis.lengthSquared() === 0) {
  2249. this._xAxis.x = 1.0;
  2250. }
  2251. else {
  2252. this._xAxis.normalize();
  2253. }
  2254. // Y axis
  2255. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2256. this._yAxis.normalize();
  2257. // Eye angles
  2258. var ex = -Vector3.Dot(this._xAxis, eye);
  2259. var ey = -Vector3.Dot(this._yAxis, eye);
  2260. var ez = -Vector3.Dot(this._zAxis, eye);
  2261. 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);
  2262. };
  2263. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2264. var matrix = Matrix.Zero();
  2265. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2266. return matrix;
  2267. };
  2268. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2269. var hw = 2.0 / width;
  2270. var hh = 2.0 / height;
  2271. var id = 1.0 / (zfar - znear);
  2272. var nid = znear / (znear - zfar);
  2273. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2274. };
  2275. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2276. var matrix = Matrix.Zero();
  2277. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2278. return matrix;
  2279. };
  2280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2281. result.m[0] = 2.0 / (right - left);
  2282. result.m[1] = result.m[2] = result.m[3] = 0;
  2283. result.m[5] = 2.0 / (top - bottom);
  2284. result.m[4] = result.m[6] = result.m[7] = 0;
  2285. result.m[10] = -1.0 / (znear - zfar);
  2286. result.m[8] = result.m[9] = result.m[11] = 0;
  2287. result.m[12] = (left + right) / (left - right);
  2288. result.m[13] = (top + bottom) / (bottom - top);
  2289. result.m[14] = znear / (znear - zfar);
  2290. result.m[15] = 1.0;
  2291. };
  2292. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2293. var matrix = Matrix.Zero();
  2294. matrix.m[0] = (2.0 * znear) / width;
  2295. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2296. matrix.m[5] = (2.0 * znear) / height;
  2297. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2298. matrix.m[10] = -zfar / (znear - zfar);
  2299. matrix.m[8] = matrix.m[9] = 0.0;
  2300. matrix.m[11] = 1.0;
  2301. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2302. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2303. return matrix;
  2304. };
  2305. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2306. var matrix = Matrix.Zero();
  2307. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2308. return matrix;
  2309. };
  2310. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2311. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2312. var tan = 1.0 / (Math.tan(fov * 0.5));
  2313. if (isVerticalFovFixed) {
  2314. result.m[0] = tan / aspect;
  2315. }
  2316. else {
  2317. result.m[0] = tan;
  2318. }
  2319. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2320. if (isVerticalFovFixed) {
  2321. result.m[5] = tan;
  2322. }
  2323. else {
  2324. result.m[5] = tan * aspect;
  2325. }
  2326. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2327. result.m[8] = result.m[9] = 0.0;
  2328. result.m[10] = -zfar / (znear - zfar);
  2329. result.m[11] = 1.0;
  2330. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2331. result.m[14] = (znear * zfar) / (znear - zfar);
  2332. };
  2333. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2334. var cw = viewport.width;
  2335. var ch = viewport.height;
  2336. var cx = viewport.x;
  2337. var cy = viewport.y;
  2338. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2339. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2340. };
  2341. Matrix.GetAsMatrix2x2 = function (matrix) {
  2342. return new Float32Array([
  2343. matrix.m[0], matrix.m[1],
  2344. matrix.m[4], matrix.m[5]
  2345. ]);
  2346. };
  2347. Matrix.GetAsMatrix3x3 = function (matrix) {
  2348. return new Float32Array([
  2349. matrix.m[0], matrix.m[1], matrix.m[2],
  2350. matrix.m[4], matrix.m[5], matrix.m[6],
  2351. matrix.m[8], matrix.m[9], matrix.m[10]
  2352. ]);
  2353. };
  2354. Matrix.Transpose = function (matrix) {
  2355. var result = new Matrix();
  2356. result.m[0] = matrix.m[0];
  2357. result.m[1] = matrix.m[4];
  2358. result.m[2] = matrix.m[8];
  2359. result.m[3] = matrix.m[12];
  2360. result.m[4] = matrix.m[1];
  2361. result.m[5] = matrix.m[5];
  2362. result.m[6] = matrix.m[9];
  2363. result.m[7] = matrix.m[13];
  2364. result.m[8] = matrix.m[2];
  2365. result.m[9] = matrix.m[6];
  2366. result.m[10] = matrix.m[10];
  2367. result.m[11] = matrix.m[14];
  2368. result.m[12] = matrix.m[3];
  2369. result.m[13] = matrix.m[7];
  2370. result.m[14] = matrix.m[11];
  2371. result.m[15] = matrix.m[15];
  2372. return result;
  2373. };
  2374. Matrix.Reflection = function (plane) {
  2375. var matrix = new Matrix();
  2376. Matrix.ReflectionToRef(plane, matrix);
  2377. return matrix;
  2378. };
  2379. Matrix.ReflectionToRef = function (plane, result) {
  2380. plane.normalize();
  2381. var x = plane.normal.x;
  2382. var y = plane.normal.y;
  2383. var z = plane.normal.z;
  2384. var temp = -2 * x;
  2385. var temp2 = -2 * y;
  2386. var temp3 = -2 * z;
  2387. result.m[0] = (temp * x) + 1;
  2388. result.m[1] = temp2 * x;
  2389. result.m[2] = temp3 * x;
  2390. result.m[3] = 0.0;
  2391. result.m[4] = temp * y;
  2392. result.m[5] = (temp2 * y) + 1;
  2393. result.m[6] = temp3 * y;
  2394. result.m[7] = 0.0;
  2395. result.m[8] = temp * z;
  2396. result.m[9] = temp2 * z;
  2397. result.m[10] = (temp3 * z) + 1;
  2398. result.m[11] = 0.0;
  2399. result.m[12] = temp * plane.d;
  2400. result.m[13] = temp2 * plane.d;
  2401. result.m[14] = temp3 * plane.d;
  2402. result.m[15] = 1.0;
  2403. };
  2404. Matrix._tempQuaternion = new Quaternion();
  2405. Matrix._xAxis = Vector3.Zero();
  2406. Matrix._yAxis = Vector3.Zero();
  2407. Matrix._zAxis = Vector3.Zero();
  2408. return Matrix;
  2409. }());
  2410. BABYLON.Matrix = Matrix;
  2411. var Plane = (function () {
  2412. function Plane(a, b, c, d) {
  2413. this.normal = new Vector3(a, b, c);
  2414. this.d = d;
  2415. }
  2416. Plane.prototype.asArray = function () {
  2417. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2418. };
  2419. // Methods
  2420. Plane.prototype.clone = function () {
  2421. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2422. };
  2423. Plane.prototype.getClassName = function () {
  2424. return "Plane";
  2425. };
  2426. Plane.prototype.getHashCode = function () {
  2427. var hash = this.normal.getHashCode();
  2428. hash = (hash * 397) ^ (this.d || 0);
  2429. return hash;
  2430. };
  2431. Plane.prototype.normalize = function () {
  2432. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2433. var magnitude = 0;
  2434. if (norm !== 0) {
  2435. magnitude = 1.0 / norm;
  2436. }
  2437. this.normal.x *= magnitude;
  2438. this.normal.y *= magnitude;
  2439. this.normal.z *= magnitude;
  2440. this.d *= magnitude;
  2441. return this;
  2442. };
  2443. Plane.prototype.transform = function (transformation) {
  2444. var transposedMatrix = Matrix.Transpose(transformation);
  2445. var x = this.normal.x;
  2446. var y = this.normal.y;
  2447. var z = this.normal.z;
  2448. var d = this.d;
  2449. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2450. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2451. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2452. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2453. return new Plane(normalX, normalY, normalZ, finalD);
  2454. };
  2455. Plane.prototype.dotCoordinate = function (point) {
  2456. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2457. };
  2458. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2459. var x1 = point2.x - point1.x;
  2460. var y1 = point2.y - point1.y;
  2461. var z1 = point2.z - point1.z;
  2462. var x2 = point3.x - point1.x;
  2463. var y2 = point3.y - point1.y;
  2464. var z2 = point3.z - point1.z;
  2465. var yz = (y1 * z2) - (z1 * y2);
  2466. var xz = (z1 * x2) - (x1 * z2);
  2467. var xy = (x1 * y2) - (y1 * x2);
  2468. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2469. var invPyth;
  2470. if (pyth !== 0) {
  2471. invPyth = 1.0 / pyth;
  2472. }
  2473. else {
  2474. invPyth = 0;
  2475. }
  2476. this.normal.x = yz * invPyth;
  2477. this.normal.y = xz * invPyth;
  2478. this.normal.z = xy * invPyth;
  2479. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2480. return this;
  2481. };
  2482. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2483. var dot = Vector3.Dot(this.normal, direction);
  2484. return (dot <= epsilon);
  2485. };
  2486. Plane.prototype.signedDistanceTo = function (point) {
  2487. return Vector3.Dot(point, this.normal) + this.d;
  2488. };
  2489. // Statics
  2490. Plane.FromArray = function (array) {
  2491. return new Plane(array[0], array[1], array[2], array[3]);
  2492. };
  2493. Plane.FromPoints = function (point1, point2, point3) {
  2494. var result = new Plane(0, 0, 0, 0);
  2495. result.copyFromPoints(point1, point2, point3);
  2496. return result;
  2497. };
  2498. Plane.FromPositionAndNormal = function (origin, normal) {
  2499. var result = new Plane(0, 0, 0, 0);
  2500. normal.normalize();
  2501. result.normal = normal;
  2502. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2503. return result;
  2504. };
  2505. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2506. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2507. return Vector3.Dot(point, normal) + d;
  2508. };
  2509. return Plane;
  2510. }());
  2511. BABYLON.Plane = Plane;
  2512. var Viewport = (function () {
  2513. function Viewport(x, y, width, height) {
  2514. this.x = x;
  2515. this.y = y;
  2516. this.width = width;
  2517. this.height = height;
  2518. }
  2519. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2520. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2521. };
  2522. return Viewport;
  2523. }());
  2524. BABYLON.Viewport = Viewport;
  2525. var Frustum = (function () {
  2526. function Frustum() {
  2527. }
  2528. Frustum.GetPlanes = function (transform) {
  2529. var frustumPlanes = [];
  2530. for (var index = 0; index < 6; index++) {
  2531. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2532. }
  2533. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2534. return frustumPlanes;
  2535. };
  2536. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2537. // Near
  2538. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2539. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2540. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2541. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2542. frustumPlanes[0].normalize();
  2543. // Far
  2544. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2545. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2546. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2547. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2548. frustumPlanes[1].normalize();
  2549. // Left
  2550. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2551. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2552. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2553. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2554. frustumPlanes[2].normalize();
  2555. // Right
  2556. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2557. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2558. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2559. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2560. frustumPlanes[3].normalize();
  2561. // Top
  2562. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2563. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2564. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2565. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2566. frustumPlanes[4].normalize();
  2567. // Bottom
  2568. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2569. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2570. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2571. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2572. frustumPlanes[5].normalize();
  2573. };
  2574. return Frustum;
  2575. }());
  2576. BABYLON.Frustum = Frustum;
  2577. (function (Space) {
  2578. Space[Space["LOCAL"] = 0] = "LOCAL";
  2579. Space[Space["WORLD"] = 1] = "WORLD";
  2580. })(BABYLON.Space || (BABYLON.Space = {}));
  2581. var Space = BABYLON.Space;
  2582. var Axis = (function () {
  2583. function Axis() {
  2584. }
  2585. Axis.X = new Vector3(1, 0, 0);
  2586. Axis.Y = new Vector3(0, 1, 0);
  2587. Axis.Z = new Vector3(0, 0, 1);
  2588. return Axis;
  2589. }());
  2590. BABYLON.Axis = Axis;
  2591. ;
  2592. var BezierCurve = (function () {
  2593. function BezierCurve() {
  2594. }
  2595. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2596. // Extract X (which is equal to time here)
  2597. var f0 = 1 - 3 * x2 + 3 * x1;
  2598. var f1 = 3 * x2 - 6 * x1;
  2599. var f2 = 3 * x1;
  2600. var refinedT = t;
  2601. for (var i = 0; i < 5; i++) {
  2602. var refinedT2 = refinedT * refinedT;
  2603. var refinedT3 = refinedT2 * refinedT;
  2604. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2605. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2606. refinedT -= (x - t) * slope;
  2607. refinedT = Math.min(1, Math.max(0, refinedT));
  2608. }
  2609. // Resolve cubic bezier for the given x
  2610. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2611. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2612. Math.pow(refinedT, 3);
  2613. };
  2614. return BezierCurve;
  2615. }());
  2616. BABYLON.BezierCurve = BezierCurve;
  2617. (function (Orientation) {
  2618. Orientation[Orientation["CW"] = 0] = "CW";
  2619. Orientation[Orientation["CCW"] = 1] = "CCW";
  2620. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2621. var Orientation = BABYLON.Orientation;
  2622. var Angle = (function () {
  2623. function Angle(radians) {
  2624. var _this = this;
  2625. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2626. this.radians = function () { return _this._radians; };
  2627. this._radians = radians;
  2628. if (this._radians < 0)
  2629. this._radians += (2 * Math.PI);
  2630. }
  2631. Angle.BetweenTwoPoints = function (a, b) {
  2632. var delta = b.subtract(a);
  2633. var theta = Math.atan2(delta.y, delta.x);
  2634. return new Angle(theta);
  2635. };
  2636. Angle.FromRadians = function (radians) {
  2637. return new Angle(radians);
  2638. };
  2639. Angle.FromDegrees = function (degrees) {
  2640. return new Angle(degrees * Math.PI / 180);
  2641. };
  2642. return Angle;
  2643. }());
  2644. BABYLON.Angle = Angle;
  2645. var Arc2 = (function () {
  2646. function Arc2(startPoint, midPoint, endPoint) {
  2647. this.startPoint = startPoint;
  2648. this.midPoint = midPoint;
  2649. this.endPoint = endPoint;
  2650. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2651. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2652. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2653. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2654. 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);
  2655. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2656. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2657. var a1 = this.startAngle.degrees();
  2658. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2659. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2660. // angles correction
  2661. if (a2 - a1 > +180.0)
  2662. a2 -= 360.0;
  2663. if (a2 - a1 < -180.0)
  2664. a2 += 360.0;
  2665. if (a3 - a2 > +180.0)
  2666. a3 -= 360.0;
  2667. if (a3 - a2 < -180.0)
  2668. a3 += 360.0;
  2669. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2670. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2671. }
  2672. return Arc2;
  2673. }());
  2674. BABYLON.Arc2 = Arc2;
  2675. var Path2 = (function () {
  2676. function Path2(x, y) {
  2677. this._points = new Array();
  2678. this._length = 0;
  2679. this.closed = false;
  2680. this._points.push(new Vector2(x, y));
  2681. }
  2682. Path2.prototype.addLineTo = function (x, y) {
  2683. if (closed) {
  2684. //Tools.Error("cannot add lines to closed paths");
  2685. return this;
  2686. }
  2687. var newPoint = new Vector2(x, y);
  2688. var previousPoint = this._points[this._points.length - 1];
  2689. this._points.push(newPoint);
  2690. this._length += newPoint.subtract(previousPoint).length();
  2691. return this;
  2692. };
  2693. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2694. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2695. if (closed) {
  2696. //Tools.Error("cannot add arcs to closed paths");
  2697. return this;
  2698. }
  2699. var startPoint = this._points[this._points.length - 1];
  2700. var midPoint = new Vector2(midX, midY);
  2701. var endPoint = new Vector2(endX, endY);
  2702. var arc = new Arc2(startPoint, midPoint, endPoint);
  2703. var increment = arc.angle.radians() / numberOfSegments;
  2704. if (arc.orientation === Orientation.CW)
  2705. increment *= -1;
  2706. var currentAngle = arc.startAngle.radians() + increment;
  2707. for (var i = 0; i < numberOfSegments; i++) {
  2708. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2709. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2710. this.addLineTo(x, y);
  2711. currentAngle += increment;
  2712. }
  2713. return this;
  2714. };
  2715. Path2.prototype.close = function () {
  2716. this.closed = true;
  2717. return this;
  2718. };
  2719. Path2.prototype.length = function () {
  2720. var result = this._length;
  2721. if (!this.closed) {
  2722. var lastPoint = this._points[this._points.length - 1];
  2723. var firstPoint = this._points[0];
  2724. result += (firstPoint.subtract(lastPoint).length());
  2725. }
  2726. return result;
  2727. };
  2728. Path2.prototype.getPoints = function () {
  2729. return this._points;
  2730. };
  2731. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2732. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2733. //Tools.Error("normalized length position should be between 0 and 1.");
  2734. return Vector2.Zero();
  2735. }
  2736. var lengthPosition = normalizedLengthPosition * this.length();
  2737. var previousOffset = 0;
  2738. for (var i = 0; i < this._points.length; i++) {
  2739. var j = (i + 1) % this._points.length;
  2740. var a = this._points[i];
  2741. var b = this._points[j];
  2742. var bToA = b.subtract(a);
  2743. var nextOffset = (bToA.length() + previousOffset);
  2744. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2745. var dir = bToA.normalize();
  2746. var localOffset = lengthPosition - previousOffset;
  2747. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2748. }
  2749. previousOffset = nextOffset;
  2750. }
  2751. //Tools.Error("internal error");
  2752. return Vector2.Zero();
  2753. };
  2754. Path2.StartingAt = function (x, y) {
  2755. return new Path2(x, y);
  2756. };
  2757. return Path2;
  2758. }());
  2759. BABYLON.Path2 = Path2;
  2760. var Path3D = (function () {
  2761. /**
  2762. * new Path3D(path, normal, raw)
  2763. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2764. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2765. * path : an array of Vector3, the curve axis of the Path3D
  2766. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2767. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2768. */
  2769. function Path3D(path, firstNormal, raw) {
  2770. this.path = path;
  2771. this._curve = new Array();
  2772. this._distances = new Array();
  2773. this._tangents = new Array();
  2774. this._normals = new Array();
  2775. this._binormals = new Array();
  2776. for (var p = 0; p < path.length; p++) {
  2777. this._curve[p] = path[p].clone(); // hard copy
  2778. }
  2779. this._raw = raw || false;
  2780. this._compute(firstNormal);
  2781. }
  2782. /**
  2783. * Returns the Path3D array of successive Vector3 designing its curve.
  2784. */
  2785. Path3D.prototype.getCurve = function () {
  2786. return this._curve;
  2787. };
  2788. /**
  2789. * Returns an array populated with tangent vectors on each Path3D curve point.
  2790. */
  2791. Path3D.prototype.getTangents = function () {
  2792. return this._tangents;
  2793. };
  2794. /**
  2795. * Returns an array populated with normal vectors on each Path3D curve point.
  2796. */
  2797. Path3D.prototype.getNormals = function () {
  2798. return this._normals;
  2799. };
  2800. /**
  2801. * Returns an array populated with binormal vectors on each Path3D curve point.
  2802. */
  2803. Path3D.prototype.getBinormals = function () {
  2804. return this._binormals;
  2805. };
  2806. /**
  2807. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2808. */
  2809. Path3D.prototype.getDistances = function () {
  2810. return this._distances;
  2811. };
  2812. /**
  2813. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2814. * Returns the same object updated.
  2815. */
  2816. Path3D.prototype.update = function (path, firstNormal) {
  2817. for (var p = 0; p < path.length; p++) {
  2818. this._curve[p].x = path[p].x;
  2819. this._curve[p].y = path[p].y;
  2820. this._curve[p].z = path[p].z;
  2821. }
  2822. this._compute(firstNormal);
  2823. return this;
  2824. };
  2825. // private function compute() : computes tangents, normals and binormals
  2826. Path3D.prototype._compute = function (firstNormal) {
  2827. var l = this._curve.length;
  2828. // first and last tangents
  2829. this._tangents[0] = this._getFirstNonNullVector(0);
  2830. if (!this._raw) {
  2831. this._tangents[0].normalize();
  2832. }
  2833. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2834. if (!this._raw) {
  2835. this._tangents[l - 1].normalize();
  2836. }
  2837. // normals and binormals at first point : arbitrary vector with _normalVector()
  2838. var tg0 = this._tangents[0];
  2839. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2840. this._normals[0] = pp0;
  2841. if (!this._raw) {
  2842. this._normals[0].normalize();
  2843. }
  2844. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2845. if (!this._raw) {
  2846. this._binormals[0].normalize();
  2847. }
  2848. this._distances[0] = 0;
  2849. // normals and binormals : next points
  2850. var prev; // previous vector (segment)
  2851. var cur; // current vector (segment)
  2852. var curTang; // current tangent
  2853. // previous normal
  2854. var prevBinor; // previous binormal
  2855. for (var i = 1; i < l; i++) {
  2856. // tangents
  2857. prev = this._getLastNonNullVector(i);
  2858. if (i < l - 1) {
  2859. cur = this._getFirstNonNullVector(i);
  2860. this._tangents[i] = prev.add(cur);
  2861. this._tangents[i].normalize();
  2862. }
  2863. this._distances[i] = this._distances[i - 1] + prev.length();
  2864. // normals and binormals
  2865. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2866. curTang = this._tangents[i];
  2867. prevBinor = this._binormals[i - 1];
  2868. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2869. if (!this._raw) {
  2870. this._normals[i].normalize();
  2871. }
  2872. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2873. if (!this._raw) {
  2874. this._binormals[i].normalize();
  2875. }
  2876. }
  2877. };
  2878. // private function getFirstNonNullVector(index)
  2879. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2880. Path3D.prototype._getFirstNonNullVector = function (index) {
  2881. var i = 1;
  2882. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2883. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2884. i++;
  2885. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2886. }
  2887. return nNVector;
  2888. };
  2889. // private function getLastNonNullVector(index)
  2890. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2891. Path3D.prototype._getLastNonNullVector = function (index) {
  2892. var i = 1;
  2893. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2894. while (nLVector.length() === 0 && index > i + 1) {
  2895. i++;
  2896. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2897. }
  2898. return nLVector;
  2899. };
  2900. // private function normalVector(v0, vt, va) :
  2901. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2902. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2903. Path3D.prototype._normalVector = function (v0, vt, va) {
  2904. var normal0;
  2905. if (va === undefined || va === null) {
  2906. var point;
  2907. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2908. point = new Vector3(0, -1, 0);
  2909. }
  2910. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2911. point = new Vector3(1, 0, 0);
  2912. }
  2913. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2914. point = new Vector3(0, 0, 1);
  2915. }
  2916. normal0 = Vector3.Cross(vt, point);
  2917. }
  2918. else {
  2919. normal0 = Vector3.Cross(vt, va);
  2920. Vector3.CrossToRef(normal0, vt, normal0);
  2921. }
  2922. normal0.normalize();
  2923. return normal0;
  2924. };
  2925. return Path3D;
  2926. }());
  2927. BABYLON.Path3D = Path3D;
  2928. var Curve3 = (function () {
  2929. /**
  2930. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2931. * A Curve3 is designed from a series of successive Vector3.
  2932. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2933. */
  2934. function Curve3(points) {
  2935. this._length = 0;
  2936. this._points = points;
  2937. this._length = this._computeLength(points);
  2938. }
  2939. /**
  2940. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2941. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2942. * @param v1 (Vector3) the control point
  2943. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2944. * @param nbPoints (integer) the wanted number of points in the curve
  2945. */
  2946. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2947. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2948. var bez = new Array();
  2949. var equation = function (t, val0, val1, val2) {
  2950. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2951. return res;
  2952. };
  2953. for (var i = 0; i <= nbPoints; i++) {
  2954. 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)));
  2955. }
  2956. return new Curve3(bez);
  2957. };
  2958. /**
  2959. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2960. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2961. * @param v1 (Vector3) the first control point
  2962. * @param v2 (Vector3) the second control point
  2963. * @param v3 (Vector3) the end point of the Cubic Bezier
  2964. * @param nbPoints (integer) the wanted number of points in the curve
  2965. */
  2966. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2967. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2968. var bez = new Array();
  2969. var equation = function (t, val0, val1, val2, val3) {
  2970. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2971. return res;
  2972. };
  2973. for (var i = 0; i <= nbPoints; i++) {
  2974. 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)));
  2975. }
  2976. return new Curve3(bez);
  2977. };
  2978. /**
  2979. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2980. * @param p1 (Vector3) the origin point of the Hermite Spline
  2981. * @param t1 (Vector3) the tangent vector at the origin point
  2982. * @param p2 (Vector3) the end point of the Hermite Spline
  2983. * @param t2 (Vector3) the tangent vector at the end point
  2984. * @param nbPoints (integer) the wanted number of points in the curve
  2985. */
  2986. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2987. var hermite = new Array();
  2988. var step = 1 / nbPoints;
  2989. for (var i = 0; i <= nbPoints; i++) {
  2990. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2991. }
  2992. return new Curve3(hermite);
  2993. };
  2994. /**
  2995. * Returns the Curve3 stored array of successive Vector3
  2996. */
  2997. Curve3.prototype.getPoints = function () {
  2998. return this._points;
  2999. };
  3000. /**
  3001. * Returns the computed length (float) of the curve.
  3002. */
  3003. Curve3.prototype.length = function () {
  3004. return this._length;
  3005. };
  3006. /**
  3007. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3008. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3009. * curveA and curveB keep unchanged.
  3010. */
  3011. Curve3.prototype.continue = function (curve) {
  3012. var lastPoint = this._points[this._points.length - 1];
  3013. var continuedPoints = this._points.slice();
  3014. var curvePoints = curve.getPoints();
  3015. for (var i = 1; i < curvePoints.length; i++) {
  3016. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3017. }
  3018. var continuedCurve = new Curve3(continuedPoints);
  3019. return continuedCurve;
  3020. };
  3021. Curve3.prototype._computeLength = function (path) {
  3022. var l = 0;
  3023. for (var i = 1; i < path.length; i++) {
  3024. l += (path[i].subtract(path[i - 1])).length();
  3025. }
  3026. return l;
  3027. };
  3028. return Curve3;
  3029. }());
  3030. BABYLON.Curve3 = Curve3;
  3031. // SphericalHarmonics
  3032. var SphericalHarmonics = (function () {
  3033. function SphericalHarmonics() {
  3034. this.L00 = Vector3.Zero();
  3035. this.L1_1 = Vector3.Zero();
  3036. this.L10 = Vector3.Zero();
  3037. this.L11 = Vector3.Zero();
  3038. this.L2_2 = Vector3.Zero();
  3039. this.L2_1 = Vector3.Zero();
  3040. this.L20 = Vector3.Zero();
  3041. this.L21 = Vector3.Zero();
  3042. this.L22 = Vector3.Zero();
  3043. }
  3044. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3045. var colorVector = new Vector3(color.r, color.g, color.b);
  3046. var c = colorVector.scale(deltaSolidAngle);
  3047. this.L00 = this.L00.add(c.scale(0.282095));
  3048. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3049. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3050. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3051. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3052. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3053. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3054. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3055. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3056. };
  3057. SphericalHarmonics.prototype.scale = function (scale) {
  3058. this.L00 = this.L00.scale(scale);
  3059. this.L1_1 = this.L1_1.scale(scale);
  3060. this.L10 = this.L10.scale(scale);
  3061. this.L11 = this.L11.scale(scale);
  3062. this.L2_2 = this.L2_2.scale(scale);
  3063. this.L2_1 = this.L2_1.scale(scale);
  3064. this.L20 = this.L20.scale(scale);
  3065. this.L21 = this.L21.scale(scale);
  3066. this.L22 = this.L22.scale(scale);
  3067. };
  3068. return SphericalHarmonics;
  3069. }());
  3070. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3071. // SphericalPolynomial
  3072. var SphericalPolynomial = (function () {
  3073. function SphericalPolynomial() {
  3074. this.x = Vector3.Zero();
  3075. this.y = Vector3.Zero();
  3076. this.z = Vector3.Zero();
  3077. this.xx = Vector3.Zero();
  3078. this.yy = Vector3.Zero();
  3079. this.zz = Vector3.Zero();
  3080. this.xy = Vector3.Zero();
  3081. this.yz = Vector3.Zero();
  3082. this.zx = Vector3.Zero();
  3083. }
  3084. SphericalPolynomial.prototype.addAmbient = function (color) {
  3085. var colorVector = new Vector3(color.r, color.g, color.b);
  3086. this.xx = this.xx.add(colorVector);
  3087. this.yy = this.yy.add(colorVector);
  3088. this.zz = this.zz.add(colorVector);
  3089. };
  3090. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3091. var result = new SphericalPolynomial();
  3092. result.x = harmonics.L11.scale(1.02333);
  3093. result.y = harmonics.L1_1.scale(1.02333);
  3094. result.z = harmonics.L10.scale(1.02333);
  3095. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3096. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3097. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3098. result.yz = harmonics.L2_1.scale(0.858086);
  3099. result.zx = harmonics.L21.scale(0.858086);
  3100. result.xy = harmonics.L2_2.scale(0.858086);
  3101. return result;
  3102. };
  3103. return SphericalPolynomial;
  3104. }());
  3105. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3106. // Vertex formats
  3107. var PositionNormalVertex = (function () {
  3108. function PositionNormalVertex(position, normal) {
  3109. if (position === void 0) { position = Vector3.Zero(); }
  3110. if (normal === void 0) { normal = Vector3.Up(); }
  3111. this.position = position;
  3112. this.normal = normal;
  3113. }
  3114. PositionNormalVertex.prototype.clone = function () {
  3115. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3116. };
  3117. return PositionNormalVertex;
  3118. }());
  3119. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3120. var PositionNormalTextureVertex = (function () {
  3121. function PositionNormalTextureVertex(position, normal, uv) {
  3122. if (position === void 0) { position = Vector3.Zero(); }
  3123. if (normal === void 0) { normal = Vector3.Up(); }
  3124. if (uv === void 0) { uv = Vector2.Zero(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. this.uv = uv;
  3128. }
  3129. PositionNormalTextureVertex.prototype.clone = function () {
  3130. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3131. };
  3132. return PositionNormalTextureVertex;
  3133. }());
  3134. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3135. // Temporary pre-allocated objects for engine internal use
  3136. // usage in any internal function :
  3137. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3138. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3139. var Tmp = (function () {
  3140. function Tmp() {
  3141. }
  3142. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3143. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3144. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3145. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3146. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3147. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3148. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3149. Matrix.Zero(), Matrix.Zero(),
  3150. Matrix.Zero(), Matrix.Zero(),
  3151. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3152. return Tmp;
  3153. }());
  3154. BABYLON.Tmp = Tmp;
  3155. })(BABYLON || (BABYLON = {}));
  3156. var BABYLON;
  3157. (function (BABYLON) {
  3158. function generateSerializableMember(type, sourceName) {
  3159. return function (target, propertyKey) {
  3160. if (!target.__serializableMembers) {
  3161. target.__serializableMembers = {};
  3162. }
  3163. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3164. };
  3165. }
  3166. function serialize(sourceName) {
  3167. return generateSerializableMember(0, sourceName); // value member
  3168. }
  3169. BABYLON.serialize = serialize;
  3170. function serializeAsTexture(sourceName) {
  3171. return generateSerializableMember(1, sourceName); // texture member
  3172. }
  3173. BABYLON.serializeAsTexture = serializeAsTexture;
  3174. function serializeAsColor3(sourceName) {
  3175. return generateSerializableMember(2, sourceName); // color3 member
  3176. }
  3177. BABYLON.serializeAsColor3 = serializeAsColor3;
  3178. function serializeAsFresnelParameters(sourceName) {
  3179. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3180. }
  3181. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3182. function serializeAsVector2(sourceName) {
  3183. return generateSerializableMember(4, sourceName); // vector2 member
  3184. }
  3185. BABYLON.serializeAsVector2 = serializeAsVector2;
  3186. function serializeAsVector3(sourceName) {
  3187. return generateSerializableMember(5, sourceName); // vector3 member
  3188. }
  3189. BABYLON.serializeAsVector3 = serializeAsVector3;
  3190. function serializeAsMeshReference(sourceName) {
  3191. return generateSerializableMember(6, sourceName); // mesh reference member
  3192. }
  3193. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3194. function serializeAsColorCurves(sourceName) {
  3195. return generateSerializableMember(7, sourceName); // color curves
  3196. }
  3197. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3198. var SerializationHelper = (function () {
  3199. function SerializationHelper() {
  3200. }
  3201. SerializationHelper.Serialize = function (entity, serializationObject) {
  3202. if (!serializationObject) {
  3203. serializationObject = {};
  3204. }
  3205. // Tags
  3206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3207. // Properties
  3208. for (var property in entity.__serializableMembers) {
  3209. var propertyDescriptor = entity.__serializableMembers[property];
  3210. var targetPropertyName = propertyDescriptor.sourceName || property;
  3211. var propertyType = propertyDescriptor.type;
  3212. var sourceProperty = entity[property];
  3213. if (sourceProperty !== undefined && sourceProperty !== null) {
  3214. switch (propertyType) {
  3215. case 0:
  3216. serializationObject[targetPropertyName] = sourceProperty;
  3217. break;
  3218. case 1:
  3219. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3220. break;
  3221. case 2:
  3222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3223. break;
  3224. case 3:
  3225. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3226. break;
  3227. case 4:
  3228. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3229. break;
  3230. case 5:
  3231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3232. break;
  3233. case 6:
  3234. serializationObject[targetPropertyName] = sourceProperty.id;
  3235. break;
  3236. case 7:
  3237. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3238. break;
  3239. }
  3240. }
  3241. }
  3242. return serializationObject;
  3243. };
  3244. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3245. var destination = creationFunction();
  3246. // Tags
  3247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3248. // Properties
  3249. for (var property in destination.__serializableMembers) {
  3250. var propertyDescriptor = destination.__serializableMembers[property];
  3251. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3252. var propertyType = propertyDescriptor.type;
  3253. if (sourceProperty !== undefined && sourceProperty !== null) {
  3254. switch (propertyType) {
  3255. case 0:
  3256. destination[property] = sourceProperty;
  3257. break;
  3258. case 1:
  3259. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3260. break;
  3261. case 2:
  3262. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3263. break;
  3264. case 3:
  3265. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3266. break;
  3267. case 4:
  3268. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3269. break;
  3270. case 5:
  3271. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3272. break;
  3273. case 6:
  3274. destination[property] = scene.getLastMeshByID(sourceProperty);
  3275. break;
  3276. case 7:
  3277. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3278. break;
  3279. }
  3280. }
  3281. }
  3282. return destination;
  3283. };
  3284. SerializationHelper.Clone = function (creationFunction, source) {
  3285. var destination = creationFunction();
  3286. // Tags
  3287. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3288. // Properties
  3289. for (var property in destination.__serializableMembers) {
  3290. var propertyDescriptor = destination.__serializableMembers[property];
  3291. var sourceProperty = source[property];
  3292. var propertyType = propertyDescriptor.type;
  3293. if (sourceProperty !== undefined && sourceProperty !== null) {
  3294. switch (propertyType) {
  3295. case 0: // Value
  3296. case 6:
  3297. destination[property] = sourceProperty;
  3298. break;
  3299. case 1: // Texture
  3300. case 2: // Color3
  3301. case 3: // FresnelParameters
  3302. case 4: // Vector2
  3303. case 5: // Vector3
  3304. case 7:
  3305. destination[property] = sourceProperty.clone();
  3306. break;
  3307. }
  3308. }
  3309. }
  3310. return destination;
  3311. };
  3312. return SerializationHelper;
  3313. }());
  3314. BABYLON.SerializationHelper = SerializationHelper;
  3315. })(BABYLON || (BABYLON = {}));
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. /**
  3319. * A class serves as a medium between the observable and its observers
  3320. */
  3321. var EventState = (function () {
  3322. /**
  3323. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3324. */
  3325. function EventState(mask, skipNextObservers) {
  3326. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3327. this.initalize(mask, skipNextObservers);
  3328. }
  3329. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3330. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3331. this.mask = mask;
  3332. this.skipNextObservers = skipNextObservers;
  3333. return this;
  3334. };
  3335. return EventState;
  3336. }());
  3337. BABYLON.EventState = EventState;
  3338. /**
  3339. * Represent an Observer registered to a given Observable object.
  3340. */
  3341. var Observer = (function () {
  3342. function Observer(callback, mask) {
  3343. this.callback = callback;
  3344. this.mask = mask;
  3345. }
  3346. return Observer;
  3347. }());
  3348. BABYLON.Observer = Observer;
  3349. /**
  3350. * The Observable class is a simple implementation of the Observable pattern.
  3351. * 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.
  3352. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3353. * 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).
  3354. * 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.
  3355. */
  3356. var Observable = (function () {
  3357. function Observable() {
  3358. this._observers = new Array();
  3359. }
  3360. /**
  3361. * Create a new Observer with the specified callback
  3362. * @param callback the callback that will be executed for that Observer
  3363. * @param mask the mask used to filter observers
  3364. * @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.
  3365. */
  3366. Observable.prototype.add = function (callback, mask, insertFirst) {
  3367. if (mask === void 0) { mask = -1; }
  3368. if (insertFirst === void 0) { insertFirst = false; }
  3369. if (!callback) {
  3370. return null;
  3371. }
  3372. var observer = new Observer(callback, mask);
  3373. if (insertFirst) {
  3374. this._observers.unshift(observer);
  3375. }
  3376. else {
  3377. this._observers.push(observer);
  3378. }
  3379. return observer;
  3380. };
  3381. /**
  3382. * Remove an Observer from the Observable object
  3383. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3384. */
  3385. Observable.prototype.remove = function (observer) {
  3386. var index = this._observers.indexOf(observer);
  3387. if (index !== -1) {
  3388. this._observers.splice(index, 1);
  3389. return true;
  3390. }
  3391. return false;
  3392. };
  3393. /**
  3394. * Remove a callback from the Observable object
  3395. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3396. */
  3397. Observable.prototype.removeCallback = function (callback) {
  3398. for (var index = 0; index < this._observers.length; index++) {
  3399. if (this._observers[index].callback === callback) {
  3400. this._observers.splice(index, 1);
  3401. return true;
  3402. }
  3403. }
  3404. return false;
  3405. };
  3406. /**
  3407. * Notify all Observers by calling their respective callback with the given data
  3408. * @param eventData
  3409. * @param mask
  3410. */
  3411. Observable.prototype.notifyObservers = function (eventData, mask) {
  3412. if (mask === void 0) { mask = -1; }
  3413. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3414. Observable._pooledEventState = null;
  3415. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3416. var obs = _a[_i];
  3417. if (obs.mask & mask) {
  3418. obs.callback(eventData, state);
  3419. }
  3420. if (state.skipNextObservers) {
  3421. break;
  3422. }
  3423. }
  3424. Observable._pooledEventState = state;
  3425. };
  3426. /**
  3427. * return true is the Observable has at least one Observer registered
  3428. */
  3429. Observable.prototype.hasObservers = function () {
  3430. return this._observers.length > 0;
  3431. };
  3432. /**
  3433. * Clear the list of observers
  3434. */
  3435. Observable.prototype.clear = function () {
  3436. this._observers = new Array();
  3437. };
  3438. /**
  3439. * Clone the current observable
  3440. */
  3441. Observable.prototype.clone = function () {
  3442. var result = new Observable();
  3443. result._observers = this._observers.slice(0);
  3444. return result;
  3445. };
  3446. Observable._pooledEventState = null;
  3447. return Observable;
  3448. }());
  3449. BABYLON.Observable = Observable;
  3450. })(BABYLON || (BABYLON = {}));
  3451. var BABYLON;
  3452. (function (BABYLON) {
  3453. var Database = (function () {
  3454. function Database(urlToScene, callbackManifestChecked) {
  3455. // Handling various flavors of prefixed version of IndexedDB
  3456. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3457. this.callbackManifestChecked = callbackManifestChecked;
  3458. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3459. this.db = null;
  3460. this.enableSceneOffline = false;
  3461. this.enableTexturesOffline = false;
  3462. this.manifestVersionFound = 0;
  3463. this.mustUpdateRessources = false;
  3464. this.hasReachedQuota = false;
  3465. if (!Database.IDBStorageEnabled) {
  3466. this.callbackManifestChecked(true);
  3467. }
  3468. else {
  3469. this.checkManifestFile();
  3470. }
  3471. }
  3472. Database.prototype.checkManifestFile = function () {
  3473. var _this = this;
  3474. function noManifestFile() {
  3475. that.enableSceneOffline = false;
  3476. that.enableTexturesOffline = false;
  3477. that.callbackManifestChecked(false);
  3478. }
  3479. var that = this;
  3480. var timeStampUsed = false;
  3481. var manifestURL = this.currentSceneUrl + ".manifest";
  3482. var xhr = new XMLHttpRequest();
  3483. if (navigator.onLine) {
  3484. // Adding a timestamp to by-pass browsers' cache
  3485. timeStampUsed = true;
  3486. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3487. }
  3488. xhr.open("GET", manifestURL, true);
  3489. xhr.addEventListener("load", function () {
  3490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3491. try {
  3492. var manifestFile = JSON.parse(xhr.response);
  3493. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3494. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3496. _this.manifestVersionFound = manifestFile.version;
  3497. }
  3498. if (_this.callbackManifestChecked) {
  3499. _this.callbackManifestChecked(true);
  3500. }
  3501. }
  3502. catch (ex) {
  3503. noManifestFile();
  3504. }
  3505. }
  3506. else {
  3507. noManifestFile();
  3508. }
  3509. }, false);
  3510. xhr.addEventListener("error", function (event) {
  3511. if (timeStampUsed) {
  3512. timeStampUsed = false;
  3513. // Let's retry without the timeStamp
  3514. // It could fail when coupled with HTML5 Offline API
  3515. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3516. xhr.open("GET", retryManifestURL, true);
  3517. xhr.send();
  3518. }
  3519. else {
  3520. noManifestFile();
  3521. }
  3522. }, false);
  3523. try {
  3524. xhr.send();
  3525. }
  3526. catch (ex) {
  3527. BABYLON.Tools.Error("Error on XHR send request.");
  3528. that.callbackManifestChecked(false);
  3529. }
  3530. };
  3531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3532. var _this = this;
  3533. function handleError() {
  3534. that.isSupported = false;
  3535. if (errorCallback)
  3536. errorCallback();
  3537. }
  3538. var that = this;
  3539. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3540. // Your browser doesn't support IndexedDB
  3541. this.isSupported = false;
  3542. if (errorCallback)
  3543. errorCallback();
  3544. }
  3545. else {
  3546. // If the DB hasn't been opened or created yet
  3547. if (!this.db) {
  3548. this.hasReachedQuota = false;
  3549. this.isSupported = true;
  3550. var request = this.idbFactory.open("babylonjs", 1);
  3551. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3552. request.onerror = function (event) {
  3553. handleError();
  3554. };
  3555. // executes when a version change transaction cannot complete due to other active transactions
  3556. request.onblocked = function (event) {
  3557. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3558. handleError();
  3559. };
  3560. // DB has been opened successfully
  3561. request.onsuccess = function (event) {
  3562. _this.db = request.result;
  3563. successCallback();
  3564. };
  3565. // Initialization of the DB. Creating Scenes & Textures stores
  3566. request.onupgradeneeded = function (event) {
  3567. _this.db = (event.target).result;
  3568. try {
  3569. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3570. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3571. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3572. }
  3573. catch (ex) {
  3574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3575. handleError();
  3576. }
  3577. };
  3578. }
  3579. else {
  3580. if (successCallback)
  3581. successCallback();
  3582. }
  3583. }
  3584. };
  3585. Database.prototype.loadImageFromDB = function (url, image) {
  3586. var _this = this;
  3587. var completeURL = Database.ReturnFullUrlLocation(url);
  3588. var saveAndLoadImage = function () {
  3589. if (!_this.hasReachedQuota && _this.db !== null) {
  3590. // the texture is not yet in the DB, let's try to save it
  3591. _this._saveImageIntoDBAsync(completeURL, image);
  3592. }
  3593. else {
  3594. image.src = url;
  3595. }
  3596. };
  3597. if (!this.mustUpdateRessources) {
  3598. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3599. }
  3600. else {
  3601. saveAndLoadImage();
  3602. }
  3603. };
  3604. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3605. if (this.isSupported && this.db !== null) {
  3606. var texture;
  3607. var transaction = this.db.transaction(["textures"]);
  3608. transaction.onabort = function (event) {
  3609. image.src = url;
  3610. };
  3611. transaction.oncomplete = function (event) {
  3612. var blobTextureURL;
  3613. if (texture) {
  3614. var URL = window.URL || window.webkitURL;
  3615. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3616. image.onerror = function () {
  3617. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3618. image.src = url;
  3619. };
  3620. image.src = blobTextureURL;
  3621. }
  3622. else {
  3623. notInDBCallback();
  3624. }
  3625. };
  3626. var getRequest = transaction.objectStore("textures").get(url);
  3627. getRequest.onsuccess = function (event) {
  3628. texture = (event.target).result;
  3629. };
  3630. getRequest.onerror = function (event) {
  3631. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3632. image.src = url;
  3633. };
  3634. }
  3635. else {
  3636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3637. image.src = url;
  3638. }
  3639. };
  3640. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3641. var _this = this;
  3642. if (this.isSupported) {
  3643. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3644. var generateBlobUrl = function () {
  3645. var blobTextureURL;
  3646. if (blob) {
  3647. var URL = window.URL || window.webkitURL;
  3648. try {
  3649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3650. }
  3651. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3652. catch (ex) {
  3653. blobTextureURL = URL.createObjectURL(blob);
  3654. }
  3655. }
  3656. image.src = blobTextureURL;
  3657. };
  3658. if (Database.IsUASupportingBlobStorage) {
  3659. var xhr = new XMLHttpRequest(), blob;
  3660. xhr.open("GET", url, true);
  3661. xhr.responseType = "blob";
  3662. xhr.addEventListener("load", function () {
  3663. if (xhr.status === 200) {
  3664. // Blob as response (XHR2)
  3665. blob = xhr.response;
  3666. var transaction = _this.db.transaction(["textures"], "readwrite");
  3667. // the transaction could abort because of a QuotaExceededError error
  3668. transaction.onabort = function (event) {
  3669. try {
  3670. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3671. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3672. this.hasReachedQuota = true;
  3673. }
  3674. }
  3675. catch (ex) { }
  3676. generateBlobUrl();
  3677. };
  3678. transaction.oncomplete = function (event) {
  3679. generateBlobUrl();
  3680. };
  3681. var newTexture = { textureUrl: url, data: blob };
  3682. try {
  3683. // Put the blob into the dabase
  3684. var addRequest = transaction.objectStore("textures").put(newTexture);
  3685. addRequest.onsuccess = function (event) {
  3686. };
  3687. addRequest.onerror = function (event) {
  3688. generateBlobUrl();
  3689. };
  3690. }
  3691. catch (ex) {
  3692. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3693. if (ex.code === 25) {
  3694. Database.IsUASupportingBlobStorage = false;
  3695. }
  3696. image.src = url;
  3697. }
  3698. }
  3699. else {
  3700. image.src = url;
  3701. }
  3702. }, false);
  3703. xhr.addEventListener("error", function (event) {
  3704. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3705. image.src = url;
  3706. }, false);
  3707. xhr.send();
  3708. }
  3709. else {
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3715. image.src = url;
  3716. }
  3717. };
  3718. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3719. var _this = this;
  3720. var updateVersion = function (event) {
  3721. // the version is not yet in the DB or we need to update it
  3722. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3723. };
  3724. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3725. };
  3726. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3727. var _this = this;
  3728. if (this.isSupported) {
  3729. var version;
  3730. try {
  3731. var transaction = this.db.transaction(["versions"]);
  3732. transaction.oncomplete = function (event) {
  3733. if (version) {
  3734. // If the version in the JSON file is > than the version in DB
  3735. if (_this.manifestVersionFound > version.data) {
  3736. _this.mustUpdateRessources = true;
  3737. updateInDBCallback();
  3738. }
  3739. else {
  3740. callback(version.data);
  3741. }
  3742. }
  3743. else {
  3744. _this.mustUpdateRessources = true;
  3745. updateInDBCallback();
  3746. }
  3747. };
  3748. transaction.onabort = function (event) {
  3749. callback(-1);
  3750. };
  3751. var getRequest = transaction.objectStore("versions").get(url);
  3752. getRequest.onsuccess = function (event) {
  3753. version = (event.target).result;
  3754. };
  3755. getRequest.onerror = function (event) {
  3756. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3757. callback(-1);
  3758. };
  3759. }
  3760. catch (ex) {
  3761. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3762. callback(-1);
  3763. }
  3764. }
  3765. else {
  3766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3767. callback(-1);
  3768. }
  3769. };
  3770. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3771. var _this = this;
  3772. if (this.isSupported && !this.hasReachedQuota) {
  3773. try {
  3774. // Open a transaction to the database
  3775. var transaction = this.db.transaction(["versions"], "readwrite");
  3776. // the transaction could abort because of a QuotaExceededError error
  3777. transaction.onabort = function (event) {
  3778. try {
  3779. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3780. _this.hasReachedQuota = true;
  3781. }
  3782. }
  3783. catch (ex) { }
  3784. callback(-1);
  3785. };
  3786. transaction.oncomplete = function (event) {
  3787. callback(_this.manifestVersionFound);
  3788. };
  3789. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3790. // Put the scene into the database
  3791. var addRequest = transaction.objectStore("versions").put(newVersion);
  3792. addRequest.onsuccess = function (event) {
  3793. };
  3794. addRequest.onerror = function (event) {
  3795. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3796. };
  3797. }
  3798. catch (ex) {
  3799. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3800. callback(-1);
  3801. }
  3802. }
  3803. else {
  3804. callback(-1);
  3805. }
  3806. };
  3807. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3808. var _this = this;
  3809. var completeUrl = Database.ReturnFullUrlLocation(url);
  3810. var saveAndLoadFile = function (event) {
  3811. // the scene is not yet in the DB, let's try to save it
  3812. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3813. };
  3814. this._checkVersionFromDB(completeUrl, function (version) {
  3815. if (version !== -1) {
  3816. if (!_this.mustUpdateRessources) {
  3817. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3818. }
  3819. else {
  3820. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3821. }
  3822. }
  3823. else {
  3824. errorCallback();
  3825. }
  3826. });
  3827. };
  3828. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3829. if (this.isSupported) {
  3830. var targetStore;
  3831. if (url.indexOf(".babylon") !== -1) {
  3832. targetStore = "scenes";
  3833. }
  3834. else {
  3835. targetStore = "textures";
  3836. }
  3837. var file;
  3838. var transaction = this.db.transaction([targetStore]);
  3839. transaction.oncomplete = function (event) {
  3840. if (file) {
  3841. callback(file.data);
  3842. }
  3843. else {
  3844. notInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. notInDBCallback();
  3849. };
  3850. var getRequest = transaction.objectStore(targetStore).get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. file = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3856. notInDBCallback();
  3857. };
  3858. }
  3859. else {
  3860. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3861. callback();
  3862. }
  3863. };
  3864. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3865. var _this = this;
  3866. if (this.isSupported) {
  3867. var targetStore;
  3868. if (url.indexOf(".babylon") !== -1) {
  3869. targetStore = "scenes";
  3870. }
  3871. else {
  3872. targetStore = "textures";
  3873. }
  3874. // Create XHR
  3875. var xhr = new XMLHttpRequest(), fileData;
  3876. xhr.open("GET", url, true);
  3877. if (useArrayBuffer) {
  3878. xhr.responseType = "arraybuffer";
  3879. }
  3880. xhr.onprogress = progressCallback;
  3881. xhr.addEventListener("load", function () {
  3882. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3883. // Blob as response (XHR2)
  3884. //fileData = xhr.responseText;
  3885. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3886. if (!_this.hasReachedQuota) {
  3887. // Open a transaction to the database
  3888. var transaction = _this.db.transaction([targetStore], "readwrite");
  3889. // the transaction could abort because of a QuotaExceededError error
  3890. transaction.onabort = function (event) {
  3891. try {
  3892. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3893. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3894. this.hasReachedQuota = true;
  3895. }
  3896. }
  3897. catch (ex) { }
  3898. callback(fileData);
  3899. };
  3900. transaction.oncomplete = function (event) {
  3901. callback(fileData);
  3902. };
  3903. var newFile;
  3904. if (targetStore === "scenes") {
  3905. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3906. }
  3907. else {
  3908. newFile = { textureUrl: url, data: fileData };
  3909. }
  3910. try {
  3911. // Put the scene into the database
  3912. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3913. addRequest.onsuccess = function (event) {
  3914. };
  3915. addRequest.onerror = function (event) {
  3916. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3917. };
  3918. }
  3919. catch (ex) {
  3920. callback(fileData);
  3921. }
  3922. }
  3923. else {
  3924. callback(fileData);
  3925. }
  3926. }
  3927. else {
  3928. callback();
  3929. }
  3930. }, false);
  3931. xhr.addEventListener("error", function (event) {
  3932. BABYLON.Tools.Error("error on XHR request.");
  3933. callback();
  3934. }, false);
  3935. xhr.send();
  3936. }
  3937. else {
  3938. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3939. callback();
  3940. }
  3941. };
  3942. Database.IsUASupportingBlobStorage = true;
  3943. Database.IDBStorageEnabled = true;
  3944. Database.parseURL = function (url) {
  3945. var a = document.createElement('a');
  3946. a.href = url;
  3947. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3948. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3949. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3950. return absLocation;
  3951. };
  3952. Database.ReturnFullUrlLocation = function (url) {
  3953. if (url.indexOf("http:/") === -1) {
  3954. return (Database.parseURL(window.location.href) + url);
  3955. }
  3956. else {
  3957. return url;
  3958. }
  3959. };
  3960. return Database;
  3961. }());
  3962. BABYLON.Database = Database;
  3963. })(BABYLON || (BABYLON = {}));
  3964. var BABYLON;
  3965. (function (BABYLON) {
  3966. var Internals;
  3967. (function (Internals) {
  3968. /*
  3969. * Based on jsTGALoader - Javascript loader for TGA file
  3970. * By Vincent Thibault
  3971. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3972. */
  3973. var TGATools = (function () {
  3974. function TGATools() {
  3975. }
  3976. TGATools.GetTGAHeader = function (data) {
  3977. var offset = 0;
  3978. var header = {
  3979. id_length: data[offset++],
  3980. colormap_type: data[offset++],
  3981. image_type: data[offset++],
  3982. colormap_index: data[offset++] | data[offset++] << 8,
  3983. colormap_length: data[offset++] | data[offset++] << 8,
  3984. colormap_size: data[offset++],
  3985. origin: [
  3986. data[offset++] | data[offset++] << 8,
  3987. data[offset++] | data[offset++] << 8
  3988. ],
  3989. width: data[offset++] | data[offset++] << 8,
  3990. height: data[offset++] | data[offset++] << 8,
  3991. pixel_size: data[offset++],
  3992. flags: data[offset++]
  3993. };
  3994. return header;
  3995. };
  3996. TGATools.UploadContent = function (gl, data) {
  3997. // Not enough data to contain header ?
  3998. if (data.length < 19) {
  3999. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4000. return;
  4001. }
  4002. // Read Header
  4003. var offset = 18;
  4004. var header = TGATools.GetTGAHeader(data);
  4005. // Assume it's a valid Targa file.
  4006. if (header.id_length + offset > data.length) {
  4007. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4008. return;
  4009. }
  4010. // Skip not needed data
  4011. offset += header.id_length;
  4012. var use_rle = false;
  4013. var use_pal = false;
  4014. var use_rgb = false;
  4015. var use_grey = false;
  4016. // Get some informations.
  4017. switch (header.image_type) {
  4018. case TGATools._TYPE_RLE_INDEXED:
  4019. use_rle = true;
  4020. case TGATools._TYPE_INDEXED:
  4021. use_pal = true;
  4022. break;
  4023. case TGATools._TYPE_RLE_RGB:
  4024. use_rle = true;
  4025. case TGATools._TYPE_RGB:
  4026. use_rgb = true;
  4027. break;
  4028. case TGATools._TYPE_RLE_GREY:
  4029. use_rle = true;
  4030. case TGATools._TYPE_GREY:
  4031. use_grey = true;
  4032. break;
  4033. }
  4034. var pixel_data;
  4035. var numAlphaBits = header.flags & 0xf;
  4036. var pixel_size = header.pixel_size >> 3;
  4037. var pixel_total = header.width * header.height * pixel_size;
  4038. // Read palettes
  4039. var palettes;
  4040. if (use_pal) {
  4041. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4042. }
  4043. // Read LRE
  4044. if (use_rle) {
  4045. pixel_data = new Uint8Array(pixel_total);
  4046. var c, count, i;
  4047. var localOffset = 0;
  4048. var pixels = new Uint8Array(pixel_size);
  4049. while (offset < pixel_total && localOffset < pixel_total) {
  4050. c = data[offset++];
  4051. count = (c & 0x7f) + 1;
  4052. // RLE pixels
  4053. if (c & 0x80) {
  4054. // Bind pixel tmp array
  4055. for (i = 0; i < pixel_size; ++i) {
  4056. pixels[i] = data[offset++];
  4057. }
  4058. // Copy pixel array
  4059. for (i = 0; i < count; ++i) {
  4060. pixel_data.set(pixels, localOffset + i * pixel_size);
  4061. }
  4062. localOffset += pixel_size * count;
  4063. }
  4064. else {
  4065. count *= pixel_size;
  4066. for (i = 0; i < count; ++i) {
  4067. pixel_data[localOffset + i] = data[offset++];
  4068. }
  4069. localOffset += count;
  4070. }
  4071. }
  4072. }
  4073. else {
  4074. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4075. }
  4076. // Load to texture
  4077. var x_start, y_start, x_step, y_step, y_end, x_end;
  4078. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4079. default:
  4080. case TGATools._ORIGIN_UL:
  4081. x_start = 0;
  4082. x_step = 1;
  4083. x_end = header.width;
  4084. y_start = 0;
  4085. y_step = 1;
  4086. y_end = header.height;
  4087. break;
  4088. case TGATools._ORIGIN_BL:
  4089. x_start = 0;
  4090. x_step = 1;
  4091. x_end = header.width;
  4092. y_start = header.height - 1;
  4093. y_step = -1;
  4094. y_end = -1;
  4095. break;
  4096. case TGATools._ORIGIN_UR:
  4097. x_start = header.width - 1;
  4098. x_step = -1;
  4099. x_end = -1;
  4100. y_start = 0;
  4101. y_step = 1;
  4102. y_end = header.height;
  4103. break;
  4104. case TGATools._ORIGIN_BR:
  4105. x_start = header.width - 1;
  4106. x_step = -1;
  4107. x_end = -1;
  4108. y_start = header.height - 1;
  4109. y_step = -1;
  4110. y_end = -1;
  4111. break;
  4112. }
  4113. // Load the specify method
  4114. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4115. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4116. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4117. };
  4118. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4119. var image = pixel_data, colormap = palettes;
  4120. var width = header.width, height = header.height;
  4121. var color, i = 0, x, y;
  4122. var imageData = new Uint8Array(width * height * 4);
  4123. for (y = y_start; y !== y_end; y += y_step) {
  4124. for (x = x_start; x !== x_end; x += x_step, i++) {
  4125. color = image[i];
  4126. imageData[(x + width * y) * 4 + 3] = 255;
  4127. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4128. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4129. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4130. }
  4131. }
  4132. return imageData;
  4133. };
  4134. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4135. var image = pixel_data;
  4136. var width = header.width, height = header.height;
  4137. var color, i = 0, x, y;
  4138. var imageData = new Uint8Array(width * height * 4);
  4139. for (y = y_start; y !== y_end; y += y_step) {
  4140. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4141. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4142. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4143. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4144. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4145. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4146. }
  4147. }
  4148. return imageData;
  4149. };
  4150. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4151. var image = pixel_data;
  4152. var width = header.width, height = header.height;
  4153. var i = 0, x, y;
  4154. var imageData = new Uint8Array(width * height * 4);
  4155. for (y = y_start; y !== y_end; y += y_step) {
  4156. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4157. imageData[(x + width * y) * 4 + 3] = 255;
  4158. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4159. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4160. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4161. }
  4162. }
  4163. return imageData;
  4164. };
  4165. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4166. var image = pixel_data;
  4167. var width = header.width, height = header.height;
  4168. var i = 0, x, y;
  4169. var imageData = new Uint8Array(width * height * 4);
  4170. for (y = y_start; y !== y_end; y += y_step) {
  4171. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4176. }
  4177. }
  4178. return imageData;
  4179. };
  4180. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4181. var image = pixel_data;
  4182. var width = header.width, height = header.height;
  4183. var color, i = 0, x, y;
  4184. var imageData = new Uint8Array(width * height * 4);
  4185. for (y = y_start; y !== y_end; y += y_step) {
  4186. for (x = x_start; x !== x_end; x += x_step, i++) {
  4187. color = image[i];
  4188. imageData[(x + width * y) * 4 + 0] = color;
  4189. imageData[(x + width * y) * 4 + 1] = color;
  4190. imageData[(x + width * y) * 4 + 2] = color;
  4191. imageData[(x + width * y) * 4 + 3] = 255;
  4192. }
  4193. }
  4194. return imageData;
  4195. };
  4196. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4197. var image = pixel_data;
  4198. var width = header.width, height = header.height;
  4199. var i = 0, x, y;
  4200. var imageData = new Uint8Array(width * height * 4);
  4201. for (y = y_start; y !== y_end; y += y_step) {
  4202. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4203. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4204. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4205. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4206. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4207. }
  4208. }
  4209. return imageData;
  4210. };
  4211. TGATools._TYPE_NO_DATA = 0;
  4212. TGATools._TYPE_INDEXED = 1;
  4213. TGATools._TYPE_RGB = 2;
  4214. TGATools._TYPE_GREY = 3;
  4215. TGATools._TYPE_RLE_INDEXED = 9;
  4216. TGATools._TYPE_RLE_RGB = 10;
  4217. TGATools._TYPE_RLE_GREY = 11;
  4218. TGATools._ORIGIN_MASK = 0x30;
  4219. TGATools._ORIGIN_SHIFT = 0x04;
  4220. TGATools._ORIGIN_BL = 0x00;
  4221. TGATools._ORIGIN_BR = 0x01;
  4222. TGATools._ORIGIN_UL = 0x02;
  4223. TGATools._ORIGIN_UR = 0x03;
  4224. return TGATools;
  4225. }());
  4226. Internals.TGATools = TGATools;
  4227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4228. })(BABYLON || (BABYLON = {}));
  4229. var BABYLON;
  4230. (function (BABYLON) {
  4231. var SmartArray = (function () {
  4232. function SmartArray(capacity) {
  4233. this.length = 0;
  4234. this._duplicateId = 0;
  4235. this.data = new Array(capacity);
  4236. this._id = SmartArray._GlobalId++;
  4237. }
  4238. SmartArray.prototype.push = function (value) {
  4239. this.data[this.length++] = value;
  4240. if (this.length > this.data.length) {
  4241. this.data.length *= 2;
  4242. }
  4243. if (!value.__smartArrayFlags) {
  4244. value.__smartArrayFlags = {};
  4245. }
  4246. value.__smartArrayFlags[this._id] = this._duplicateId;
  4247. };
  4248. SmartArray.prototype.pushNoDuplicate = function (value) {
  4249. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4250. return false;
  4251. }
  4252. this.push(value);
  4253. return true;
  4254. };
  4255. SmartArray.prototype.sort = function (compareFn) {
  4256. this.data.sort(compareFn);
  4257. };
  4258. SmartArray.prototype.reset = function () {
  4259. this.length = 0;
  4260. this._duplicateId++;
  4261. };
  4262. SmartArray.prototype.concat = function (array) {
  4263. if (array.length === 0) {
  4264. return;
  4265. }
  4266. if (this.length + array.length > this.data.length) {
  4267. this.data.length = (this.length + array.length) * 2;
  4268. }
  4269. for (var index = 0; index < array.length; index++) {
  4270. this.data[this.length++] = (array.data || array)[index];
  4271. }
  4272. };
  4273. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4274. if (array.length === 0) {
  4275. return;
  4276. }
  4277. if (this.length + array.length > this.data.length) {
  4278. this.data.length = (this.length + array.length) * 2;
  4279. }
  4280. for (var index = 0; index < array.length; index++) {
  4281. var item = (array.data || array)[index];
  4282. this.pushNoDuplicate(item);
  4283. }
  4284. };
  4285. SmartArray.prototype.indexOf = function (value) {
  4286. var position = this.data.indexOf(value);
  4287. if (position >= this.length) {
  4288. return -1;
  4289. }
  4290. return position;
  4291. };
  4292. // Statics
  4293. SmartArray._GlobalId = 0;
  4294. return SmartArray;
  4295. }());
  4296. BABYLON.SmartArray = SmartArray;
  4297. })(BABYLON || (BABYLON = {}));
  4298. var BABYLON;
  4299. (function (BABYLON) {
  4300. /**
  4301. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4302. * The underlying implementation relies on an associative array to ensure the best performances.
  4303. * The value can be anything including 'null' but except 'undefined'
  4304. */
  4305. var StringDictionary = (function () {
  4306. function StringDictionary() {
  4307. this._count = 0;
  4308. this._data = {};
  4309. }
  4310. /**
  4311. * Get a value based from its key
  4312. * @param key the given key to get the matching value from
  4313. * @return the value if found, otherwise undefined is returned
  4314. */
  4315. StringDictionary.prototype.get = function (key) {
  4316. var val = this._data[key];
  4317. if (val !== undefined) {
  4318. return val;
  4319. }
  4320. return undefined;
  4321. };
  4322. /**
  4323. * Get a value from its key or add it if it doesn't exist.
  4324. * This method will ensure you that a given key/data will be present in the dictionary.
  4325. * @param key the given key to get the matching value from
  4326. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4327. * The factory will only be invoked if there's no data for the given key.
  4328. * @return the value corresponding to the key.
  4329. */
  4330. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4331. var val = this.get(key);
  4332. if (val !== undefined) {
  4333. return val;
  4334. }
  4335. val = factory(key);
  4336. if (val) {
  4337. this.add(key, val);
  4338. }
  4339. return val;
  4340. };
  4341. /**
  4342. * Get a value from its key if present in the dictionary otherwise add it
  4343. * @param key the key to get the value from
  4344. * @param val if there's no such key/value pair in the dictionary add it with this value
  4345. * @return the value corresponding to the key
  4346. */
  4347. StringDictionary.prototype.getOrAdd = function (key, val) {
  4348. var curVal = this.get(key);
  4349. if (curVal !== undefined) {
  4350. return curVal;
  4351. }
  4352. this.add(key, val);
  4353. return val;
  4354. };
  4355. /**
  4356. * Check if there's a given key in the dictionary
  4357. * @param key the key to check for
  4358. * @return true if the key is present, false otherwise
  4359. */
  4360. StringDictionary.prototype.contains = function (key) {
  4361. return this._data[key] !== undefined;
  4362. };
  4363. /**
  4364. * Add a new key and its corresponding value
  4365. * @param key the key to add
  4366. * @param value the value corresponding to the key
  4367. * @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
  4368. */
  4369. StringDictionary.prototype.add = function (key, value) {
  4370. if (this._data[key] !== undefined) {
  4371. return false;
  4372. }
  4373. this._data[key] = value;
  4374. ++this._count;
  4375. return true;
  4376. };
  4377. StringDictionary.prototype.set = function (key, value) {
  4378. if (this._data[key] === undefined) {
  4379. return false;
  4380. }
  4381. this._data[key] = value;
  4382. return true;
  4383. };
  4384. /**
  4385. * Remove a key/value from the dictionary.
  4386. * @param key the key to remove
  4387. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4388. */
  4389. StringDictionary.prototype.remove = function (key) {
  4390. if (this.contains(key)) {
  4391. delete this._data[key];
  4392. --this._count;
  4393. return true;
  4394. }
  4395. return false;
  4396. };
  4397. /**
  4398. * Clear the whole content of the dictionary
  4399. */
  4400. StringDictionary.prototype.clear = function () {
  4401. this._data = {};
  4402. this._count = 0;
  4403. };
  4404. Object.defineProperty(StringDictionary.prototype, "count", {
  4405. get: function () {
  4406. return this._count;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Execute a callback on each key/val of the dictionary.
  4413. * Note that you can remove any element in this dictionary in the callback implementation
  4414. * @param callback the callback to execute on a given key/value pair
  4415. */
  4416. StringDictionary.prototype.forEach = function (callback) {
  4417. for (var cur in this._data) {
  4418. var val = this._data[cur];
  4419. callback(cur, val);
  4420. }
  4421. };
  4422. /**
  4423. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4424. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4425. * Note that you can remove any element in this dictionary in the callback implementation
  4426. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4427. */
  4428. StringDictionary.prototype.first = function (callback) {
  4429. for (var cur in this._data) {
  4430. var val = this._data[cur];
  4431. var res = callback(cur, val);
  4432. if (res) {
  4433. return res;
  4434. }
  4435. }
  4436. return null;
  4437. };
  4438. return StringDictionary;
  4439. }());
  4440. BABYLON.StringDictionary = StringDictionary;
  4441. })(BABYLON || (BABYLON = {}));
  4442. var BABYLON;
  4443. (function (BABYLON) {
  4444. // Screenshots
  4445. var screenshotCanvas;
  4446. var cloneValue = function (source, destinationObject) {
  4447. if (!source)
  4448. return null;
  4449. if (source instanceof BABYLON.Mesh) {
  4450. return null;
  4451. }
  4452. if (source instanceof BABYLON.SubMesh) {
  4453. return source.clone(destinationObject);
  4454. }
  4455. else if (source.clone) {
  4456. return source.clone();
  4457. }
  4458. return null;
  4459. };
  4460. var Tools = (function () {
  4461. function Tools() {
  4462. }
  4463. Tools.Instantiate = function (className) {
  4464. var arr = className.split(".");
  4465. var fn = (window || this);
  4466. for (var i = 0, len = arr.length; i < len; i++) {
  4467. fn = fn[arr[i]];
  4468. }
  4469. if (typeof fn !== "function") {
  4470. return null;
  4471. }
  4472. return fn;
  4473. };
  4474. Tools.SetImmediate = function (action) {
  4475. if (window.setImmediate) {
  4476. window.setImmediate(action);
  4477. }
  4478. else {
  4479. setTimeout(action, 1);
  4480. }
  4481. };
  4482. Tools.IsExponentOfTwo = function (value) {
  4483. var count = 1;
  4484. do {
  4485. count *= 2;
  4486. } while (count < value);
  4487. return count === value;
  4488. };
  4489. Tools.GetExponentOfTwo = function (value, max) {
  4490. var count = 1;
  4491. do {
  4492. count *= 2;
  4493. } while (count < value);
  4494. if (count > max)
  4495. count = max;
  4496. return count;
  4497. };
  4498. Tools.GetFilename = function (path) {
  4499. var index = path.lastIndexOf("/");
  4500. if (index < 0)
  4501. return path;
  4502. return path.substring(index + 1);
  4503. };
  4504. Tools.GetDOMTextContent = function (element) {
  4505. var result = "";
  4506. var child = element.firstChild;
  4507. while (child) {
  4508. if (child.nodeType === 3) {
  4509. result += child.textContent;
  4510. }
  4511. child = child.nextSibling;
  4512. }
  4513. return result;
  4514. };
  4515. Tools.ToDegrees = function (angle) {
  4516. return angle * 180 / Math.PI;
  4517. };
  4518. Tools.ToRadians = function (angle) {
  4519. return angle * Math.PI / 180;
  4520. };
  4521. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4522. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4523. var output = "";
  4524. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4525. var i = 0;
  4526. var bytes = new Uint8Array(buffer);
  4527. while (i < bytes.length) {
  4528. chr1 = bytes[i++];
  4529. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4530. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4531. enc1 = chr1 >> 2;
  4532. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4533. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4534. enc4 = chr3 & 63;
  4535. if (isNaN(chr2)) {
  4536. enc3 = enc4 = 64;
  4537. }
  4538. else if (isNaN(chr3)) {
  4539. enc4 = 64;
  4540. }
  4541. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4542. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4543. }
  4544. return "data:image/png;base64," + output;
  4545. };
  4546. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4547. if (bias === void 0) { bias = null; }
  4548. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4549. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4550. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4551. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4552. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4553. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4554. }
  4555. if (bias) {
  4556. minimum.x -= minimum.x * bias.x + bias.y;
  4557. minimum.y -= minimum.y * bias.x + bias.y;
  4558. minimum.z -= minimum.z * bias.x + bias.y;
  4559. maximum.x += maximum.x * bias.x + bias.y;
  4560. maximum.y += maximum.y * bias.x + bias.y;
  4561. maximum.z += maximum.z * bias.x + bias.y;
  4562. }
  4563. return {
  4564. minimum: minimum,
  4565. maximum: maximum
  4566. };
  4567. };
  4568. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4569. if (bias === void 0) { bias = null; }
  4570. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4571. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4572. if (!stride) {
  4573. stride = 3;
  4574. }
  4575. for (var index = start; index < start + count; index++) {
  4576. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4577. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4578. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4579. }
  4580. if (bias) {
  4581. minimum.x -= minimum.x * bias.x + bias.y;
  4582. minimum.y -= minimum.y * bias.x + bias.y;
  4583. minimum.z -= minimum.z * bias.x + bias.y;
  4584. maximum.x += maximum.x * bias.x + bias.y;
  4585. maximum.y += maximum.y * bias.x + bias.y;
  4586. maximum.z += maximum.z * bias.x + bias.y;
  4587. }
  4588. return {
  4589. minimum: minimum,
  4590. maximum: maximum
  4591. };
  4592. };
  4593. Tools.Vector2ArrayFeeder = function (array) {
  4594. return function (index) {
  4595. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4596. var length = isFloatArray ? array.length / 2 : array.length;
  4597. if (index >= length) {
  4598. return null;
  4599. }
  4600. if (isFloatArray) {
  4601. var fa = array;
  4602. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4603. }
  4604. var a = array;
  4605. return a[index];
  4606. };
  4607. };
  4608. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4609. if (bias === void 0) { bias = null; }
  4610. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4611. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4612. var i = 0;
  4613. var cur = feeder(i++);
  4614. while (cur) {
  4615. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4616. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4617. cur = feeder(i++);
  4618. }
  4619. if (bias) {
  4620. minimum.x -= minimum.x * bias.x + bias.y;
  4621. minimum.y -= minimum.y * bias.x + bias.y;
  4622. maximum.x += maximum.x * bias.x + bias.y;
  4623. maximum.y += maximum.y * bias.x + bias.y;
  4624. }
  4625. return {
  4626. minimum: minimum,
  4627. maximum: maximum
  4628. };
  4629. };
  4630. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4631. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4632. return undefined;
  4633. return Array.isArray(obj) ? obj : [obj];
  4634. };
  4635. // Misc.
  4636. Tools.GetPointerPrefix = function () {
  4637. var eventPrefix = "pointer";
  4638. // Check if pointer events are supported
  4639. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4640. eventPrefix = "mouse";
  4641. }
  4642. return eventPrefix;
  4643. };
  4644. Tools.QueueNewFrame = function (func) {
  4645. if (window.requestAnimationFrame)
  4646. window.requestAnimationFrame(func);
  4647. else if (window.msRequestAnimationFrame)
  4648. window.msRequestAnimationFrame(func);
  4649. else if (window.webkitRequestAnimationFrame)
  4650. window.webkitRequestAnimationFrame(func);
  4651. else if (window.mozRequestAnimationFrame)
  4652. window.mozRequestAnimationFrame(func);
  4653. else if (window.oRequestAnimationFrame)
  4654. window.oRequestAnimationFrame(func);
  4655. else {
  4656. window.setTimeout(func, 16);
  4657. }
  4658. };
  4659. Tools.RequestFullscreen = function (element, options) {
  4660. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4661. if (!requestFunction)
  4662. return;
  4663. requestFunction.call(element, options);
  4664. };
  4665. Tools.ExitFullscreen = function () {
  4666. if (document.exitFullscreen) {
  4667. document.exitFullscreen();
  4668. }
  4669. else if (document.mozCancelFullScreen) {
  4670. document.mozCancelFullScreen();
  4671. }
  4672. else if (document.webkitCancelFullScreen) {
  4673. document.webkitCancelFullScreen();
  4674. }
  4675. else if (document.msCancelFullScreen) {
  4676. document.msCancelFullScreen();
  4677. }
  4678. };
  4679. // External files
  4680. Tools.CleanUrl = function (url) {
  4681. url = url.replace(/#/mg, "%23");
  4682. return url;
  4683. };
  4684. Tools.LoadImage = function (url, onload, onerror, database) {
  4685. if (url instanceof ArrayBuffer) {
  4686. url = Tools.EncodeArrayBufferTobase64(url);
  4687. }
  4688. url = Tools.CleanUrl(url);
  4689. var img = new Image();
  4690. if (url.substr(0, 5) !== "data:") {
  4691. if (Tools.CorsBehavior) {
  4692. switch (typeof (Tools.CorsBehavior)) {
  4693. case "function":
  4694. var result = Tools.CorsBehavior(url);
  4695. if (result) {
  4696. img.crossOrigin = result;
  4697. }
  4698. break;
  4699. case "string":
  4700. default:
  4701. img.crossOrigin = Tools.CorsBehavior;
  4702. break;
  4703. }
  4704. }
  4705. }
  4706. img.onload = function () {
  4707. onload(img);
  4708. };
  4709. img.onerror = function (err) {
  4710. Tools.Error("Error while trying to load texture: " + url);
  4711. if (Tools.UseFallbackTexture) {
  4712. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4713. onload(img);
  4714. }
  4715. else {
  4716. onerror();
  4717. }
  4718. };
  4719. var noIndexedDB = function () {
  4720. img.src = url;
  4721. };
  4722. var loadFromIndexedDB = function () {
  4723. database.loadImageFromDB(url, img);
  4724. };
  4725. //ANY database to do!
  4726. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4727. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4728. }
  4729. else {
  4730. if (url.indexOf("file:") === -1) {
  4731. noIndexedDB();
  4732. }
  4733. else {
  4734. try {
  4735. var textureName = url.substring(5).toLowerCase();
  4736. var blobURL;
  4737. try {
  4738. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4739. }
  4740. catch (ex) {
  4741. // Chrome doesn't support oneTimeOnly parameter
  4742. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4743. }
  4744. img.src = blobURL;
  4745. }
  4746. catch (e) {
  4747. img.src = null;
  4748. }
  4749. }
  4750. }
  4751. return img;
  4752. };
  4753. //ANY
  4754. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4755. url = Tools.CleanUrl(url);
  4756. var noIndexedDB = function () {
  4757. var request = new XMLHttpRequest();
  4758. var loadUrl = Tools.BaseUrl + url;
  4759. request.open('GET', loadUrl, true);
  4760. if (useArrayBuffer) {
  4761. request.responseType = "arraybuffer";
  4762. }
  4763. request.onprogress = progressCallBack;
  4764. request.onreadystatechange = function () {
  4765. if (request.readyState === 4) {
  4766. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4767. callback(!useArrayBuffer ? request.responseText : request.response);
  4768. }
  4769. else {
  4770. if (onError) {
  4771. onError();
  4772. }
  4773. else {
  4774. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4775. }
  4776. }
  4777. }
  4778. };
  4779. request.send(null);
  4780. };
  4781. var loadFromIndexedDB = function () {
  4782. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4783. };
  4784. if (url.indexOf("file:") !== -1) {
  4785. var fileName = url.substring(5).toLowerCase();
  4786. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4787. }
  4788. else {
  4789. // Caching all files
  4790. if (database && database.enableSceneOffline) {
  4791. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4792. }
  4793. else {
  4794. noIndexedDB();
  4795. }
  4796. }
  4797. };
  4798. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4799. var reader = new FileReader();
  4800. reader.onload = function (e) {
  4801. //target doesn't have result from ts 1.3
  4802. callback(e.target['result']);
  4803. };
  4804. reader.onprogress = progressCallback;
  4805. reader.readAsDataURL(fileToLoad);
  4806. };
  4807. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4808. var reader = new FileReader();
  4809. reader.onerror = function (e) {
  4810. Tools.Log("Error while reading file: " + fileToLoad.name);
  4811. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4812. };
  4813. reader.onload = function (e) {
  4814. //target doesn't have result from ts 1.3
  4815. callback(e.target['result']);
  4816. };
  4817. reader.onprogress = progressCallBack;
  4818. if (!useArrayBuffer) {
  4819. // Asynchronous read
  4820. reader.readAsText(fileToLoad);
  4821. }
  4822. else {
  4823. reader.readAsArrayBuffer(fileToLoad);
  4824. }
  4825. };
  4826. //returns a downloadable url to a file content.
  4827. Tools.FileAsURL = function (content) {
  4828. var fileBlob = new Blob([content]);
  4829. var url = window.URL || window.webkitURL;
  4830. var link = url.createObjectURL(fileBlob);
  4831. return link;
  4832. };
  4833. // Misc.
  4834. Tools.Format = function (value, decimals) {
  4835. if (decimals === void 0) { decimals = 2; }
  4836. return value.toFixed(decimals);
  4837. };
  4838. Tools.CheckExtends = function (v, min, max) {
  4839. if (v.x < min.x)
  4840. min.x = v.x;
  4841. if (v.y < min.y)
  4842. min.y = v.y;
  4843. if (v.z < min.z)
  4844. min.z = v.z;
  4845. if (v.x > max.x)
  4846. max.x = v.x;
  4847. if (v.y > max.y)
  4848. max.y = v.y;
  4849. if (v.z > max.z)
  4850. max.z = v.z;
  4851. };
  4852. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4853. for (var prop in source) {
  4854. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4855. continue;
  4856. }
  4857. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4858. continue;
  4859. }
  4860. var sourceValue = source[prop];
  4861. var typeOfSourceValue = typeof sourceValue;
  4862. if (typeOfSourceValue === "function") {
  4863. continue;
  4864. }
  4865. if (typeOfSourceValue === "object") {
  4866. if (sourceValue instanceof Array) {
  4867. destination[prop] = [];
  4868. if (sourceValue.length > 0) {
  4869. if (typeof sourceValue[0] == "object") {
  4870. for (var index = 0; index < sourceValue.length; index++) {
  4871. var clonedValue = cloneValue(sourceValue[index], destination);
  4872. if (destination[prop].indexOf(clonedValue) === -1) {
  4873. destination[prop].push(clonedValue);
  4874. }
  4875. }
  4876. }
  4877. else {
  4878. destination[prop] = sourceValue.slice(0);
  4879. }
  4880. }
  4881. }
  4882. else {
  4883. destination[prop] = cloneValue(sourceValue, destination);
  4884. }
  4885. }
  4886. else {
  4887. destination[prop] = sourceValue;
  4888. }
  4889. }
  4890. };
  4891. Tools.IsEmpty = function (obj) {
  4892. for (var i in obj) {
  4893. return false;
  4894. }
  4895. return true;
  4896. };
  4897. Tools.RegisterTopRootEvents = function (events) {
  4898. for (var index = 0; index < events.length; index++) {
  4899. var event = events[index];
  4900. window.addEventListener(event.name, event.handler, false);
  4901. try {
  4902. if (window.parent) {
  4903. window.parent.addEventListener(event.name, event.handler, false);
  4904. }
  4905. }
  4906. catch (e) {
  4907. }
  4908. }
  4909. };
  4910. Tools.UnregisterTopRootEvents = function (events) {
  4911. for (var index = 0; index < events.length; index++) {
  4912. var event = events[index];
  4913. window.removeEventListener(event.name, event.handler);
  4914. try {
  4915. if (window.parent) {
  4916. window.parent.removeEventListener(event.name, event.handler);
  4917. }
  4918. }
  4919. catch (e) {
  4920. }
  4921. }
  4922. };
  4923. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4924. if (mimeType === void 0) { mimeType = "image/png"; }
  4925. // Read the contents of the framebuffer
  4926. var numberOfChannelsByLine = width * 4;
  4927. var halfHeight = height / 2;
  4928. //Reading datas from WebGL
  4929. var data = engine.readPixels(0, 0, width, height);
  4930. //To flip image on Y axis.
  4931. for (var i = 0; i < halfHeight; i++) {
  4932. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4933. var currentCell = j + i * numberOfChannelsByLine;
  4934. var targetLine = height - i - 1;
  4935. var targetCell = j + targetLine * numberOfChannelsByLine;
  4936. var temp = data[currentCell];
  4937. data[currentCell] = data[targetCell];
  4938. data[targetCell] = temp;
  4939. }
  4940. }
  4941. // Create a 2D canvas to store the result
  4942. if (!screenshotCanvas) {
  4943. screenshotCanvas = document.createElement('canvas');
  4944. }
  4945. screenshotCanvas.width = width;
  4946. screenshotCanvas.height = height;
  4947. var context = screenshotCanvas.getContext('2d');
  4948. // Copy the pixels to a 2D canvas
  4949. var imageData = context.createImageData(width, height);
  4950. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4951. var castData = imageData.data;
  4952. castData.set(data);
  4953. context.putImageData(imageData, 0, 0);
  4954. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4955. if (successCallback) {
  4956. successCallback(base64Image);
  4957. }
  4958. else {
  4959. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4960. if (("download" in document.createElement("a"))) {
  4961. var a = window.document.createElement("a");
  4962. a.href = base64Image;
  4963. var date = new Date();
  4964. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4965. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4966. window.document.body.appendChild(a);
  4967. a.addEventListener("click", function () {
  4968. a.parentElement.removeChild(a);
  4969. });
  4970. a.click();
  4971. }
  4972. else {
  4973. var newWindow = window.open("");
  4974. var img = newWindow.document.createElement("img");
  4975. img.src = base64Image;
  4976. newWindow.document.body.appendChild(img);
  4977. }
  4978. }
  4979. };
  4980. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4981. if (mimeType === void 0) { mimeType = "image/png"; }
  4982. var width;
  4983. var height;
  4984. //If a precision value is specified
  4985. if (size.precision) {
  4986. width = Math.round(engine.getRenderWidth() * size.precision);
  4987. height = Math.round(width / engine.getAspectRatio(camera));
  4988. size = { width: width, height: height };
  4989. }
  4990. else if (size.width && size.height) {
  4991. width = size.width;
  4992. height = size.height;
  4993. }
  4994. else if (size.width && !size.height) {
  4995. width = size.width;
  4996. height = Math.round(width / engine.getAspectRatio(camera));
  4997. size = { width: width, height: height };
  4998. }
  4999. else if (size.height && !size.width) {
  5000. height = size.height;
  5001. width = Math.round(height * engine.getAspectRatio(camera));
  5002. size = { width: width, height: height };
  5003. }
  5004. else if (!isNaN(size)) {
  5005. height = size;
  5006. width = size;
  5007. }
  5008. else {
  5009. Tools.Error("Invalid 'size' parameter !");
  5010. return;
  5011. }
  5012. var scene = camera.getScene();
  5013. var previousCamera = null;
  5014. if (scene.activeCamera !== camera) {
  5015. previousCamera = scene.activeCamera;
  5016. scene.activeCamera = camera;
  5017. }
  5018. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5019. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5020. texture.renderList = scene.meshes;
  5021. texture.onAfterRenderObservable.add(function () {
  5022. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5023. });
  5024. scene.incrementRenderId();
  5025. scene.resetCachedMaterial();
  5026. texture.render(true);
  5027. texture.dispose();
  5028. if (previousCamera) {
  5029. scene.activeCamera = previousCamera;
  5030. }
  5031. camera.getProjectionMatrix(true); // Force cache refresh;
  5032. };
  5033. // XHR response validator for local file scenario
  5034. Tools.ValidateXHRData = function (xhr, dataType) {
  5035. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5036. if (dataType === void 0) { dataType = 7; }
  5037. try {
  5038. if (dataType & 1) {
  5039. if (xhr.responseText && xhr.responseText.length > 0) {
  5040. return true;
  5041. }
  5042. else if (dataType === 1) {
  5043. return false;
  5044. }
  5045. }
  5046. if (dataType & 2) {
  5047. // Check header width and height since there is no "TGA" magic number
  5048. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5049. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5050. return true;
  5051. }
  5052. else if (dataType === 2) {
  5053. return false;
  5054. }
  5055. }
  5056. if (dataType & 4) {
  5057. // Check for the "DDS" magic number
  5058. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5059. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5060. return true;
  5061. }
  5062. else {
  5063. return false;
  5064. }
  5065. }
  5066. }
  5067. catch (e) {
  5068. }
  5069. return false;
  5070. };
  5071. Object.defineProperty(Tools, "NoneLogLevel", {
  5072. get: function () {
  5073. return Tools._NoneLogLevel;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(Tools, "MessageLogLevel", {
  5079. get: function () {
  5080. return Tools._MessageLogLevel;
  5081. },
  5082. enumerable: true,
  5083. configurable: true
  5084. });
  5085. Object.defineProperty(Tools, "WarningLogLevel", {
  5086. get: function () {
  5087. return Tools._WarningLogLevel;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(Tools, "ErrorLogLevel", {
  5093. get: function () {
  5094. return Tools._ErrorLogLevel;
  5095. },
  5096. enumerable: true,
  5097. configurable: true
  5098. });
  5099. Object.defineProperty(Tools, "AllLogLevel", {
  5100. get: function () {
  5101. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Tools._AddLogEntry = function (entry) {
  5107. Tools._LogCache = entry + Tools._LogCache;
  5108. if (Tools.OnNewCacheEntry) {
  5109. Tools.OnNewCacheEntry(entry);
  5110. }
  5111. };
  5112. Tools._FormatMessage = function (message) {
  5113. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5114. var date = new Date();
  5115. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5116. };
  5117. Tools._LogDisabled = function (message) {
  5118. // nothing to do
  5119. };
  5120. Tools._LogEnabled = function (message) {
  5121. var formattedMessage = Tools._FormatMessage(message);
  5122. console.log("BJS - " + formattedMessage);
  5123. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5124. Tools._AddLogEntry(entry);
  5125. };
  5126. Tools._WarnDisabled = function (message) {
  5127. // nothing to do
  5128. };
  5129. Tools._WarnEnabled = function (message) {
  5130. var formattedMessage = Tools._FormatMessage(message);
  5131. console.warn("BJS - " + formattedMessage);
  5132. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5133. Tools._AddLogEntry(entry);
  5134. };
  5135. Tools._ErrorDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._ErrorEnabled = function (message) {
  5139. Tools.errorsCount++;
  5140. var formattedMessage = Tools._FormatMessage(message);
  5141. console.error("BJS - " + formattedMessage);
  5142. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5143. Tools._AddLogEntry(entry);
  5144. };
  5145. Object.defineProperty(Tools, "LogCache", {
  5146. get: function () {
  5147. return Tools._LogCache;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Tools.ClearLogCache = function () {
  5153. Tools._LogCache = "";
  5154. Tools.errorsCount = 0;
  5155. };
  5156. Object.defineProperty(Tools, "LogLevels", {
  5157. set: function (level) {
  5158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5159. Tools.Log = Tools._LogEnabled;
  5160. }
  5161. else {
  5162. Tools.Log = Tools._LogDisabled;
  5163. }
  5164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5165. Tools.Warn = Tools._WarnEnabled;
  5166. }
  5167. else {
  5168. Tools.Warn = Tools._WarnDisabled;
  5169. }
  5170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5171. Tools.Error = Tools._ErrorEnabled;
  5172. }
  5173. else {
  5174. Tools.Error = Tools._ErrorDisabled;
  5175. }
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5181. get: function () {
  5182. return Tools._PerformanceNoneLogLevel;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5188. get: function () {
  5189. return Tools._PerformanceUserMarkLogLevel;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5195. get: function () {
  5196. return Tools._PerformanceConsoleLogLevel;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5202. set: function (level) {
  5203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5206. return;
  5207. }
  5208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5211. return;
  5212. }
  5213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5222. };
  5223. Tools._StartUserMark = function (counterName, condition) {
  5224. if (condition === void 0) { condition = true; }
  5225. if (!condition || !Tools._performance.mark) {
  5226. return;
  5227. }
  5228. Tools._performance.mark(counterName + "-Begin");
  5229. };
  5230. Tools._EndUserMark = function (counterName, condition) {
  5231. if (condition === void 0) { condition = true; }
  5232. if (!condition || !Tools._performance.mark) {
  5233. return;
  5234. }
  5235. Tools._performance.mark(counterName + "-End");
  5236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5237. };
  5238. Tools._StartPerformanceConsole = function (counterName, condition) {
  5239. if (condition === void 0) { condition = true; }
  5240. if (!condition) {
  5241. return;
  5242. }
  5243. Tools._StartUserMark(counterName, condition);
  5244. if (console.time) {
  5245. console.time(counterName);
  5246. }
  5247. };
  5248. Tools._EndPerformanceConsole = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition) {
  5251. return;
  5252. }
  5253. Tools._EndUserMark(counterName, condition);
  5254. if (console.time) {
  5255. console.timeEnd(counterName);
  5256. }
  5257. };
  5258. Object.defineProperty(Tools, "Now", {
  5259. get: function () {
  5260. if (window.performance && window.performance.now) {
  5261. return window.performance.now();
  5262. }
  5263. return new Date().getTime();
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. /**
  5269. * This method will return the name of the class used to create the instance of the given object.
  5270. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5271. * @param object the object to get the class name from
  5272. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5273. */
  5274. Tools.getClassName = function (object, isType) {
  5275. if (isType === void 0) { isType = false; }
  5276. var name = null;
  5277. if (!isType && object.getClassName) {
  5278. name = object.getClassName();
  5279. }
  5280. else {
  5281. if (object instanceof Object) {
  5282. var classObj = isType ? object : Object.getPrototypeOf(object);
  5283. name = classObj.constructor["__bjsclassName__"];
  5284. }
  5285. if (!name) {
  5286. name = typeof object;
  5287. }
  5288. }
  5289. return name;
  5290. };
  5291. Tools.first = function (array, predicate) {
  5292. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5293. var el = array_1[_i];
  5294. if (predicate(el)) {
  5295. return el;
  5296. }
  5297. }
  5298. };
  5299. /**
  5300. * 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.
  5301. * @param array
  5302. */
  5303. Tools.arrayOrStringFeeder = function (array) {
  5304. return function (index) {
  5305. if (index >= array.length) {
  5306. return null;
  5307. }
  5308. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5309. if (val && val.getHashCode) {
  5310. val = val.getHashCode();
  5311. }
  5312. if (typeof val === "string") {
  5313. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5314. }
  5315. return val;
  5316. };
  5317. };
  5318. /**
  5319. * Compute the hashCode of a stream of number
  5320. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5321. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5322. * @return the hash code computed
  5323. */
  5324. Tools.hashCodeFromStream = function (feeder) {
  5325. // Based from here: http://stackoverflow.com/a/7616484/802124
  5326. var hash = 0;
  5327. var index = 0;
  5328. var chr = feeder(index++);
  5329. while (chr != null) {
  5330. hash = ((hash << 5) - hash) + chr;
  5331. hash |= 0; // Convert to 32bit integer
  5332. chr = feeder(index++);
  5333. }
  5334. return hash;
  5335. };
  5336. Tools.BaseUrl = "";
  5337. Tools.CorsBehavior = "anonymous";
  5338. Tools.UseFallbackTexture = true;
  5339. // Logs
  5340. Tools._NoneLogLevel = 0;
  5341. Tools._MessageLogLevel = 1;
  5342. Tools._WarningLogLevel = 2;
  5343. Tools._ErrorLogLevel = 4;
  5344. Tools._LogCache = "";
  5345. Tools.errorsCount = 0;
  5346. Tools.Log = Tools._LogEnabled;
  5347. Tools.Warn = Tools._WarnEnabled;
  5348. Tools.Error = Tools._ErrorEnabled;
  5349. // Performances
  5350. Tools._PerformanceNoneLogLevel = 0;
  5351. Tools._PerformanceUserMarkLogLevel = 1;
  5352. Tools._PerformanceConsoleLogLevel = 2;
  5353. Tools._performance = window.performance;
  5354. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5355. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5356. return Tools;
  5357. }());
  5358. BABYLON.Tools = Tools;
  5359. /**
  5360. * This class is used to track a performance counter which is number based.
  5361. * The user has access to many properties which give statistics of different nature
  5362. *
  5363. * The implementer can track two kinds of Performance Counter: time and count
  5364. * 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.
  5365. * 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.
  5366. */
  5367. var PerfCounter = (function () {
  5368. function PerfCounter() {
  5369. this._startMonitoringTime = 0;
  5370. this._min = 0;
  5371. this._max = 0;
  5372. this._average = 0;
  5373. this._lastSecAverage = 0;
  5374. this._current = 0;
  5375. this._totalValueCount = 0;
  5376. this._totalAccumulated = 0;
  5377. this._lastSecAccumulated = 0;
  5378. this._lastSecTime = 0;
  5379. this._lastSecValueCount = 0;
  5380. }
  5381. Object.defineProperty(PerfCounter.prototype, "min", {
  5382. /**
  5383. * Returns the smallest value ever
  5384. */
  5385. get: function () {
  5386. return this._min;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(PerfCounter.prototype, "max", {
  5392. /**
  5393. * Returns the biggest value ever
  5394. */
  5395. get: function () {
  5396. return this._max;
  5397. },
  5398. enumerable: true,
  5399. configurable: true
  5400. });
  5401. Object.defineProperty(PerfCounter.prototype, "average", {
  5402. /**
  5403. * Returns the average value since the performance counter is running
  5404. */
  5405. get: function () {
  5406. return this._average;
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5412. /**
  5413. * Returns the average value of the last second the counter was monitored
  5414. */
  5415. get: function () {
  5416. return this._lastSecAverage;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(PerfCounter.prototype, "current", {
  5422. /**
  5423. * Returns the current value
  5424. */
  5425. get: function () {
  5426. return this._current;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(PerfCounter.prototype, "total", {
  5432. get: function () {
  5433. return this._totalAccumulated;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Call this method to start monitoring a new frame.
  5440. * 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.
  5441. */
  5442. PerfCounter.prototype.fetchNewFrame = function () {
  5443. this._totalValueCount++;
  5444. this._current = 0;
  5445. this._lastSecValueCount++;
  5446. };
  5447. /**
  5448. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5449. * @param newCount the count value to add to the monitored count
  5450. * @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.
  5451. */
  5452. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5453. this._current += newCount;
  5454. if (fetchResult) {
  5455. this._fetchResult();
  5456. }
  5457. };
  5458. /**
  5459. * Start monitoring this performance counter
  5460. */
  5461. PerfCounter.prototype.beginMonitoring = function () {
  5462. this._startMonitoringTime = Tools.Now;
  5463. };
  5464. /**
  5465. * Compute the time lapsed since the previous beginMonitoring() call.
  5466. * @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
  5467. */
  5468. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5469. if (newFrame === void 0) { newFrame = true; }
  5470. if (newFrame) {
  5471. this.fetchNewFrame();
  5472. }
  5473. var currentTime = Tools.Now;
  5474. this._current = currentTime - this._startMonitoringTime;
  5475. if (newFrame) {
  5476. this._fetchResult();
  5477. }
  5478. };
  5479. PerfCounter.prototype._fetchResult = function () {
  5480. this._totalAccumulated += this._current;
  5481. this._lastSecAccumulated += this._current;
  5482. // Min/Max update
  5483. this._min = Math.min(this._min, this._current);
  5484. this._max = Math.max(this._max, this._current);
  5485. this._average = this._totalAccumulated / this._totalValueCount;
  5486. // Reset last sec?
  5487. var now = Tools.Now;
  5488. if ((now - this._lastSecTime) > 1000) {
  5489. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5490. this._lastSecTime = now;
  5491. this._lastSecAccumulated = 0;
  5492. this._lastSecValueCount = 0;
  5493. }
  5494. };
  5495. return PerfCounter;
  5496. }());
  5497. BABYLON.PerfCounter = PerfCounter;
  5498. /**
  5499. * Use this className as a decorator on a given class definition to add it a name.
  5500. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5501. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5502. * @param name
  5503. */
  5504. function className(name) {
  5505. return function (target) {
  5506. target["__bjsclassName__"] = name;
  5507. };
  5508. }
  5509. BABYLON.className = className;
  5510. /**
  5511. * An implementation of a loop for asynchronous functions.
  5512. */
  5513. var AsyncLoop = (function () {
  5514. /**
  5515. * Constroctor.
  5516. * @param iterations the number of iterations.
  5517. * @param _fn the function to run each iteration
  5518. * @param _successCallback the callback that will be called upon succesful execution
  5519. * @param offset starting offset.
  5520. */
  5521. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5522. if (offset === void 0) { offset = 0; }
  5523. this.iterations = iterations;
  5524. this._fn = _fn;
  5525. this._successCallback = _successCallback;
  5526. this.index = offset - 1;
  5527. this._done = false;
  5528. }
  5529. /**
  5530. * Execute the next iteration. Must be called after the last iteration was finished.
  5531. */
  5532. AsyncLoop.prototype.executeNext = function () {
  5533. if (!this._done) {
  5534. if (this.index + 1 < this.iterations) {
  5535. ++this.index;
  5536. this._fn(this);
  5537. }
  5538. else {
  5539. this.breakLoop();
  5540. }
  5541. }
  5542. };
  5543. /**
  5544. * Break the loop and run the success callback.
  5545. */
  5546. AsyncLoop.prototype.breakLoop = function () {
  5547. this._done = true;
  5548. this._successCallback();
  5549. };
  5550. /**
  5551. * Helper function
  5552. */
  5553. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5554. if (offset === void 0) { offset = 0; }
  5555. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5556. loop.executeNext();
  5557. return loop;
  5558. };
  5559. /**
  5560. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5561. * @param iterations total number of iterations
  5562. * @param syncedIterations number of synchronous iterations in each async iteration.
  5563. * @param fn the function to call each iteration.
  5564. * @param callback a success call back that will be called when iterating stops.
  5565. * @param breakFunction a break condition (optional)
  5566. * @param timeout timeout settings for the setTimeout function. default - 0.
  5567. * @constructor
  5568. */
  5569. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5570. if (timeout === void 0) { timeout = 0; }
  5571. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5572. if (breakFunction && breakFunction())
  5573. loop.breakLoop();
  5574. else {
  5575. setTimeout(function () {
  5576. for (var i = 0; i < syncedIterations; ++i) {
  5577. var iteration = (loop.index * syncedIterations) + i;
  5578. if (iteration >= iterations)
  5579. break;
  5580. fn(iteration);
  5581. if (breakFunction && breakFunction()) {
  5582. loop.breakLoop();
  5583. break;
  5584. }
  5585. }
  5586. loop.executeNext();
  5587. }, timeout);
  5588. }
  5589. }, callback);
  5590. };
  5591. return AsyncLoop;
  5592. }());
  5593. BABYLON.AsyncLoop = AsyncLoop;
  5594. })(BABYLON || (BABYLON = {}));
  5595. var BABYLON;
  5596. (function (BABYLON) {
  5597. var Internals;
  5598. (function (Internals) {
  5599. var _AlphaState = (function () {
  5600. function _AlphaState() {
  5601. this._isAlphaBlendDirty = false;
  5602. this._isBlendFunctionParametersDirty = false;
  5603. this._alphaBlend = false;
  5604. this._blendFunctionParameters = new Array(4);
  5605. }
  5606. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5607. get: function () {
  5608. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5614. get: function () {
  5615. return this._alphaBlend;
  5616. },
  5617. set: function (value) {
  5618. if (this._alphaBlend === value) {
  5619. return;
  5620. }
  5621. this._alphaBlend = value;
  5622. this._isAlphaBlendDirty = true;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5628. if (this._blendFunctionParameters[0] === value0 &&
  5629. this._blendFunctionParameters[1] === value1 &&
  5630. this._blendFunctionParameters[2] === value2 &&
  5631. this._blendFunctionParameters[3] === value3) {
  5632. return;
  5633. }
  5634. this._blendFunctionParameters[0] = value0;
  5635. this._blendFunctionParameters[1] = value1;
  5636. this._blendFunctionParameters[2] = value2;
  5637. this._blendFunctionParameters[3] = value3;
  5638. this._isBlendFunctionParametersDirty = true;
  5639. };
  5640. _AlphaState.prototype.reset = function () {
  5641. this._alphaBlend = false;
  5642. this._blendFunctionParameters[0] = null;
  5643. this._blendFunctionParameters[1] = null;
  5644. this._blendFunctionParameters[2] = null;
  5645. this._blendFunctionParameters[3] = null;
  5646. this._isAlphaBlendDirty = true;
  5647. this._isBlendFunctionParametersDirty = false;
  5648. };
  5649. _AlphaState.prototype.apply = function (gl) {
  5650. if (!this.isDirty) {
  5651. return;
  5652. }
  5653. // Alpha blend
  5654. if (this._isAlphaBlendDirty) {
  5655. if (this._alphaBlend) {
  5656. gl.enable(gl.BLEND);
  5657. }
  5658. else {
  5659. gl.disable(gl.BLEND);
  5660. }
  5661. this._isAlphaBlendDirty = false;
  5662. }
  5663. // Alpha function
  5664. if (this._isBlendFunctionParametersDirty) {
  5665. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5666. this._isBlendFunctionParametersDirty = false;
  5667. }
  5668. };
  5669. return _AlphaState;
  5670. }());
  5671. Internals._AlphaState = _AlphaState;
  5672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5673. })(BABYLON || (BABYLON = {}));
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var Internals;
  5677. (function (Internals) {
  5678. var _DepthCullingState = (function () {
  5679. function _DepthCullingState() {
  5680. this._isDepthTestDirty = false;
  5681. this._isDepthMaskDirty = false;
  5682. this._isDepthFuncDirty = false;
  5683. this._isCullFaceDirty = false;
  5684. this._isCullDirty = false;
  5685. this._isZOffsetDirty = false;
  5686. }
  5687. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5688. get: function () {
  5689. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5695. get: function () {
  5696. return this._zOffset;
  5697. },
  5698. set: function (value) {
  5699. if (this._zOffset === value) {
  5700. return;
  5701. }
  5702. this._zOffset = value;
  5703. this._isZOffsetDirty = true;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5709. get: function () {
  5710. return this._cullFace;
  5711. },
  5712. set: function (value) {
  5713. if (this._cullFace === value) {
  5714. return;
  5715. }
  5716. this._cullFace = value;
  5717. this._isCullFaceDirty = true;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5723. get: function () {
  5724. return this._cull;
  5725. },
  5726. set: function (value) {
  5727. if (this._cull === value) {
  5728. return;
  5729. }
  5730. this._cull = value;
  5731. this._isCullDirty = true;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5737. get: function () {
  5738. return this._depthFunc;
  5739. },
  5740. set: function (value) {
  5741. if (this._depthFunc === value) {
  5742. return;
  5743. }
  5744. this._depthFunc = value;
  5745. this._isDepthFuncDirty = true;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5751. get: function () {
  5752. return this._depthMask;
  5753. },
  5754. set: function (value) {
  5755. if (this._depthMask === value) {
  5756. return;
  5757. }
  5758. this._depthMask = value;
  5759. this._isDepthMaskDirty = true;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5765. get: function () {
  5766. return this._depthTest;
  5767. },
  5768. set: function (value) {
  5769. if (this._depthTest === value) {
  5770. return;
  5771. }
  5772. this._depthTest = value;
  5773. this._isDepthTestDirty = true;
  5774. },
  5775. enumerable: true,
  5776. configurable: true
  5777. });
  5778. _DepthCullingState.prototype.reset = function () {
  5779. this._depthMask = true;
  5780. this._depthTest = true;
  5781. this._depthFunc = null;
  5782. this._cullFace = null;
  5783. this._cull = null;
  5784. this._zOffset = 0;
  5785. this._isDepthTestDirty = true;
  5786. this._isDepthMaskDirty = true;
  5787. this._isDepthFuncDirty = false;
  5788. this._isCullFaceDirty = false;
  5789. this._isCullDirty = false;
  5790. this._isZOffsetDirty = false;
  5791. };
  5792. _DepthCullingState.prototype.apply = function (gl) {
  5793. if (!this.isDirty) {
  5794. return;
  5795. }
  5796. // Cull
  5797. if (this._isCullDirty) {
  5798. if (this.cull) {
  5799. gl.enable(gl.CULL_FACE);
  5800. }
  5801. else {
  5802. gl.disable(gl.CULL_FACE);
  5803. }
  5804. this._isCullDirty = false;
  5805. }
  5806. // Cull face
  5807. if (this._isCullFaceDirty) {
  5808. gl.cullFace(this.cullFace);
  5809. this._isCullFaceDirty = false;
  5810. }
  5811. // Depth mask
  5812. if (this._isDepthMaskDirty) {
  5813. gl.depthMask(this.depthMask);
  5814. this._isDepthMaskDirty = false;
  5815. }
  5816. // Depth test
  5817. if (this._isDepthTestDirty) {
  5818. if (this.depthTest) {
  5819. gl.enable(gl.DEPTH_TEST);
  5820. }
  5821. else {
  5822. gl.disable(gl.DEPTH_TEST);
  5823. }
  5824. this._isDepthTestDirty = false;
  5825. }
  5826. // Depth func
  5827. if (this._isDepthFuncDirty) {
  5828. gl.depthFunc(this.depthFunc);
  5829. this._isDepthFuncDirty = false;
  5830. }
  5831. // zOffset
  5832. if (this._isZOffsetDirty) {
  5833. if (this.zOffset) {
  5834. gl.enable(gl.POLYGON_OFFSET_FILL);
  5835. gl.polygonOffset(this.zOffset, 0);
  5836. }
  5837. else {
  5838. gl.disable(gl.POLYGON_OFFSET_FILL);
  5839. }
  5840. this._isZOffsetDirty = false;
  5841. }
  5842. };
  5843. return _DepthCullingState;
  5844. }());
  5845. Internals._DepthCullingState = _DepthCullingState;
  5846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5847. })(BABYLON || (BABYLON = {}));
  5848. var BABYLON;
  5849. (function (BABYLON) {
  5850. var compileShader = function (gl, source, type, defines) {
  5851. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5852. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5853. gl.compileShader(shader);
  5854. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5855. throw new Error(gl.getShaderInfoLog(shader));
  5856. }
  5857. return shader;
  5858. };
  5859. var HALF_FLOAT_OES = 0x8D61;
  5860. var getWebGLTextureType = function (gl, type) {
  5861. if (type === Engine.TEXTURETYPE_FLOAT) {
  5862. return gl.FLOAT;
  5863. }
  5864. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5865. // Add Half Float Constant.
  5866. return HALF_FLOAT_OES;
  5867. }
  5868. return gl.UNSIGNED_BYTE;
  5869. };
  5870. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5871. var magFilter = gl.NEAREST;
  5872. var minFilter = gl.NEAREST;
  5873. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5874. magFilter = gl.LINEAR;
  5875. if (generateMipMaps) {
  5876. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5877. }
  5878. else {
  5879. minFilter = gl.LINEAR;
  5880. }
  5881. }
  5882. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5883. magFilter = gl.LINEAR;
  5884. if (generateMipMaps) {
  5885. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5886. }
  5887. else {
  5888. minFilter = gl.LINEAR;
  5889. }
  5890. }
  5891. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5892. magFilter = gl.NEAREST;
  5893. if (generateMipMaps) {
  5894. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5895. }
  5896. else {
  5897. minFilter = gl.NEAREST;
  5898. }
  5899. }
  5900. return {
  5901. min: minFilter,
  5902. mag: magFilter
  5903. };
  5904. };
  5905. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5907. var engine = scene.getEngine();
  5908. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5909. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5910. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5912. texture._baseWidth = width;
  5913. texture._baseHeight = height;
  5914. texture._width = potWidth;
  5915. texture._height = potHeight;
  5916. texture.isReady = true;
  5917. processFunction(potWidth, potHeight);
  5918. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5921. if (!noMipmap && !isCompressed) {
  5922. gl.generateMipmap(gl.TEXTURE_2D);
  5923. }
  5924. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5925. engine.resetTextureCache();
  5926. scene._removePendingData(texture);
  5927. if (onLoad) {
  5928. onLoad();
  5929. }
  5930. };
  5931. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5932. var img;
  5933. var onload = function () {
  5934. loadedImages[index] = img;
  5935. loadedImages._internalCount++;
  5936. scene._removePendingData(img);
  5937. if (loadedImages._internalCount === 6) {
  5938. onfinish(loadedImages);
  5939. }
  5940. };
  5941. var onerror = function () {
  5942. scene._removePendingData(img);
  5943. };
  5944. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5945. scene._addPendingData(img);
  5946. };
  5947. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5948. var loadedImages = [];
  5949. loadedImages._internalCount = 0;
  5950. for (var index = 0; index < 6; index++) {
  5951. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5952. }
  5953. };
  5954. var InstancingAttributeInfo = (function () {
  5955. function InstancingAttributeInfo() {
  5956. }
  5957. return InstancingAttributeInfo;
  5958. }());
  5959. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5960. var EngineCapabilities = (function () {
  5961. function EngineCapabilities() {
  5962. }
  5963. return EngineCapabilities;
  5964. }());
  5965. BABYLON.EngineCapabilities = EngineCapabilities;
  5966. /**
  5967. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5968. */
  5969. var Engine = (function () {
  5970. /**
  5971. * @constructor
  5972. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5973. * @param {boolean} [antialias] - enable antialias
  5974. * @param options - further options to be sent to the getContext function
  5975. */
  5976. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5977. var _this = this;
  5978. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5979. // Public members
  5980. this.isFullscreen = false;
  5981. this.isPointerLock = false;
  5982. this.cullBackFaces = true;
  5983. this.renderEvenInBackground = true;
  5984. // To enable/disable IDB support and avoid XHR on .manifest
  5985. this.enableOfflineSupport = true;
  5986. this.scenes = new Array();
  5987. this._windowIsBackground = false;
  5988. this._webGLVersion = "1.0";
  5989. this._drawCalls = new BABYLON.PerfCounter();
  5990. this._renderingQueueLaunched = false;
  5991. this._activeRenderLoops = [];
  5992. // FPS
  5993. this.fpsRange = 60;
  5994. this.previousFramesDuration = [];
  5995. this.fps = 60;
  5996. this.deltaTime = 0;
  5997. // States
  5998. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5999. this._alphaState = new BABYLON.Internals._AlphaState();
  6000. this._alphaMode = Engine.ALPHA_DISABLE;
  6001. // Cache
  6002. this._loadedTexturesCache = new Array();
  6003. this._maxTextureChannels = 16;
  6004. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6005. this._compiledEffects = {};
  6006. this._uintIndicesCurrentlySet = false;
  6007. this._currentBoundBuffer = new Array();
  6008. this._currentBufferPointers = [];
  6009. this._currentInstanceLocations = new Array();
  6010. this._currentInstanceBuffers = new Array();
  6011. this._renderingCanvas = canvas;
  6012. this._externalData = new BABYLON.StringDictionary();
  6013. options = options || {};
  6014. options.antialias = antialias;
  6015. if (options.preserveDrawingBuffer === undefined) {
  6016. options.preserveDrawingBuffer = false;
  6017. }
  6018. // GL
  6019. //try {
  6020. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6021. // if (this._gl) {
  6022. // this._webGLVersion = "2.0";
  6023. // }
  6024. //} catch (e) {
  6025. // // Do nothing
  6026. //}
  6027. if (!this._gl) {
  6028. try {
  6029. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6030. }
  6031. catch (e) {
  6032. throw new Error("WebGL not supported");
  6033. }
  6034. }
  6035. if (!this._gl) {
  6036. throw new Error("WebGL not supported");
  6037. }
  6038. this._onBlur = function () {
  6039. _this._windowIsBackground = true;
  6040. };
  6041. this._onFocus = function () {
  6042. _this._windowIsBackground = false;
  6043. };
  6044. window.addEventListener("blur", this._onBlur);
  6045. window.addEventListener("focus", this._onFocus);
  6046. // Viewport
  6047. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6048. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6049. this.resize();
  6050. // Caps
  6051. this._caps = new EngineCapabilities();
  6052. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6053. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6054. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6055. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6056. // Infos
  6057. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6058. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6059. if (rendererInfo != null) {
  6060. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6061. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6062. }
  6063. if (!this._glVendor) {
  6064. this._glVendor = "Unknown vendor";
  6065. }
  6066. if (!this._glRenderer) {
  6067. this._glRenderer = "Unknown renderer";
  6068. }
  6069. // Extensions
  6070. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6071. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6072. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6073. 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');
  6074. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6075. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6076. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6077. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6078. this._caps.highPrecisionShaderSupported = true;
  6079. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6080. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6081. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6082. this._caps.textureFloatRender = this._canRenderToFloatTexture();
  6083. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6084. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6085. this._caps.textureHalfFloatRender = this._canRenderToHalfFloatTexture();
  6086. if (this._gl.getShaderPrecisionFormat) {
  6087. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6088. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6089. }
  6090. // Depth buffer
  6091. this.setDepthBuffer(true);
  6092. this.setDepthFunctionToLessOrEqual();
  6093. this.setDepthWrite(true);
  6094. // Fullscreen
  6095. this._onFullscreenChange = function () {
  6096. if (document.fullscreen !== undefined) {
  6097. _this.isFullscreen = document.fullscreen;
  6098. }
  6099. else if (document.mozFullScreen !== undefined) {
  6100. _this.isFullscreen = document.mozFullScreen;
  6101. }
  6102. else if (document.webkitIsFullScreen !== undefined) {
  6103. _this.isFullscreen = document.webkitIsFullScreen;
  6104. }
  6105. else if (document.msIsFullScreen !== undefined) {
  6106. _this.isFullscreen = document.msIsFullScreen;
  6107. }
  6108. // Pointer lock
  6109. if (_this.isFullscreen && _this._pointerLockRequested) {
  6110. canvas.requestPointerLock = canvas.requestPointerLock ||
  6111. canvas.msRequestPointerLock ||
  6112. canvas.mozRequestPointerLock ||
  6113. canvas.webkitRequestPointerLock;
  6114. if (canvas.requestPointerLock) {
  6115. canvas.requestPointerLock();
  6116. }
  6117. }
  6118. };
  6119. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6120. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6121. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6122. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6123. // Pointer lock
  6124. this._onPointerLockChange = function () {
  6125. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6126. document.webkitPointerLockElement === canvas ||
  6127. document.msPointerLockElement === canvas ||
  6128. document.pointerLockElement === canvas);
  6129. };
  6130. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6131. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6132. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6133. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6134. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6135. Engine.audioEngine = new BABYLON.AudioEngine();
  6136. }
  6137. //default loading screen
  6138. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6139. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6140. }
  6141. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6142. get: function () {
  6143. return Engine._ALPHA_DISABLE;
  6144. },
  6145. enumerable: true,
  6146. configurable: true
  6147. });
  6148. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6149. get: function () {
  6150. return Engine._ALPHA_ONEONE;
  6151. },
  6152. enumerable: true,
  6153. configurable: true
  6154. });
  6155. Object.defineProperty(Engine, "ALPHA_ADD", {
  6156. get: function () {
  6157. return Engine._ALPHA_ADD;
  6158. },
  6159. enumerable: true,
  6160. configurable: true
  6161. });
  6162. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6163. get: function () {
  6164. return Engine._ALPHA_COMBINE;
  6165. },
  6166. enumerable: true,
  6167. configurable: true
  6168. });
  6169. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6170. get: function () {
  6171. return Engine._ALPHA_SUBTRACT;
  6172. },
  6173. enumerable: true,
  6174. configurable: true
  6175. });
  6176. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6177. get: function () {
  6178. return Engine._ALPHA_MULTIPLY;
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6184. get: function () {
  6185. return Engine._ALPHA_MAXIMIZED;
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6191. get: function () {
  6192. return Engine._DELAYLOADSTATE_NONE;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6198. get: function () {
  6199. return Engine._DELAYLOADSTATE_LOADED;
  6200. },
  6201. enumerable: true,
  6202. configurable: true
  6203. });
  6204. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6205. get: function () {
  6206. return Engine._DELAYLOADSTATE_LOADING;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6212. get: function () {
  6213. return Engine._DELAYLOADSTATE_NOTLOADED;
  6214. },
  6215. enumerable: true,
  6216. configurable: true
  6217. });
  6218. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6219. get: function () {
  6220. return Engine._TEXTUREFORMAT_ALPHA;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6226. get: function () {
  6227. return Engine._TEXTUREFORMAT_LUMINANCE;
  6228. },
  6229. enumerable: true,
  6230. configurable: true
  6231. });
  6232. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6233. get: function () {
  6234. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6240. get: function () {
  6241. return Engine._TEXTUREFORMAT_RGB;
  6242. },
  6243. enumerable: true,
  6244. configurable: true
  6245. });
  6246. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6247. get: function () {
  6248. return Engine._TEXTUREFORMAT_RGBA;
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6254. get: function () {
  6255. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6256. },
  6257. enumerable: true,
  6258. configurable: true
  6259. });
  6260. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6261. get: function () {
  6262. return Engine._TEXTURETYPE_FLOAT;
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6268. get: function () {
  6269. return Engine._TEXTURETYPE_HALF_FLOAT;
  6270. },
  6271. enumerable: true,
  6272. configurable: true
  6273. });
  6274. Object.defineProperty(Engine, "Version", {
  6275. get: function () {
  6276. return "2.5-alpha";
  6277. },
  6278. enumerable: true,
  6279. configurable: true
  6280. });
  6281. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6282. get: function () {
  6283. return this._webGLVersion;
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Engine.prototype._prepareWorkingCanvas = function () {
  6289. if (this._workingCanvas) {
  6290. return;
  6291. }
  6292. this._workingCanvas = document.createElement("canvas");
  6293. this._workingContext = this._workingCanvas.getContext("2d");
  6294. };
  6295. Engine.prototype.resetTextureCache = function () {
  6296. for (var index = 0; index < this._maxTextureChannels; index++) {
  6297. this._activeTexturesCache[index] = null;
  6298. }
  6299. };
  6300. Engine.prototype.getGlInfo = function () {
  6301. return {
  6302. vendor: this._glVendor,
  6303. renderer: this._glRenderer,
  6304. version: this._glVersion
  6305. };
  6306. };
  6307. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6308. if (useScreen === void 0) { useScreen = false; }
  6309. var viewport = camera.viewport;
  6310. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6311. };
  6312. Engine.prototype.getRenderWidth = function (useScreen) {
  6313. if (useScreen === void 0) { useScreen = false; }
  6314. if (!useScreen && this._currentRenderTarget) {
  6315. return this._currentRenderTarget._width;
  6316. }
  6317. return this._renderingCanvas.width;
  6318. };
  6319. Engine.prototype.getRenderHeight = function (useScreen) {
  6320. if (useScreen === void 0) { useScreen = false; }
  6321. if (!useScreen && this._currentRenderTarget) {
  6322. return this._currentRenderTarget._height;
  6323. }
  6324. return this._renderingCanvas.height;
  6325. };
  6326. Engine.prototype.getRenderingCanvas = function () {
  6327. return this._renderingCanvas;
  6328. };
  6329. Engine.prototype.getRenderingCanvasClientRect = function () {
  6330. return this._renderingCanvas.getBoundingClientRect();
  6331. };
  6332. Engine.prototype.setHardwareScalingLevel = function (level) {
  6333. this._hardwareScalingLevel = level;
  6334. this.resize();
  6335. };
  6336. Engine.prototype.getHardwareScalingLevel = function () {
  6337. return this._hardwareScalingLevel;
  6338. };
  6339. Engine.prototype.getLoadedTexturesCache = function () {
  6340. return this._loadedTexturesCache;
  6341. };
  6342. Engine.prototype.getCaps = function () {
  6343. return this._caps;
  6344. };
  6345. Object.defineProperty(Engine.prototype, "drawCalls", {
  6346. get: function () {
  6347. return this._drawCalls.current;
  6348. },
  6349. enumerable: true,
  6350. configurable: true
  6351. });
  6352. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6353. get: function () {
  6354. return this._drawCalls;
  6355. },
  6356. enumerable: true,
  6357. configurable: true
  6358. });
  6359. Engine.prototype.getDepthFunction = function () {
  6360. return this._depthCullingState.depthFunc;
  6361. };
  6362. Engine.prototype.setDepthFunction = function (depthFunc) {
  6363. this._depthCullingState.depthFunc = depthFunc;
  6364. };
  6365. Engine.prototype.setDepthFunctionToGreater = function () {
  6366. this._depthCullingState.depthFunc = this._gl.GREATER;
  6367. };
  6368. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6369. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6370. };
  6371. Engine.prototype.setDepthFunctionToLess = function () {
  6372. this._depthCullingState.depthFunc = this._gl.LESS;
  6373. };
  6374. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6375. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6376. };
  6377. /**
  6378. * stop executing a render loop function and remove it from the execution array
  6379. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6380. */
  6381. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6382. if (!renderFunction) {
  6383. this._activeRenderLoops = [];
  6384. return;
  6385. }
  6386. var index = this._activeRenderLoops.indexOf(renderFunction);
  6387. if (index >= 0) {
  6388. this._activeRenderLoops.splice(index, 1);
  6389. }
  6390. };
  6391. Engine.prototype._renderLoop = function () {
  6392. var shouldRender = true;
  6393. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6394. shouldRender = false;
  6395. }
  6396. if (shouldRender) {
  6397. // Start new frame
  6398. this.beginFrame();
  6399. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6400. var renderFunction = this._activeRenderLoops[index];
  6401. renderFunction();
  6402. }
  6403. // Present
  6404. this.endFrame();
  6405. }
  6406. if (this._activeRenderLoops.length > 0) {
  6407. // Register new frame
  6408. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6409. }
  6410. else {
  6411. this._renderingQueueLaunched = false;
  6412. }
  6413. };
  6414. /**
  6415. * Register and execute a render loop. The engine can have more than one render function.
  6416. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6417. * @example
  6418. * engine.runRenderLoop(function () {
  6419. * scene.render()
  6420. * })
  6421. */
  6422. Engine.prototype.runRenderLoop = function (renderFunction) {
  6423. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6424. return;
  6425. }
  6426. this._activeRenderLoops.push(renderFunction);
  6427. if (!this._renderingQueueLaunched) {
  6428. this._renderingQueueLaunched = true;
  6429. this._bindedRenderFunction = this._renderLoop.bind(this);
  6430. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6431. }
  6432. };
  6433. /**
  6434. * Toggle full screen mode.
  6435. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6436. * @param {any} options - an options object to be sent to the requestFullscreen function
  6437. */
  6438. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6439. if (this.isFullscreen) {
  6440. BABYLON.Tools.ExitFullscreen();
  6441. }
  6442. else {
  6443. this._pointerLockRequested = requestPointerLock;
  6444. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6445. }
  6446. };
  6447. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6448. this.applyStates();
  6449. if (backBuffer) {
  6450. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6451. }
  6452. if (depthStencil && this._depthCullingState.depthMask) {
  6453. this._gl.clearDepth(1.0);
  6454. }
  6455. var mode = 0;
  6456. if (backBuffer) {
  6457. mode |= this._gl.COLOR_BUFFER_BIT;
  6458. }
  6459. if (depthStencil && this._depthCullingState.depthMask) {
  6460. mode |= this._gl.DEPTH_BUFFER_BIT;
  6461. }
  6462. this._gl.clear(mode);
  6463. };
  6464. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6465. var gl = this._gl;
  6466. // Save state
  6467. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6468. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6469. // Change state
  6470. gl.enable(gl.SCISSOR_TEST);
  6471. gl.scissor(x, y, width, height);
  6472. // Clear
  6473. this.clear(clearColor, true, true);
  6474. // Restore state
  6475. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6476. if (curScissor === true) {
  6477. gl.enable(gl.SCISSOR_TEST);
  6478. }
  6479. else {
  6480. gl.disable(gl.SCISSOR_TEST);
  6481. }
  6482. };
  6483. /**
  6484. * Set the WebGL's viewport
  6485. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6486. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6487. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6488. */
  6489. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6490. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6491. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6492. var x = viewport.x || 0;
  6493. var y = viewport.y || 0;
  6494. this._cachedViewport = viewport;
  6495. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6496. };
  6497. /**
  6498. * Directly set the WebGL Viewport
  6499. * The x, y, width & height are directly passed to the WebGL call
  6500. * @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.
  6501. */
  6502. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6503. var currentViewport = this._cachedViewport;
  6504. this._cachedViewport = null;
  6505. this._gl.viewport(x, y, width, height);
  6506. return currentViewport;
  6507. };
  6508. Engine.prototype.beginFrame = function () {
  6509. this._measureFps();
  6510. };
  6511. Engine.prototype.endFrame = function () {
  6512. //this.flushFramebuffer();
  6513. };
  6514. /**
  6515. * resize the view according to the canvas' size.
  6516. * @example
  6517. * window.addEventListener("resize", function () {
  6518. * engine.resize();
  6519. * });
  6520. */
  6521. Engine.prototype.resize = function () {
  6522. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6523. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6524. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6525. for (var index = 0; index < this.scenes.length; index++) {
  6526. var scene = this.scenes[index];
  6527. if (scene.debugLayer.isVisible()) {
  6528. scene.debugLayer._syncPositions();
  6529. }
  6530. }
  6531. };
  6532. /**
  6533. * force a specific size of the canvas
  6534. * @param {number} width - the new canvas' width
  6535. * @param {number} height - the new canvas' height
  6536. */
  6537. Engine.prototype.setSize = function (width, height) {
  6538. this._renderingCanvas.width = width;
  6539. this._renderingCanvas.height = height;
  6540. for (var index = 0; index < this.scenes.length; index++) {
  6541. var scene = this.scenes[index];
  6542. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6543. var cam = scene.cameras[camIndex];
  6544. cam._currentRenderId = 0;
  6545. }
  6546. }
  6547. };
  6548. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6549. this._currentRenderTarget = texture;
  6550. var gl = this._gl;
  6551. this.bindUnboundFramebuffer(texture._framebuffer);
  6552. if (texture.isCube) {
  6553. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6554. }
  6555. else {
  6556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6557. }
  6558. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6559. this.wipeCaches();
  6560. };
  6561. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6562. if (this._currentFramebuffer !== framebuffer) {
  6563. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6564. this._currentFramebuffer = framebuffer;
  6565. }
  6566. };
  6567. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6568. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6569. this._currentRenderTarget = null;
  6570. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6571. var gl = this._gl;
  6572. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6573. gl.generateMipmap(gl.TEXTURE_2D);
  6574. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6575. }
  6576. this.bindUnboundFramebuffer(null);
  6577. };
  6578. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6579. if (texture.generateMipMaps) {
  6580. var gl = this._gl;
  6581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6582. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6583. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6584. }
  6585. };
  6586. Engine.prototype.flushFramebuffer = function () {
  6587. this._gl.flush();
  6588. };
  6589. Engine.prototype.restoreDefaultFramebuffer = function () {
  6590. this._currentRenderTarget = null;
  6591. this.bindUnboundFramebuffer(null);
  6592. this.setViewport(this._cachedViewport);
  6593. this.wipeCaches();
  6594. };
  6595. // VBOs
  6596. Engine.prototype._resetVertexBufferBinding = function () {
  6597. this.bindArrayBuffer(null);
  6598. this._cachedVertexBuffers = null;
  6599. };
  6600. Engine.prototype.createVertexBuffer = function (vertices) {
  6601. var vbo = this._gl.createBuffer();
  6602. this.bindArrayBuffer(vbo);
  6603. if (vertices instanceof Float32Array) {
  6604. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6605. }
  6606. else {
  6607. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6608. }
  6609. this._resetVertexBufferBinding();
  6610. vbo.references = 1;
  6611. return vbo;
  6612. };
  6613. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6614. var vbo = this._gl.createBuffer();
  6615. this.bindArrayBuffer(vbo);
  6616. if (vertices instanceof Float32Array) {
  6617. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6618. }
  6619. else {
  6620. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6621. }
  6622. this._resetVertexBufferBinding();
  6623. vbo.references = 1;
  6624. return vbo;
  6625. };
  6626. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6627. this.bindArrayBuffer(vertexBuffer);
  6628. if (offset === undefined) {
  6629. offset = 0;
  6630. }
  6631. if (count === undefined) {
  6632. if (vertices instanceof Float32Array) {
  6633. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6634. }
  6635. else {
  6636. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6637. }
  6638. }
  6639. else {
  6640. if (vertices instanceof Float32Array) {
  6641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6642. }
  6643. else {
  6644. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6645. }
  6646. }
  6647. this._resetVertexBufferBinding();
  6648. };
  6649. Engine.prototype._resetIndexBufferBinding = function () {
  6650. this.bindIndexBuffer(null);
  6651. this._cachedIndexBuffer = null;
  6652. };
  6653. Engine.prototype.createIndexBuffer = function (indices) {
  6654. var vbo = this._gl.createBuffer();
  6655. this.bindIndexBuffer(vbo);
  6656. // Check for 32 bits indices
  6657. var arrayBuffer;
  6658. var need32Bits = false;
  6659. if (this._caps.uintIndices) {
  6660. for (var index = 0; index < indices.length; index++) {
  6661. if (indices[index] > 65535) {
  6662. need32Bits = true;
  6663. break;
  6664. }
  6665. }
  6666. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6667. }
  6668. else {
  6669. arrayBuffer = new Uint16Array(indices);
  6670. }
  6671. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6672. this._resetIndexBufferBinding();
  6673. vbo.references = 1;
  6674. vbo.is32Bits = need32Bits;
  6675. return vbo;
  6676. };
  6677. Engine.prototype.bindArrayBuffer = function (buffer) {
  6678. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6679. };
  6680. Engine.prototype.bindIndexBuffer = function (buffer) {
  6681. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6682. };
  6683. Engine.prototype.bindBuffer = function (buffer, target) {
  6684. if (this._currentBoundBuffer[target] !== buffer) {
  6685. this._gl.bindBuffer(target, buffer);
  6686. this._currentBoundBuffer[target] = buffer;
  6687. }
  6688. };
  6689. Engine.prototype.updateArrayBuffer = function (data) {
  6690. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6691. };
  6692. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6693. var pointer = this._currentBufferPointers[indx];
  6694. var changed = false;
  6695. if (!pointer) {
  6696. changed = true;
  6697. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6698. }
  6699. else {
  6700. if (pointer.buffer !== buffer) {
  6701. pointer.buffer = buffer;
  6702. changed = true;
  6703. }
  6704. if (pointer.size !== size) {
  6705. pointer.size = size;
  6706. changed = true;
  6707. }
  6708. if (pointer.type !== type) {
  6709. pointer.type = type;
  6710. changed = true;
  6711. }
  6712. if (pointer.normalized !== normalized) {
  6713. pointer.normalized = normalized;
  6714. changed = true;
  6715. }
  6716. if (pointer.stride !== stride) {
  6717. pointer.stride = stride;
  6718. changed = true;
  6719. }
  6720. if (pointer.offset !== offset) {
  6721. pointer.offset = offset;
  6722. changed = true;
  6723. }
  6724. }
  6725. if (changed) {
  6726. this.bindArrayBuffer(buffer);
  6727. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6728. }
  6729. };
  6730. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6731. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6732. this._cachedVertexBuffers = vertexBuffer;
  6733. this._cachedEffectForVertexBuffers = effect;
  6734. var offset = 0;
  6735. for (var index = 0; index < vertexDeclaration.length; index++) {
  6736. var order = effect.getAttributeLocation(index);
  6737. if (order >= 0) {
  6738. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6739. }
  6740. offset += vertexDeclaration[index] * 4;
  6741. }
  6742. }
  6743. if (this._cachedIndexBuffer !== indexBuffer) {
  6744. this._cachedIndexBuffer = indexBuffer;
  6745. this.bindIndexBuffer(indexBuffer);
  6746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6747. }
  6748. };
  6749. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6750. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6751. this._cachedVertexBuffers = vertexBuffers;
  6752. this._cachedEffectForVertexBuffers = effect;
  6753. var attributes = effect.getAttributesNames();
  6754. for (var index = 0; index < attributes.length; index++) {
  6755. var order = effect.getAttributeLocation(index);
  6756. if (order >= 0) {
  6757. var vertexBuffer = vertexBuffers[attributes[index]];
  6758. if (!vertexBuffer) {
  6759. continue;
  6760. }
  6761. var buffer = vertexBuffer.getBuffer();
  6762. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6763. if (vertexBuffer.getIsInstanced()) {
  6764. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6765. this._currentInstanceLocations.push(order);
  6766. this._currentInstanceBuffers.push(buffer);
  6767. }
  6768. }
  6769. }
  6770. }
  6771. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6772. this._cachedIndexBuffer = indexBuffer;
  6773. this.bindIndexBuffer(indexBuffer);
  6774. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6775. }
  6776. };
  6777. Engine.prototype.unbindInstanceAttributes = function () {
  6778. var boundBuffer;
  6779. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6780. var instancesBuffer = this._currentInstanceBuffers[i];
  6781. if (boundBuffer != instancesBuffer) {
  6782. boundBuffer = instancesBuffer;
  6783. this.bindArrayBuffer(instancesBuffer);
  6784. }
  6785. var offsetLocation = this._currentInstanceLocations[i];
  6786. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6787. }
  6788. this._currentInstanceBuffers.length = 0;
  6789. this._currentInstanceLocations.length = 0;
  6790. };
  6791. Engine.prototype._releaseBuffer = function (buffer) {
  6792. buffer.references--;
  6793. if (buffer.references === 0) {
  6794. this._gl.deleteBuffer(buffer);
  6795. return true;
  6796. }
  6797. return false;
  6798. };
  6799. Engine.prototype.createInstancesBuffer = function (capacity) {
  6800. var buffer = this._gl.createBuffer();
  6801. buffer.capacity = capacity;
  6802. this.bindArrayBuffer(buffer);
  6803. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6804. return buffer;
  6805. };
  6806. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6807. this._gl.deleteBuffer(buffer);
  6808. };
  6809. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6810. this.bindArrayBuffer(instancesBuffer);
  6811. if (data) {
  6812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6813. }
  6814. if (offsetLocations[0].index !== undefined) {
  6815. var stride = 0;
  6816. for (var i = 0; i < offsetLocations.length; i++) {
  6817. var ai = offsetLocations[i];
  6818. stride += ai.attributeSize * 4;
  6819. }
  6820. for (var i = 0; i < offsetLocations.length; i++) {
  6821. var ai = offsetLocations[i];
  6822. this._gl.enableVertexAttribArray(ai.index);
  6823. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6824. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6825. this._currentInstanceLocations.push(ai.index);
  6826. this._currentInstanceBuffers.push(instancesBuffer);
  6827. }
  6828. }
  6829. else {
  6830. for (var index = 0; index < 4; index++) {
  6831. var offsetLocation = offsetLocations[index];
  6832. this._gl.enableVertexAttribArray(offsetLocation);
  6833. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6834. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6835. this._currentInstanceLocations.push(offsetLocation);
  6836. this._currentInstanceBuffers.push(instancesBuffer);
  6837. }
  6838. }
  6839. };
  6840. Engine.prototype.applyStates = function () {
  6841. this._depthCullingState.apply(this._gl);
  6842. this._alphaState.apply(this._gl);
  6843. };
  6844. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6845. // Apply states
  6846. this.applyStates();
  6847. this._drawCalls.addCount(1, false);
  6848. // Render
  6849. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6850. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6851. if (instancesCount) {
  6852. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6853. return;
  6854. }
  6855. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6856. };
  6857. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6858. // Apply states
  6859. this.applyStates();
  6860. this._drawCalls.addCount(1, false);
  6861. if (instancesCount) {
  6862. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6863. return;
  6864. }
  6865. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6866. };
  6867. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6868. // Apply states
  6869. this.applyStates();
  6870. this._drawCalls.addCount(1, false);
  6871. if (instancesCount) {
  6872. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6873. return;
  6874. }
  6875. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6876. };
  6877. // Shaders
  6878. Engine.prototype._releaseEffect = function (effect) {
  6879. if (this._compiledEffects[effect._key]) {
  6880. delete this._compiledEffects[effect._key];
  6881. if (effect.getProgram()) {
  6882. this._gl.deleteProgram(effect.getProgram());
  6883. }
  6884. }
  6885. };
  6886. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6887. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6888. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6889. var name = vertex + "+" + fragment + "@" + defines;
  6890. if (this._compiledEffects[name]) {
  6891. return this._compiledEffects[name];
  6892. }
  6893. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6894. effect._key = name;
  6895. this._compiledEffects[name] = effect;
  6896. return effect;
  6897. };
  6898. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6899. if (uniformsNames === void 0) { uniformsNames = []; }
  6900. if (samplers === void 0) { samplers = []; }
  6901. if (defines === void 0) { defines = ""; }
  6902. return this.createEffect({
  6903. vertex: "particles",
  6904. fragmentElement: fragmentName
  6905. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6906. };
  6907. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  6908. context = context || this._gl;
  6909. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  6910. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  6911. var shaderProgram = context.createProgram();
  6912. context.attachShader(shaderProgram, vertexShader);
  6913. context.attachShader(shaderProgram, fragmentShader);
  6914. context.linkProgram(shaderProgram);
  6915. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  6916. if (!linked) {
  6917. var error = context.getProgramInfoLog(shaderProgram);
  6918. if (error) {
  6919. throw new Error(error);
  6920. }
  6921. }
  6922. context.deleteShader(vertexShader);
  6923. context.deleteShader(fragmentShader);
  6924. return shaderProgram;
  6925. };
  6926. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6927. var results = [];
  6928. for (var index = 0; index < uniformsNames.length; index++) {
  6929. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6930. }
  6931. return results;
  6932. };
  6933. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6934. var results = [];
  6935. for (var index = 0; index < attributesNames.length; index++) {
  6936. try {
  6937. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6938. }
  6939. catch (e) {
  6940. results.push(-1);
  6941. }
  6942. }
  6943. return results;
  6944. };
  6945. Engine.prototype.enableEffect = function (effect) {
  6946. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6947. if (effect && effect.onBind) {
  6948. effect.onBind(effect);
  6949. }
  6950. return;
  6951. }
  6952. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6953. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6954. // Use program
  6955. this.setProgram(effect.getProgram());
  6956. var i, ul;
  6957. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6958. this._vertexAttribArraysToUse[i] = false;
  6959. }
  6960. var attributesCount = effect.getAttributesCount();
  6961. for (i = 0; i < attributesCount; i++) {
  6962. // Attributes
  6963. var order = effect.getAttributeLocation(i);
  6964. if (order >= 0) {
  6965. this._vertexAttribArraysToUse[order] = true;
  6966. }
  6967. }
  6968. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6969. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6970. continue;
  6971. }
  6972. this._vertexAttribArraysEnabled[i] = false;
  6973. this._gl.disableVertexAttribArray(i);
  6974. }
  6975. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6976. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6977. this._vertexAttribArraysEnabled[i] = true;
  6978. this._gl.enableVertexAttribArray(i);
  6979. }
  6980. }
  6981. this._currentEffect = effect;
  6982. if (effect.onBind) {
  6983. effect.onBind(effect);
  6984. }
  6985. };
  6986. Engine.prototype.setArray = function (uniform, array) {
  6987. if (!uniform)
  6988. return;
  6989. this._gl.uniform1fv(uniform, array);
  6990. };
  6991. Engine.prototype.setArray2 = function (uniform, array) {
  6992. if (!uniform || array.length % 2 !== 0)
  6993. return;
  6994. this._gl.uniform2fv(uniform, array);
  6995. };
  6996. Engine.prototype.setArray3 = function (uniform, array) {
  6997. if (!uniform || array.length % 3 !== 0)
  6998. return;
  6999. this._gl.uniform3fv(uniform, array);
  7000. };
  7001. Engine.prototype.setArray4 = function (uniform, array) {
  7002. if (!uniform || array.length % 4 !== 0)
  7003. return;
  7004. this._gl.uniform4fv(uniform, array);
  7005. };
  7006. Engine.prototype.setMatrices = function (uniform, matrices) {
  7007. if (!uniform)
  7008. return;
  7009. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7010. };
  7011. Engine.prototype.setMatrix = function (uniform, matrix) {
  7012. if (!uniform)
  7013. return;
  7014. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7015. };
  7016. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7017. if (!uniform)
  7018. return;
  7019. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7020. };
  7021. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7022. if (!uniform)
  7023. return;
  7024. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7025. };
  7026. Engine.prototype.setFloat = function (uniform, value) {
  7027. if (!uniform)
  7028. return;
  7029. this._gl.uniform1f(uniform, value);
  7030. };
  7031. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7032. if (!uniform)
  7033. return;
  7034. this._gl.uniform2f(uniform, x, y);
  7035. };
  7036. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7037. if (!uniform)
  7038. return;
  7039. this._gl.uniform3f(uniform, x, y, z);
  7040. };
  7041. Engine.prototype.setBool = function (uniform, bool) {
  7042. if (!uniform)
  7043. return;
  7044. this._gl.uniform1i(uniform, bool);
  7045. };
  7046. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7047. if (!uniform)
  7048. return;
  7049. this._gl.uniform4f(uniform, x, y, z, w);
  7050. };
  7051. Engine.prototype.setColor3 = function (uniform, color3) {
  7052. if (!uniform)
  7053. return;
  7054. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7055. };
  7056. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7057. if (!uniform)
  7058. return;
  7059. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7060. };
  7061. // States
  7062. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7063. if (zOffset === void 0) { zOffset = 0; }
  7064. if (reverseSide === void 0) { reverseSide = false; }
  7065. // Culling
  7066. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7067. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7068. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7069. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7070. if (culling) {
  7071. this._depthCullingState.cullFace = cullFace;
  7072. this._depthCullingState.cull = true;
  7073. }
  7074. else {
  7075. this._depthCullingState.cull = false;
  7076. }
  7077. }
  7078. // Z offset
  7079. this._depthCullingState.zOffset = zOffset;
  7080. };
  7081. Engine.prototype.setDepthBuffer = function (enable) {
  7082. this._depthCullingState.depthTest = enable;
  7083. };
  7084. Engine.prototype.getDepthWrite = function () {
  7085. return this._depthCullingState.depthMask;
  7086. };
  7087. Engine.prototype.setDepthWrite = function (enable) {
  7088. this._depthCullingState.depthMask = enable;
  7089. };
  7090. Engine.prototype.setColorWrite = function (enable) {
  7091. this._gl.colorMask(enable, enable, enable, enable);
  7092. };
  7093. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7094. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7095. if (this._alphaMode === mode) {
  7096. return;
  7097. }
  7098. switch (mode) {
  7099. case Engine.ALPHA_DISABLE:
  7100. this._alphaState.alphaBlend = false;
  7101. break;
  7102. case Engine.ALPHA_COMBINE:
  7103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7104. this._alphaState.alphaBlend = true;
  7105. break;
  7106. case Engine.ALPHA_ONEONE:
  7107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7108. this._alphaState.alphaBlend = true;
  7109. break;
  7110. case Engine.ALPHA_ADD:
  7111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7112. this._alphaState.alphaBlend = true;
  7113. break;
  7114. case Engine.ALPHA_SUBTRACT:
  7115. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7116. this._alphaState.alphaBlend = true;
  7117. break;
  7118. case Engine.ALPHA_MULTIPLY:
  7119. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7120. this._alphaState.alphaBlend = true;
  7121. break;
  7122. case Engine.ALPHA_MAXIMIZED:
  7123. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7124. this._alphaState.alphaBlend = true;
  7125. break;
  7126. }
  7127. if (!noDepthWriteChange) {
  7128. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7129. }
  7130. this._alphaMode = mode;
  7131. };
  7132. Engine.prototype.getAlphaMode = function () {
  7133. return this._alphaMode;
  7134. };
  7135. Engine.prototype.setAlphaTesting = function (enable) {
  7136. this._alphaTest = enable;
  7137. };
  7138. Engine.prototype.getAlphaTesting = function () {
  7139. return this._alphaTest;
  7140. };
  7141. // Textures
  7142. Engine.prototype.wipeCaches = function () {
  7143. this.resetTextureCache();
  7144. this._currentEffect = null;
  7145. this._depthCullingState.reset();
  7146. this.setDepthFunctionToLessOrEqual();
  7147. this._alphaState.reset();
  7148. this._cachedVertexBuffers = null;
  7149. this._cachedIndexBuffer = null;
  7150. this._cachedEffectForVertexBuffers = null;
  7151. };
  7152. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7153. var gl = this._gl;
  7154. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7155. var magFilter = gl.NEAREST;
  7156. var minFilter = gl.NEAREST;
  7157. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7158. magFilter = gl.LINEAR;
  7159. minFilter = gl.LINEAR;
  7160. }
  7161. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7162. magFilter = gl.LINEAR;
  7163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7164. }
  7165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7168. texture.samplingMode = samplingMode;
  7169. };
  7170. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7171. var _this = this;
  7172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7173. if (onLoad === void 0) { onLoad = null; }
  7174. if (onError === void 0) { onError = null; }
  7175. if (buffer === void 0) { buffer = null; }
  7176. var texture = this._gl.createTexture();
  7177. var extension;
  7178. var fromData = false;
  7179. if (url.substr(0, 5) === "data:") {
  7180. fromData = true;
  7181. }
  7182. if (!fromData)
  7183. extension = url.substr(url.length - 4, 4).toLowerCase();
  7184. else {
  7185. var oldUrl = url;
  7186. fromData = oldUrl.split(':');
  7187. url = oldUrl;
  7188. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7189. }
  7190. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7191. var isTGA = (extension === ".tga");
  7192. scene._addPendingData(texture);
  7193. texture.url = url;
  7194. texture.noMipmap = noMipmap;
  7195. texture.references = 1;
  7196. texture.samplingMode = samplingMode;
  7197. this._loadedTexturesCache.push(texture);
  7198. var onerror = function () {
  7199. scene._removePendingData(texture);
  7200. if (onError) {
  7201. onError();
  7202. }
  7203. };
  7204. var callback;
  7205. if (isTGA) {
  7206. callback = function (arrayBuffer) {
  7207. var data = new Uint8Array(arrayBuffer);
  7208. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7209. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7210. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7211. }, onLoad, samplingMode);
  7212. };
  7213. if (!(fromData instanceof Array))
  7214. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7215. callback(arrayBuffer);
  7216. }, onerror, scene.database, true);
  7217. else
  7218. callback(buffer);
  7219. }
  7220. else if (isDDS) {
  7221. callback = function (data) {
  7222. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7223. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7224. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7225. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7226. }, onLoad, samplingMode);
  7227. };
  7228. if (!(fromData instanceof Array))
  7229. BABYLON.Tools.LoadFile(url, function (data) {
  7230. callback(data);
  7231. }, onerror, scene.database, true);
  7232. else
  7233. callback(buffer);
  7234. }
  7235. else {
  7236. var onload = function (img) {
  7237. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7238. var isPot = (img.width === potWidth && img.height === potHeight);
  7239. if (!isPot) {
  7240. _this._prepareWorkingCanvas();
  7241. _this._workingCanvas.width = potWidth;
  7242. _this._workingCanvas.height = potHeight;
  7243. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7244. _this._workingContext.imageSmoothingEnabled = false;
  7245. _this._workingContext.mozImageSmoothingEnabled = false;
  7246. _this._workingContext.oImageSmoothingEnabled = false;
  7247. _this._workingContext.webkitImageSmoothingEnabled = false;
  7248. _this._workingContext.msImageSmoothingEnabled = false;
  7249. }
  7250. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7251. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7252. _this._workingContext.imageSmoothingEnabled = true;
  7253. _this._workingContext.mozImageSmoothingEnabled = true;
  7254. _this._workingContext.oImageSmoothingEnabled = true;
  7255. _this._workingContext.webkitImageSmoothingEnabled = true;
  7256. _this._workingContext.msImageSmoothingEnabled = true;
  7257. }
  7258. }
  7259. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7260. }, onLoad, samplingMode);
  7261. };
  7262. if (!(fromData instanceof Array))
  7263. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7264. else
  7265. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7266. }
  7267. return texture;
  7268. };
  7269. Engine.prototype._getInternalFormat = function (format) {
  7270. var internalFormat = this._gl.RGBA;
  7271. switch (format) {
  7272. case Engine.TEXTUREFORMAT_ALPHA:
  7273. internalFormat = this._gl.ALPHA;
  7274. break;
  7275. case Engine.TEXTUREFORMAT_LUMINANCE:
  7276. internalFormat = this._gl.LUMINANCE;
  7277. break;
  7278. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7279. internalFormat = this._gl.LUMINANCE_ALPHA;
  7280. break;
  7281. case Engine.TEXTUREFORMAT_RGB:
  7282. internalFormat = this._gl.RGB;
  7283. break;
  7284. case Engine.TEXTUREFORMAT_RGBA:
  7285. internalFormat = this._gl.RGBA;
  7286. break;
  7287. }
  7288. return internalFormat;
  7289. };
  7290. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7291. if (compression === void 0) { compression = null; }
  7292. var internalFormat = this._getInternalFormat(format);
  7293. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7294. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7295. if (texture._width % 4 !== 0) {
  7296. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7297. }
  7298. if (compression) {
  7299. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7300. }
  7301. else {
  7302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7303. }
  7304. if (texture.generateMipMaps) {
  7305. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7306. }
  7307. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7308. this.resetTextureCache();
  7309. texture.isReady = true;
  7310. };
  7311. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7312. if (compression === void 0) { compression = null; }
  7313. var texture = this._gl.createTexture();
  7314. texture._baseWidth = width;
  7315. texture._baseHeight = height;
  7316. texture._width = width;
  7317. texture._height = height;
  7318. texture.references = 1;
  7319. this.updateRawTexture(texture, data, format, invertY, compression);
  7320. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7321. // Filters
  7322. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7324. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7325. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7326. texture.samplingMode = samplingMode;
  7327. this._loadedTexturesCache.push(texture);
  7328. return texture;
  7329. };
  7330. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7331. var texture = this._gl.createTexture();
  7332. texture._baseWidth = width;
  7333. texture._baseHeight = height;
  7334. if (generateMipMaps) {
  7335. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7336. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7337. }
  7338. this.resetTextureCache();
  7339. texture._width = width;
  7340. texture._height = height;
  7341. texture.isReady = false;
  7342. texture.generateMipMaps = generateMipMaps;
  7343. texture.references = 1;
  7344. texture.samplingMode = samplingMode;
  7345. this.updateTextureSamplingMode(samplingMode, texture);
  7346. this._loadedTexturesCache.push(texture);
  7347. return texture;
  7348. };
  7349. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7350. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7351. if (texture.isCube) {
  7352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7353. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7354. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7356. }
  7357. else {
  7358. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7359. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7360. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7361. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7362. }
  7363. };
  7364. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7365. if (premulAlpha === void 0) { premulAlpha = false; }
  7366. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7367. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7368. if (premulAlpha) {
  7369. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7370. }
  7371. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7372. if (texture.generateMipMaps) {
  7373. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7374. }
  7375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7376. this.resetTextureCache();
  7377. texture.isReady = true;
  7378. };
  7379. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7380. if (texture._isDisabled) {
  7381. return;
  7382. }
  7383. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7385. try {
  7386. // Testing video texture support
  7387. if (this._videoTextureSupported === undefined) {
  7388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7389. if (this._gl.getError() !== 0) {
  7390. this._videoTextureSupported = false;
  7391. }
  7392. else {
  7393. this._videoTextureSupported = true;
  7394. }
  7395. }
  7396. // Copy video through the current working canvas if video texture is not supported
  7397. if (!this._videoTextureSupported) {
  7398. if (!texture._workingCanvas) {
  7399. texture._workingCanvas = document.createElement("canvas");
  7400. texture._workingContext = texture._workingCanvas.getContext("2d");
  7401. texture._workingCanvas.width = texture._width;
  7402. texture._workingCanvas.height = texture._height;
  7403. }
  7404. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7405. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7406. }
  7407. else {
  7408. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7409. }
  7410. if (texture.generateMipMaps) {
  7411. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7412. }
  7413. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7414. this.resetTextureCache();
  7415. texture.isReady = true;
  7416. }
  7417. catch (ex) {
  7418. // Something unexpected
  7419. // Let's disable the texture
  7420. texture._isDisabled = true;
  7421. }
  7422. };
  7423. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7424. // old version had a "generateMipMaps" arg instead of options.
  7425. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7426. // in the same way, generateDepthBuffer is defaulted to true
  7427. var generateMipMaps = false;
  7428. var generateDepthBuffer = true;
  7429. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7430. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7431. if (options !== undefined) {
  7432. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7433. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7434. type = options.type === undefined ? type : options.type;
  7435. if (options.samplingMode !== undefined) {
  7436. samplingMode = options.samplingMode;
  7437. }
  7438. if (type === BABYLON.Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7439. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7440. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7441. }
  7442. else if (type === BABYLON.Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7443. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7445. }
  7446. }
  7447. var gl = this._gl;
  7448. var texture = gl.createTexture();
  7449. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7450. var width = size.width || size;
  7451. var height = size.height || size;
  7452. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7453. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7454. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7455. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7456. }
  7457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7461. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7462. var depthBuffer;
  7463. // Create the depth buffer
  7464. if (generateDepthBuffer) {
  7465. depthBuffer = gl.createRenderbuffer();
  7466. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7467. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7468. }
  7469. // Create the framebuffer
  7470. var framebuffer = gl.createFramebuffer();
  7471. this.bindUnboundFramebuffer(framebuffer);
  7472. if (generateDepthBuffer) {
  7473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7474. }
  7475. if (generateMipMaps) {
  7476. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7477. }
  7478. // Unbind
  7479. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7481. this.bindUnboundFramebuffer(null);
  7482. texture._framebuffer = framebuffer;
  7483. if (generateDepthBuffer) {
  7484. texture._depthBuffer = depthBuffer;
  7485. }
  7486. texture._baseWidth = width;
  7487. texture._baseHeight = height;
  7488. texture._width = width;
  7489. texture._height = height;
  7490. texture.isReady = true;
  7491. texture.generateMipMaps = generateMipMaps;
  7492. texture.references = 1;
  7493. texture.samplingMode = samplingMode;
  7494. texture.type = type;
  7495. this.resetTextureCache();
  7496. this._loadedTexturesCache.push(texture);
  7497. return texture;
  7498. };
  7499. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7500. var gl = this._gl;
  7501. var texture = gl.createTexture();
  7502. var generateMipMaps = true;
  7503. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7504. if (options !== undefined) {
  7505. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7506. if (options.samplingMode !== undefined) {
  7507. samplingMode = options.samplingMode;
  7508. }
  7509. }
  7510. texture.isCube = true;
  7511. texture.references = 1;
  7512. texture.generateMipMaps = generateMipMaps;
  7513. texture.references = 1;
  7514. texture.samplingMode = samplingMode;
  7515. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7516. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7517. for (var face = 0; face < 6; face++) {
  7518. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7519. }
  7520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7524. // Create the depth buffer
  7525. var depthBuffer = gl.createRenderbuffer();
  7526. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7527. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7528. // Create the framebuffer
  7529. var framebuffer = gl.createFramebuffer();
  7530. this.bindUnboundFramebuffer(framebuffer);
  7531. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7532. // Mipmaps
  7533. if (texture.generateMipMaps) {
  7534. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7535. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7536. }
  7537. // Unbind
  7538. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7539. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7540. this.bindUnboundFramebuffer(null);
  7541. texture._framebuffer = framebuffer;
  7542. texture._depthBuffer = depthBuffer;
  7543. this.resetTextureCache();
  7544. texture._width = size;
  7545. texture._height = size;
  7546. texture.isReady = true;
  7547. return texture;
  7548. };
  7549. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7550. var _this = this;
  7551. var gl = this._gl;
  7552. var texture = gl.createTexture();
  7553. texture.isCube = true;
  7554. texture.url = rootUrl;
  7555. texture.references = 1;
  7556. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7557. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7558. if (isDDS) {
  7559. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7560. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7561. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7562. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7563. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7564. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7565. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7566. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7567. }
  7568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7573. _this.resetTextureCache();
  7574. texture._width = info.width;
  7575. texture._height = info.height;
  7576. texture.isReady = true;
  7577. }, null, null, true);
  7578. }
  7579. else {
  7580. cascadeLoad(rootUrl, scene, function (imgs) {
  7581. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7582. var height = width;
  7583. _this._prepareWorkingCanvas();
  7584. _this._workingCanvas.width = width;
  7585. _this._workingCanvas.height = height;
  7586. var faces = [
  7587. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7588. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7589. ];
  7590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7591. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7592. for (var index = 0; index < faces.length; index++) {
  7593. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7594. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7595. }
  7596. if (!noMipmap) {
  7597. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7598. }
  7599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7603. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7604. _this.resetTextureCache();
  7605. texture._width = width;
  7606. texture._height = height;
  7607. texture.isReady = true;
  7608. }, files);
  7609. }
  7610. return texture;
  7611. };
  7612. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7613. texture._width = width;
  7614. texture._height = height;
  7615. texture._size = width * height;
  7616. texture._baseWidth = width;
  7617. texture._baseHeight = height;
  7618. };
  7619. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7620. var _this = this;
  7621. var gl = this._gl;
  7622. var texture = gl.createTexture();
  7623. scene._addPendingData(texture);
  7624. texture.isCube = true;
  7625. texture.references = 1;
  7626. texture.url = url;
  7627. var internalFormat = this._getInternalFormat(format);
  7628. var textureType = gl.UNSIGNED_BYTE;
  7629. if (type === Engine.TEXTURETYPE_FLOAT) {
  7630. textureType = gl.FLOAT;
  7631. }
  7632. var width = size;
  7633. var height = width;
  7634. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7635. texture._width = width;
  7636. texture._height = height;
  7637. var onerror = function () {
  7638. scene._removePendingData(texture);
  7639. };
  7640. var internalCallback = function (data) {
  7641. var rgbeDataArrays = callback(data);
  7642. var facesIndex = [
  7643. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7644. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7645. ];
  7646. width = texture._width;
  7647. height = texture._height;
  7648. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7650. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7651. if (!noMipmap && isPot) {
  7652. if (mipmmapGenerator) {
  7653. var arrayTemp = [];
  7654. // Data are known to be in +X +Y +Z -X -Y -Z
  7655. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7656. arrayTemp.push(rgbeDataArrays[0]); // +X
  7657. arrayTemp.push(rgbeDataArrays[3]); // -X
  7658. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7659. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7660. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7661. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7662. var mipData = mipmmapGenerator(arrayTemp);
  7663. for (var level = 0; level < mipData.length; level++) {
  7664. var mipSize = width >> level;
  7665. // mipData is order in +X -X +Y -Y +Z -Z
  7666. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7667. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7668. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7669. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7670. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7671. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7672. }
  7673. }
  7674. else {
  7675. // Data are known to be in +X +Y +Z -X -Y -Z
  7676. for (var index = 0; index < facesIndex.length; index++) {
  7677. var faceData = rgbeDataArrays[index];
  7678. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7679. }
  7680. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7681. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7682. // By following the webgl standard changes from Revision 7, 2014/11/24
  7683. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7684. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7685. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7686. // Data are known to be in +X +Y +Z -X -Y -Z
  7687. for (var index = 0; index < facesIndex.length; index++) {
  7688. var faceData = rgbeDataArrays[index];
  7689. // Create a new RGBA Face.
  7690. var newFaceData = new Float32Array(width * height * 4);
  7691. for (var x = 0; x < width; x++) {
  7692. for (var y = 0; y < height; y++) {
  7693. var index_1 = (y * width + x) * 3;
  7694. var newIndex = (y * width + x) * 4;
  7695. // Map Old Value to new value.
  7696. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7697. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7698. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7699. // Add fully opaque alpha channel.
  7700. newFaceData[newIndex + 3] = 1;
  7701. }
  7702. }
  7703. // Reupload the face.
  7704. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7705. }
  7706. // Try to generate mipmap again.
  7707. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7708. }
  7709. }
  7710. }
  7711. else {
  7712. noMipmap = true;
  7713. }
  7714. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7717. }
  7718. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  7719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7721. }
  7722. else {
  7723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7725. }
  7726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7728. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7729. texture.isReady = true;
  7730. _this.resetTextureCache();
  7731. scene._removePendingData(texture);
  7732. };
  7733. BABYLON.Tools.LoadFile(url, function (data) {
  7734. internalCallback(data);
  7735. }, onerror, scene.database, true);
  7736. return texture;
  7737. };
  7738. ;
  7739. Engine.prototype._releaseTexture = function (texture) {
  7740. var gl = this._gl;
  7741. if (texture._framebuffer) {
  7742. gl.deleteFramebuffer(texture._framebuffer);
  7743. }
  7744. if (texture._depthBuffer) {
  7745. gl.deleteRenderbuffer(texture._depthBuffer);
  7746. }
  7747. gl.deleteTexture(texture);
  7748. // Unbind channels
  7749. this.unbindAllTextures();
  7750. var index = this._loadedTexturesCache.indexOf(texture);
  7751. if (index !== -1) {
  7752. this._loadedTexturesCache.splice(index, 1);
  7753. }
  7754. };
  7755. Engine.prototype.setProgram = function (program) {
  7756. if (this._currentProgram !== program) {
  7757. this._gl.useProgram(program);
  7758. this._currentProgram = program;
  7759. }
  7760. };
  7761. Engine.prototype.bindSamplers = function (effect) {
  7762. this.setProgram(effect.getProgram());
  7763. var samplers = effect.getSamplers();
  7764. for (var index = 0; index < samplers.length; index++) {
  7765. var uniform = effect.getUniform(samplers[index]);
  7766. this._gl.uniform1i(uniform, index);
  7767. }
  7768. this._currentEffect = null;
  7769. };
  7770. Engine.prototype.activateTexture = function (texture) {
  7771. if (this._activeTexture !== texture) {
  7772. this._gl.activeTexture(texture);
  7773. this._activeTexture = texture;
  7774. }
  7775. };
  7776. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7777. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7778. this._gl.bindTexture(target, texture);
  7779. this._activeTexturesCache[this._activeTexture] = texture;
  7780. }
  7781. };
  7782. Engine.prototype._bindTexture = function (channel, texture) {
  7783. if (channel < 0) {
  7784. return;
  7785. }
  7786. this.activateTexture(this._gl["TEXTURE" + channel]);
  7787. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7788. };
  7789. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7790. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7791. };
  7792. Engine.prototype.unbindAllTextures = function () {
  7793. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7794. this.activateTexture(this._gl["TEXTURE" + channel]);
  7795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7796. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7797. }
  7798. };
  7799. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7800. if (channel < 0) {
  7801. return;
  7802. }
  7803. this._gl.uniform1i(uniform, channel);
  7804. this._setTexture(channel, texture);
  7805. };
  7806. Engine.prototype._setTexture = function (channel, texture) {
  7807. // Not ready?
  7808. if (!texture || !texture.isReady()) {
  7809. if (this._activeTexturesCache[channel] != null) {
  7810. this.activateTexture(this._gl["TEXTURE" + channel]);
  7811. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7812. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7813. }
  7814. return;
  7815. }
  7816. // Video
  7817. var alreadyActivated = false;
  7818. if (texture instanceof BABYLON.VideoTexture) {
  7819. this.activateTexture(this._gl["TEXTURE" + channel]);
  7820. alreadyActivated = true;
  7821. texture.update();
  7822. }
  7823. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7824. texture.delayLoad();
  7825. return;
  7826. }
  7827. var internalTexture = texture.getInternalTexture();
  7828. if (this._activeTexturesCache[channel] === internalTexture) {
  7829. return;
  7830. }
  7831. if (!alreadyActivated) {
  7832. this.activateTexture(this._gl["TEXTURE" + channel]);
  7833. }
  7834. if (internalTexture.isCube) {
  7835. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7836. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7837. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7838. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7839. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7840. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7841. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7842. }
  7843. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7844. }
  7845. else {
  7846. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7847. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7848. internalTexture._cachedWrapU = texture.wrapU;
  7849. switch (texture.wrapU) {
  7850. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7852. break;
  7853. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7855. break;
  7856. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7857. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7858. break;
  7859. }
  7860. }
  7861. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7862. internalTexture._cachedWrapV = texture.wrapV;
  7863. switch (texture.wrapV) {
  7864. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7866. break;
  7867. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7869. break;
  7870. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7872. break;
  7873. }
  7874. }
  7875. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7876. }
  7877. };
  7878. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7879. if (channel < 0) {
  7880. return;
  7881. }
  7882. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7883. this._textureUnits = new Int32Array(textures.length);
  7884. }
  7885. for (var i = 0; i < textures.length; i++) {
  7886. this._textureUnits[i] = channel + i;
  7887. }
  7888. this._gl.uniform1iv(uniform, this._textureUnits);
  7889. for (var index = 0; index < textures.length; index++) {
  7890. this._setTexture(channel + index, textures[index]);
  7891. }
  7892. };
  7893. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7894. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7895. var value = texture.anisotropicFilteringLevel;
  7896. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7897. value = 1;
  7898. }
  7899. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7900. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7901. texture._cachedAnisotropicFilteringLevel = value;
  7902. }
  7903. };
  7904. Engine.prototype.readPixels = function (x, y, width, height) {
  7905. var data = new Uint8Array(height * width * 4);
  7906. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7907. return data;
  7908. };
  7909. /**
  7910. * Add an externaly attached data from its key.
  7911. * This method call will fail and return false, if such key already exists.
  7912. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7913. * @param key the unique key that identifies the data
  7914. * @param data the data object to associate to the key for this Engine instance
  7915. * @return true if no such key were already present and the data was added successfully, false otherwise
  7916. */
  7917. Engine.prototype.addExternalData = function (key, data) {
  7918. return this._externalData.add(key, data);
  7919. };
  7920. /**
  7921. * Get an externaly attached data from its key
  7922. * @param key the unique key that identifies the data
  7923. * @return the associated data, if present (can be null), or undefined if not present
  7924. */
  7925. Engine.prototype.getExternalData = function (key) {
  7926. return this._externalData.get(key);
  7927. };
  7928. /**
  7929. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7930. * @param key the unique key that identifies the data
  7931. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7932. * @return the associated data, can be null if the factory returned null.
  7933. */
  7934. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7935. return this._externalData.getOrAddWithFactory(key, factory);
  7936. };
  7937. /**
  7938. * Remove an externaly attached data from the Engine instance
  7939. * @param key the unique key that identifies the data
  7940. * @return true if the data was successfully removed, false if it doesn't exist
  7941. */
  7942. Engine.prototype.removeExternalData = function (key) {
  7943. return this._externalData.remove(key);
  7944. };
  7945. Engine.prototype.releaseInternalTexture = function (texture) {
  7946. if (!texture) {
  7947. return;
  7948. }
  7949. texture.references--;
  7950. // Final reference ?
  7951. if (texture.references === 0) {
  7952. var texturesCache = this.getLoadedTexturesCache();
  7953. var index = texturesCache.indexOf(texture);
  7954. if (index > -1) {
  7955. texturesCache.splice(index, 1);
  7956. }
  7957. this._releaseTexture(texture);
  7958. }
  7959. };
  7960. // Dispose
  7961. Engine.prototype.dispose = function () {
  7962. this.hideLoadingUI();
  7963. this.stopRenderLoop();
  7964. // Release scenes
  7965. while (this.scenes.length) {
  7966. this.scenes[0].dispose();
  7967. }
  7968. // Release audio engine
  7969. Engine.audioEngine.dispose();
  7970. // Release effects
  7971. for (var name in this._compiledEffects) {
  7972. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7973. }
  7974. // Unbind
  7975. if (this._vertexAttribArraysEnabled) {
  7976. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7977. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7978. continue;
  7979. }
  7980. this._gl.disableVertexAttribArray(i);
  7981. }
  7982. }
  7983. this._gl = null;
  7984. // Events
  7985. window.removeEventListener("blur", this._onBlur);
  7986. window.removeEventListener("focus", this._onFocus);
  7987. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7988. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7989. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7990. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7991. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7992. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7993. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7994. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7995. };
  7996. // Loading screen
  7997. Engine.prototype.displayLoadingUI = function () {
  7998. this._loadingScreen.displayLoadingUI();
  7999. };
  8000. Engine.prototype.hideLoadingUI = function () {
  8001. this._loadingScreen.hideLoadingUI();
  8002. };
  8003. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8004. get: function () {
  8005. return this._loadingScreen;
  8006. },
  8007. set: function (loadingScreen) {
  8008. this._loadingScreen = loadingScreen;
  8009. },
  8010. enumerable: true,
  8011. configurable: true
  8012. });
  8013. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8014. set: function (text) {
  8015. this._loadingScreen.loadingUIText = text;
  8016. },
  8017. enumerable: true,
  8018. configurable: true
  8019. });
  8020. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8021. set: function (color) {
  8022. this._loadingScreen.loadingUIBackgroundColor = color;
  8023. },
  8024. enumerable: true,
  8025. configurable: true
  8026. });
  8027. // FPS
  8028. Engine.prototype.getFps = function () {
  8029. return this.fps;
  8030. };
  8031. Engine.prototype.getDeltaTime = function () {
  8032. return this.deltaTime;
  8033. };
  8034. Engine.prototype._measureFps = function () {
  8035. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8036. var length = this.previousFramesDuration.length;
  8037. if (length >= 2) {
  8038. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8039. }
  8040. if (length >= this.fpsRange) {
  8041. if (length > this.fpsRange) {
  8042. this.previousFramesDuration.splice(0, 1);
  8043. length = this.previousFramesDuration.length;
  8044. }
  8045. var sum = 0;
  8046. for (var id = 0; id < length - 1; id++) {
  8047. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8048. }
  8049. this.fps = 1000.0 / (sum / (length - 1));
  8050. }
  8051. };
  8052. Engine.prototype._canRenderToFloatTexture = function () {
  8053. if (!this.getCaps().textureFloat) {
  8054. return false;
  8055. }
  8056. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8057. };
  8058. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8059. if (!this.getCaps().textureHalfFloat) {
  8060. return false;
  8061. }
  8062. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8063. };
  8064. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8065. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8066. var tempcanvas = document.createElement("canvas");
  8067. tempcanvas.height = 16;
  8068. tempcanvas.width = 16;
  8069. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8070. // extension.
  8071. var ext = gl.getExtension(extension);
  8072. // setup GLSL program
  8073. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8074. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8075. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8076. gl.useProgram(program);
  8077. // look up where the vertex data needs to go.
  8078. var positionLocation = gl.getAttribLocation(program, "a_position");
  8079. var colorLoc = gl.getUniformLocation(program, "u_color");
  8080. // provide texture coordinates for the rectangle.
  8081. var positionBuffer = gl.createBuffer();
  8082. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8083. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8084. -1.0, -1.0,
  8085. 1.0, -1.0,
  8086. -1.0, 1.0,
  8087. -1.0, 1.0,
  8088. 1.0, -1.0,
  8089. 1.0, 1.0]), gl.STATIC_DRAW);
  8090. gl.enableVertexAttribArray(positionLocation);
  8091. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8092. var whiteTex = gl.createTexture();
  8093. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8094. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8095. var tex = gl.createTexture();
  8096. gl.bindTexture(gl.TEXTURE_2D, tex);
  8097. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8100. var fb = gl.createFramebuffer();
  8101. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8103. var cleanup = function () {
  8104. gl.deleteProgram(program);
  8105. gl.disableVertexAttribArray(positionLocation);
  8106. gl.deleteBuffer(positionBuffer);
  8107. gl.deleteFramebuffer(fb);
  8108. gl.deleteTexture(whiteTex);
  8109. gl.deleteTexture(tex);
  8110. };
  8111. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8112. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8113. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8114. cleanup();
  8115. return false;
  8116. }
  8117. // Draw the rectangle.
  8118. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8119. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8120. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8121. gl.bindTexture(gl.TEXTURE_2D, tex);
  8122. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8123. gl.clearColor(1, 0, 0, 1);
  8124. gl.clear(gl.COLOR_BUFFER_BIT);
  8125. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8126. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8127. var pixel = new Uint8Array(4);
  8128. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8129. if (pixel[0] !== 0 ||
  8130. pixel[1] < 248 ||
  8131. pixel[2] < 248 ||
  8132. pixel[3] < 254) {
  8133. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8134. cleanup();
  8135. return false;
  8136. }
  8137. // Succesfully rendered to "format" texture.
  8138. cleanup();
  8139. return true;
  8140. };
  8141. // Statics
  8142. Engine.isSupported = function () {
  8143. try {
  8144. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8145. if (navigator.isCocoonJS) {
  8146. return true;
  8147. }
  8148. var tempcanvas = document.createElement("canvas");
  8149. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8150. return gl != null && !!window.WebGLRenderingContext;
  8151. }
  8152. catch (e) {
  8153. return false;
  8154. }
  8155. };
  8156. // Const statics
  8157. Engine._ALPHA_DISABLE = 0;
  8158. Engine._ALPHA_ADD = 1;
  8159. Engine._ALPHA_COMBINE = 2;
  8160. Engine._ALPHA_SUBTRACT = 3;
  8161. Engine._ALPHA_MULTIPLY = 4;
  8162. Engine._ALPHA_MAXIMIZED = 5;
  8163. Engine._ALPHA_ONEONE = 6;
  8164. Engine._DELAYLOADSTATE_NONE = 0;
  8165. Engine._DELAYLOADSTATE_LOADED = 1;
  8166. Engine._DELAYLOADSTATE_LOADING = 2;
  8167. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8168. Engine._TEXTUREFORMAT_ALPHA = 0;
  8169. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8170. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8171. Engine._TEXTUREFORMAT_RGB = 4;
  8172. Engine._TEXTUREFORMAT_RGBA = 5;
  8173. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8174. Engine._TEXTURETYPE_FLOAT = 1;
  8175. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8176. // Updatable statics so stick with vars here
  8177. Engine.CollisionsEpsilon = 0.001;
  8178. Engine.CodeRepository = "src/";
  8179. Engine.ShadersRepository = "src/Shaders/";
  8180. return Engine;
  8181. }());
  8182. BABYLON.Engine = Engine;
  8183. })(BABYLON || (BABYLON = {}));
  8184. var BABYLON;
  8185. (function (BABYLON) {
  8186. /**
  8187. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8188. */
  8189. var Node = (function () {
  8190. /**
  8191. * @constructor
  8192. * @param {string} name - the name and id to be given to this node
  8193. * @param {BABYLON.Scene} the scene this node will be added to
  8194. */
  8195. function Node(name, scene) {
  8196. this.state = "";
  8197. this.animations = new Array();
  8198. this._ranges = {};
  8199. this._childrenFlag = -1;
  8200. this._isEnabled = true;
  8201. this._isReady = true;
  8202. this._currentRenderId = -1;
  8203. this._parentRenderId = -1;
  8204. this.name = name;
  8205. this.id = name;
  8206. this._scene = scene;
  8207. this._initCache();
  8208. }
  8209. Object.defineProperty(Node.prototype, "parent", {
  8210. get: function () {
  8211. return this._parentNode;
  8212. },
  8213. set: function (parent) {
  8214. if (this._parentNode === parent) {
  8215. return;
  8216. }
  8217. if (this._parentNode) {
  8218. var index = this._parentNode._children.indexOf(this);
  8219. if (index !== -1) {
  8220. this._parentNode._children.splice(index, 1);
  8221. }
  8222. }
  8223. this._parentNode = parent;
  8224. if (this._parentNode) {
  8225. if (!this._parentNode._children) {
  8226. this._parentNode._children = new Array();
  8227. }
  8228. this._parentNode._children.push(this);
  8229. }
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Node.prototype.getScene = function () {
  8235. return this._scene;
  8236. };
  8237. Node.prototype.getEngine = function () {
  8238. return this._scene.getEngine();
  8239. };
  8240. // override it in derived class
  8241. Node.prototype.getWorldMatrix = function () {
  8242. return BABYLON.Matrix.Identity();
  8243. };
  8244. // override it in derived class if you add new variables to the cache
  8245. // and call the parent class method
  8246. Node.prototype._initCache = function () {
  8247. this._cache = {};
  8248. this._cache.parent = undefined;
  8249. };
  8250. Node.prototype.updateCache = function (force) {
  8251. if (!force && this.isSynchronized())
  8252. return;
  8253. this._cache.parent = this.parent;
  8254. this._updateCache();
  8255. };
  8256. // override it in derived class if you add new variables to the cache
  8257. // and call the parent class method if !ignoreParentClass
  8258. Node.prototype._updateCache = function (ignoreParentClass) {
  8259. };
  8260. // override it in derived class if you add new variables to the cache
  8261. Node.prototype._isSynchronized = function () {
  8262. return true;
  8263. };
  8264. Node.prototype._markSyncedWithParent = function () {
  8265. this._parentRenderId = this.parent._currentRenderId;
  8266. };
  8267. Node.prototype.isSynchronizedWithParent = function () {
  8268. if (!this.parent) {
  8269. return true;
  8270. }
  8271. if (this._parentRenderId !== this.parent._currentRenderId) {
  8272. return false;
  8273. }
  8274. return this.parent.isSynchronized();
  8275. };
  8276. Node.prototype.isSynchronized = function (updateCache) {
  8277. var check = this.hasNewParent();
  8278. check = check || !this.isSynchronizedWithParent();
  8279. check = check || !this._isSynchronized();
  8280. if (updateCache)
  8281. this.updateCache(true);
  8282. return !check;
  8283. };
  8284. Node.prototype.hasNewParent = function (update) {
  8285. if (this._cache.parent === this.parent)
  8286. return false;
  8287. if (update)
  8288. this._cache.parent = this.parent;
  8289. return true;
  8290. };
  8291. /**
  8292. * Is this node ready to be used/rendered
  8293. * @return {boolean} is it ready
  8294. */
  8295. Node.prototype.isReady = function () {
  8296. return this._isReady;
  8297. };
  8298. /**
  8299. * Is this node enabled.
  8300. * If the node has a parent and is enabled, the parent will be inspected as well.
  8301. * @return {boolean} whether this node (and its parent) is enabled.
  8302. * @see setEnabled
  8303. */
  8304. Node.prototype.isEnabled = function () {
  8305. if (!this._isEnabled) {
  8306. return false;
  8307. }
  8308. if (this.parent) {
  8309. return this.parent.isEnabled();
  8310. }
  8311. return true;
  8312. };
  8313. /**
  8314. * Set the enabled state of this node.
  8315. * @param {boolean} value - the new enabled state
  8316. * @see isEnabled
  8317. */
  8318. Node.prototype.setEnabled = function (value) {
  8319. this._isEnabled = value;
  8320. };
  8321. /**
  8322. * Is this node a descendant of the given node.
  8323. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8324. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8325. * @see parent
  8326. */
  8327. Node.prototype.isDescendantOf = function (ancestor) {
  8328. if (this.parent) {
  8329. if (this.parent === ancestor) {
  8330. return true;
  8331. }
  8332. return this.parent.isDescendantOf(ancestor);
  8333. }
  8334. return false;
  8335. };
  8336. /**
  8337. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8338. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8339. * @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.
  8340. * @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.
  8341. */
  8342. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8343. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8344. if (!this._children) {
  8345. return;
  8346. }
  8347. for (var index = 0; index < this._children.length; index++) {
  8348. var item = this._children[index];
  8349. if (!predicate || predicate(item)) {
  8350. results.push(item);
  8351. }
  8352. if (!directDescendantsOnly) {
  8353. item._getDescendants(results, false, predicate);
  8354. }
  8355. }
  8356. };
  8357. /**
  8358. * Will return all nodes that have this node as ascendant.
  8359. * @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.
  8360. * @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.
  8361. * @return {BABYLON.Node[]} all children nodes of all types.
  8362. */
  8363. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8364. var results = [];
  8365. this._getDescendants(results, directDescendantsOnly, predicate);
  8366. return results;
  8367. };
  8368. /**
  8369. * @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.
  8370. * @Deprecated, legacy support.
  8371. * use getDecendants instead.
  8372. */
  8373. Node.prototype.getChildren = function (predicate) {
  8374. return this.getDescendants(true, predicate);
  8375. };
  8376. /**
  8377. * Get all child-meshes of this node.
  8378. */
  8379. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8380. var results = [];
  8381. this._getDescendants(results, directDecendantsOnly, function (node) {
  8382. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8383. });
  8384. return results;
  8385. };
  8386. Node.prototype._setReady = function (state) {
  8387. if (state === this._isReady) {
  8388. return;
  8389. }
  8390. if (!state) {
  8391. this._isReady = false;
  8392. return;
  8393. }
  8394. this._isReady = true;
  8395. if (this.onReady) {
  8396. this.onReady(this);
  8397. }
  8398. };
  8399. Node.prototype.getAnimationByName = function (name) {
  8400. for (var i = 0; i < this.animations.length; i++) {
  8401. var animation = this.animations[i];
  8402. if (animation.name === name) {
  8403. return animation;
  8404. }
  8405. }
  8406. return null;
  8407. };
  8408. Node.prototype.createAnimationRange = function (name, from, to) {
  8409. // check name not already in use
  8410. if (!this._ranges[name]) {
  8411. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8412. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8413. if (this.animations[i]) {
  8414. this.animations[i].createRange(name, from, to);
  8415. }
  8416. }
  8417. }
  8418. };
  8419. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8420. if (deleteFrames === void 0) { deleteFrames = true; }
  8421. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8422. if (this.animations[i]) {
  8423. this.animations[i].deleteRange(name, deleteFrames);
  8424. }
  8425. }
  8426. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8427. };
  8428. Node.prototype.getAnimationRange = function (name) {
  8429. return this._ranges[name];
  8430. };
  8431. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8432. var range = this.getAnimationRange(name);
  8433. if (!range) {
  8434. return null;
  8435. }
  8436. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8437. };
  8438. Node.prototype.serializeAnimationRanges = function () {
  8439. var serializationRanges = [];
  8440. for (var name in this._ranges) {
  8441. var range = {};
  8442. range.name = name;
  8443. range.from = this._ranges[name].from;
  8444. range.to = this._ranges[name].to;
  8445. serializationRanges.push(range);
  8446. }
  8447. return serializationRanges;
  8448. };
  8449. Node.prototype.dispose = function () {
  8450. this.parent = null;
  8451. };
  8452. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8453. if (parsedNode.ranges) {
  8454. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8455. var data = parsedNode.ranges[index];
  8456. node.createAnimationRange(data.name, data.from, data.to);
  8457. }
  8458. }
  8459. };
  8460. __decorate([
  8461. BABYLON.serialize()
  8462. ], Node.prototype, "name", void 0);
  8463. __decorate([
  8464. BABYLON.serialize()
  8465. ], Node.prototype, "id", void 0);
  8466. __decorate([
  8467. BABYLON.serialize()
  8468. ], Node.prototype, "uniqueId", void 0);
  8469. __decorate([
  8470. BABYLON.serialize()
  8471. ], Node.prototype, "state", void 0);
  8472. return Node;
  8473. }());
  8474. BABYLON.Node = Node;
  8475. })(BABYLON || (BABYLON = {}));
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. var FilesInput = (function () {
  8479. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8480. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8481. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8482. this._engine = p_engine;
  8483. this._canvas = p_canvas;
  8484. this._currentScene = p_scene;
  8485. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8486. this._progressCallback = p_progressCallback;
  8487. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8488. this._textureLoadingCallback = p_textureLoadingCallback;
  8489. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8490. }
  8491. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8492. var _this = this;
  8493. if (p_elementToMonitor) {
  8494. this._elementToMonitor = p_elementToMonitor;
  8495. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8496. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8497. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8498. }
  8499. };
  8500. FilesInput.prototype.renderFunction = function () {
  8501. if (this._additionnalRenderLoopLogicCallback) {
  8502. this._additionnalRenderLoopLogicCallback();
  8503. }
  8504. if (this._currentScene) {
  8505. if (this._textureLoadingCallback) {
  8506. var remaining = this._currentScene.getWaitingItemsCount();
  8507. if (remaining > 0) {
  8508. this._textureLoadingCallback(remaining);
  8509. }
  8510. }
  8511. this._currentScene.render();
  8512. }
  8513. };
  8514. FilesInput.prototype.drag = function (e) {
  8515. e.stopPropagation();
  8516. e.preventDefault();
  8517. };
  8518. FilesInput.prototype.drop = function (eventDrop) {
  8519. eventDrop.stopPropagation();
  8520. eventDrop.preventDefault();
  8521. this.loadFiles(eventDrop);
  8522. };
  8523. FilesInput.prototype.loadFiles = function (event) {
  8524. if (this._startingProcessingFilesCallback)
  8525. this._startingProcessingFilesCallback();
  8526. // Handling data transfer via drag'n'drop
  8527. if (event && event.dataTransfer && event.dataTransfer.files) {
  8528. this._filesToLoad = event.dataTransfer.files;
  8529. }
  8530. // Handling files from input files
  8531. if (event && event.target && event.target.files) {
  8532. this._filesToLoad = event.target.files;
  8533. }
  8534. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8535. for (var i = 0; i < this._filesToLoad.length; i++) {
  8536. switch (this._filesToLoad[i].type) {
  8537. case "image/jpeg":
  8538. case "image/png":
  8539. case "image/bmp":
  8540. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8541. break;
  8542. case "image/targa":
  8543. case "image/vnd.ms-dds":
  8544. case "audio/wav":
  8545. case "audio/x-wav":
  8546. case "audio/mp3":
  8547. case "audio/mpeg":
  8548. case "audio/mpeg3":
  8549. case "audio/x-mpeg-3":
  8550. case "audio/ogg":
  8551. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8552. break;
  8553. default:
  8554. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8555. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8556. }
  8557. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8558. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8559. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8560. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8561. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8562. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8563. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8564. this._sceneFileToLoad = this._filesToLoad[i];
  8565. }
  8566. break;
  8567. }
  8568. }
  8569. this.reload();
  8570. }
  8571. };
  8572. FilesInput.prototype.reload = function () {
  8573. var _this = this;
  8574. var that = this;
  8575. // If a ".babylon" file has been provided
  8576. if (this._sceneFileToLoad) {
  8577. if (this._currentScene) {
  8578. if (BABYLON.Tools.errorsCount > 0) {
  8579. BABYLON.Tools.ClearLogCache();
  8580. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8581. }
  8582. this._engine.stopRenderLoop();
  8583. this._currentScene.dispose();
  8584. }
  8585. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8586. that._currentScene = newScene;
  8587. // Wait for textures and shaders to be ready
  8588. that._currentScene.executeWhenReady(function () {
  8589. // Attach camera to canvas inputs
  8590. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8591. that._currentScene.createDefaultCameraOrLight();
  8592. }
  8593. that._currentScene.activeCamera.attachControl(that._canvas);
  8594. if (that._sceneLoadedCallback) {
  8595. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8596. }
  8597. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8598. });
  8599. }, function (progress) {
  8600. if (_this._progressCallback) {
  8601. _this._progressCallback(progress);
  8602. }
  8603. });
  8604. }
  8605. else {
  8606. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8607. }
  8608. };
  8609. FilesInput.FilesTextures = new Array();
  8610. FilesInput.FilesToLoad = new Array();
  8611. return FilesInput;
  8612. }());
  8613. BABYLON.FilesInput = FilesInput;
  8614. })(BABYLON || (BABYLON = {}));
  8615. var BABYLON;
  8616. (function (BABYLON) {
  8617. var IntersectionInfo = (function () {
  8618. function IntersectionInfo(bu, bv, distance) {
  8619. this.bu = bu;
  8620. this.bv = bv;
  8621. this.distance = distance;
  8622. this.faceId = 0;
  8623. this.subMeshId = 0;
  8624. }
  8625. return IntersectionInfo;
  8626. }());
  8627. BABYLON.IntersectionInfo = IntersectionInfo;
  8628. var PickingInfo = (function () {
  8629. function PickingInfo() {
  8630. this.hit = false;
  8631. this.distance = 0;
  8632. this.pickedPoint = null;
  8633. this.pickedMesh = null;
  8634. this.bu = 0;
  8635. this.bv = 0;
  8636. this.faceId = -1;
  8637. this.subMeshId = 0;
  8638. this.pickedSprite = null;
  8639. }
  8640. // Methods
  8641. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8642. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8643. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8644. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8645. return null;
  8646. }
  8647. var indices = this.pickedMesh.getIndices();
  8648. var result;
  8649. if (useVerticesNormals) {
  8650. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8651. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8652. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8653. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8654. normal0 = normal0.scale(this.bu);
  8655. normal1 = normal1.scale(this.bv);
  8656. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8657. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8658. }
  8659. else {
  8660. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8661. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8662. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8663. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8664. var p1p2 = vertex1.subtract(vertex2);
  8665. var p3p2 = vertex3.subtract(vertex2);
  8666. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8667. }
  8668. if (useWorldCoordinates) {
  8669. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8670. }
  8671. return BABYLON.Vector3.Normalize(result);
  8672. };
  8673. PickingInfo.prototype.getTextureCoordinates = function () {
  8674. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8675. return null;
  8676. }
  8677. var indices = this.pickedMesh.getIndices();
  8678. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8679. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8680. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8681. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8682. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8683. uv1 = uv1.scale(this.bu);
  8684. uv2 = uv2.scale(this.bv);
  8685. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8686. };
  8687. return PickingInfo;
  8688. }());
  8689. BABYLON.PickingInfo = PickingInfo;
  8690. })(BABYLON || (BABYLON = {}));
  8691. var BABYLON;
  8692. (function (BABYLON) {
  8693. var BoundingSphere = (function () {
  8694. function BoundingSphere(minimum, maximum) {
  8695. this.minimum = minimum;
  8696. this.maximum = maximum;
  8697. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8698. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8699. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8700. this.radius = distance * 0.5;
  8701. this.centerWorld = BABYLON.Vector3.Zero();
  8702. this._update(BABYLON.Matrix.Identity());
  8703. }
  8704. // Methods
  8705. BoundingSphere.prototype._update = function (world) {
  8706. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8707. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8708. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8709. };
  8710. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8711. for (var i = 0; i < 6; i++) {
  8712. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8713. return false;
  8714. }
  8715. return true;
  8716. };
  8717. BoundingSphere.prototype.intersectsPoint = function (point) {
  8718. var x = this.centerWorld.x - point.x;
  8719. var y = this.centerWorld.y - point.y;
  8720. var z = this.centerWorld.z - point.z;
  8721. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8722. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8723. return false;
  8724. return true;
  8725. };
  8726. // Statics
  8727. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8728. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8729. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8730. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8731. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8732. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8733. return false;
  8734. return true;
  8735. };
  8736. return BoundingSphere;
  8737. }());
  8738. BABYLON.BoundingSphere = BoundingSphere;
  8739. })(BABYLON || (BABYLON = {}));
  8740. var BABYLON;
  8741. (function (BABYLON) {
  8742. var BoundingBox = (function () {
  8743. function BoundingBox(minimum, maximum) {
  8744. this.minimum = minimum;
  8745. this.maximum = maximum;
  8746. this.vectors = new Array();
  8747. this.vectorsWorld = new Array();
  8748. // Bounding vectors
  8749. this.vectors.push(this.minimum.clone());
  8750. this.vectors.push(this.maximum.clone());
  8751. this.vectors.push(this.minimum.clone());
  8752. this.vectors[2].x = this.maximum.x;
  8753. this.vectors.push(this.minimum.clone());
  8754. this.vectors[3].y = this.maximum.y;
  8755. this.vectors.push(this.minimum.clone());
  8756. this.vectors[4].z = this.maximum.z;
  8757. this.vectors.push(this.maximum.clone());
  8758. this.vectors[5].z = this.minimum.z;
  8759. this.vectors.push(this.maximum.clone());
  8760. this.vectors[6].x = this.minimum.x;
  8761. this.vectors.push(this.maximum.clone());
  8762. this.vectors[7].y = this.minimum.y;
  8763. // OBB
  8764. this.center = this.maximum.add(this.minimum).scale(0.5);
  8765. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8766. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8767. // World
  8768. for (var index = 0; index < this.vectors.length; index++) {
  8769. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8770. }
  8771. this.minimumWorld = BABYLON.Vector3.Zero();
  8772. this.maximumWorld = BABYLON.Vector3.Zero();
  8773. this._update(BABYLON.Matrix.Identity());
  8774. }
  8775. // Methods
  8776. BoundingBox.prototype.getWorldMatrix = function () {
  8777. return this._worldMatrix;
  8778. };
  8779. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8780. this._worldMatrix.copyFrom(matrix);
  8781. return this;
  8782. };
  8783. BoundingBox.prototype._update = function (world) {
  8784. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8785. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8786. for (var index = 0; index < this.vectors.length; index++) {
  8787. var v = this.vectorsWorld[index];
  8788. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8789. if (v.x < this.minimumWorld.x)
  8790. this.minimumWorld.x = v.x;
  8791. if (v.y < this.minimumWorld.y)
  8792. this.minimumWorld.y = v.y;
  8793. if (v.z < this.minimumWorld.z)
  8794. this.minimumWorld.z = v.z;
  8795. if (v.x > this.maximumWorld.x)
  8796. this.maximumWorld.x = v.x;
  8797. if (v.y > this.maximumWorld.y)
  8798. this.maximumWorld.y = v.y;
  8799. if (v.z > this.maximumWorld.z)
  8800. this.maximumWorld.z = v.z;
  8801. }
  8802. // OBB
  8803. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8804. this.center.scaleInPlace(0.5);
  8805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8806. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8807. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8808. this._worldMatrix = world;
  8809. };
  8810. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8811. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8812. };
  8813. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8814. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8815. };
  8816. BoundingBox.prototype.intersectsPoint = function (point) {
  8817. var delta = -BABYLON.Epsilon;
  8818. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8819. return false;
  8820. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8821. return false;
  8822. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8823. return false;
  8824. return true;
  8825. };
  8826. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8827. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8828. };
  8829. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8830. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8831. return false;
  8832. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8833. return false;
  8834. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8835. return false;
  8836. return true;
  8837. };
  8838. // Statics
  8839. BoundingBox.Intersects = function (box0, box1) {
  8840. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8841. return false;
  8842. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8843. return false;
  8844. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8845. return false;
  8846. return true;
  8847. };
  8848. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8849. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8850. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8851. return (num <= (sphereRadius * sphereRadius));
  8852. };
  8853. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8854. for (var p = 0; p < 6; p++) {
  8855. for (var i = 0; i < 8; i++) {
  8856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8857. return false;
  8858. }
  8859. }
  8860. }
  8861. return true;
  8862. };
  8863. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8864. for (var p = 0; p < 6; p++) {
  8865. var inCount = 8;
  8866. for (var i = 0; i < 8; i++) {
  8867. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8868. --inCount;
  8869. }
  8870. else {
  8871. break;
  8872. }
  8873. }
  8874. if (inCount === 0)
  8875. return false;
  8876. }
  8877. return true;
  8878. };
  8879. return BoundingBox;
  8880. }());
  8881. BABYLON.BoundingBox = BoundingBox;
  8882. })(BABYLON || (BABYLON = {}));
  8883. var BABYLON;
  8884. (function (BABYLON) {
  8885. var computeBoxExtents = function (axis, box) {
  8886. var p = BABYLON.Vector3.Dot(box.center, axis);
  8887. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8888. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8889. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8890. var r = r0 + r1 + r2;
  8891. return {
  8892. min: p - r,
  8893. max: p + r
  8894. };
  8895. };
  8896. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8897. var axisOverlap = function (axis, box0, box1) {
  8898. var result0 = computeBoxExtents(axis, box0);
  8899. var result1 = computeBoxExtents(axis, box1);
  8900. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8901. };
  8902. var BoundingInfo = (function () {
  8903. function BoundingInfo(minimum, maximum) {
  8904. this.minimum = minimum;
  8905. this.maximum = maximum;
  8906. this._isLocked = false;
  8907. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8908. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8909. }
  8910. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8911. get: function () {
  8912. return this._isLocked;
  8913. },
  8914. set: function (value) {
  8915. this._isLocked = value;
  8916. },
  8917. enumerable: true,
  8918. configurable: true
  8919. });
  8920. // Methods
  8921. BoundingInfo.prototype.update = function (world) {
  8922. if (this._isLocked) {
  8923. return;
  8924. }
  8925. this.boundingBox._update(world);
  8926. this.boundingSphere._update(world);
  8927. };
  8928. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8929. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8930. return false;
  8931. return this.boundingBox.isInFrustum(frustumPlanes);
  8932. };
  8933. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8934. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8935. };
  8936. BoundingInfo.prototype._checkCollision = function (collider) {
  8937. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8938. };
  8939. BoundingInfo.prototype.intersectsPoint = function (point) {
  8940. if (!this.boundingSphere.centerWorld) {
  8941. return false;
  8942. }
  8943. if (!this.boundingSphere.intersectsPoint(point)) {
  8944. return false;
  8945. }
  8946. if (!this.boundingBox.intersectsPoint(point)) {
  8947. return false;
  8948. }
  8949. return true;
  8950. };
  8951. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8952. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8953. return false;
  8954. }
  8955. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8956. return false;
  8957. }
  8958. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8959. return false;
  8960. }
  8961. if (!precise) {
  8962. return true;
  8963. }
  8964. var box0 = this.boundingBox;
  8965. var box1 = boundingInfo.boundingBox;
  8966. if (!axisOverlap(box0.directions[0], box0, box1))
  8967. return false;
  8968. if (!axisOverlap(box0.directions[1], box0, box1))
  8969. return false;
  8970. if (!axisOverlap(box0.directions[2], box0, box1))
  8971. return false;
  8972. if (!axisOverlap(box1.directions[0], box0, box1))
  8973. return false;
  8974. if (!axisOverlap(box1.directions[1], box0, box1))
  8975. return false;
  8976. if (!axisOverlap(box1.directions[2], box0, box1))
  8977. return false;
  8978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8979. return false;
  8980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8981. return false;
  8982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8983. return false;
  8984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8985. return false;
  8986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8987. return false;
  8988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8989. return false;
  8990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8991. return false;
  8992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8993. return false;
  8994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8995. return false;
  8996. return true;
  8997. };
  8998. return BoundingInfo;
  8999. }());
  9000. BABYLON.BoundingInfo = BoundingInfo;
  9001. })(BABYLON || (BABYLON = {}));
  9002. var BABYLON;
  9003. (function (BABYLON) {
  9004. var Ray = (function () {
  9005. function Ray(origin, direction, length) {
  9006. if (length === void 0) { length = Number.MAX_VALUE; }
  9007. this.origin = origin;
  9008. this.direction = direction;
  9009. this.length = length;
  9010. }
  9011. // Methods
  9012. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9013. var d = 0.0;
  9014. var maxValue = Number.MAX_VALUE;
  9015. var inv;
  9016. var min;
  9017. var max;
  9018. var temp;
  9019. if (Math.abs(this.direction.x) < 0.0000001) {
  9020. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9021. return false;
  9022. }
  9023. }
  9024. else {
  9025. inv = 1.0 / this.direction.x;
  9026. min = (minimum.x - this.origin.x) * inv;
  9027. max = (maximum.x - this.origin.x) * inv;
  9028. if (max === -Infinity) {
  9029. max = Infinity;
  9030. }
  9031. if (min > max) {
  9032. temp = min;
  9033. min = max;
  9034. max = temp;
  9035. }
  9036. d = Math.max(min, d);
  9037. maxValue = Math.min(max, maxValue);
  9038. if (d > maxValue) {
  9039. return false;
  9040. }
  9041. }
  9042. if (Math.abs(this.direction.y) < 0.0000001) {
  9043. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9044. return false;
  9045. }
  9046. }
  9047. else {
  9048. inv = 1.0 / this.direction.y;
  9049. min = (minimum.y - this.origin.y) * inv;
  9050. max = (maximum.y - this.origin.y) * inv;
  9051. if (max === -Infinity) {
  9052. max = Infinity;
  9053. }
  9054. if (min > max) {
  9055. temp = min;
  9056. min = max;
  9057. max = temp;
  9058. }
  9059. d = Math.max(min, d);
  9060. maxValue = Math.min(max, maxValue);
  9061. if (d > maxValue) {
  9062. return false;
  9063. }
  9064. }
  9065. if (Math.abs(this.direction.z) < 0.0000001) {
  9066. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9067. return false;
  9068. }
  9069. }
  9070. else {
  9071. inv = 1.0 / this.direction.z;
  9072. min = (minimum.z - this.origin.z) * inv;
  9073. max = (maximum.z - this.origin.z) * inv;
  9074. if (max === -Infinity) {
  9075. max = Infinity;
  9076. }
  9077. if (min > max) {
  9078. temp = min;
  9079. min = max;
  9080. max = temp;
  9081. }
  9082. d = Math.max(min, d);
  9083. maxValue = Math.min(max, maxValue);
  9084. if (d > maxValue) {
  9085. return false;
  9086. }
  9087. }
  9088. return true;
  9089. };
  9090. Ray.prototype.intersectsBox = function (box) {
  9091. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9092. };
  9093. Ray.prototype.intersectsSphere = function (sphere) {
  9094. var x = sphere.center.x - this.origin.x;
  9095. var y = sphere.center.y - this.origin.y;
  9096. var z = sphere.center.z - this.origin.z;
  9097. var pyth = (x * x) + (y * y) + (z * z);
  9098. var rr = sphere.radius * sphere.radius;
  9099. if (pyth <= rr) {
  9100. return true;
  9101. }
  9102. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9103. if (dot < 0.0) {
  9104. return false;
  9105. }
  9106. var temp = pyth - (dot * dot);
  9107. return temp <= rr;
  9108. };
  9109. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9110. if (!this._edge1) {
  9111. this._edge1 = BABYLON.Vector3.Zero();
  9112. this._edge2 = BABYLON.Vector3.Zero();
  9113. this._pvec = BABYLON.Vector3.Zero();
  9114. this._tvec = BABYLON.Vector3.Zero();
  9115. this._qvec = BABYLON.Vector3.Zero();
  9116. }
  9117. vertex1.subtractToRef(vertex0, this._edge1);
  9118. vertex2.subtractToRef(vertex0, this._edge2);
  9119. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9120. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9121. if (det === 0) {
  9122. return null;
  9123. }
  9124. var invdet = 1 / det;
  9125. this.origin.subtractToRef(vertex0, this._tvec);
  9126. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9127. if (bu < 0 || bu > 1.0) {
  9128. return null;
  9129. }
  9130. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9131. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9132. if (bv < 0 || bu + bv > 1.0) {
  9133. return null;
  9134. }
  9135. //check if the distance is longer than the predefined length.
  9136. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9137. if (distance > this.length) {
  9138. return null;
  9139. }
  9140. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9141. };
  9142. Ray.prototype.intersectsPlane = function (plane) {
  9143. var distance;
  9144. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9145. if (Math.abs(result1) < 9.99999997475243E-07) {
  9146. return null;
  9147. }
  9148. else {
  9149. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9150. distance = (-plane.d - result2) / result1;
  9151. if (distance < 0.0) {
  9152. if (distance < -9.99999997475243E-07) {
  9153. return null;
  9154. }
  9155. else {
  9156. return 0;
  9157. }
  9158. }
  9159. return distance;
  9160. }
  9161. };
  9162. /**
  9163. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9164. * @param sega the first point of the segment to test the intersection against
  9165. * @param segb the second point of the segment to test the intersection against
  9166. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9167. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9168. */
  9169. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9170. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9171. var u = segb.subtract(sega);
  9172. var v = rsegb.subtract(this.origin);
  9173. var w = sega.subtract(this.origin);
  9174. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9175. var b = BABYLON.Vector3.Dot(u, v);
  9176. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9177. var d = BABYLON.Vector3.Dot(u, w);
  9178. var e = BABYLON.Vector3.Dot(v, w);
  9179. var D = a * c - b * b; // always >= 0
  9180. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9181. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9182. // compute the line parameters of the two closest points
  9183. if (D < Ray.smallnum) {
  9184. sN = 0.0; // force using point P0 on segment S1
  9185. sD = 1.0; // to prevent possible division by 0.0 later
  9186. tN = e;
  9187. tD = c;
  9188. }
  9189. else {
  9190. sN = (b * e - c * d);
  9191. tN = (a * e - b * d);
  9192. if (sN < 0.0) {
  9193. sN = 0.0;
  9194. tN = e;
  9195. tD = c;
  9196. }
  9197. else if (sN > sD) {
  9198. sN = sD;
  9199. tN = e + b;
  9200. tD = c;
  9201. }
  9202. }
  9203. if (tN < 0.0) {
  9204. tN = 0.0;
  9205. // recompute sc for this edge
  9206. if (-d < 0.0) {
  9207. sN = 0.0;
  9208. }
  9209. else if (-d > a)
  9210. sN = sD;
  9211. else {
  9212. sN = -d;
  9213. sD = a;
  9214. }
  9215. }
  9216. else if (tN > tD) {
  9217. tN = tD;
  9218. // recompute sc for this edge
  9219. if ((-d + b) < 0.0) {
  9220. sN = 0;
  9221. }
  9222. else if ((-d + b) > a) {
  9223. sN = sD;
  9224. }
  9225. else {
  9226. sN = (-d + b);
  9227. sD = a;
  9228. }
  9229. }
  9230. // finally do the division to get sc and tc
  9231. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9232. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9233. // get the difference of the two closest points
  9234. var qtc = v.multiplyByFloats(tc, tc, tc);
  9235. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9236. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9237. if (isIntersected) {
  9238. return qtc.length();
  9239. }
  9240. return -1;
  9241. };
  9242. // Statics
  9243. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9244. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9245. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9246. var direction = end.subtract(start);
  9247. direction.normalize();
  9248. return new Ray(start, direction);
  9249. };
  9250. /**
  9251. * 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
  9252. * transformed to the given world matrix.
  9253. * @param origin The origin point
  9254. * @param end The end point
  9255. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9256. */
  9257. Ray.CreateNewFromTo = function (origin, end, world) {
  9258. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9259. var direction = end.subtract(origin);
  9260. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9261. direction.normalize();
  9262. return Ray.Transform(new Ray(origin, direction, length), world);
  9263. };
  9264. Ray.Transform = function (ray, matrix) {
  9265. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9266. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9267. newDirection.normalize();
  9268. return new Ray(newOrigin, newDirection, ray.length);
  9269. };
  9270. Ray.smallnum = 0.00000001;
  9271. Ray.rayl = 10e8;
  9272. return Ray;
  9273. }());
  9274. BABYLON.Ray = Ray;
  9275. })(BABYLON || (BABYLON = {}));
  9276. var BABYLON;
  9277. (function (BABYLON) {
  9278. var AbstractMesh = (function (_super) {
  9279. __extends(AbstractMesh, _super);
  9280. // Constructor
  9281. function AbstractMesh(name, scene) {
  9282. var _this = this;
  9283. _super.call(this, name, scene);
  9284. // Events
  9285. /**
  9286. * An event triggered when the mesh is disposed.
  9287. * @type {BABYLON.Observable}
  9288. */
  9289. this.onDisposeObservable = new BABYLON.Observable();
  9290. /**
  9291. * An event triggered when this mesh collides with another one
  9292. * @type {BABYLON.Observable}
  9293. */
  9294. this.onCollideObservable = new BABYLON.Observable();
  9295. /**
  9296. * An event triggered when the collision's position changes
  9297. * @type {BABYLON.Observable}
  9298. */
  9299. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9300. /**
  9301. * An event triggered after the world matrix is updated
  9302. * @type {BABYLON.Observable}
  9303. */
  9304. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9305. // Properties
  9306. this.definedFacingForward = true; // orientation for POV movement & rotation
  9307. this.position = new BABYLON.Vector3(0, 0, 0);
  9308. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9309. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9310. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9311. this.visibility = 1.0;
  9312. this.alphaIndex = Number.MAX_VALUE;
  9313. this.infiniteDistance = false;
  9314. this.isVisible = true;
  9315. this.isPickable = true;
  9316. this.showBoundingBox = false;
  9317. this.showSubMeshesBoundingBox = false;
  9318. this.isBlocker = false;
  9319. this.renderingGroupId = 0;
  9320. this.receiveShadows = false;
  9321. this.renderOutline = false;
  9322. this.outlineColor = BABYLON.Color3.Red();
  9323. this.outlineWidth = 0.02;
  9324. this.renderOverlay = false;
  9325. this.overlayColor = BABYLON.Color3.Red();
  9326. this.overlayAlpha = 0.5;
  9327. this.hasVertexAlpha = false;
  9328. this.useVertexColors = true;
  9329. this.applyFog = true;
  9330. this.computeBonesUsingShaders = true;
  9331. this.scalingDeterminant = 1;
  9332. this.numBoneInfluencers = 4;
  9333. this.useOctreeForRenderingSelection = true;
  9334. this.useOctreeForPicking = true;
  9335. this.useOctreeForCollisions = true;
  9336. this.layerMask = 0x0FFFFFFF;
  9337. this.alwaysSelectAsActiveMesh = false;
  9338. // Collisions
  9339. this._checkCollisions = false;
  9340. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9341. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9342. this._collider = new BABYLON.Collider();
  9343. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9344. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9345. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9346. // Edges
  9347. this.edgesWidth = 1;
  9348. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9349. // Cache
  9350. this._localWorld = BABYLON.Matrix.Zero();
  9351. this._worldMatrix = BABYLON.Matrix.Zero();
  9352. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9353. this._absolutePosition = BABYLON.Vector3.Zero();
  9354. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9355. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9356. this._isDirty = false;
  9357. this._pivotMatrix = BABYLON.Matrix.Identity();
  9358. this._isDisposed = false;
  9359. this._renderId = 0;
  9360. this._intersectionsInProgress = new Array();
  9361. this._isWorldMatrixFrozen = false;
  9362. this._unIndexed = false;
  9363. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9364. if (collidedMesh === void 0) { collidedMesh = null; }
  9365. //TODO move this to the collision coordinator!
  9366. if (_this.getScene().workerCollisions)
  9367. newPosition.multiplyInPlace(_this._collider.radius);
  9368. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9369. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9370. _this.position.addInPlace(_this._diffPositionForCollisions);
  9371. }
  9372. if (collidedMesh) {
  9373. _this.onCollideObservable.notifyObservers(collidedMesh);
  9374. }
  9375. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9376. };
  9377. scene.addMesh(this);
  9378. }
  9379. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9380. get: function () {
  9381. return AbstractMesh._BILLBOARDMODE_NONE;
  9382. },
  9383. enumerable: true,
  9384. configurable: true
  9385. });
  9386. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9387. get: function () {
  9388. return AbstractMesh._BILLBOARDMODE_X;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9394. get: function () {
  9395. return AbstractMesh._BILLBOARDMODE_Y;
  9396. },
  9397. enumerable: true,
  9398. configurable: true
  9399. });
  9400. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9401. get: function () {
  9402. return AbstractMesh._BILLBOARDMODE_Z;
  9403. },
  9404. enumerable: true,
  9405. configurable: true
  9406. });
  9407. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9408. get: function () {
  9409. return AbstractMesh._BILLBOARDMODE_ALL;
  9410. },
  9411. enumerable: true,
  9412. configurable: true
  9413. });
  9414. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9415. set: function (callback) {
  9416. if (this._onDisposeObserver) {
  9417. this.onDisposeObservable.remove(this._onDisposeObserver);
  9418. }
  9419. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9425. set: function (callback) {
  9426. if (this._onCollideObserver) {
  9427. this.onCollideObservable.remove(this._onCollideObserver);
  9428. }
  9429. this._onCollideObserver = this.onCollideObservable.add(callback);
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9435. set: function (callback) {
  9436. if (this._onCollisionPositionChangeObserver) {
  9437. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9438. }
  9439. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9445. get: function () {
  9446. return this._skeleton;
  9447. },
  9448. set: function (value) {
  9449. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9450. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9451. }
  9452. if (value && value.needInitialSkinMatrix) {
  9453. value._registerMeshWithPoseMatrix(this);
  9454. }
  9455. this._skeleton = value;
  9456. if (!this._skeleton) {
  9457. this._bonesTransformMatrices = null;
  9458. }
  9459. },
  9460. enumerable: true,
  9461. configurable: true
  9462. });
  9463. /**
  9464. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9465. */
  9466. AbstractMesh.prototype.toString = function (fullDetails) {
  9467. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9468. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9469. if (this._skeleton) {
  9470. ret += ", skeleton: " + this._skeleton.name;
  9471. }
  9472. if (fullDetails) {
  9473. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9474. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9475. }
  9476. return ret;
  9477. };
  9478. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9479. /**
  9480. * Getting the rotation object.
  9481. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9482. */
  9483. get: function () {
  9484. return this._rotation;
  9485. },
  9486. set: function (newRotation) {
  9487. this._rotation = newRotation;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9493. get: function () {
  9494. return this._scaling;
  9495. },
  9496. set: function (newScaling) {
  9497. this._scaling = newScaling;
  9498. if (this.physicsImpostor) {
  9499. this.physicsImpostor.forceUpdate();
  9500. }
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9506. get: function () {
  9507. return this._rotationQuaternion;
  9508. },
  9509. set: function (quaternion) {
  9510. this._rotationQuaternion = quaternion;
  9511. //reset the rotation vector.
  9512. if (quaternion && this.rotation.length()) {
  9513. this.rotation.copyFromFloats(0, 0, 0);
  9514. }
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. // Methods
  9520. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9521. this._poseMatrix.copyFrom(matrix);
  9522. };
  9523. AbstractMesh.prototype.getPoseMatrix = function () {
  9524. return this._poseMatrix;
  9525. };
  9526. AbstractMesh.prototype.disableEdgesRendering = function () {
  9527. if (this._edgesRenderer !== undefined) {
  9528. this._edgesRenderer.dispose();
  9529. this._edgesRenderer = undefined;
  9530. }
  9531. };
  9532. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9533. if (epsilon === void 0) { epsilon = 0.95; }
  9534. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9535. this.disableEdgesRendering();
  9536. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9537. };
  9538. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9539. get: function () {
  9540. return false;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. AbstractMesh.prototype.getLOD = function (camera) {
  9546. return this;
  9547. };
  9548. AbstractMesh.prototype.getTotalVertices = function () {
  9549. return 0;
  9550. };
  9551. AbstractMesh.prototype.getIndices = function () {
  9552. return null;
  9553. };
  9554. AbstractMesh.prototype.getVerticesData = function (kind) {
  9555. return null;
  9556. };
  9557. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9558. return false;
  9559. };
  9560. AbstractMesh.prototype.getBoundingInfo = function () {
  9561. if (this._masterMesh) {
  9562. return this._masterMesh.getBoundingInfo();
  9563. }
  9564. if (!this._boundingInfo) {
  9565. this._updateBoundingInfo();
  9566. }
  9567. return this._boundingInfo;
  9568. };
  9569. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9570. this._boundingInfo = boundingInfo;
  9571. };
  9572. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9573. get: function () {
  9574. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. AbstractMesh.prototype._preActivate = function () {
  9580. };
  9581. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9582. };
  9583. AbstractMesh.prototype._activate = function (renderId) {
  9584. this._renderId = renderId;
  9585. };
  9586. AbstractMesh.prototype.getWorldMatrix = function () {
  9587. if (this._masterMesh) {
  9588. return this._masterMesh.getWorldMatrix();
  9589. }
  9590. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9591. this.computeWorldMatrix();
  9592. }
  9593. return this._worldMatrix;
  9594. };
  9595. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9596. get: function () {
  9597. return this._worldMatrix;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9603. get: function () {
  9604. return this._absolutePosition;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9610. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9611. this.computeWorldMatrix(true);
  9612. this._isWorldMatrixFrozen = true;
  9613. };
  9614. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9615. this._isWorldMatrixFrozen = false;
  9616. this.computeWorldMatrix(true);
  9617. };
  9618. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9619. get: function () {
  9620. return this._isWorldMatrixFrozen;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9626. axis.normalize();
  9627. if (!this.rotationQuaternion) {
  9628. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9629. this.rotation = BABYLON.Vector3.Zero();
  9630. }
  9631. var rotationQuaternion;
  9632. if (!space || space === BABYLON.Space.LOCAL) {
  9633. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9634. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9635. }
  9636. else {
  9637. if (this.parent) {
  9638. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9639. invertParentWorldMatrix.invert();
  9640. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9641. }
  9642. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9643. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9644. }
  9645. };
  9646. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9647. var displacementVector = axis.scale(distance);
  9648. if (!space || space === BABYLON.Space.LOCAL) {
  9649. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9650. this.setPositionWithLocalVector(tempV3);
  9651. }
  9652. else {
  9653. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9654. }
  9655. };
  9656. AbstractMesh.prototype.getAbsolutePosition = function () {
  9657. this.computeWorldMatrix();
  9658. return this._absolutePosition;
  9659. };
  9660. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9661. if (!absolutePosition) {
  9662. return;
  9663. }
  9664. var absolutePositionX;
  9665. var absolutePositionY;
  9666. var absolutePositionZ;
  9667. if (absolutePosition.x === undefined) {
  9668. if (arguments.length < 3) {
  9669. return;
  9670. }
  9671. absolutePositionX = arguments[0];
  9672. absolutePositionY = arguments[1];
  9673. absolutePositionZ = arguments[2];
  9674. }
  9675. else {
  9676. absolutePositionX = absolutePosition.x;
  9677. absolutePositionY = absolutePosition.y;
  9678. absolutePositionZ = absolutePosition.z;
  9679. }
  9680. if (this.parent) {
  9681. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9682. invertParentWorldMatrix.invert();
  9683. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9684. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9685. }
  9686. else {
  9687. this.position.x = absolutePositionX;
  9688. this.position.y = absolutePositionY;
  9689. this.position.z = absolutePositionZ;
  9690. }
  9691. };
  9692. // ================================== Point of View Movement =================================
  9693. /**
  9694. * Perform relative position change from the point of view of behind the front of the mesh.
  9695. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9696. * Supports definition of mesh facing forward or backward.
  9697. * @param {number} amountRight
  9698. * @param {number} amountUp
  9699. * @param {number} amountForward
  9700. */
  9701. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9702. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9703. };
  9704. /**
  9705. * Calculate relative position change from the point of view of behind the front of the mesh.
  9706. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9707. * Supports definition of mesh facing forward or backward.
  9708. * @param {number} amountRight
  9709. * @param {number} amountUp
  9710. * @param {number} amountForward
  9711. */
  9712. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9713. var rotMatrix = new BABYLON.Matrix();
  9714. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9715. rotQuaternion.toRotationMatrix(rotMatrix);
  9716. var translationDelta = BABYLON.Vector3.Zero();
  9717. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9719. return translationDelta;
  9720. };
  9721. // ================================== Point of View Rotation =================================
  9722. /**
  9723. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9724. * Supports definition of mesh facing forward or backward.
  9725. * @param {number} flipBack
  9726. * @param {number} twirlClockwise
  9727. * @param {number} tiltRight
  9728. */
  9729. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9730. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9731. };
  9732. /**
  9733. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9734. * Supports definition of mesh facing forward or backward.
  9735. * @param {number} flipBack
  9736. * @param {number} twirlClockwise
  9737. * @param {number} tiltRight
  9738. */
  9739. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9740. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9741. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9742. };
  9743. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9744. this._pivotMatrix = matrix;
  9745. this._cache.pivotMatrixUpdated = true;
  9746. };
  9747. AbstractMesh.prototype.getPivotMatrix = function () {
  9748. return this._pivotMatrix;
  9749. };
  9750. AbstractMesh.prototype._isSynchronized = function () {
  9751. if (this._isDirty) {
  9752. return false;
  9753. }
  9754. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9755. return false;
  9756. if (this._cache.pivotMatrixUpdated) {
  9757. return false;
  9758. }
  9759. if (this.infiniteDistance) {
  9760. return false;
  9761. }
  9762. if (!this._cache.position.equals(this.position))
  9763. return false;
  9764. if (this.rotationQuaternion) {
  9765. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9766. return false;
  9767. }
  9768. else {
  9769. if (!this._cache.rotation.equals(this.rotation))
  9770. return false;
  9771. }
  9772. if (!this._cache.scaling.equals(this.scaling))
  9773. return false;
  9774. return true;
  9775. };
  9776. AbstractMesh.prototype._initCache = function () {
  9777. _super.prototype._initCache.call(this);
  9778. this._cache.localMatrixUpdated = false;
  9779. this._cache.position = BABYLON.Vector3.Zero();
  9780. this._cache.scaling = BABYLON.Vector3.Zero();
  9781. this._cache.rotation = BABYLON.Vector3.Zero();
  9782. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9783. this._cache.billboardMode = -1;
  9784. };
  9785. AbstractMesh.prototype.markAsDirty = function (property) {
  9786. if (property === "rotation") {
  9787. this.rotationQuaternion = null;
  9788. }
  9789. this._currentRenderId = Number.MAX_VALUE;
  9790. this._isDirty = true;
  9791. };
  9792. AbstractMesh.prototype._updateBoundingInfo = function () {
  9793. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9794. this._boundingInfo.update(this.worldMatrixFromCache);
  9795. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9796. };
  9797. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9798. if (!this.subMeshes) {
  9799. return;
  9800. }
  9801. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9802. var subMesh = this.subMeshes[subIndex];
  9803. if (!subMesh.IsGlobal) {
  9804. subMesh.updateBoundingInfo(matrix);
  9805. }
  9806. }
  9807. };
  9808. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9809. if (this._isWorldMatrixFrozen) {
  9810. return this._worldMatrix;
  9811. }
  9812. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9813. this._currentRenderId = this.getScene().getRenderId();
  9814. return this._worldMatrix;
  9815. }
  9816. this._cache.position.copyFrom(this.position);
  9817. this._cache.scaling.copyFrom(this.scaling);
  9818. this._cache.pivotMatrixUpdated = false;
  9819. this._cache.billboardMode = this.billboardMode;
  9820. this._currentRenderId = this.getScene().getRenderId();
  9821. this._isDirty = false;
  9822. // Scaling
  9823. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9824. // Rotation
  9825. //rotate, if quaternion is set and rotation was used
  9826. if (this.rotationQuaternion) {
  9827. var len = this.rotation.length();
  9828. if (len) {
  9829. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9830. this.rotation.copyFromFloats(0, 0, 0);
  9831. }
  9832. }
  9833. if (this.rotationQuaternion) {
  9834. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9835. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9836. }
  9837. else {
  9838. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9839. this._cache.rotation.copyFrom(this.rotation);
  9840. }
  9841. // Translation
  9842. if (this.infiniteDistance && !this.parent) {
  9843. var camera = this.getScene().activeCamera;
  9844. if (camera) {
  9845. var cameraWorldMatrix = camera.getWorldMatrix();
  9846. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9847. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9848. }
  9849. }
  9850. else {
  9851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9852. }
  9853. // Composing transformations
  9854. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9855. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9856. // Billboarding
  9857. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9858. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9859. var localPosition = BABYLON.Tmp.Vector3[0];
  9860. if (this.parent && this.parent.getWorldMatrix) {
  9861. this._markSyncedWithParent();
  9862. var parentMatrix;
  9863. if (this._meshToBoneReferal) {
  9864. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9865. parentMatrix = BABYLON.Tmp.Matrix[6];
  9866. }
  9867. else {
  9868. parentMatrix = this.parent.getWorldMatrix();
  9869. }
  9870. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9871. localPosition = BABYLON.Tmp.Vector3[1];
  9872. }
  9873. var zero = this.getScene().activeCamera.globalPosition.clone();
  9874. if (this.parent && this.parent.position) {
  9875. localPosition.addInPlace(this.parent.position);
  9876. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9877. }
  9878. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9879. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9880. zero.x = localPosition.x + BABYLON.Epsilon;
  9881. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9882. zero.y = localPosition.y + BABYLON.Epsilon;
  9883. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9884. zero.z = localPosition.z + BABYLON.Epsilon;
  9885. }
  9886. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9887. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9888. BABYLON.Tmp.Matrix[3].invert();
  9889. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9890. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9891. }
  9892. // Local world
  9893. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9894. // Parent
  9895. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9896. this._markSyncedWithParent();
  9897. if (this._meshToBoneReferal) {
  9898. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9899. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9900. }
  9901. else {
  9902. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9903. }
  9904. }
  9905. else {
  9906. this._worldMatrix.copyFrom(this._localWorld);
  9907. }
  9908. // Bounding info
  9909. this._updateBoundingInfo();
  9910. // Absolute position
  9911. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9912. // Callbacks
  9913. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9914. if (!this._poseMatrix) {
  9915. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9916. }
  9917. return this._worldMatrix;
  9918. };
  9919. /**
  9920. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9921. * @param func: callback function to add
  9922. */
  9923. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9924. this.onAfterWorldMatrixUpdateObservable.add(func);
  9925. };
  9926. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9927. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9928. };
  9929. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9930. this.computeWorldMatrix();
  9931. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9932. };
  9933. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9934. this.computeWorldMatrix();
  9935. var invLocalWorldMatrix = this._localWorld.clone();
  9936. invLocalWorldMatrix.invert();
  9937. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9938. };
  9939. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9940. this.computeWorldMatrix(true);
  9941. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9942. };
  9943. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9944. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9945. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9946. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9947. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9948. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9949. /// <returns>Mesh oriented towards targetMesh</returns>
  9950. if (yawCor === void 0) { yawCor = 0; }
  9951. if (pitchCor === void 0) { pitchCor = 0; }
  9952. if (rollCor === void 0) { rollCor = 0; }
  9953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  9954. var dv = AbstractMesh._lookAtVectorCache;
  9955. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  9956. targetPoint.subtractToRef(pos, dv);
  9957. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9958. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9959. var pitch = Math.atan2(dv.y, len);
  9960. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  9961. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  9962. };
  9963. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9964. this._meshToBoneReferal = affectedMesh;
  9965. this.parent = bone;
  9966. if (bone.getWorldMatrix().determinant() < 0) {
  9967. this.scalingDeterminant *= -1;
  9968. }
  9969. };
  9970. AbstractMesh.prototype.detachFromBone = function () {
  9971. if (this.parent.getWorldMatrix().determinant() < 0) {
  9972. this.scalingDeterminant *= -1;
  9973. }
  9974. this._meshToBoneReferal = null;
  9975. this.parent = null;
  9976. };
  9977. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9978. return this._boundingInfo.isInFrustum(frustumPlanes);
  9979. };
  9980. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9981. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  9982. ;
  9983. };
  9984. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9985. if (!this._boundingInfo || !mesh._boundingInfo) {
  9986. return false;
  9987. }
  9988. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9989. };
  9990. AbstractMesh.prototype.intersectsPoint = function (point) {
  9991. if (!this._boundingInfo) {
  9992. return false;
  9993. }
  9994. return this._boundingInfo.intersectsPoint(point);
  9995. };
  9996. // Physics
  9997. /**
  9998. * @Deprecated. Use new PhysicsImpostor instead.
  9999. * */
  10000. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10001. //legacy support
  10002. if (impostor.impostor) {
  10003. options = impostor;
  10004. impostor = impostor.impostor;
  10005. }
  10006. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10007. return this.physicsImpostor.physicsBody;
  10008. };
  10009. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10010. return this.physicsImpostor;
  10011. };
  10012. /**
  10013. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10014. */
  10015. AbstractMesh.prototype.getPhysicsMass = function () {
  10016. return this.physicsImpostor.getParam("mass");
  10017. };
  10018. /**
  10019. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10020. */
  10021. AbstractMesh.prototype.getPhysicsFriction = function () {
  10022. return this.physicsImpostor.getParam("friction");
  10023. };
  10024. /**
  10025. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10026. */
  10027. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10028. return this.physicsImpostor.getParam("restitution");
  10029. };
  10030. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10031. if (!camera) {
  10032. camera = this.getScene().activeCamera;
  10033. }
  10034. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10035. };
  10036. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10037. if (!camera) {
  10038. camera = this.getScene().activeCamera;
  10039. }
  10040. return this.absolutePosition.subtract(camera.position).length();
  10041. };
  10042. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10043. if (!this.physicsImpostor) {
  10044. return;
  10045. }
  10046. this.physicsImpostor.applyImpulse(force, contactPoint);
  10047. };
  10048. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10049. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10050. return;
  10051. }
  10052. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10053. mainPivot: pivot1,
  10054. connectedPivot: pivot2,
  10055. nativeParams: options
  10056. });
  10057. };
  10058. /**
  10059. * @Deprecated
  10060. */
  10061. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10062. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10063. this.updatePhysicsBody();
  10064. };
  10065. /**
  10066. * @Deprecated
  10067. * Calling this function is not needed anymore.
  10068. * The physics engine takes care of transofmration automatically.
  10069. */
  10070. AbstractMesh.prototype.updatePhysicsBody = function () {
  10071. //Unneeded
  10072. };
  10073. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10074. // Collisions
  10075. get: function () {
  10076. return this._checkCollisions;
  10077. },
  10078. set: function (collisionEnabled) {
  10079. this._checkCollisions = collisionEnabled;
  10080. if (this.getScene().workerCollisions) {
  10081. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10082. }
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10088. var globalPosition = this.getAbsolutePosition();
  10089. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10090. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10091. this._collider.radius = this.ellipsoid;
  10092. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10093. };
  10094. // Submeshes octree
  10095. /**
  10096. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10097. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10098. */
  10099. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10100. if (maxCapacity === void 0) { maxCapacity = 64; }
  10101. if (maxDepth === void 0) { maxDepth = 2; }
  10102. if (!this._submeshesOctree) {
  10103. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10104. }
  10105. this.computeWorldMatrix(true);
  10106. // Update octree
  10107. var bbox = this.getBoundingInfo().boundingBox;
  10108. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10109. return this._submeshesOctree;
  10110. };
  10111. // Collisions
  10112. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10113. this._generatePointsArray();
  10114. // Transformation
  10115. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10116. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10117. subMesh._lastColliderWorldVertices = [];
  10118. subMesh._trianglePlanes = [];
  10119. var start = subMesh.verticesStart;
  10120. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10121. for (var i = start; i < end; i++) {
  10122. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10123. }
  10124. }
  10125. // Collide
  10126. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10127. if (collider.collisionFound) {
  10128. collider.collidedMesh = this;
  10129. }
  10130. };
  10131. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10132. var subMeshes;
  10133. var len;
  10134. // Octrees
  10135. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10136. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10137. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10138. len = intersections.length;
  10139. subMeshes = intersections.data;
  10140. }
  10141. else {
  10142. subMeshes = this.subMeshes;
  10143. len = subMeshes.length;
  10144. }
  10145. for (var index = 0; index < len; index++) {
  10146. var subMesh = subMeshes[index];
  10147. // Bounding test
  10148. if (len > 1 && !subMesh._checkCollision(collider))
  10149. continue;
  10150. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10151. }
  10152. };
  10153. AbstractMesh.prototype._checkCollision = function (collider) {
  10154. // Bounding box test
  10155. if (!this._boundingInfo._checkCollision(collider))
  10156. return;
  10157. // Transformation matrix
  10158. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10159. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10160. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10161. };
  10162. // Picking
  10163. AbstractMesh.prototype._generatePointsArray = function () {
  10164. return false;
  10165. };
  10166. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10167. var pickingInfo = new BABYLON.PickingInfo();
  10168. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10169. return pickingInfo;
  10170. }
  10171. if (!this._generatePointsArray()) {
  10172. return pickingInfo;
  10173. }
  10174. var intersectInfo = null;
  10175. // Octrees
  10176. var subMeshes;
  10177. var len;
  10178. if (this._submeshesOctree && this.useOctreeForPicking) {
  10179. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10180. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10181. len = intersections.length;
  10182. subMeshes = intersections.data;
  10183. }
  10184. else {
  10185. subMeshes = this.subMeshes;
  10186. len = subMeshes.length;
  10187. }
  10188. for (var index = 0; index < len; index++) {
  10189. var subMesh = subMeshes[index];
  10190. // Bounding test
  10191. if (len > 1 && !subMesh.canIntersects(ray))
  10192. continue;
  10193. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10194. if (currentIntersectInfo) {
  10195. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10196. intersectInfo = currentIntersectInfo;
  10197. intersectInfo.subMeshId = index;
  10198. if (fastCheck) {
  10199. break;
  10200. }
  10201. }
  10202. }
  10203. }
  10204. if (intersectInfo) {
  10205. // Get picked point
  10206. var world = this.getWorldMatrix();
  10207. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10208. var direction = ray.direction.clone();
  10209. direction = direction.scale(intersectInfo.distance);
  10210. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10211. var pickedPoint = worldOrigin.add(worldDirection);
  10212. // Return result
  10213. pickingInfo.hit = true;
  10214. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10215. pickingInfo.pickedPoint = pickedPoint;
  10216. pickingInfo.pickedMesh = this;
  10217. pickingInfo.bu = intersectInfo.bu;
  10218. pickingInfo.bv = intersectInfo.bv;
  10219. pickingInfo.faceId = intersectInfo.faceId;
  10220. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10221. return pickingInfo;
  10222. }
  10223. return pickingInfo;
  10224. };
  10225. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10226. return null;
  10227. };
  10228. AbstractMesh.prototype.releaseSubMeshes = function () {
  10229. if (this.subMeshes) {
  10230. while (this.subMeshes.length) {
  10231. this.subMeshes[0].dispose();
  10232. }
  10233. }
  10234. else {
  10235. this.subMeshes = new Array();
  10236. }
  10237. };
  10238. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10239. var _this = this;
  10240. var index;
  10241. // Action manager
  10242. if (this.actionManager) {
  10243. this.actionManager.dispose();
  10244. this.actionManager = null;
  10245. }
  10246. // Skeleton
  10247. this.skeleton = null;
  10248. // Animations
  10249. this.getScene().stopAnimation(this);
  10250. // Physics
  10251. if (this.physicsImpostor) {
  10252. this.physicsImpostor.dispose();
  10253. }
  10254. // Intersections in progress
  10255. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10256. var other = this._intersectionsInProgress[index];
  10257. var pos = other._intersectionsInProgress.indexOf(this);
  10258. other._intersectionsInProgress.splice(pos, 1);
  10259. }
  10260. this._intersectionsInProgress = [];
  10261. // Lights
  10262. var lights = this.getScene().lights;
  10263. lights.forEach(function (light) {
  10264. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10265. if (meshIndex !== -1) {
  10266. light.includedOnlyMeshes.splice(meshIndex, 1);
  10267. }
  10268. meshIndex = light.excludedMeshes.indexOf(_this);
  10269. if (meshIndex !== -1) {
  10270. light.excludedMeshes.splice(meshIndex, 1);
  10271. }
  10272. });
  10273. // Edges
  10274. if (this._edgesRenderer) {
  10275. this._edgesRenderer.dispose();
  10276. this._edgesRenderer = null;
  10277. }
  10278. // SubMeshes
  10279. this.releaseSubMeshes();
  10280. // Remove from scene
  10281. this.getScene().removeMesh(this);
  10282. if (!doNotRecurse) {
  10283. // Particles
  10284. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10285. if (this.getScene().particleSystems[index].emitter === this) {
  10286. this.getScene().particleSystems[index].dispose();
  10287. index--;
  10288. }
  10289. }
  10290. // Children
  10291. var objects = this.getDescendants(true);
  10292. for (index = 0; index < objects.length; index++) {
  10293. objects[index].dispose();
  10294. }
  10295. }
  10296. else {
  10297. var childMeshes = this.getChildMeshes(true);
  10298. for (index = 0; index < childMeshes.length; index++) {
  10299. var child = childMeshes[index];
  10300. child.parent = null;
  10301. child.computeWorldMatrix(true);
  10302. }
  10303. }
  10304. _super.prototype.dispose.call(this);
  10305. this.onAfterWorldMatrixUpdateObservable.clear();
  10306. this.onCollideObservable.clear();
  10307. this.onCollisionPositionChangeObservable.clear();
  10308. this._isDisposed = true;
  10309. // Callback
  10310. this.onDisposeObservable.notifyObservers(this);
  10311. this.onDisposeObservable.clear();
  10312. };
  10313. // Statics
  10314. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10315. AbstractMesh._BILLBOARDMODE_X = 1;
  10316. AbstractMesh._BILLBOARDMODE_Y = 2;
  10317. AbstractMesh._BILLBOARDMODE_Z = 4;
  10318. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10319. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10320. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10321. return AbstractMesh;
  10322. }(BABYLON.Node));
  10323. BABYLON.AbstractMesh = AbstractMesh;
  10324. })(BABYLON || (BABYLON = {}));
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var Light = (function (_super) {
  10328. __extends(Light, _super);
  10329. function Light(name, scene) {
  10330. _super.call(this, name, scene);
  10331. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10332. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10333. this.intensity = 1.0;
  10334. this.range = Number.MAX_VALUE;
  10335. this.includeOnlyWithLayerMask = 0;
  10336. this.includedOnlyMeshes = new Array();
  10337. this.excludedMeshes = new Array();
  10338. this.excludeWithLayerMask = 0;
  10339. // PBR Properties.
  10340. this.radius = 0.00001;
  10341. this._excludedMeshesIds = new Array();
  10342. this._includedOnlyMeshesIds = new Array();
  10343. scene.addLight(this);
  10344. }
  10345. /**
  10346. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10347. */
  10348. Light.prototype.toString = function (fullDetails) {
  10349. var ret = "Name: " + this.name;
  10350. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10351. if (this.animations) {
  10352. for (var i = 0; i < this.animations.length; i++) {
  10353. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10354. }
  10355. }
  10356. if (fullDetails) {
  10357. }
  10358. return ret;
  10359. };
  10360. Light.prototype.getShadowGenerator = function () {
  10361. return this._shadowGenerator;
  10362. };
  10363. Light.prototype.getAbsolutePosition = function () {
  10364. return BABYLON.Vector3.Zero();
  10365. };
  10366. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10367. };
  10368. Light.prototype._getWorldMatrix = function () {
  10369. return BABYLON.Matrix.Identity();
  10370. };
  10371. Light.prototype.canAffectMesh = function (mesh) {
  10372. if (!mesh) {
  10373. return true;
  10374. }
  10375. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10376. return false;
  10377. }
  10378. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10379. return false;
  10380. }
  10381. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10382. return false;
  10383. }
  10384. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10385. return false;
  10386. }
  10387. return true;
  10388. };
  10389. Light.prototype.getWorldMatrix = function () {
  10390. this._currentRenderId = this.getScene().getRenderId();
  10391. var worldMatrix = this._getWorldMatrix();
  10392. if (this.parent && this.parent.getWorldMatrix) {
  10393. if (!this._parentedWorldMatrix) {
  10394. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10395. }
  10396. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10397. this._markSyncedWithParent();
  10398. return this._parentedWorldMatrix;
  10399. }
  10400. return worldMatrix;
  10401. };
  10402. Light.prototype.dispose = function () {
  10403. if (this._shadowGenerator) {
  10404. this._shadowGenerator.dispose();
  10405. this._shadowGenerator = null;
  10406. }
  10407. // Animations
  10408. this.getScene().stopAnimation(this);
  10409. // Remove from scene
  10410. this.getScene().removeLight(this);
  10411. _super.prototype.dispose.call(this);
  10412. };
  10413. Light.prototype.getTypeID = function () {
  10414. return 0;
  10415. };
  10416. Light.prototype.clone = function (name) {
  10417. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10418. };
  10419. Light.prototype.serialize = function () {
  10420. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10421. // Type
  10422. serializationObject.type = this.getTypeID();
  10423. // Parent
  10424. if (this.parent) {
  10425. serializationObject.parentId = this.parent.id;
  10426. }
  10427. // Inclusion / exclusions
  10428. if (this.excludedMeshes.length > 0) {
  10429. serializationObject.excludedMeshesIds = [];
  10430. this.excludedMeshes.forEach(function (mesh) {
  10431. serializationObject.excludedMeshesIds.push(mesh.id);
  10432. });
  10433. }
  10434. if (this.includedOnlyMeshes.length > 0) {
  10435. serializationObject.includedOnlyMeshesIds = [];
  10436. this.includedOnlyMeshes.forEach(function (mesh) {
  10437. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10438. });
  10439. }
  10440. // Animations
  10441. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10442. serializationObject.ranges = this.serializeAnimationRanges();
  10443. return serializationObject;
  10444. };
  10445. Light.GetConstructorFromName = function (type, name, scene) {
  10446. switch (type) {
  10447. case 0:
  10448. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10449. case 1:
  10450. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10451. case 2:
  10452. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10453. case 3:
  10454. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10455. }
  10456. };
  10457. Light.Parse = function (parsedLight, scene) {
  10458. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10459. // Inclusion / exclusions
  10460. if (parsedLight.excludedMeshesIds) {
  10461. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10462. }
  10463. if (parsedLight.includedOnlyMeshesIds) {
  10464. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10465. }
  10466. // Parent
  10467. if (parsedLight.parentId) {
  10468. light._waitingParentId = parsedLight.parentId;
  10469. }
  10470. // Animations
  10471. if (parsedLight.animations) {
  10472. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10473. var parsedAnimation = parsedLight.animations[animationIndex];
  10474. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10475. }
  10476. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10477. }
  10478. if (parsedLight.autoAnimate) {
  10479. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10480. }
  10481. return light;
  10482. };
  10483. __decorate([
  10484. BABYLON.serializeAsColor3()
  10485. ], Light.prototype, "diffuse", void 0);
  10486. __decorate([
  10487. BABYLON.serializeAsColor3()
  10488. ], Light.prototype, "specular", void 0);
  10489. __decorate([
  10490. BABYLON.serialize()
  10491. ], Light.prototype, "intensity", void 0);
  10492. __decorate([
  10493. BABYLON.serialize()
  10494. ], Light.prototype, "range", void 0);
  10495. __decorate([
  10496. BABYLON.serialize()
  10497. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10498. __decorate([
  10499. BABYLON.serialize()
  10500. ], Light.prototype, "excludeWithLayerMask", void 0);
  10501. __decorate([
  10502. BABYLON.serialize()
  10503. ], Light.prototype, "radius", void 0);
  10504. return Light;
  10505. }(BABYLON.Node));
  10506. BABYLON.Light = Light;
  10507. })(BABYLON || (BABYLON = {}));
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. var PointLight = (function (_super) {
  10511. __extends(PointLight, _super);
  10512. function PointLight(name, position, scene) {
  10513. _super.call(this, name, scene);
  10514. this.position = position;
  10515. }
  10516. PointLight.prototype.getAbsolutePosition = function () {
  10517. return this.transformedPosition ? this.transformedPosition : this.position;
  10518. };
  10519. PointLight.prototype.computeTransformedPosition = function () {
  10520. if (this.parent && this.parent.getWorldMatrix) {
  10521. if (!this.transformedPosition) {
  10522. this.transformedPosition = BABYLON.Vector3.Zero();
  10523. }
  10524. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10525. return true;
  10526. }
  10527. return false;
  10528. };
  10529. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10530. if (this.parent && this.parent.getWorldMatrix) {
  10531. this.computeTransformedPosition();
  10532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10533. return;
  10534. }
  10535. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10536. };
  10537. PointLight.prototype.needCube = function () {
  10538. return true;
  10539. };
  10540. PointLight.prototype.supportsVSM = function () {
  10541. return false;
  10542. };
  10543. PointLight.prototype.needRefreshPerFrame = function () {
  10544. return false;
  10545. };
  10546. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10547. switch (faceIndex) {
  10548. case 0:
  10549. return new BABYLON.Vector3(1, 0, 0);
  10550. case 1:
  10551. return new BABYLON.Vector3(-1, 0, 0);
  10552. case 2:
  10553. return new BABYLON.Vector3(0, -1, 0);
  10554. case 3:
  10555. return new BABYLON.Vector3(0, 1, 0);
  10556. case 4:
  10557. return new BABYLON.Vector3(0, 0, 1);
  10558. case 5:
  10559. return new BABYLON.Vector3(0, 0, -1);
  10560. }
  10561. return BABYLON.Vector3.Zero();
  10562. };
  10563. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10564. var activeCamera = this.getScene().activeCamera;
  10565. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10566. };
  10567. PointLight.prototype._getWorldMatrix = function () {
  10568. if (!this._worldMatrix) {
  10569. this._worldMatrix = BABYLON.Matrix.Identity();
  10570. }
  10571. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10572. return this._worldMatrix;
  10573. };
  10574. PointLight.prototype.getTypeID = function () {
  10575. return 0;
  10576. };
  10577. __decorate([
  10578. BABYLON.serializeAsVector3()
  10579. ], PointLight.prototype, "position", void 0);
  10580. return PointLight;
  10581. }(BABYLON.Light));
  10582. BABYLON.PointLight = PointLight;
  10583. })(BABYLON || (BABYLON = {}));
  10584. var BABYLON;
  10585. (function (BABYLON) {
  10586. var SpotLight = (function (_super) {
  10587. __extends(SpotLight, _super);
  10588. function SpotLight(name, position, direction, angle, exponent, scene) {
  10589. _super.call(this, name, scene);
  10590. this.position = position;
  10591. this.direction = direction;
  10592. this.angle = angle;
  10593. this.exponent = exponent;
  10594. }
  10595. SpotLight.prototype.getAbsolutePosition = function () {
  10596. return this.transformedPosition ? this.transformedPosition : this.position;
  10597. };
  10598. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10599. var activeCamera = this.getScene().activeCamera;
  10600. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10601. };
  10602. SpotLight.prototype.needCube = function () {
  10603. return false;
  10604. };
  10605. SpotLight.prototype.supportsVSM = function () {
  10606. return true;
  10607. };
  10608. SpotLight.prototype.needRefreshPerFrame = function () {
  10609. return false;
  10610. };
  10611. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10612. return this.direction;
  10613. };
  10614. SpotLight.prototype.setDirectionToTarget = function (target) {
  10615. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10616. return this.direction;
  10617. };
  10618. SpotLight.prototype.computeTransformedPosition = function () {
  10619. if (this.parent && this.parent.getWorldMatrix) {
  10620. if (!this.transformedPosition) {
  10621. this.transformedPosition = BABYLON.Vector3.Zero();
  10622. }
  10623. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10624. return true;
  10625. }
  10626. return false;
  10627. };
  10628. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10629. var normalizeDirection;
  10630. if (this.parent && this.parent.getWorldMatrix) {
  10631. if (!this._transformedDirection) {
  10632. this._transformedDirection = BABYLON.Vector3.Zero();
  10633. }
  10634. this.computeTransformedPosition();
  10635. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10636. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10637. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10638. }
  10639. else {
  10640. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10641. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10642. }
  10643. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10644. };
  10645. SpotLight.prototype._getWorldMatrix = function () {
  10646. if (!this._worldMatrix) {
  10647. this._worldMatrix = BABYLON.Matrix.Identity();
  10648. }
  10649. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10650. return this._worldMatrix;
  10651. };
  10652. SpotLight.prototype.getTypeID = function () {
  10653. return 2;
  10654. };
  10655. __decorate([
  10656. BABYLON.serializeAsVector3()
  10657. ], SpotLight.prototype, "position", void 0);
  10658. __decorate([
  10659. BABYLON.serializeAsVector3()
  10660. ], SpotLight.prototype, "direction", void 0);
  10661. __decorate([
  10662. BABYLON.serialize()
  10663. ], SpotLight.prototype, "angle", void 0);
  10664. __decorate([
  10665. BABYLON.serialize()
  10666. ], SpotLight.prototype, "exponent", void 0);
  10667. return SpotLight;
  10668. }(BABYLON.Light));
  10669. BABYLON.SpotLight = SpotLight;
  10670. })(BABYLON || (BABYLON = {}));
  10671. var BABYLON;
  10672. (function (BABYLON) {
  10673. var HemisphericLight = (function (_super) {
  10674. __extends(HemisphericLight, _super);
  10675. function HemisphericLight(name, direction, scene) {
  10676. _super.call(this, name, scene);
  10677. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10678. this.direction = direction;
  10679. }
  10680. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10681. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10682. return this.direction;
  10683. };
  10684. HemisphericLight.prototype.getShadowGenerator = function () {
  10685. return null;
  10686. };
  10687. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10688. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10689. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10690. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10691. };
  10692. HemisphericLight.prototype._getWorldMatrix = function () {
  10693. if (!this._worldMatrix) {
  10694. this._worldMatrix = BABYLON.Matrix.Identity();
  10695. }
  10696. return this._worldMatrix;
  10697. };
  10698. HemisphericLight.prototype.getTypeID = function () {
  10699. return 3;
  10700. };
  10701. __decorate([
  10702. BABYLON.serializeAsColor3()
  10703. ], HemisphericLight.prototype, "groundColor", void 0);
  10704. __decorate([
  10705. BABYLON.serializeAsVector3()
  10706. ], HemisphericLight.prototype, "direction", void 0);
  10707. return HemisphericLight;
  10708. }(BABYLON.Light));
  10709. BABYLON.HemisphericLight = HemisphericLight;
  10710. })(BABYLON || (BABYLON = {}));
  10711. var BABYLON;
  10712. (function (BABYLON) {
  10713. var DirectionalLight = (function (_super) {
  10714. __extends(DirectionalLight, _super);
  10715. function DirectionalLight(name, direction, scene) {
  10716. _super.call(this, name, scene);
  10717. this.shadowOrthoScale = 0.5;
  10718. this.autoUpdateExtends = true;
  10719. // Cache
  10720. this._orthoLeft = Number.MAX_VALUE;
  10721. this._orthoRight = Number.MIN_VALUE;
  10722. this._orthoTop = Number.MIN_VALUE;
  10723. this._orthoBottom = Number.MAX_VALUE;
  10724. this.position = direction.scale(-1);
  10725. this.direction = direction;
  10726. }
  10727. DirectionalLight.prototype.getAbsolutePosition = function () {
  10728. return this.transformedPosition ? this.transformedPosition : this.position;
  10729. };
  10730. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10731. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10732. return this.direction;
  10733. };
  10734. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10735. var activeCamera = this.getScene().activeCamera;
  10736. // Check extends
  10737. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10738. var tempVector3 = BABYLON.Vector3.Zero();
  10739. this._orthoLeft = Number.MAX_VALUE;
  10740. this._orthoRight = Number.MIN_VALUE;
  10741. this._orthoTop = Number.MIN_VALUE;
  10742. this._orthoBottom = Number.MAX_VALUE;
  10743. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10744. var mesh = renderList[meshIndex];
  10745. if (!mesh) {
  10746. continue;
  10747. }
  10748. var boundingInfo = mesh.getBoundingInfo();
  10749. if (!boundingInfo) {
  10750. continue;
  10751. }
  10752. var boundingBox = boundingInfo.boundingBox;
  10753. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10754. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10755. if (tempVector3.x < this._orthoLeft)
  10756. this._orthoLeft = tempVector3.x;
  10757. if (tempVector3.y < this._orthoBottom)
  10758. this._orthoBottom = tempVector3.y;
  10759. if (tempVector3.x > this._orthoRight)
  10760. this._orthoRight = tempVector3.x;
  10761. if (tempVector3.y > this._orthoTop)
  10762. this._orthoTop = tempVector3.y;
  10763. }
  10764. }
  10765. }
  10766. var xOffset = this._orthoRight - this._orthoLeft;
  10767. var yOffset = this._orthoTop - this._orthoBottom;
  10768. 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);
  10769. };
  10770. DirectionalLight.prototype.supportsVSM = function () {
  10771. return true;
  10772. };
  10773. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10774. return true;
  10775. };
  10776. DirectionalLight.prototype.needCube = function () {
  10777. return false;
  10778. };
  10779. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10780. return this.direction;
  10781. };
  10782. DirectionalLight.prototype.computeTransformedPosition = function () {
  10783. if (this.parent && this.parent.getWorldMatrix) {
  10784. if (!this.transformedPosition) {
  10785. this.transformedPosition = BABYLON.Vector3.Zero();
  10786. }
  10787. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10788. return true;
  10789. }
  10790. return false;
  10791. };
  10792. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10793. if (this.parent && this.parent.getWorldMatrix) {
  10794. if (!this._transformedDirection) {
  10795. this._transformedDirection = BABYLON.Vector3.Zero();
  10796. }
  10797. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10798. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10799. return;
  10800. }
  10801. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10802. };
  10803. DirectionalLight.prototype._getWorldMatrix = function () {
  10804. if (!this._worldMatrix) {
  10805. this._worldMatrix = BABYLON.Matrix.Identity();
  10806. }
  10807. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10808. return this._worldMatrix;
  10809. };
  10810. DirectionalLight.prototype.getTypeID = function () {
  10811. return 1;
  10812. };
  10813. __decorate([
  10814. BABYLON.serializeAsVector3()
  10815. ], DirectionalLight.prototype, "position", void 0);
  10816. __decorate([
  10817. BABYLON.serializeAsVector3()
  10818. ], DirectionalLight.prototype, "direction", void 0);
  10819. __decorate([
  10820. BABYLON.serialize()
  10821. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10822. __decorate([
  10823. BABYLON.serialize()
  10824. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10825. return DirectionalLight;
  10826. }(BABYLON.Light));
  10827. BABYLON.DirectionalLight = DirectionalLight;
  10828. })(BABYLON || (BABYLON = {}));
  10829. var BABYLON;
  10830. (function (BABYLON) {
  10831. var ShadowGenerator = (function () {
  10832. function ShadowGenerator(mapSize, light) {
  10833. var _this = this;
  10834. // Members
  10835. this._filter = ShadowGenerator.FILTER_NONE;
  10836. this.blurScale = 2;
  10837. this._blurBoxOffset = 0;
  10838. this._bias = 0.00005;
  10839. this._lightDirection = BABYLON.Vector3.Zero();
  10840. this.forceBackFacesOnly = false;
  10841. this._darkness = 0;
  10842. this._transparencyShadow = false;
  10843. this._viewMatrix = BABYLON.Matrix.Zero();
  10844. this._projectionMatrix = BABYLON.Matrix.Zero();
  10845. this._transformMatrix = BABYLON.Matrix.Zero();
  10846. this._worldViewProjection = BABYLON.Matrix.Zero();
  10847. this._currentFaceIndex = 0;
  10848. this._currentFaceIndexCache = 0;
  10849. this._useFullFloat = true;
  10850. this._light = light;
  10851. this._scene = light.getScene();
  10852. this._mapSize = mapSize;
  10853. light._shadowGenerator = this;
  10854. // Texture type fallback from float to int if not supported.
  10855. var textureType;
  10856. var caps = this._scene.getEngine().getCaps();
  10857. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  10858. this._useFullFloat = true;
  10859. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  10860. }
  10861. else {
  10862. this._useFullFloat = false;
  10863. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  10864. }
  10865. // Render target
  10866. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  10867. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10868. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10869. this._shadowMap.anisotropicFilteringLevel = 1;
  10870. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10871. this._shadowMap.renderParticles = false;
  10872. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10873. _this._currentFaceIndex = faceIndex;
  10874. });
  10875. this._shadowMap.onAfterUnbindObservable.add(function () {
  10876. if (!_this.useBlurVarianceShadowMap) {
  10877. return;
  10878. }
  10879. if (!_this._shadowMap2) {
  10880. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  10881. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10882. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10883. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10884. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10885. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10886. effect.setTexture("textureSampler", _this._shadowMap);
  10887. });
  10888. _this.blurBoxOffset = 1;
  10889. }
  10890. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10891. });
  10892. // Custom render function
  10893. var renderSubMesh = function (subMesh) {
  10894. var mesh = subMesh.getRenderingMesh();
  10895. var scene = _this._scene;
  10896. var engine = scene.getEngine();
  10897. // Culling
  10898. engine.setState(subMesh.getMaterial().backFaceCulling);
  10899. // Managing instances
  10900. var batch = mesh._getInstancesRenderList(subMesh._id);
  10901. if (batch.mustReturn) {
  10902. return;
  10903. }
  10904. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10905. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10906. engine.enableEffect(_this._effect);
  10907. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10908. var material = subMesh.getMaterial();
  10909. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10910. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10911. if (_this.getLight().needCube()) {
  10912. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10913. }
  10914. // Alpha test
  10915. if (material && material.needAlphaTesting()) {
  10916. var alphaTexture = material.getAlphaTestTexture();
  10917. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10918. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10919. }
  10920. // Bones
  10921. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10922. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10923. }
  10924. if (_this.forceBackFacesOnly) {
  10925. engine.setState(true, 0, false, true);
  10926. }
  10927. // Draw
  10928. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10929. if (_this.forceBackFacesOnly) {
  10930. engine.setState(true, 0, false, false);
  10931. }
  10932. }
  10933. else {
  10934. // Need to reset refresh rate of the shadowMap
  10935. _this._shadowMap.resetRefreshCounter();
  10936. }
  10937. };
  10938. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10939. var index;
  10940. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10941. renderSubMesh(opaqueSubMeshes.data[index]);
  10942. }
  10943. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10944. renderSubMesh(alphaTestSubMeshes.data[index]);
  10945. }
  10946. if (_this._transparencyShadow) {
  10947. for (index = 0; index < transparentSubMeshes.length; index++) {
  10948. renderSubMesh(transparentSubMeshes.data[index]);
  10949. }
  10950. }
  10951. };
  10952. this._shadowMap.onClearObservable.add(function (engine) {
  10953. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10954. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10955. }
  10956. else {
  10957. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10958. }
  10959. });
  10960. }
  10961. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10962. // Static
  10963. get: function () {
  10964. return ShadowGenerator._FILTER_NONE;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10970. get: function () {
  10971. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10977. get: function () {
  10978. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10984. get: function () {
  10985. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10991. get: function () {
  10992. return this._bias;
  10993. },
  10994. set: function (bias) {
  10995. this._bias = bias;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11001. get: function () {
  11002. return this._blurBoxOffset;
  11003. },
  11004. set: function (value) {
  11005. var _this = this;
  11006. if (this._blurBoxOffset === value) {
  11007. return;
  11008. }
  11009. this._blurBoxOffset = value;
  11010. if (this._boxBlurPostprocess) {
  11011. this._boxBlurPostprocess.dispose();
  11012. }
  11013. 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);
  11014. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11015. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11016. });
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11022. get: function () {
  11023. return this._filter;
  11024. },
  11025. set: function (value) {
  11026. if (this._filter === value) {
  11027. return;
  11028. }
  11029. this._filter = value;
  11030. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11031. this._shadowMap.anisotropicFilteringLevel = 16;
  11032. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11033. }
  11034. else {
  11035. this._shadowMap.anisotropicFilteringLevel = 1;
  11036. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11037. }
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11043. get: function () {
  11044. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11045. },
  11046. set: function (value) {
  11047. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11053. get: function () {
  11054. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11055. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11056. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11057. },
  11058. set: function (value) {
  11059. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11065. get: function () {
  11066. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11067. },
  11068. set: function (value) {
  11069. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11075. var defines = [];
  11076. if (this._useFullFloat) {
  11077. defines.push("#define FULLFLOAT");
  11078. }
  11079. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11080. defines.push("#define VSM");
  11081. }
  11082. if (this.getLight().needCube()) {
  11083. defines.push("#define CUBEMAP");
  11084. }
  11085. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11086. var mesh = subMesh.getMesh();
  11087. var material = subMesh.getMaterial();
  11088. // Alpha test
  11089. if (material && material.needAlphaTesting()) {
  11090. defines.push("#define ALPHATEST");
  11091. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11092. attribs.push(BABYLON.VertexBuffer.UVKind);
  11093. defines.push("#define UV1");
  11094. }
  11095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11096. var alphaTexture = material.getAlphaTestTexture();
  11097. if (alphaTexture.coordinatesIndex === 1) {
  11098. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11099. defines.push("#define UV2");
  11100. }
  11101. }
  11102. }
  11103. // Bones
  11104. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11107. if (mesh.numBoneInfluencers > 4) {
  11108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11110. }
  11111. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11112. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11113. }
  11114. else {
  11115. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11116. }
  11117. // Instances
  11118. if (useInstances) {
  11119. defines.push("#define INSTANCES");
  11120. attribs.push("world0");
  11121. attribs.push("world1");
  11122. attribs.push("world2");
  11123. attribs.push("world3");
  11124. }
  11125. // Get correct effect
  11126. var join = defines.join("\n");
  11127. if (this._cachedDefines !== join) {
  11128. this._cachedDefines = join;
  11129. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11130. }
  11131. return this._effect.isReady();
  11132. };
  11133. ShadowGenerator.prototype.getShadowMap = function () {
  11134. return this._shadowMap;
  11135. };
  11136. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11137. if (this._shadowMap2) {
  11138. return this._shadowMap2;
  11139. }
  11140. return this._shadowMap;
  11141. };
  11142. ShadowGenerator.prototype.getLight = function () {
  11143. return this._light;
  11144. };
  11145. // Methods
  11146. ShadowGenerator.prototype.getTransformMatrix = function () {
  11147. var scene = this._scene;
  11148. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11149. return this._transformMatrix;
  11150. }
  11151. this._currentRenderID = scene.getRenderId();
  11152. this._currentFaceIndexCache = this._currentFaceIndex;
  11153. var lightPosition = this._light.position;
  11154. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11155. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11156. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11157. }
  11158. if (this._light.computeTransformedPosition()) {
  11159. lightPosition = this._light.transformedPosition;
  11160. }
  11161. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11162. this._cachedPosition = lightPosition.clone();
  11163. this._cachedDirection = this._lightDirection.clone();
  11164. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11165. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11166. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11167. }
  11168. return this._transformMatrix;
  11169. };
  11170. ShadowGenerator.prototype.getDarkness = function () {
  11171. return this._darkness;
  11172. };
  11173. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11174. if (darkness >= 1.0)
  11175. this._darkness = 1.0;
  11176. else if (darkness <= 0.0)
  11177. this._darkness = 0.0;
  11178. else
  11179. this._darkness = darkness;
  11180. };
  11181. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11182. this._transparencyShadow = hasShadow;
  11183. };
  11184. ShadowGenerator.prototype._packHalf = function (depth) {
  11185. var scale = depth * 255.0;
  11186. var fract = scale - Math.floor(scale);
  11187. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11188. };
  11189. ShadowGenerator.prototype.dispose = function () {
  11190. this._shadowMap.dispose();
  11191. if (this._shadowMap2) {
  11192. this._shadowMap2.dispose();
  11193. }
  11194. if (this._downSamplePostprocess) {
  11195. this._downSamplePostprocess.dispose();
  11196. }
  11197. if (this._boxBlurPostprocess) {
  11198. this._boxBlurPostprocess.dispose();
  11199. }
  11200. };
  11201. ShadowGenerator.prototype.serialize = function () {
  11202. var serializationObject = {};
  11203. serializationObject.lightId = this._light.id;
  11204. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11205. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11206. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11207. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11208. serializationObject.renderList = [];
  11209. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11210. var mesh = this.getShadowMap().renderList[meshIndex];
  11211. serializationObject.renderList.push(mesh.id);
  11212. }
  11213. return serializationObject;
  11214. };
  11215. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11216. //casting to point light, as light is missing the position attr and typescript complains.
  11217. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11218. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11219. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11220. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11221. meshes.forEach(function (mesh) {
  11222. shadowGenerator.getShadowMap().renderList.push(mesh);
  11223. });
  11224. }
  11225. if (parsedShadowGenerator.usePoissonSampling) {
  11226. shadowGenerator.usePoissonSampling = true;
  11227. }
  11228. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11229. shadowGenerator.useVarianceShadowMap = true;
  11230. }
  11231. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11232. shadowGenerator.useBlurVarianceShadowMap = true;
  11233. if (parsedShadowGenerator.blurScale) {
  11234. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11235. }
  11236. if (parsedShadowGenerator.blurBoxOffset) {
  11237. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11238. }
  11239. }
  11240. if (parsedShadowGenerator.bias !== undefined) {
  11241. shadowGenerator.bias = parsedShadowGenerator.bias;
  11242. }
  11243. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11244. return shadowGenerator;
  11245. };
  11246. ShadowGenerator._FILTER_NONE = 0;
  11247. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11248. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11249. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11250. return ShadowGenerator;
  11251. }());
  11252. BABYLON.ShadowGenerator = ShadowGenerator;
  11253. })(BABYLON || (BABYLON = {}));
  11254. var BABYLON;
  11255. (function (BABYLON) {
  11256. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11257. if (boxMin.x > sphereCenter.x + sphereRadius)
  11258. return false;
  11259. if (sphereCenter.x - sphereRadius > boxMax.x)
  11260. return false;
  11261. if (boxMin.y > sphereCenter.y + sphereRadius)
  11262. return false;
  11263. if (sphereCenter.y - sphereRadius > boxMax.y)
  11264. return false;
  11265. if (boxMin.z > sphereCenter.z + sphereRadius)
  11266. return false;
  11267. if (sphereCenter.z - sphereRadius > boxMax.z)
  11268. return false;
  11269. return true;
  11270. };
  11271. var getLowestRoot = (function () {
  11272. var result = { root: 0, found: false };
  11273. return function (a, b, c, maxR) {
  11274. result.root = 0;
  11275. result.found = false;
  11276. var determinant = b * b - 4.0 * a * c;
  11277. if (determinant < 0)
  11278. return result;
  11279. var sqrtD = Math.sqrt(determinant);
  11280. var r1 = (-b - sqrtD) / (2.0 * a);
  11281. var r2 = (-b + sqrtD) / (2.0 * a);
  11282. if (r1 > r2) {
  11283. var temp = r2;
  11284. r2 = r1;
  11285. r1 = temp;
  11286. }
  11287. if (r1 > 0 && r1 < maxR) {
  11288. result.root = r1;
  11289. result.found = true;
  11290. return result;
  11291. }
  11292. if (r2 > 0 && r2 < maxR) {
  11293. result.root = r2;
  11294. result.found = true;
  11295. return result;
  11296. }
  11297. return result;
  11298. };
  11299. })();
  11300. var Collider = (function () {
  11301. function Collider() {
  11302. this.radius = new BABYLON.Vector3(1, 1, 1);
  11303. this.retry = 0;
  11304. this.basePointWorld = BABYLON.Vector3.Zero();
  11305. this.velocityWorld = BABYLON.Vector3.Zero();
  11306. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11307. this._collisionPoint = BABYLON.Vector3.Zero();
  11308. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11309. this._tempVector = BABYLON.Vector3.Zero();
  11310. this._tempVector2 = BABYLON.Vector3.Zero();
  11311. this._tempVector3 = BABYLON.Vector3.Zero();
  11312. this._tempVector4 = BABYLON.Vector3.Zero();
  11313. this._edge = BABYLON.Vector3.Zero();
  11314. this._baseToVertex = BABYLON.Vector3.Zero();
  11315. this._destinationPoint = BABYLON.Vector3.Zero();
  11316. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11317. this._displacementVector = BABYLON.Vector3.Zero();
  11318. }
  11319. // Methods
  11320. Collider.prototype._initialize = function (source, dir, e) {
  11321. this.velocity = dir;
  11322. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11323. this.basePoint = source;
  11324. source.multiplyToRef(this.radius, this.basePointWorld);
  11325. dir.multiplyToRef(this.radius, this.velocityWorld);
  11326. this.velocityWorldLength = this.velocityWorld.length();
  11327. this.epsilon = e;
  11328. this.collisionFound = false;
  11329. };
  11330. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11331. pa.subtractToRef(point, this._tempVector);
  11332. pb.subtractToRef(point, this._tempVector2);
  11333. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11334. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11335. if (d < 0)
  11336. return false;
  11337. pc.subtractToRef(point, this._tempVector3);
  11338. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11339. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11340. if (d < 0)
  11341. return false;
  11342. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11343. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11344. return d >= 0;
  11345. };
  11346. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11347. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11348. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11349. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11350. return false;
  11351. }
  11352. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11353. return false;
  11354. return true;
  11355. };
  11356. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11357. var t0;
  11358. var embeddedInPlane = false;
  11359. //defensive programming, actually not needed.
  11360. if (!trianglePlaneArray) {
  11361. trianglePlaneArray = [];
  11362. }
  11363. if (!trianglePlaneArray[faceIndex]) {
  11364. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11365. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11366. }
  11367. var trianglePlane = trianglePlaneArray[faceIndex];
  11368. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11369. return;
  11370. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11371. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11372. if (normalDotVelocity == 0) {
  11373. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11374. return;
  11375. embeddedInPlane = true;
  11376. t0 = 0;
  11377. }
  11378. else {
  11379. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11380. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11381. if (t0 > t1) {
  11382. var temp = t1;
  11383. t1 = t0;
  11384. t0 = temp;
  11385. }
  11386. if (t0 > 1.0 || t1 < 0.0)
  11387. return;
  11388. if (t0 < 0)
  11389. t0 = 0;
  11390. if (t0 > 1.0)
  11391. t0 = 1.0;
  11392. }
  11393. this._collisionPoint.copyFromFloats(0, 0, 0);
  11394. var found = false;
  11395. var t = 1.0;
  11396. if (!embeddedInPlane) {
  11397. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11398. this.velocity.scaleToRef(t0, this._tempVector);
  11399. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11400. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11401. found = true;
  11402. t = t0;
  11403. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11404. }
  11405. }
  11406. if (!found) {
  11407. var velocitySquaredLength = this.velocity.lengthSquared();
  11408. var a = velocitySquaredLength;
  11409. this.basePoint.subtractToRef(p1, this._tempVector);
  11410. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11411. var c = this._tempVector.lengthSquared() - 1.0;
  11412. var lowestRoot = getLowestRoot(a, b, c, t);
  11413. if (lowestRoot.found) {
  11414. t = lowestRoot.root;
  11415. found = true;
  11416. this._collisionPoint.copyFrom(p1);
  11417. }
  11418. this.basePoint.subtractToRef(p2, this._tempVector);
  11419. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11420. c = this._tempVector.lengthSquared() - 1.0;
  11421. lowestRoot = getLowestRoot(a, b, c, t);
  11422. if (lowestRoot.found) {
  11423. t = lowestRoot.root;
  11424. found = true;
  11425. this._collisionPoint.copyFrom(p2);
  11426. }
  11427. this.basePoint.subtractToRef(p3, this._tempVector);
  11428. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11429. c = this._tempVector.lengthSquared() - 1.0;
  11430. lowestRoot = getLowestRoot(a, b, c, t);
  11431. if (lowestRoot.found) {
  11432. t = lowestRoot.root;
  11433. found = true;
  11434. this._collisionPoint.copyFrom(p3);
  11435. }
  11436. p2.subtractToRef(p1, this._edge);
  11437. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11438. var edgeSquaredLength = this._edge.lengthSquared();
  11439. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11440. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11441. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11442. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11443. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11444. lowestRoot = getLowestRoot(a, b, c, t);
  11445. if (lowestRoot.found) {
  11446. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11447. if (f >= 0.0 && f <= 1.0) {
  11448. t = lowestRoot.root;
  11449. found = true;
  11450. this._edge.scaleInPlace(f);
  11451. p1.addToRef(this._edge, this._collisionPoint);
  11452. }
  11453. }
  11454. p3.subtractToRef(p2, this._edge);
  11455. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11456. edgeSquaredLength = this._edge.lengthSquared();
  11457. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11458. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11459. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11460. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11461. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11462. lowestRoot = getLowestRoot(a, b, c, t);
  11463. if (lowestRoot.found) {
  11464. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11465. if (f >= 0.0 && f <= 1.0) {
  11466. t = lowestRoot.root;
  11467. found = true;
  11468. this._edge.scaleInPlace(f);
  11469. p2.addToRef(this._edge, this._collisionPoint);
  11470. }
  11471. }
  11472. p1.subtractToRef(p3, this._edge);
  11473. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11474. edgeSquaredLength = this._edge.lengthSquared();
  11475. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11476. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11477. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11478. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11479. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11480. lowestRoot = getLowestRoot(a, b, c, t);
  11481. if (lowestRoot.found) {
  11482. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11483. if (f >= 0.0 && f <= 1.0) {
  11484. t = lowestRoot.root;
  11485. found = true;
  11486. this._edge.scaleInPlace(f);
  11487. p3.addToRef(this._edge, this._collisionPoint);
  11488. }
  11489. }
  11490. }
  11491. if (found) {
  11492. var distToCollision = t * this.velocity.length();
  11493. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11494. if (!this.intersectionPoint) {
  11495. this.intersectionPoint = this._collisionPoint.clone();
  11496. }
  11497. else {
  11498. this.intersectionPoint.copyFrom(this._collisionPoint);
  11499. }
  11500. this.nearestDistance = distToCollision;
  11501. this.collisionFound = true;
  11502. }
  11503. }
  11504. };
  11505. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11506. for (var i = indexStart; i < indexEnd; i += 3) {
  11507. var p1 = pts[indices[i] - decal];
  11508. var p2 = pts[indices[i + 1] - decal];
  11509. var p3 = pts[indices[i + 2] - decal];
  11510. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11511. }
  11512. };
  11513. Collider.prototype._getResponse = function (pos, vel) {
  11514. pos.addToRef(vel, this._destinationPoint);
  11515. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11516. this.basePoint.addToRef(vel, pos);
  11517. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11518. this._slidePlaneNormal.normalize();
  11519. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11520. pos.addInPlace(this._displacementVector);
  11521. this.intersectionPoint.addInPlace(this._displacementVector);
  11522. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11523. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11524. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11525. };
  11526. return Collider;
  11527. }());
  11528. BABYLON.Collider = Collider;
  11529. })(BABYLON || (BABYLON = {}));
  11530. var BABYLON;
  11531. (function (BABYLON) {
  11532. //WebWorker code will be inserted to this variable.
  11533. BABYLON.CollisionWorker = "";
  11534. (function (WorkerTaskType) {
  11535. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11536. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11537. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11538. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11539. var WorkerTaskType = BABYLON.WorkerTaskType;
  11540. (function (WorkerReplyType) {
  11541. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11542. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11543. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11544. var WorkerReplyType = BABYLON.WorkerReplyType;
  11545. var CollisionCoordinatorWorker = (function () {
  11546. function CollisionCoordinatorWorker() {
  11547. var _this = this;
  11548. this._scaledPosition = BABYLON.Vector3.Zero();
  11549. this._scaledVelocity = BABYLON.Vector3.Zero();
  11550. this.onMeshUpdated = function (mesh) {
  11551. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11552. };
  11553. this.onGeometryUpdated = function (geometry) {
  11554. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11555. };
  11556. this._afterRender = function () {
  11557. if (!_this._init)
  11558. return;
  11559. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11560. return;
  11561. }
  11562. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11563. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11564. if (_this._runningUpdated > 4) {
  11565. return;
  11566. }
  11567. ++_this._runningUpdated;
  11568. var payload = {
  11569. updatedMeshes: _this._addUpdateMeshesList,
  11570. updatedGeometries: _this._addUpdateGeometriesList,
  11571. removedGeometries: _this._toRemoveGeometryArray,
  11572. removedMeshes: _this._toRemoveMeshesArray
  11573. };
  11574. var message = {
  11575. payload: payload,
  11576. taskType: WorkerTaskType.UPDATE
  11577. };
  11578. var serializable = [];
  11579. for (var id in payload.updatedGeometries) {
  11580. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11581. //prepare transferables
  11582. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11583. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11584. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11585. }
  11586. }
  11587. _this._worker.postMessage(message, serializable);
  11588. _this._addUpdateMeshesList = {};
  11589. _this._addUpdateGeometriesList = {};
  11590. _this._toRemoveGeometryArray = [];
  11591. _this._toRemoveMeshesArray = [];
  11592. };
  11593. this._onMessageFromWorker = function (e) {
  11594. var returnData = e.data;
  11595. if (returnData.error != WorkerReplyType.SUCCESS) {
  11596. //TODO what errors can be returned from the worker?
  11597. BABYLON.Tools.Warn("error returned from worker!");
  11598. return;
  11599. }
  11600. switch (returnData.taskType) {
  11601. case WorkerTaskType.INIT:
  11602. _this._init = true;
  11603. //Update the worked with ALL of the scene's current state
  11604. _this._scene.meshes.forEach(function (mesh) {
  11605. _this.onMeshAdded(mesh);
  11606. });
  11607. _this._scene.getGeometries().forEach(function (geometry) {
  11608. _this.onGeometryAdded(geometry);
  11609. });
  11610. break;
  11611. case WorkerTaskType.UPDATE:
  11612. _this._runningUpdated--;
  11613. break;
  11614. case WorkerTaskType.COLLIDE:
  11615. _this._runningCollisionTask = false;
  11616. var returnPayload = returnData.payload;
  11617. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11618. return;
  11619. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11620. //cleanup
  11621. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11622. break;
  11623. }
  11624. };
  11625. this._collisionsCallbackArray = [];
  11626. this._init = false;
  11627. this._runningUpdated = 0;
  11628. this._runningCollisionTask = false;
  11629. this._addUpdateMeshesList = {};
  11630. this._addUpdateGeometriesList = {};
  11631. this._toRemoveGeometryArray = [];
  11632. this._toRemoveMeshesArray = [];
  11633. }
  11634. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11635. if (!this._init)
  11636. return;
  11637. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11638. return;
  11639. position.divideToRef(collider.radius, this._scaledPosition);
  11640. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11641. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11642. var payload = {
  11643. collider: {
  11644. position: this._scaledPosition.asArray(),
  11645. velocity: this._scaledVelocity.asArray(),
  11646. radius: collider.radius.asArray()
  11647. },
  11648. collisionId: collisionIndex,
  11649. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11650. maximumRetry: maximumRetry
  11651. };
  11652. var message = {
  11653. payload: payload,
  11654. taskType: WorkerTaskType.COLLIDE
  11655. };
  11656. this._worker.postMessage(message);
  11657. };
  11658. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11659. this._scene = scene;
  11660. this._scene.registerAfterRender(this._afterRender);
  11661. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11662. this._worker = new Worker(workerUrl);
  11663. this._worker.onmessage = this._onMessageFromWorker;
  11664. var message = {
  11665. payload: {},
  11666. taskType: WorkerTaskType.INIT
  11667. };
  11668. this._worker.postMessage(message);
  11669. };
  11670. CollisionCoordinatorWorker.prototype.destroy = function () {
  11671. this._scene.unregisterAfterRender(this._afterRender);
  11672. this._worker.terminate();
  11673. };
  11674. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11675. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11676. this.onMeshUpdated(mesh);
  11677. };
  11678. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11679. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11680. };
  11681. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11682. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11683. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11684. this.onGeometryUpdated(geometry);
  11685. };
  11686. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11687. this._toRemoveGeometryArray.push(geometry.id);
  11688. };
  11689. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11690. var submeshes = [];
  11691. if (mesh.subMeshes) {
  11692. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11693. return {
  11694. position: idx,
  11695. verticesStart: sm.verticesStart,
  11696. verticesCount: sm.verticesCount,
  11697. indexStart: sm.indexStart,
  11698. indexCount: sm.indexCount,
  11699. hasMaterial: !!sm.getMaterial(),
  11700. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11701. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11702. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11703. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11704. };
  11705. });
  11706. }
  11707. var geometryId = null;
  11708. if (mesh instanceof BABYLON.Mesh) {
  11709. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11710. }
  11711. else if (mesh instanceof BABYLON.InstancedMesh) {
  11712. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11713. }
  11714. return {
  11715. uniqueId: mesh.uniqueId,
  11716. id: mesh.id,
  11717. name: mesh.name,
  11718. geometryId: geometryId,
  11719. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11720. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11721. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11722. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11723. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11724. subMeshes: submeshes,
  11725. checkCollisions: mesh.checkCollisions
  11726. };
  11727. };
  11728. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11729. return {
  11730. id: geometry.id,
  11731. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11732. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11733. indices: new Int32Array(geometry.getIndices() || []),
  11734. };
  11735. };
  11736. return CollisionCoordinatorWorker;
  11737. }());
  11738. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11739. var CollisionCoordinatorLegacy = (function () {
  11740. function CollisionCoordinatorLegacy() {
  11741. this._scaledPosition = BABYLON.Vector3.Zero();
  11742. this._scaledVelocity = BABYLON.Vector3.Zero();
  11743. this._finalPosition = BABYLON.Vector3.Zero();
  11744. }
  11745. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11746. position.divideToRef(collider.radius, this._scaledPosition);
  11747. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11748. collider.collidedMesh = null;
  11749. collider.retry = 0;
  11750. collider.initialVelocity = this._scaledVelocity;
  11751. collider.initialPosition = this._scaledPosition;
  11752. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11753. this._finalPosition.multiplyInPlace(collider.radius);
  11754. //run the callback
  11755. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11756. };
  11757. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11758. this._scene = scene;
  11759. };
  11760. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11761. //Legacy need no destruction method.
  11762. };
  11763. //No update in legacy mode
  11764. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11765. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11766. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11767. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11768. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11769. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11770. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11771. if (excludedMesh === void 0) { excludedMesh = null; }
  11772. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11773. if (collider.retry >= maximumRetry) {
  11774. finalPosition.copyFrom(position);
  11775. return;
  11776. }
  11777. collider._initialize(position, velocity, closeDistance);
  11778. // Check all meshes
  11779. for (var index = 0; index < this._scene.meshes.length; index++) {
  11780. var mesh = this._scene.meshes[index];
  11781. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11782. mesh._checkCollision(collider);
  11783. }
  11784. }
  11785. if (!collider.collisionFound) {
  11786. position.addToRef(velocity, finalPosition);
  11787. return;
  11788. }
  11789. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11790. collider._getResponse(position, velocity);
  11791. }
  11792. if (velocity.length() <= closeDistance) {
  11793. finalPosition.copyFrom(position);
  11794. return;
  11795. }
  11796. collider.retry++;
  11797. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11798. };
  11799. return CollisionCoordinatorLegacy;
  11800. }());
  11801. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11802. })(BABYLON || (BABYLON = {}));
  11803. var BABYLON;
  11804. (function (BABYLON) {
  11805. var Camera = (function (_super) {
  11806. __extends(Camera, _super);
  11807. function Camera(name, position, scene) {
  11808. _super.call(this, name, scene);
  11809. this.upVector = BABYLON.Vector3.Up();
  11810. this.orthoLeft = null;
  11811. this.orthoRight = null;
  11812. this.orthoBottom = null;
  11813. this.orthoTop = null;
  11814. this.fov = 0.8;
  11815. this.minZ = 1.0;
  11816. this.maxZ = 10000.0;
  11817. this.inertia = 0.9;
  11818. this.mode = Camera.PERSPECTIVE_CAMERA;
  11819. this.isIntermediate = false;
  11820. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11821. this.layerMask = 0x0FFFFFFF;
  11822. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11823. // Camera rig members
  11824. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11825. this._rigCameras = new Array();
  11826. // Cache
  11827. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11828. this._projectionMatrix = new BABYLON.Matrix();
  11829. this._postProcesses = new Array();
  11830. this._transformMatrix = BABYLON.Matrix.Zero();
  11831. this._activeMeshes = new BABYLON.SmartArray(256);
  11832. this._globalPosition = BABYLON.Vector3.Zero();
  11833. this._refreshFrustumPlanes = true;
  11834. scene.addCamera(this);
  11835. if (!scene.activeCamera) {
  11836. scene.activeCamera = this;
  11837. }
  11838. this.position = position;
  11839. }
  11840. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11841. get: function () {
  11842. return Camera._PERSPECTIVE_CAMERA;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11848. get: function () {
  11849. return Camera._ORTHOGRAPHIC_CAMERA;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11855. get: function () {
  11856. return Camera._FOVMODE_VERTICAL_FIXED;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11862. get: function () {
  11863. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11869. get: function () {
  11870. return Camera._RIG_MODE_NONE;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11876. get: function () {
  11877. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11883. get: function () {
  11884. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11890. get: function () {
  11891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11897. get: function () {
  11898. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11904. get: function () {
  11905. return Camera._RIG_MODE_VR;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. /**
  11911. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11912. */
  11913. Camera.prototype.toString = function (fullDetails) {
  11914. var ret = "Name: " + this.name;
  11915. ret += ", type: " + this.getTypeName();
  11916. if (this.animations) {
  11917. for (var i = 0; i < this.animations.length; i++) {
  11918. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11919. }
  11920. }
  11921. if (fullDetails) {
  11922. }
  11923. return ret;
  11924. };
  11925. Object.defineProperty(Camera.prototype, "globalPosition", {
  11926. get: function () {
  11927. return this._globalPosition;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Camera.prototype.getActiveMeshes = function () {
  11933. return this._activeMeshes;
  11934. };
  11935. Camera.prototype.isActiveMesh = function (mesh) {
  11936. return (this._activeMeshes.indexOf(mesh) !== -1);
  11937. };
  11938. //Cache
  11939. Camera.prototype._initCache = function () {
  11940. _super.prototype._initCache.call(this);
  11941. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11942. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11943. this._cache.mode = undefined;
  11944. this._cache.minZ = undefined;
  11945. this._cache.maxZ = undefined;
  11946. this._cache.fov = undefined;
  11947. this._cache.aspectRatio = undefined;
  11948. this._cache.orthoLeft = undefined;
  11949. this._cache.orthoRight = undefined;
  11950. this._cache.orthoBottom = undefined;
  11951. this._cache.orthoTop = undefined;
  11952. this._cache.renderWidth = undefined;
  11953. this._cache.renderHeight = undefined;
  11954. };
  11955. Camera.prototype._updateCache = function (ignoreParentClass) {
  11956. if (!ignoreParentClass) {
  11957. _super.prototype._updateCache.call(this);
  11958. }
  11959. var engine = this.getEngine();
  11960. this._cache.position.copyFrom(this.position);
  11961. this._cache.upVector.copyFrom(this.upVector);
  11962. this._cache.mode = this.mode;
  11963. this._cache.minZ = this.minZ;
  11964. this._cache.maxZ = this.maxZ;
  11965. this._cache.fov = this.fov;
  11966. this._cache.aspectRatio = engine.getAspectRatio(this);
  11967. this._cache.orthoLeft = this.orthoLeft;
  11968. this._cache.orthoRight = this.orthoRight;
  11969. this._cache.orthoBottom = this.orthoBottom;
  11970. this._cache.orthoTop = this.orthoTop;
  11971. this._cache.renderWidth = engine.getRenderWidth();
  11972. this._cache.renderHeight = engine.getRenderHeight();
  11973. };
  11974. Camera.prototype._updateFromScene = function () {
  11975. this.updateCache();
  11976. this._update();
  11977. };
  11978. // Synchronized
  11979. Camera.prototype._isSynchronized = function () {
  11980. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11981. };
  11982. Camera.prototype._isSynchronizedViewMatrix = function () {
  11983. if (!_super.prototype._isSynchronized.call(this))
  11984. return false;
  11985. return this._cache.position.equals(this.position)
  11986. && this._cache.upVector.equals(this.upVector)
  11987. && this.isSynchronizedWithParent();
  11988. };
  11989. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11990. var check = this._cache.mode === this.mode
  11991. && this._cache.minZ === this.minZ
  11992. && this._cache.maxZ === this.maxZ;
  11993. if (!check) {
  11994. return false;
  11995. }
  11996. var engine = this.getEngine();
  11997. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11998. check = this._cache.fov === this.fov
  11999. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12000. }
  12001. else {
  12002. check = this._cache.orthoLeft === this.orthoLeft
  12003. && this._cache.orthoRight === this.orthoRight
  12004. && this._cache.orthoBottom === this.orthoBottom
  12005. && this._cache.orthoTop === this.orthoTop
  12006. && this._cache.renderWidth === engine.getRenderWidth()
  12007. && this._cache.renderHeight === engine.getRenderHeight();
  12008. }
  12009. return check;
  12010. };
  12011. // Controls
  12012. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12013. };
  12014. Camera.prototype.detachControl = function (element) {
  12015. };
  12016. Camera.prototype._update = function () {
  12017. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12018. this._updateRigCameras();
  12019. }
  12020. this._checkInputs();
  12021. };
  12022. Camera.prototype._checkInputs = function () {
  12023. };
  12024. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12025. // invalidate framebuffer
  12026. if (this._postProcesses.length > 0) {
  12027. this._postProcesses[0].markTextureDirty();
  12028. }
  12029. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12030. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12031. var cam = this._rigCameras[i];
  12032. var rigPostProcess = cam._rigPostProcess;
  12033. // for VR rig, there does not have to be a post process
  12034. if (rigPostProcess) {
  12035. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12036. if (isPass) {
  12037. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12038. cam.isIntermediate = this._postProcesses.length === 0;
  12039. }
  12040. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12041. rigPostProcess.markTextureDirty();
  12042. }
  12043. else {
  12044. cam._postProcesses = this._postProcesses.slice(0);
  12045. }
  12046. }
  12047. };
  12048. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12049. if (insertAt === void 0) { insertAt = null; }
  12050. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12051. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12052. return 0;
  12053. }
  12054. if (insertAt == null || insertAt < 0) {
  12055. this._postProcesses.push(postProcess);
  12056. }
  12057. else {
  12058. this._postProcesses.splice(insertAt, 0, postProcess);
  12059. }
  12060. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12061. return this._postProcesses.indexOf(postProcess);
  12062. };
  12063. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12064. if (atIndices === void 0) { atIndices = null; }
  12065. var result = [];
  12066. var i;
  12067. var index;
  12068. if (!atIndices) {
  12069. var idx = this._postProcesses.indexOf(postProcess);
  12070. if (idx !== -1) {
  12071. this._postProcesses.splice(idx, 1);
  12072. }
  12073. }
  12074. else {
  12075. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12076. // iterate descending, so can just splice as we go
  12077. for (i = atIndices.length - 1; i >= 0; i--) {
  12078. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12079. result.push(i);
  12080. continue;
  12081. }
  12082. this._postProcesses.splice(index, 1);
  12083. }
  12084. }
  12085. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12086. return result;
  12087. };
  12088. Camera.prototype.getWorldMatrix = function () {
  12089. if (!this._worldMatrix) {
  12090. this._worldMatrix = BABYLON.Matrix.Identity();
  12091. }
  12092. var viewMatrix = this.getViewMatrix();
  12093. viewMatrix.invertToRef(this._worldMatrix);
  12094. return this._worldMatrix;
  12095. };
  12096. Camera.prototype._getViewMatrix = function () {
  12097. return BABYLON.Matrix.Identity();
  12098. };
  12099. Camera.prototype.getViewMatrix = function (force) {
  12100. this._computedViewMatrix = this._computeViewMatrix(force);
  12101. if (!force && this._isSynchronizedViewMatrix()) {
  12102. return this._computedViewMatrix;
  12103. }
  12104. this._refreshFrustumPlanes = true;
  12105. if (!this.parent || !this.parent.getWorldMatrix) {
  12106. this._globalPosition.copyFrom(this.position);
  12107. }
  12108. else {
  12109. if (!this._worldMatrix) {
  12110. this._worldMatrix = BABYLON.Matrix.Identity();
  12111. }
  12112. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12113. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12114. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12115. this._computedViewMatrix.invert();
  12116. this._markSyncedWithParent();
  12117. }
  12118. this._currentRenderId = this.getScene().getRenderId();
  12119. return this._computedViewMatrix;
  12120. };
  12121. Camera.prototype._computeViewMatrix = function (force) {
  12122. if (!force && this._isSynchronizedViewMatrix()) {
  12123. return this._computedViewMatrix;
  12124. }
  12125. this._computedViewMatrix = this._getViewMatrix();
  12126. this._currentRenderId = this.getScene().getRenderId();
  12127. return this._computedViewMatrix;
  12128. };
  12129. Camera.prototype.getProjectionMatrix = function (force) {
  12130. if (!force && this._isSynchronizedProjectionMatrix()) {
  12131. return this._projectionMatrix;
  12132. }
  12133. this._refreshFrustumPlanes = true;
  12134. var engine = this.getEngine();
  12135. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12136. if (this.minZ <= 0) {
  12137. this.minZ = 0.1;
  12138. }
  12139. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12140. return this._projectionMatrix;
  12141. }
  12142. var halfWidth = engine.getRenderWidth() / 2.0;
  12143. var halfHeight = engine.getRenderHeight() / 2.0;
  12144. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12145. return this._projectionMatrix;
  12146. };
  12147. Camera.prototype.getTranformationMatrix = function () {
  12148. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12149. return this._transformMatrix;
  12150. };
  12151. Camera.prototype.updateFrustumPlanes = function () {
  12152. if (!this._refreshFrustumPlanes) {
  12153. return;
  12154. }
  12155. this.getTranformationMatrix();
  12156. if (!this._frustumPlanes) {
  12157. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12158. }
  12159. else {
  12160. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12161. }
  12162. this._refreshFrustumPlanes = false;
  12163. };
  12164. Camera.prototype.isInFrustum = function (target) {
  12165. this.updateFrustumPlanes();
  12166. return target.isInFrustum(this._frustumPlanes);
  12167. };
  12168. Camera.prototype.isCompletelyInFrustum = function (target) {
  12169. this.updateFrustumPlanes();
  12170. return target.isCompletelyInFrustum(this._frustumPlanes);
  12171. };
  12172. Camera.prototype.dispose = function () {
  12173. // Animations
  12174. this.getScene().stopAnimation(this);
  12175. // Remove from scene
  12176. this.getScene().removeCamera(this);
  12177. while (this._rigCameras.length > 0) {
  12178. this._rigCameras.pop().dispose();
  12179. }
  12180. // Postprocesses
  12181. for (var i = 0; i < this._postProcesses.length; ++i) {
  12182. this._postProcesses[i].dispose(this);
  12183. }
  12184. _super.prototype.dispose.call(this);
  12185. };
  12186. // ---- Camera rigs section ----
  12187. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12188. while (this._rigCameras.length > 0) {
  12189. this._rigCameras.pop().dispose();
  12190. }
  12191. this.cameraRigMode = mode;
  12192. this._cameraRigParams = {};
  12193. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12194. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12195. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12196. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12197. // create the rig cameras, unless none
  12198. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12199. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12200. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12201. }
  12202. switch (this.cameraRigMode) {
  12203. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12204. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12205. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12206. break;
  12207. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12209. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12210. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12211. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12212. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12213. break;
  12214. case Camera.RIG_MODE_VR:
  12215. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12216. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12217. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12218. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12219. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12220. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12221. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12222. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12223. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12224. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12225. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12226. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12227. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12228. if (metrics.compensateDistortion) {
  12229. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12230. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12231. }
  12232. break;
  12233. }
  12234. this._cascadePostProcessesToRigCams();
  12235. this._update();
  12236. };
  12237. Camera.prototype._getVRProjectionMatrix = function () {
  12238. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12239. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12240. return this._projectionMatrix;
  12241. };
  12242. Camera.prototype.setCameraRigParameter = function (name, value) {
  12243. if (!this._cameraRigParams) {
  12244. this._cameraRigParams = {};
  12245. }
  12246. this._cameraRigParams[name] = value;
  12247. //provisionnally:
  12248. if (name === "interaxialDistance") {
  12249. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12250. }
  12251. };
  12252. /**
  12253. * needs to be overridden by children so sub has required properties to be copied
  12254. */
  12255. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12256. return null;
  12257. };
  12258. /**
  12259. * May need to be overridden by children
  12260. */
  12261. Camera.prototype._updateRigCameras = function () {
  12262. for (var i = 0; i < this._rigCameras.length; i++) {
  12263. this._rigCameras[i].minZ = this.minZ;
  12264. this._rigCameras[i].maxZ = this.maxZ;
  12265. this._rigCameras[i].fov = this.fov;
  12266. }
  12267. // only update viewport when ANAGLYPH
  12268. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12269. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12270. }
  12271. };
  12272. Camera.prototype._setupInputs = function () {
  12273. };
  12274. Camera.prototype.serialize = function () {
  12275. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12276. // Type
  12277. serializationObject.type = this.getTypeName();
  12278. // Parent
  12279. if (this.parent) {
  12280. serializationObject.parentId = this.parent.id;
  12281. }
  12282. if (this.inputs) {
  12283. this.inputs.serialize(serializationObject);
  12284. }
  12285. // Animations
  12286. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12287. serializationObject.ranges = this.serializeAnimationRanges();
  12288. return serializationObject;
  12289. };
  12290. Camera.prototype.getTypeName = function () {
  12291. return "Camera";
  12292. };
  12293. Camera.prototype.clone = function (name) {
  12294. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12295. };
  12296. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12297. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12298. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12299. switch (type) {
  12300. case "ArcRotateCamera":
  12301. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12302. case "DeviceOrientationCamera":
  12303. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12304. case "FollowCamera":
  12305. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12306. case "ArcFollowCamera":
  12307. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12308. case "GamepadCamera":
  12309. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12310. case "TouchCamera":
  12311. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12312. case "VirtualJoysticksCamera":
  12313. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12314. case "WebVRFreeCamera":
  12315. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12316. case "VRDeviceOrientationFreeCamera":
  12317. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12318. case "AnaglyphArcRotateCamera":
  12319. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12320. case "AnaglyphFreeCamera":
  12321. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12322. case "AnaglyphGamepadCamera":
  12323. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12324. case "AnaglyphUniversalCamera":
  12325. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12326. case "StereoscopicArcRotateCamera":
  12327. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12328. case "StereoscopicFreeCamera":
  12329. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12330. case "StereoscopicGamepadCamera":
  12331. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12332. case "StereoscopicUniversalCamera":
  12333. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12334. case "FreeCamera":
  12335. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12336. default:
  12337. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12338. }
  12339. };
  12340. Camera.Parse = function (parsedCamera, scene) {
  12341. var type = parsedCamera.type;
  12342. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12343. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12344. // Parent
  12345. if (parsedCamera.parentId) {
  12346. camera._waitingParentId = parsedCamera.parentId;
  12347. }
  12348. //If camera has an input manager, let it parse inputs settings
  12349. if (camera.inputs) {
  12350. camera.inputs.parse(parsedCamera);
  12351. camera._setupInputs();
  12352. }
  12353. // Target
  12354. if (parsedCamera.target) {
  12355. if (camera.setTarget) {
  12356. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12357. }
  12358. }
  12359. // Apply 3d rig, when found
  12360. if (parsedCamera.cameraRigMode) {
  12361. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12362. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12363. }
  12364. // Animations
  12365. if (parsedCamera.animations) {
  12366. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12367. var parsedAnimation = parsedCamera.animations[animationIndex];
  12368. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12369. }
  12370. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12371. }
  12372. if (parsedCamera.autoAnimate) {
  12373. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12374. }
  12375. return camera;
  12376. };
  12377. // Statics
  12378. Camera._PERSPECTIVE_CAMERA = 0;
  12379. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12380. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12381. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12382. Camera._RIG_MODE_NONE = 0;
  12383. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12384. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12385. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12386. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12387. Camera._RIG_MODE_VR = 20;
  12388. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12389. __decorate([
  12390. BABYLON.serializeAsVector3()
  12391. ], Camera.prototype, "position", void 0);
  12392. __decorate([
  12393. BABYLON.serializeAsVector3()
  12394. ], Camera.prototype, "upVector", void 0);
  12395. __decorate([
  12396. BABYLON.serialize()
  12397. ], Camera.prototype, "orthoLeft", void 0);
  12398. __decorate([
  12399. BABYLON.serialize()
  12400. ], Camera.prototype, "orthoRight", void 0);
  12401. __decorate([
  12402. BABYLON.serialize()
  12403. ], Camera.prototype, "orthoBottom", void 0);
  12404. __decorate([
  12405. BABYLON.serialize()
  12406. ], Camera.prototype, "orthoTop", void 0);
  12407. __decorate([
  12408. BABYLON.serialize()
  12409. ], Camera.prototype, "fov", void 0);
  12410. __decorate([
  12411. BABYLON.serialize()
  12412. ], Camera.prototype, "minZ", void 0);
  12413. __decorate([
  12414. BABYLON.serialize()
  12415. ], Camera.prototype, "maxZ", void 0);
  12416. __decorate([
  12417. BABYLON.serialize()
  12418. ], Camera.prototype, "inertia", void 0);
  12419. __decorate([
  12420. BABYLON.serialize()
  12421. ], Camera.prototype, "mode", void 0);
  12422. __decorate([
  12423. BABYLON.serialize()
  12424. ], Camera.prototype, "layerMask", void 0);
  12425. __decorate([
  12426. BABYLON.serialize()
  12427. ], Camera.prototype, "fovMode", void 0);
  12428. __decorate([
  12429. BABYLON.serialize()
  12430. ], Camera.prototype, "cameraRigMode", void 0);
  12431. __decorate([
  12432. BABYLON.serialize()
  12433. ], Camera.prototype, "interaxialDistance", void 0);
  12434. __decorate([
  12435. BABYLON.serialize()
  12436. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12437. return Camera;
  12438. }(BABYLON.Node));
  12439. BABYLON.Camera = Camera;
  12440. })(BABYLON || (BABYLON = {}));
  12441. var BABYLON;
  12442. (function (BABYLON) {
  12443. BABYLON.CameraInputTypes = {};
  12444. var CameraInputsManager = (function () {
  12445. function CameraInputsManager(camera) {
  12446. this.attached = {};
  12447. this.camera = camera;
  12448. this.checkInputs = function () { };
  12449. }
  12450. CameraInputsManager.prototype.add = function (input) {
  12451. var type = input.getSimpleName();
  12452. if (this.attached[type]) {
  12453. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12454. return;
  12455. }
  12456. this.attached[type] = input;
  12457. input.camera = this.camera;
  12458. //for checkInputs, we are dynamically creating a function
  12459. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12460. if (input.checkInputs) {
  12461. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12462. }
  12463. if (this.attachedElement) {
  12464. input.attachControl(this.attachedElement);
  12465. }
  12466. };
  12467. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12468. for (var cam in this.attached) {
  12469. var input = this.attached[cam];
  12470. if (input === inputToRemove) {
  12471. input.detachControl(this.attachedElement);
  12472. delete this.attached[cam];
  12473. this.rebuildInputCheck();
  12474. }
  12475. }
  12476. };
  12477. CameraInputsManager.prototype.removeByType = function (inputType) {
  12478. for (var cam in this.attached) {
  12479. var input = this.attached[cam];
  12480. if (input.getTypeName() === inputType) {
  12481. input.detachControl(this.attachedElement);
  12482. delete this.attached[cam];
  12483. this.rebuildInputCheck();
  12484. }
  12485. }
  12486. };
  12487. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12488. var current = this.checkInputs;
  12489. return function () {
  12490. current();
  12491. fn();
  12492. };
  12493. };
  12494. CameraInputsManager.prototype.attachInput = function (input) {
  12495. input.attachControl(this.attachedElement, this.noPreventDefault);
  12496. };
  12497. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12498. if (this.attachedElement) {
  12499. return;
  12500. }
  12501. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12502. this.attachedElement = element;
  12503. this.noPreventDefault = noPreventDefault;
  12504. for (var cam in this.attached) {
  12505. var input = this.attached[cam];
  12506. this.attached[cam].attachControl(element, noPreventDefault);
  12507. }
  12508. };
  12509. CameraInputsManager.prototype.detachElement = function (element) {
  12510. if (this.attachedElement !== element) {
  12511. return;
  12512. }
  12513. for (var cam in this.attached) {
  12514. var input = this.attached[cam];
  12515. this.attached[cam].detachControl(element);
  12516. }
  12517. this.attachedElement = null;
  12518. };
  12519. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12520. this.checkInputs = function () { };
  12521. for (var cam in this.attached) {
  12522. var input = this.attached[cam];
  12523. if (input.checkInputs) {
  12524. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12525. }
  12526. }
  12527. };
  12528. CameraInputsManager.prototype.clear = function () {
  12529. if (this.attachedElement) {
  12530. this.detachElement(this.attachedElement);
  12531. }
  12532. this.attached = {};
  12533. this.attachedElement = null;
  12534. this.checkInputs = function () { };
  12535. };
  12536. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12537. var inputs = {};
  12538. for (var cam in this.attached) {
  12539. var input = this.attached[cam];
  12540. var res = BABYLON.SerializationHelper.Serialize(input);
  12541. inputs[input.getTypeName()] = res;
  12542. }
  12543. serializedCamera.inputsmgr = inputs;
  12544. };
  12545. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12546. var parsedInputs = parsedCamera.inputsmgr;
  12547. if (parsedInputs) {
  12548. this.clear();
  12549. for (var n in parsedInputs) {
  12550. var construct = BABYLON.CameraInputTypes[n];
  12551. if (construct) {
  12552. var parsedinput = parsedInputs[n];
  12553. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12554. this.add(input);
  12555. }
  12556. }
  12557. }
  12558. else {
  12559. //2016-03-08 this part is for managing backward compatibility
  12560. for (var n in this.attached) {
  12561. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12562. if (construct) {
  12563. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12564. this.remove(this.attached[n]);
  12565. this.add(input);
  12566. }
  12567. }
  12568. }
  12569. };
  12570. return CameraInputsManager;
  12571. }());
  12572. BABYLON.CameraInputsManager = CameraInputsManager;
  12573. })(BABYLON || (BABYLON = {}));
  12574. var BABYLON;
  12575. (function (BABYLON) {
  12576. var FreeCameraMouseInput = (function () {
  12577. function FreeCameraMouseInput(touchEnabled) {
  12578. if (touchEnabled === void 0) { touchEnabled = true; }
  12579. this.touchEnabled = touchEnabled;
  12580. this.angularSensibility = 2000.0;
  12581. }
  12582. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12583. var _this = this;
  12584. if (!this._pointerInput) {
  12585. var camera = this.camera;
  12586. var engine = this.camera.getEngine();
  12587. this._pointerInput = function (p, s) {
  12588. var evt = p.event;
  12589. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12590. return;
  12591. }
  12592. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12593. try {
  12594. evt.srcElement.setPointerCapture(evt.pointerId);
  12595. }
  12596. catch (e) {
  12597. }
  12598. _this.previousPosition = {
  12599. x: evt.clientX,
  12600. y: evt.clientY
  12601. };
  12602. if (!noPreventDefault) {
  12603. evt.preventDefault();
  12604. element.focus();
  12605. }
  12606. }
  12607. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12608. try {
  12609. evt.srcElement.releasePointerCapture(evt.pointerId);
  12610. }
  12611. catch (e) {
  12612. }
  12613. _this.previousPosition = null;
  12614. if (!noPreventDefault) {
  12615. evt.preventDefault();
  12616. }
  12617. }
  12618. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12619. if (!_this.previousPosition && !engine.isPointerLock) {
  12620. return;
  12621. }
  12622. var offsetX;
  12623. var offsetY;
  12624. if (!engine.isPointerLock) {
  12625. offsetX = evt.clientX - _this.previousPosition.x;
  12626. offsetY = evt.clientY - _this.previousPosition.y;
  12627. }
  12628. else {
  12629. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12630. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12631. }
  12632. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12633. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12634. _this.previousPosition = {
  12635. x: evt.clientX,
  12636. y: evt.clientY
  12637. };
  12638. if (!noPreventDefault) {
  12639. evt.preventDefault();
  12640. }
  12641. }
  12642. };
  12643. }
  12644. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12645. };
  12646. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12647. if (this._observer && element) {
  12648. this.camera.getScene().onPointerObservable.remove(this._observer);
  12649. this._observer = null;
  12650. this.previousPosition = null;
  12651. }
  12652. };
  12653. FreeCameraMouseInput.prototype.getTypeName = function () {
  12654. return "FreeCameraMouseInput";
  12655. };
  12656. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12657. return "mouse";
  12658. };
  12659. __decorate([
  12660. BABYLON.serialize()
  12661. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12662. return FreeCameraMouseInput;
  12663. }());
  12664. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12665. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12666. })(BABYLON || (BABYLON = {}));
  12667. var BABYLON;
  12668. (function (BABYLON) {
  12669. var FreeCameraKeyboardMoveInput = (function () {
  12670. function FreeCameraKeyboardMoveInput() {
  12671. this._keys = [];
  12672. this.keysUp = [38];
  12673. this.keysDown = [40];
  12674. this.keysLeft = [37];
  12675. this.keysRight = [39];
  12676. }
  12677. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12678. var _this = this;
  12679. if (!this._onKeyDown) {
  12680. element.tabIndex = 1;
  12681. this._onKeyDown = function (evt) {
  12682. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12683. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12684. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12685. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12686. var index = _this._keys.indexOf(evt.keyCode);
  12687. if (index === -1) {
  12688. _this._keys.push(evt.keyCode);
  12689. }
  12690. if (!noPreventDefault) {
  12691. evt.preventDefault();
  12692. }
  12693. }
  12694. };
  12695. this._onKeyUp = function (evt) {
  12696. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12697. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12698. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12699. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12700. var index = _this._keys.indexOf(evt.keyCode);
  12701. if (index >= 0) {
  12702. _this._keys.splice(index, 1);
  12703. }
  12704. if (!noPreventDefault) {
  12705. evt.preventDefault();
  12706. }
  12707. }
  12708. };
  12709. element.addEventListener("keydown", this._onKeyDown, false);
  12710. element.addEventListener("keyup", this._onKeyUp, false);
  12711. BABYLON.Tools.RegisterTopRootEvents([
  12712. { name: "blur", handler: this._onLostFocus }
  12713. ]);
  12714. }
  12715. };
  12716. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12717. if (this._onKeyDown) {
  12718. element.removeEventListener("keydown", this._onKeyDown);
  12719. element.removeEventListener("keyup", this._onKeyUp);
  12720. BABYLON.Tools.UnregisterTopRootEvents([
  12721. { name: "blur", handler: this._onLostFocus }
  12722. ]);
  12723. this._keys = [];
  12724. this._onKeyDown = null;
  12725. this._onKeyUp = null;
  12726. }
  12727. };
  12728. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12729. if (this._onKeyDown) {
  12730. var camera = this.camera;
  12731. // Keyboard
  12732. for (var index = 0; index < this._keys.length; index++) {
  12733. var keyCode = this._keys[index];
  12734. var speed = camera._computeLocalCameraSpeed();
  12735. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12736. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12737. }
  12738. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12739. camera._localDirection.copyFromFloats(0, 0, speed);
  12740. }
  12741. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12742. camera._localDirection.copyFromFloats(speed, 0, 0);
  12743. }
  12744. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12745. camera._localDirection.copyFromFloats(0, 0, -speed);
  12746. }
  12747. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12748. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12749. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12750. }
  12751. }
  12752. };
  12753. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12754. return "FreeCameraKeyboardMoveInput";
  12755. };
  12756. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12757. this._keys = [];
  12758. };
  12759. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12760. return "keyboard";
  12761. };
  12762. __decorate([
  12763. BABYLON.serialize()
  12764. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12765. __decorate([
  12766. BABYLON.serialize()
  12767. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12768. __decorate([
  12769. BABYLON.serialize()
  12770. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12771. __decorate([
  12772. BABYLON.serialize()
  12773. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12774. return FreeCameraKeyboardMoveInput;
  12775. }());
  12776. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12777. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12778. })(BABYLON || (BABYLON = {}));
  12779. var BABYLON;
  12780. (function (BABYLON) {
  12781. var FreeCameraTouchInput = (function () {
  12782. function FreeCameraTouchInput() {
  12783. this._offsetX = null;
  12784. this._offsetY = null;
  12785. this._pointerCount = 0;
  12786. this._pointerPressed = [];
  12787. this.touchAngularSensibility = 200000.0;
  12788. this.touchMoveSensibility = 250.0;
  12789. }
  12790. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12791. var _this = this;
  12792. var previousPosition;
  12793. if (this._pointerInput === undefined) {
  12794. this._onLostFocus = function (evt) {
  12795. _this._offsetX = null;
  12796. _this._offsetY = null;
  12797. };
  12798. this._pointerInput = function (p, s) {
  12799. var evt = p.event;
  12800. if (evt.pointerType === "mouse") {
  12801. return;
  12802. }
  12803. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12804. if (!noPreventDefault) {
  12805. evt.preventDefault();
  12806. }
  12807. _this._pointerPressed.push(evt.pointerId);
  12808. if (_this._pointerPressed.length !== 1) {
  12809. return;
  12810. }
  12811. previousPosition = {
  12812. x: evt.clientX,
  12813. y: evt.clientY
  12814. };
  12815. }
  12816. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12817. if (!noPreventDefault) {
  12818. evt.preventDefault();
  12819. }
  12820. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12821. if (index === -1) {
  12822. return;
  12823. }
  12824. _this._pointerPressed.splice(index, 1);
  12825. if (index != 0) {
  12826. return;
  12827. }
  12828. previousPosition = null;
  12829. _this._offsetX = null;
  12830. _this._offsetY = null;
  12831. }
  12832. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12833. if (!noPreventDefault) {
  12834. evt.preventDefault();
  12835. }
  12836. if (!previousPosition) {
  12837. return;
  12838. }
  12839. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12840. if (index != 0) {
  12841. return;
  12842. }
  12843. _this._offsetX = evt.clientX - previousPosition.x;
  12844. _this._offsetY = -(evt.clientY - previousPosition.y);
  12845. }
  12846. };
  12847. }
  12848. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12849. element.addEventListener("blur", this._onLostFocus);
  12850. };
  12851. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12852. if (this._pointerInput && element) {
  12853. this.camera.getScene().onPointerObservable.remove(this._observer);
  12854. this._observer = null;
  12855. element.removeEventListener("blur", this._onLostFocus);
  12856. this._onLostFocus = null;
  12857. this._pointerPressed = [];
  12858. this._offsetX = null;
  12859. this._offsetY = null;
  12860. this._pointerCount = 0;
  12861. }
  12862. };
  12863. FreeCameraTouchInput.prototype.checkInputs = function () {
  12864. if (this._offsetX) {
  12865. var camera = this.camera;
  12866. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12867. if (this._pointerPressed.length > 1) {
  12868. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12869. }
  12870. else {
  12871. var speed = camera._computeLocalCameraSpeed();
  12872. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12873. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12874. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12875. }
  12876. }
  12877. };
  12878. FreeCameraTouchInput.prototype.getTypeName = function () {
  12879. return "FreeCameraTouchInput";
  12880. };
  12881. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12882. return "touch";
  12883. };
  12884. __decorate([
  12885. BABYLON.serialize()
  12886. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12887. __decorate([
  12888. BABYLON.serialize()
  12889. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12890. return FreeCameraTouchInput;
  12891. }());
  12892. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12893. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12894. })(BABYLON || (BABYLON = {}));
  12895. var BABYLON;
  12896. (function (BABYLON) {
  12897. var FreeCameraDeviceOrientationInput = (function () {
  12898. function FreeCameraDeviceOrientationInput() {
  12899. var _this = this;
  12900. this._screenOrientationAngle = 0;
  12901. this._screenQuaternion = new BABYLON.Quaternion();
  12902. this._alpha = 0;
  12903. this._beta = 0;
  12904. this._gamma = 0;
  12905. this._orientationChanged = function () {
  12906. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12907. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12908. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12909. };
  12910. this._deviceOrientation = function (evt) {
  12911. _this._alpha = evt.alpha;
  12912. _this._beta = evt.beta;
  12913. _this._gamma = evt.gamma;
  12914. };
  12915. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12916. this._orientationChanged();
  12917. }
  12918. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12919. get: function () {
  12920. return this._camera;
  12921. },
  12922. set: function (camera) {
  12923. this._camera = camera;
  12924. if (!this._camera.rotationQuaternion)
  12925. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12931. window.addEventListener("orientationchange", this._orientationChanged);
  12932. window.addEventListener("deviceorientation", this._deviceOrientation);
  12933. };
  12934. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12935. window.removeEventListener("orientationchange", this._orientationChanged);
  12936. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12937. };
  12938. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12939. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12940. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12941. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12942. //Mirror on XY Plane
  12943. this._camera.rotationQuaternion.z *= -1;
  12944. this._camera.rotationQuaternion.w *= -1;
  12945. };
  12946. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12947. return "FreeCameraDeviceOrientationInput";
  12948. };
  12949. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12950. return "deviceOrientation";
  12951. };
  12952. return FreeCameraDeviceOrientationInput;
  12953. }());
  12954. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12955. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12956. })(BABYLON || (BABYLON = {}));
  12957. var BABYLON;
  12958. (function (BABYLON) {
  12959. var FreeCameraVRDeviceOrientationInput = (function () {
  12960. function FreeCameraVRDeviceOrientationInput() {
  12961. this.alphaCorrection = 1;
  12962. this.betaCorrection = 1;
  12963. this.gammaCorrection = 1;
  12964. this._alpha = 0;
  12965. this._beta = 0;
  12966. this._gamma = 0;
  12967. this._dirty = false;
  12968. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12969. }
  12970. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12971. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12972. };
  12973. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12974. var camera = this.camera;
  12975. this._alpha = evt.alpha;
  12976. this._beta = evt.beta;
  12977. this._gamma = evt.gamma;
  12978. this._dirty = true;
  12979. };
  12980. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12981. if (this._dirty) {
  12982. this._dirty = false;
  12983. var rotationX = this._gamma;
  12984. if (rotationX < 0) {
  12985. rotationX = 90 + rotationX;
  12986. }
  12987. else {
  12988. // Incline it in the correct angle.
  12989. rotationX = 270 - rotationX;
  12990. }
  12991. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12992. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12993. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12994. }
  12995. };
  12996. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12997. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12998. };
  12999. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13000. return "FreeCameraVRDeviceOrientationInput";
  13001. };
  13002. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13003. return "VRDeviceOrientation";
  13004. };
  13005. return FreeCameraVRDeviceOrientationInput;
  13006. }());
  13007. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  13008. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  13009. })(BABYLON || (BABYLON = {}));
  13010. var BABYLON;
  13011. (function (BABYLON) {
  13012. var FreeCameraGamepadInput = (function () {
  13013. function FreeCameraGamepadInput() {
  13014. this.gamepadAngularSensibility = 200;
  13015. this.gamepadMoveSensibility = 40;
  13016. }
  13017. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13018. var _this = this;
  13019. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13020. };
  13021. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13022. if (this._gamepads) {
  13023. this._gamepads.dispose();
  13024. }
  13025. this.gamepad = null;
  13026. };
  13027. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13028. if (this.gamepad) {
  13029. var camera = this.camera;
  13030. var LSValues = this.gamepad.leftStick;
  13031. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13032. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13033. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13034. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13035. var RSValues = this.gamepad.rightStick;
  13036. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13037. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13038. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13039. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13040. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13041. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13042. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13043. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13044. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13045. }
  13046. };
  13047. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13048. // Only the first gamepad can control the camera
  13049. if (gamepad.index === 0) {
  13050. this.gamepad = gamepad;
  13051. }
  13052. };
  13053. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13054. return "FreeCameraGamepadInput";
  13055. };
  13056. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13057. return "gamepad";
  13058. };
  13059. __decorate([
  13060. BABYLON.serialize()
  13061. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13062. __decorate([
  13063. BABYLON.serialize()
  13064. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13065. return FreeCameraGamepadInput;
  13066. }());
  13067. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13068. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13069. })(BABYLON || (BABYLON = {}));
  13070. var BABYLON;
  13071. (function (BABYLON) {
  13072. var ArcRotateCameraKeyboardMoveInput = (function () {
  13073. function ArcRotateCameraKeyboardMoveInput() {
  13074. this._keys = [];
  13075. this.keysUp = [38];
  13076. this.keysDown = [40];
  13077. this.keysLeft = [37];
  13078. this.keysRight = [39];
  13079. }
  13080. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13081. var _this = this;
  13082. element.tabIndex = 1;
  13083. this._onKeyDown = function (evt) {
  13084. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13085. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13086. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13087. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13088. var index = _this._keys.indexOf(evt.keyCode);
  13089. if (index === -1) {
  13090. _this._keys.push(evt.keyCode);
  13091. }
  13092. if (evt.preventDefault) {
  13093. if (!noPreventDefault) {
  13094. evt.preventDefault();
  13095. }
  13096. }
  13097. }
  13098. };
  13099. this._onKeyUp = function (evt) {
  13100. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13101. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13102. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13103. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13104. var index = _this._keys.indexOf(evt.keyCode);
  13105. if (index >= 0) {
  13106. _this._keys.splice(index, 1);
  13107. }
  13108. if (evt.preventDefault) {
  13109. if (!noPreventDefault) {
  13110. evt.preventDefault();
  13111. }
  13112. }
  13113. }
  13114. };
  13115. this._onLostFocus = function () {
  13116. _this._keys = [];
  13117. };
  13118. element.addEventListener("keydown", this._onKeyDown, false);
  13119. element.addEventListener("keyup", this._onKeyUp, false);
  13120. BABYLON.Tools.RegisterTopRootEvents([
  13121. { name: "blur", handler: this._onLostFocus }
  13122. ]);
  13123. };
  13124. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13125. if (element) {
  13126. element.removeEventListener("keydown", this._onKeyDown);
  13127. element.removeEventListener("keyup", this._onKeyUp);
  13128. }
  13129. BABYLON.Tools.UnregisterTopRootEvents([
  13130. { name: "blur", handler: this._onLostFocus }
  13131. ]);
  13132. this._keys = [];
  13133. this._onKeyDown = null;
  13134. this._onKeyUp = null;
  13135. this._onLostFocus = null;
  13136. };
  13137. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13138. if (this._onKeyDown) {
  13139. var camera = this.camera;
  13140. for (var index = 0; index < this._keys.length; index++) {
  13141. var keyCode = this._keys[index];
  13142. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13143. camera.inertialAlphaOffset -= 0.01;
  13144. }
  13145. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13146. camera.inertialBetaOffset -= 0.01;
  13147. }
  13148. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13149. camera.inertialAlphaOffset += 0.01;
  13150. }
  13151. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13152. camera.inertialBetaOffset += 0.01;
  13153. }
  13154. }
  13155. }
  13156. };
  13157. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13158. return "ArcRotateCameraKeyboardMoveInput";
  13159. };
  13160. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13161. return "keyboard";
  13162. };
  13163. __decorate([
  13164. BABYLON.serialize()
  13165. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13166. __decorate([
  13167. BABYLON.serialize()
  13168. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13169. __decorate([
  13170. BABYLON.serialize()
  13171. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13172. __decorate([
  13173. BABYLON.serialize()
  13174. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13175. return ArcRotateCameraKeyboardMoveInput;
  13176. }());
  13177. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13178. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13179. })(BABYLON || (BABYLON = {}));
  13180. var BABYLON;
  13181. (function (BABYLON) {
  13182. var ArcRotateCameraMouseWheelInput = (function () {
  13183. function ArcRotateCameraMouseWheelInput() {
  13184. this.wheelPrecision = 3.0;
  13185. }
  13186. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13187. var _this = this;
  13188. this._wheel = function (p, s) {
  13189. //sanity check - this should be a PointerWheel event.
  13190. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13191. return;
  13192. var event = p.event;
  13193. var delta = 0;
  13194. if (event.wheelDelta) {
  13195. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13196. }
  13197. else if (event.detail) {
  13198. delta = -event.detail / _this.wheelPrecision;
  13199. }
  13200. if (delta)
  13201. _this.camera.inertialRadiusOffset += delta;
  13202. if (event.preventDefault) {
  13203. if (!noPreventDefault) {
  13204. event.preventDefault();
  13205. }
  13206. }
  13207. };
  13208. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13209. };
  13210. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13211. if (this._observer && element) {
  13212. this.camera.getScene().onPointerObservable.remove(this._observer);
  13213. this._observer = null;
  13214. this._wheel = null;
  13215. }
  13216. };
  13217. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13218. return "ArcRotateCameraMouseWheelInput";
  13219. };
  13220. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13221. return "mousewheel";
  13222. };
  13223. __decorate([
  13224. BABYLON.serialize()
  13225. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13226. return ArcRotateCameraMouseWheelInput;
  13227. }());
  13228. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13229. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13230. })(BABYLON || (BABYLON = {}));
  13231. var BABYLON;
  13232. (function (BABYLON) {
  13233. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13234. var ArcRotateCameraPointersInput = (function () {
  13235. function ArcRotateCameraPointersInput() {
  13236. this.angularSensibilityX = 1000.0;
  13237. this.angularSensibilityY = 1000.0;
  13238. this.pinchPrecision = 6.0;
  13239. this.panningSensibility = 50.0;
  13240. this._isPanClick = false;
  13241. this._isCtrlPushed = false;
  13242. this.pinchInwards = true;
  13243. }
  13244. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13245. var _this = this;
  13246. var engine = this.camera.getEngine();
  13247. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13248. var pointA, pointB;
  13249. var previousPinchDistance = 0;
  13250. this._pointerInput = function (p, s) {
  13251. var evt = p.event;
  13252. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13253. try {
  13254. evt.srcElement.setPointerCapture(evt.pointerId);
  13255. }
  13256. catch (e) {
  13257. }
  13258. // Manage panning with pan button click
  13259. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13260. // manage pointers
  13261. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13262. if (pointA === undefined) {
  13263. pointA = cacheSoloPointer;
  13264. }
  13265. else if (pointB === undefined) {
  13266. pointB = cacheSoloPointer;
  13267. }
  13268. if (!noPreventDefault) {
  13269. evt.preventDefault();
  13270. element.focus();
  13271. }
  13272. }
  13273. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13274. try {
  13275. evt.srcElement.releasePointerCapture(evt.pointerId);
  13276. }
  13277. catch (e) {
  13278. }
  13279. cacheSoloPointer = null;
  13280. previousPinchDistance = 0;
  13281. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13282. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13283. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13284. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13285. pointA = pointB = undefined;
  13286. if (!noPreventDefault) {
  13287. evt.preventDefault();
  13288. }
  13289. }
  13290. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13291. if (!noPreventDefault) {
  13292. evt.preventDefault();
  13293. }
  13294. // One button down
  13295. if (pointA && pointB === undefined) {
  13296. if (_this.panningSensibility !== 0 &&
  13297. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  13298. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13299. _this.camera
  13300. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13301. _this.camera
  13302. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13303. }
  13304. else {
  13305. var offsetX = evt.clientX - cacheSoloPointer.x;
  13306. var offsetY = evt.clientY - cacheSoloPointer.y;
  13307. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13308. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13309. }
  13310. cacheSoloPointer.x = evt.clientX;
  13311. cacheSoloPointer.y = evt.clientY;
  13312. }
  13313. else if (pointA && pointB) {
  13314. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13315. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13316. ed.x = evt.clientX;
  13317. ed.y = evt.clientY;
  13318. var direction = _this.pinchInwards ? 1 : -1;
  13319. var distX = pointA.x - pointB.x;
  13320. var distY = pointA.y - pointB.y;
  13321. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13322. if (previousPinchDistance === 0) {
  13323. previousPinchDistance = pinchSquaredDistance;
  13324. return;
  13325. }
  13326. if (pinchSquaredDistance !== previousPinchDistance) {
  13327. _this.camera
  13328. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13329. (_this.pinchPrecision *
  13330. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13331. direction);
  13332. previousPinchDistance = pinchSquaredDistance;
  13333. }
  13334. }
  13335. }
  13336. };
  13337. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13338. this._onContextMenu = function (evt) {
  13339. evt.preventDefault();
  13340. };
  13341. if (!this.camera._useCtrlForPanning) {
  13342. element.addEventListener("contextmenu", this._onContextMenu, false);
  13343. }
  13344. this._onLostFocus = function () {
  13345. //this._keys = [];
  13346. pointA = pointB = undefined;
  13347. previousPinchDistance = 0;
  13348. cacheSoloPointer = null;
  13349. };
  13350. this._onKeyDown = function (evt) {
  13351. _this._isCtrlPushed = evt.ctrlKey;
  13352. };
  13353. this._onKeyUp = function (evt) {
  13354. _this._isCtrlPushed = evt.ctrlKey;
  13355. };
  13356. this._onMouseMove = function (evt) {
  13357. if (!engine.isPointerLock) {
  13358. return;
  13359. }
  13360. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13361. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13362. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13363. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13364. if (!noPreventDefault) {
  13365. evt.preventDefault();
  13366. }
  13367. };
  13368. this._onGestureStart = function (e) {
  13369. if (window.MSGesture === undefined) {
  13370. return;
  13371. }
  13372. if (!_this._MSGestureHandler) {
  13373. _this._MSGestureHandler = new MSGesture();
  13374. _this._MSGestureHandler.target = element;
  13375. }
  13376. _this._MSGestureHandler.addPointer(e.pointerId);
  13377. };
  13378. this._onGesture = function (e) {
  13379. _this.camera.radius *= e.scale;
  13380. if (e.preventDefault) {
  13381. if (!noPreventDefault) {
  13382. e.stopPropagation();
  13383. e.preventDefault();
  13384. }
  13385. }
  13386. };
  13387. element.addEventListener("mousemove", this._onMouseMove, false);
  13388. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13389. element.addEventListener("MSGestureChange", this._onGesture, false);
  13390. element.addEventListener("keydown", this._onKeyDown, false);
  13391. element.addEventListener("keyup", this._onKeyUp, false);
  13392. BABYLON.Tools.RegisterTopRootEvents([
  13393. { name: "blur", handler: this._onLostFocus }
  13394. ]);
  13395. };
  13396. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13397. if (element && this._observer) {
  13398. this.camera.getScene().onPointerObservable.remove(this._observer);
  13399. this._observer = null;
  13400. element.removeEventListener("contextmenu", this._onContextMenu);
  13401. element.removeEventListener("mousemove", this._onMouseMove);
  13402. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13403. element.removeEventListener("MSGestureChange", this._onGesture);
  13404. element.removeEventListener("keydown", this._onKeyDown);
  13405. element.removeEventListener("keyup", this._onKeyUp);
  13406. this._isPanClick = false;
  13407. this._isCtrlPushed = false;
  13408. this.pinchInwards = true;
  13409. this._onKeyDown = null;
  13410. this._onKeyUp = null;
  13411. this._onMouseMove = null;
  13412. this._onGestureStart = null;
  13413. this._onGesture = null;
  13414. this._MSGestureHandler = null;
  13415. this._onLostFocus = null;
  13416. this._onContextMenu = null;
  13417. }
  13418. BABYLON.Tools.UnregisterTopRootEvents([
  13419. { name: "blur", handler: this._onLostFocus }
  13420. ]);
  13421. };
  13422. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13423. return "ArcRotateCameraPointersInput";
  13424. };
  13425. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13426. return "pointers";
  13427. };
  13428. __decorate([
  13429. BABYLON.serialize()
  13430. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13431. __decorate([
  13432. BABYLON.serialize()
  13433. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13434. __decorate([
  13435. BABYLON.serialize()
  13436. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13437. __decorate([
  13438. BABYLON.serialize()
  13439. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13440. return ArcRotateCameraPointersInput;
  13441. }());
  13442. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13443. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13444. })(BABYLON || (BABYLON = {}));
  13445. var BABYLON;
  13446. (function (BABYLON) {
  13447. var ArcRotateCameraGamepadInput = (function () {
  13448. function ArcRotateCameraGamepadInput() {
  13449. this.gamepadRotationSensibility = 80;
  13450. this.gamepadMoveSensibility = 40;
  13451. }
  13452. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13453. var _this = this;
  13454. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13455. };
  13456. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13457. if (this._gamepads) {
  13458. this._gamepads.dispose();
  13459. }
  13460. this.gamepad = null;
  13461. };
  13462. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13463. if (this.gamepad) {
  13464. var camera = this.camera;
  13465. var RSValues = this.gamepad.rightStick;
  13466. if (RSValues.x != 0) {
  13467. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13468. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13469. camera.inertialAlphaOffset += normalizedRX;
  13470. }
  13471. }
  13472. if (RSValues.y != 0) {
  13473. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13474. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13475. camera.inertialBetaOffset += normalizedRY;
  13476. }
  13477. }
  13478. var LSValues = this.gamepad.leftStick;
  13479. if (LSValues.y != 0) {
  13480. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13481. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13482. this.camera.inertialRadiusOffset -= normalizedLY;
  13483. }
  13484. }
  13485. }
  13486. };
  13487. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13488. // Only the first gamepad can control the camera
  13489. if (gamepad.index === 0) {
  13490. this.gamepad = gamepad;
  13491. }
  13492. };
  13493. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13494. return "ArcRotateCameraGamepadInput";
  13495. };
  13496. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13497. return "gamepad";
  13498. };
  13499. __decorate([
  13500. BABYLON.serialize()
  13501. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13502. __decorate([
  13503. BABYLON.serialize()
  13504. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13505. return ArcRotateCameraGamepadInput;
  13506. }());
  13507. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13508. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13509. })(BABYLON || (BABYLON = {}));
  13510. var BABYLON;
  13511. (function (BABYLON) {
  13512. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13513. function ArcRotateCameraVRDeviceOrientationInput() {
  13514. this.alphaCorrection = 1;
  13515. this.betaCorrection = 1;
  13516. this.gammaCorrection = 1;
  13517. this._alpha = 0;
  13518. this._beta = 0;
  13519. this._gamma = 0;
  13520. this._dirty = false;
  13521. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13522. }
  13523. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13524. this.camera.attachControl(element, noPreventDefault);
  13525. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13526. };
  13527. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13528. var camera = this.camera;
  13529. this._alpha = +evt.alpha | 0;
  13530. this._beta = +evt.beta | 0;
  13531. this._gamma = +evt.gamma | 0;
  13532. this._dirty = true;
  13533. };
  13534. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13535. if (this._dirty) {
  13536. this._dirty = false;
  13537. if (this._gamma < 0) {
  13538. this._gamma = 180 + this._gamma;
  13539. }
  13540. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13541. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13542. }
  13543. };
  13544. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13545. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13546. };
  13547. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13548. return "ArcRotateCameraVRDeviceOrientationInput";
  13549. };
  13550. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13551. return "VRDeviceOrientation";
  13552. };
  13553. return ArcRotateCameraVRDeviceOrientationInput;
  13554. }());
  13555. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13556. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13557. })(BABYLON || (BABYLON = {}));
  13558. var BABYLON;
  13559. (function (BABYLON) {
  13560. var TargetCamera = (function (_super) {
  13561. __extends(TargetCamera, _super);
  13562. function TargetCamera(name, position, scene) {
  13563. _super.call(this, name, position, scene);
  13564. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13565. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13566. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13567. this.speed = 2.0;
  13568. this.noRotationConstraint = false;
  13569. this.lockedTarget = null;
  13570. this._currentTarget = BABYLON.Vector3.Zero();
  13571. this._viewMatrix = BABYLON.Matrix.Zero();
  13572. this._camMatrix = BABYLON.Matrix.Zero();
  13573. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13574. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13575. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13576. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13577. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13578. this._lookAtTemp = BABYLON.Matrix.Zero();
  13579. this._tempMatrix = BABYLON.Matrix.Zero();
  13580. }
  13581. TargetCamera.prototype.getFrontPosition = function (distance) {
  13582. var direction = this.getTarget().subtract(this.position);
  13583. direction.normalize();
  13584. direction.scaleInPlace(distance);
  13585. return this.globalPosition.add(direction);
  13586. };
  13587. TargetCamera.prototype._getLockedTargetPosition = function () {
  13588. if (!this.lockedTarget) {
  13589. return null;
  13590. }
  13591. return this.lockedTarget.position || this.lockedTarget;
  13592. };
  13593. // Cache
  13594. TargetCamera.prototype._initCache = function () {
  13595. _super.prototype._initCache.call(this);
  13596. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13597. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13598. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13599. };
  13600. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13601. if (!ignoreParentClass) {
  13602. _super.prototype._updateCache.call(this);
  13603. }
  13604. var lockedTargetPosition = this._getLockedTargetPosition();
  13605. if (!lockedTargetPosition) {
  13606. this._cache.lockedTarget = null;
  13607. }
  13608. else {
  13609. if (!this._cache.lockedTarget) {
  13610. this._cache.lockedTarget = lockedTargetPosition.clone();
  13611. }
  13612. else {
  13613. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13614. }
  13615. }
  13616. this._cache.rotation.copyFrom(this.rotation);
  13617. if (this.rotationQuaternion)
  13618. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13619. };
  13620. // Synchronized
  13621. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13622. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13623. return false;
  13624. }
  13625. var lockedTargetPosition = this._getLockedTargetPosition();
  13626. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13627. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13628. };
  13629. // Methods
  13630. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13631. var engine = this.getEngine();
  13632. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13633. };
  13634. // Target
  13635. TargetCamera.prototype.setTarget = function (target) {
  13636. this.upVector.normalize();
  13637. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13638. this._camMatrix.invert();
  13639. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13640. var vDir = target.subtract(this.position);
  13641. if (vDir.x >= 0.0) {
  13642. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13643. }
  13644. else {
  13645. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13646. }
  13647. this.rotation.z = 0;
  13648. if (isNaN(this.rotation.x)) {
  13649. this.rotation.x = 0;
  13650. }
  13651. if (isNaN(this.rotation.y)) {
  13652. this.rotation.y = 0;
  13653. }
  13654. if (isNaN(this.rotation.z)) {
  13655. this.rotation.z = 0;
  13656. }
  13657. if (this.rotationQuaternion) {
  13658. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13659. }
  13660. };
  13661. TargetCamera.prototype.getTarget = function () {
  13662. return this._currentTarget;
  13663. };
  13664. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13665. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13666. };
  13667. TargetCamera.prototype._updatePosition = function () {
  13668. this.position.addInPlace(this.cameraDirection);
  13669. };
  13670. TargetCamera.prototype._checkInputs = function () {
  13671. var needToMove = this._decideIfNeedsToMove();
  13672. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13673. // Move
  13674. if (needToMove) {
  13675. this._updatePosition();
  13676. }
  13677. // Rotate
  13678. if (needToRotate) {
  13679. this.rotation.x += this.cameraRotation.x;
  13680. this.rotation.y += this.cameraRotation.y;
  13681. if (!this.noRotationConstraint) {
  13682. var limit = (Math.PI / 2) * 0.95;
  13683. if (this.rotation.x > limit)
  13684. this.rotation.x = limit;
  13685. if (this.rotation.x < -limit)
  13686. this.rotation.x = -limit;
  13687. }
  13688. }
  13689. // Inertia
  13690. if (needToMove) {
  13691. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13692. this.cameraDirection.x = 0;
  13693. }
  13694. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13695. this.cameraDirection.y = 0;
  13696. }
  13697. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13698. this.cameraDirection.z = 0;
  13699. }
  13700. this.cameraDirection.scaleInPlace(this.inertia);
  13701. }
  13702. if (needToRotate) {
  13703. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13704. this.cameraRotation.x = 0;
  13705. }
  13706. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13707. this.cameraRotation.y = 0;
  13708. }
  13709. this.cameraRotation.scaleInPlace(this.inertia);
  13710. }
  13711. _super.prototype._checkInputs.call(this);
  13712. };
  13713. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13714. if (this.rotationQuaternion) {
  13715. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13716. //update the up vector!
  13717. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13718. }
  13719. else {
  13720. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13721. }
  13722. };
  13723. TargetCamera.prototype._getViewMatrix = function () {
  13724. if (!this.lockedTarget) {
  13725. // Compute
  13726. this._updateCameraRotationMatrix();
  13727. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13728. // Computing target and final matrix
  13729. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13730. }
  13731. else {
  13732. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13733. }
  13734. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13735. return this._viewMatrix;
  13736. };
  13737. /**
  13738. * @override
  13739. * Override Camera.createRigCamera
  13740. */
  13741. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13742. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13743. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13744. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13745. if (!this.rotationQuaternion) {
  13746. this.rotationQuaternion = new BABYLON.Quaternion();
  13747. }
  13748. rigCamera._cameraRigParams = {};
  13749. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13750. }
  13751. return rigCamera;
  13752. }
  13753. return null;
  13754. };
  13755. /**
  13756. * @override
  13757. * Override Camera._updateRigCameras
  13758. */
  13759. TargetCamera.prototype._updateRigCameras = function () {
  13760. var camLeft = this._rigCameras[0];
  13761. var camRight = this._rigCameras[1];
  13762. switch (this.cameraRigMode) {
  13763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13764. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13767. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13768. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13769. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13770. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13771. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13772. camLeft.setTarget(this.getTarget());
  13773. camRight.setTarget(this.getTarget());
  13774. break;
  13775. case BABYLON.Camera.RIG_MODE_VR:
  13776. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13777. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13778. camLeft.position.copyFrom(this.position);
  13779. camRight.position.copyFrom(this.position);
  13780. break;
  13781. }
  13782. _super.prototype._updateRigCameras.call(this);
  13783. };
  13784. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13785. if (!this._rigCamTransformMatrix) {
  13786. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13787. }
  13788. var target = this.getTarget();
  13789. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13790. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13791. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13792. };
  13793. TargetCamera.prototype.getTypeName = function () {
  13794. return "TargetCamera";
  13795. };
  13796. __decorate([
  13797. BABYLON.serializeAsVector3()
  13798. ], TargetCamera.prototype, "rotation", void 0);
  13799. __decorate([
  13800. BABYLON.serialize()
  13801. ], TargetCamera.prototype, "speed", void 0);
  13802. __decorate([
  13803. BABYLON.serializeAsMeshReference("lockedTargetId")
  13804. ], TargetCamera.prototype, "lockedTarget", void 0);
  13805. return TargetCamera;
  13806. }(BABYLON.Camera));
  13807. BABYLON.TargetCamera = TargetCamera;
  13808. })(BABYLON || (BABYLON = {}));
  13809. var BABYLON;
  13810. (function (BABYLON) {
  13811. var FreeCamera = (function (_super) {
  13812. __extends(FreeCamera, _super);
  13813. function FreeCamera(name, position, scene) {
  13814. var _this = this;
  13815. _super.call(this, name, position, scene);
  13816. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13817. this.checkCollisions = false;
  13818. this.applyGravity = false;
  13819. this._collider = new BABYLON.Collider();
  13820. this._needMoveForGravity = false;
  13821. this._oldPosition = BABYLON.Vector3.Zero();
  13822. this._diffPosition = BABYLON.Vector3.Zero();
  13823. this._newPosition = BABYLON.Vector3.Zero();
  13824. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13825. if (collidedMesh === void 0) { collidedMesh = null; }
  13826. //TODO move this to the collision coordinator!
  13827. if (_this.getScene().workerCollisions)
  13828. newPosition.multiplyInPlace(_this._collider.radius);
  13829. var updatePosition = function (newPos) {
  13830. _this._newPosition.copyFrom(newPos);
  13831. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13832. var oldPosition = _this.position.clone();
  13833. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13834. _this.position.addInPlace(_this._diffPosition);
  13835. if (_this.onCollide && collidedMesh) {
  13836. _this.onCollide(collidedMesh);
  13837. }
  13838. }
  13839. };
  13840. updatePosition(newPosition);
  13841. };
  13842. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13843. this.inputs.addKeyboard().addMouse();
  13844. }
  13845. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13846. //-- begin properties for backward compatibility for inputs
  13847. get: function () {
  13848. var mouse = this.inputs.attached["mouse"];
  13849. if (mouse)
  13850. return mouse.angularSensibility;
  13851. },
  13852. set: function (value) {
  13853. var mouse = this.inputs.attached["mouse"];
  13854. if (mouse)
  13855. mouse.angularSensibility = value;
  13856. },
  13857. enumerable: true,
  13858. configurable: true
  13859. });
  13860. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13861. get: function () {
  13862. var keyboard = this.inputs.attached["keyboard"];
  13863. if (keyboard)
  13864. return keyboard.keysUp;
  13865. },
  13866. set: function (value) {
  13867. var keyboard = this.inputs.attached["keyboard"];
  13868. if (keyboard)
  13869. keyboard.keysUp = value;
  13870. },
  13871. enumerable: true,
  13872. configurable: true
  13873. });
  13874. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13875. get: function () {
  13876. var keyboard = this.inputs.attached["keyboard"];
  13877. if (keyboard)
  13878. return keyboard.keysDown;
  13879. },
  13880. set: function (value) {
  13881. var keyboard = this.inputs.attached["keyboard"];
  13882. if (keyboard)
  13883. keyboard.keysDown = value;
  13884. },
  13885. enumerable: true,
  13886. configurable: true
  13887. });
  13888. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13889. get: function () {
  13890. var keyboard = this.inputs.attached["keyboard"];
  13891. if (keyboard)
  13892. return keyboard.keysLeft;
  13893. },
  13894. set: function (value) {
  13895. var keyboard = this.inputs.attached["keyboard"];
  13896. if (keyboard)
  13897. keyboard.keysLeft = value;
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13903. get: function () {
  13904. var keyboard = this.inputs.attached["keyboard"];
  13905. if (keyboard)
  13906. return keyboard.keysRight;
  13907. },
  13908. set: function (value) {
  13909. var keyboard = this.inputs.attached["keyboard"];
  13910. if (keyboard)
  13911. keyboard.keysRight = value;
  13912. },
  13913. enumerable: true,
  13914. configurable: true
  13915. });
  13916. // Controls
  13917. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13918. this.inputs.attachElement(element, noPreventDefault);
  13919. };
  13920. FreeCamera.prototype.detachControl = function (element) {
  13921. this.inputs.detachElement(element);
  13922. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13923. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13924. };
  13925. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13926. var globalPosition;
  13927. if (this.parent) {
  13928. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13929. }
  13930. else {
  13931. globalPosition = this.position;
  13932. }
  13933. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13934. this._collider.radius = this.ellipsoid;
  13935. //no need for clone, as long as gravity is not on.
  13936. var actualVelocity = velocity;
  13937. //add gravity to the velocity to prevent the dual-collision checking
  13938. if (this.applyGravity) {
  13939. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13940. actualVelocity = velocity.add(this.getScene().gravity);
  13941. }
  13942. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13943. };
  13944. FreeCamera.prototype._checkInputs = function () {
  13945. if (!this._localDirection) {
  13946. this._localDirection = BABYLON.Vector3.Zero();
  13947. this._transformedDirection = BABYLON.Vector3.Zero();
  13948. }
  13949. this.inputs.checkInputs();
  13950. _super.prototype._checkInputs.call(this);
  13951. };
  13952. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13953. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13954. };
  13955. FreeCamera.prototype._updatePosition = function () {
  13956. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13957. this._collideWithWorld(this.cameraDirection);
  13958. }
  13959. else {
  13960. this.position.addInPlace(this.cameraDirection);
  13961. }
  13962. };
  13963. FreeCamera.prototype.dispose = function () {
  13964. this.inputs.clear();
  13965. _super.prototype.dispose.call(this);
  13966. };
  13967. FreeCamera.prototype.getTypeName = function () {
  13968. return "FreeCamera";
  13969. };
  13970. __decorate([
  13971. BABYLON.serializeAsVector3()
  13972. ], FreeCamera.prototype, "ellipsoid", void 0);
  13973. __decorate([
  13974. BABYLON.serialize()
  13975. ], FreeCamera.prototype, "checkCollisions", void 0);
  13976. __decorate([
  13977. BABYLON.serialize()
  13978. ], FreeCamera.prototype, "applyGravity", void 0);
  13979. return FreeCamera;
  13980. }(BABYLON.TargetCamera));
  13981. BABYLON.FreeCamera = FreeCamera;
  13982. })(BABYLON || (BABYLON = {}));
  13983. var BABYLON;
  13984. (function (BABYLON) {
  13985. var FreeCameraInputsManager = (function (_super) {
  13986. __extends(FreeCameraInputsManager, _super);
  13987. function FreeCameraInputsManager(camera) {
  13988. _super.call(this, camera);
  13989. }
  13990. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13991. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13992. return this;
  13993. };
  13994. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13995. if (touchEnabled === void 0) { touchEnabled = true; }
  13996. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13997. return this;
  13998. };
  13999. FreeCameraInputsManager.prototype.addGamepad = function () {
  14000. this.add(new BABYLON.FreeCameraGamepadInput());
  14001. return this;
  14002. };
  14003. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14004. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14005. return this;
  14006. };
  14007. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14008. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  14009. return this;
  14010. };
  14011. FreeCameraInputsManager.prototype.addTouch = function () {
  14012. this.add(new BABYLON.FreeCameraTouchInput());
  14013. return this;
  14014. };
  14015. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14016. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14017. return this;
  14018. };
  14019. return FreeCameraInputsManager;
  14020. }(BABYLON.CameraInputsManager));
  14021. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14022. })(BABYLON || (BABYLON = {}));
  14023. var BABYLON;
  14024. (function (BABYLON) {
  14025. var FollowCamera = (function (_super) {
  14026. __extends(FollowCamera, _super);
  14027. function FollowCamera(name, position, scene, target) {
  14028. _super.call(this, name, position, scene);
  14029. this.radius = 12;
  14030. this.rotationOffset = 0;
  14031. this.heightOffset = 4;
  14032. this.cameraAcceleration = 0.05;
  14033. this.maxCameraSpeed = 20;
  14034. this.target = target;
  14035. }
  14036. FollowCamera.prototype.getRadians = function (degrees) {
  14037. return degrees * Math.PI / 180;
  14038. };
  14039. FollowCamera.prototype.follow = function (cameraTarget) {
  14040. if (!cameraTarget)
  14041. return;
  14042. var yRotation;
  14043. if (cameraTarget.rotationQuaternion) {
  14044. var rotMatrix = new BABYLON.Matrix();
  14045. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14046. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14047. }
  14048. else {
  14049. yRotation = cameraTarget.rotation.y;
  14050. }
  14051. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14052. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14053. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14054. var dx = targetX - this.position.x;
  14055. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14056. var dz = (targetZ) - this.position.z;
  14057. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14058. var vy = dy * this.cameraAcceleration;
  14059. var vz = dz * this.cameraAcceleration * 2;
  14060. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14061. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14062. }
  14063. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14064. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14065. }
  14066. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14067. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14068. }
  14069. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14070. this.setTarget(cameraTarget.position);
  14071. };
  14072. FollowCamera.prototype._checkInputs = function () {
  14073. _super.prototype._checkInputs.call(this);
  14074. this.follow(this.target);
  14075. };
  14076. FollowCamera.prototype.getTypeName = function () {
  14077. return "FollowCamera";
  14078. };
  14079. __decorate([
  14080. BABYLON.serialize()
  14081. ], FollowCamera.prototype, "radius", void 0);
  14082. __decorate([
  14083. BABYLON.serialize()
  14084. ], FollowCamera.prototype, "rotationOffset", void 0);
  14085. __decorate([
  14086. BABYLON.serialize()
  14087. ], FollowCamera.prototype, "heightOffset", void 0);
  14088. __decorate([
  14089. BABYLON.serialize()
  14090. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14091. __decorate([
  14092. BABYLON.serialize()
  14093. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14094. __decorate([
  14095. BABYLON.serializeAsMeshReference("lockedTargetId")
  14096. ], FollowCamera.prototype, "target", void 0);
  14097. return FollowCamera;
  14098. }(BABYLON.TargetCamera));
  14099. BABYLON.FollowCamera = FollowCamera;
  14100. var ArcFollowCamera = (function (_super) {
  14101. __extends(ArcFollowCamera, _super);
  14102. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14103. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14104. this.alpha = alpha;
  14105. this.beta = beta;
  14106. this.radius = radius;
  14107. this.target = target;
  14108. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14109. this.follow();
  14110. }
  14111. ArcFollowCamera.prototype.follow = function () {
  14112. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14113. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14114. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14115. this.position = this.target.position.add(this._cartesianCoordinates);
  14116. this.setTarget(this.target.position);
  14117. };
  14118. ArcFollowCamera.prototype._checkInputs = function () {
  14119. _super.prototype._checkInputs.call(this);
  14120. this.follow();
  14121. };
  14122. ArcFollowCamera.prototype.getTypeName = function () {
  14123. return "ArcFollowCamera";
  14124. };
  14125. return ArcFollowCamera;
  14126. }(BABYLON.TargetCamera));
  14127. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14128. })(BABYLON || (BABYLON = {}));
  14129. var BABYLON;
  14130. (function (BABYLON) {
  14131. // We're mainly based on the logic defined into the FreeCamera code
  14132. var TouchCamera = (function (_super) {
  14133. __extends(TouchCamera, _super);
  14134. //-- end properties for backward compatibility for inputs
  14135. function TouchCamera(name, position, scene) {
  14136. _super.call(this, name, position, scene);
  14137. this.inputs.addTouch();
  14138. this._setupInputs();
  14139. }
  14140. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14141. //-- Begin properties for backward compatibility for inputs
  14142. get: function () {
  14143. var touch = this.inputs.attached["touch"];
  14144. if (touch)
  14145. return touch.touchAngularSensibility;
  14146. },
  14147. set: function (value) {
  14148. var touch = this.inputs.attached["touch"];
  14149. if (touch)
  14150. touch.touchAngularSensibility = value;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14156. get: function () {
  14157. var touch = this.inputs.attached["touch"];
  14158. if (touch)
  14159. return touch.touchMoveSensibility;
  14160. },
  14161. set: function (value) {
  14162. var touch = this.inputs.attached["touch"];
  14163. if (touch)
  14164. touch.touchMoveSensibility = value;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. TouchCamera.prototype.getTypeName = function () {
  14170. return "TouchCamera";
  14171. };
  14172. TouchCamera.prototype._setupInputs = function () {
  14173. var mouse = this.inputs.attached["mouse"];
  14174. if (mouse) {
  14175. mouse.touchEnabled = false;
  14176. }
  14177. };
  14178. return TouchCamera;
  14179. }(BABYLON.FreeCamera));
  14180. BABYLON.TouchCamera = TouchCamera;
  14181. })(BABYLON || (BABYLON = {}));
  14182. var BABYLON;
  14183. (function (BABYLON) {
  14184. var ArcRotateCamera = (function (_super) {
  14185. __extends(ArcRotateCamera, _super);
  14186. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14187. var _this = this;
  14188. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14189. this.inertialAlphaOffset = 0;
  14190. this.inertialBetaOffset = 0;
  14191. this.inertialRadiusOffset = 0;
  14192. this.lowerAlphaLimit = null;
  14193. this.upperAlphaLimit = null;
  14194. this.lowerBetaLimit = 0.01;
  14195. this.upperBetaLimit = Math.PI;
  14196. this.lowerRadiusLimit = null;
  14197. this.upperRadiusLimit = null;
  14198. this.inertialPanningX = 0;
  14199. this.inertialPanningY = 0;
  14200. //-- end properties for backward compatibility for inputs
  14201. this.zoomOnFactor = 1;
  14202. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14203. this.allowUpsideDown = true;
  14204. this._viewMatrix = new BABYLON.Matrix();
  14205. // Panning
  14206. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14207. this.checkCollisions = false;
  14208. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14209. this._collider = new BABYLON.Collider();
  14210. this._previousPosition = BABYLON.Vector3.Zero();
  14211. this._collisionVelocity = BABYLON.Vector3.Zero();
  14212. this._newPosition = BABYLON.Vector3.Zero();
  14213. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14214. if (collidedMesh === void 0) { collidedMesh = null; }
  14215. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14216. newPosition.multiplyInPlace(_this._collider.radius);
  14217. }
  14218. if (!collidedMesh) {
  14219. _this._previousPosition.copyFrom(_this.position);
  14220. }
  14221. else {
  14222. _this.setPosition(newPosition);
  14223. if (_this.onCollide) {
  14224. _this.onCollide(collidedMesh);
  14225. }
  14226. }
  14227. // Recompute because of constraints
  14228. var cosa = Math.cos(_this.alpha);
  14229. var sina = Math.sin(_this.alpha);
  14230. var cosb = Math.cos(_this.beta);
  14231. var sinb = Math.sin(_this.beta);
  14232. if (sinb === 0) {
  14233. sinb = 0.0001;
  14234. }
  14235. var target = _this._getTargetPosition();
  14236. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14237. _this.position.copyFrom(_this._newPosition);
  14238. var up = _this.upVector;
  14239. if (_this.allowUpsideDown && _this.beta < 0) {
  14240. up = up.clone();
  14241. up = up.negate();
  14242. }
  14243. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14244. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14245. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14246. _this._collisionTriggered = false;
  14247. };
  14248. if (!target) {
  14249. this.target = BABYLON.Vector3.Zero();
  14250. }
  14251. else {
  14252. this.target = target;
  14253. }
  14254. this.alpha = alpha;
  14255. this.beta = beta;
  14256. this.radius = radius;
  14257. this.getViewMatrix();
  14258. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14259. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14260. }
  14261. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14262. //-- begin properties for backward compatibility for inputs
  14263. get: function () {
  14264. var pointers = this.inputs.attached["pointers"];
  14265. if (pointers)
  14266. return pointers.angularSensibilityX;
  14267. },
  14268. set: function (value) {
  14269. var pointers = this.inputs.attached["pointers"];
  14270. if (pointers) {
  14271. pointers.angularSensibilityX = value;
  14272. }
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14278. get: function () {
  14279. var pointers = this.inputs.attached["pointers"];
  14280. if (pointers)
  14281. return pointers.angularSensibilityY;
  14282. },
  14283. set: function (value) {
  14284. var pointers = this.inputs.attached["pointers"];
  14285. if (pointers) {
  14286. pointers.angularSensibilityY = value;
  14287. }
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14293. get: function () {
  14294. var pointers = this.inputs.attached["pointers"];
  14295. if (pointers)
  14296. return pointers.pinchPrecision;
  14297. },
  14298. set: function (value) {
  14299. var pointers = this.inputs.attached["pointers"];
  14300. if (pointers) {
  14301. pointers.pinchPrecision = value;
  14302. }
  14303. },
  14304. enumerable: true,
  14305. configurable: true
  14306. });
  14307. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14308. get: function () {
  14309. var pointers = this.inputs.attached["pointers"];
  14310. if (pointers)
  14311. return pointers.panningSensibility;
  14312. },
  14313. set: function (value) {
  14314. var pointers = this.inputs.attached["pointers"];
  14315. if (pointers) {
  14316. pointers.panningSensibility = value;
  14317. }
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14323. get: function () {
  14324. var keyboard = this.inputs.attached["keyboard"];
  14325. if (keyboard)
  14326. return keyboard.keysUp;
  14327. },
  14328. set: function (value) {
  14329. var keyboard = this.inputs.attached["keyboard"];
  14330. if (keyboard)
  14331. keyboard.keysUp = value;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14337. get: function () {
  14338. var keyboard = this.inputs.attached["keyboard"];
  14339. if (keyboard)
  14340. return keyboard.keysDown;
  14341. },
  14342. set: function (value) {
  14343. var keyboard = this.inputs.attached["keyboard"];
  14344. if (keyboard)
  14345. keyboard.keysDown = value;
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14351. get: function () {
  14352. var keyboard = this.inputs.attached["keyboard"];
  14353. if (keyboard)
  14354. return keyboard.keysLeft;
  14355. },
  14356. set: function (value) {
  14357. var keyboard = this.inputs.attached["keyboard"];
  14358. if (keyboard)
  14359. keyboard.keysLeft = value;
  14360. },
  14361. enumerable: true,
  14362. configurable: true
  14363. });
  14364. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14365. get: function () {
  14366. var keyboard = this.inputs.attached["keyboard"];
  14367. if (keyboard)
  14368. return keyboard.keysRight;
  14369. },
  14370. set: function (value) {
  14371. var keyboard = this.inputs.attached["keyboard"];
  14372. if (keyboard)
  14373. keyboard.keysRight = value;
  14374. },
  14375. enumerable: true,
  14376. configurable: true
  14377. });
  14378. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14379. get: function () {
  14380. var mousewheel = this.inputs.attached["mousewheel"];
  14381. if (mousewheel)
  14382. return mousewheel.wheelPrecision;
  14383. },
  14384. set: function (value) {
  14385. var mousewheel = this.inputs.attached["mousewheel"];
  14386. if (mousewheel)
  14387. mousewheel.wheelPrecision = value;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. // Cache
  14393. ArcRotateCamera.prototype._initCache = function () {
  14394. _super.prototype._initCache.call(this);
  14395. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14396. this._cache.alpha = undefined;
  14397. this._cache.beta = undefined;
  14398. this._cache.radius = undefined;
  14399. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14400. };
  14401. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14402. if (!ignoreParentClass) {
  14403. _super.prototype._updateCache.call(this);
  14404. }
  14405. this._cache.target.copyFrom(this._getTargetPosition());
  14406. this._cache.alpha = this.alpha;
  14407. this._cache.beta = this.beta;
  14408. this._cache.radius = this.radius;
  14409. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14410. };
  14411. ArcRotateCamera.prototype._getTargetPosition = function () {
  14412. if (this.target.getAbsolutePosition) {
  14413. return this.target.getAbsolutePosition();
  14414. }
  14415. return this.target;
  14416. };
  14417. // Synchronized
  14418. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14419. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14420. return false;
  14421. return this._cache.target.equals(this.target)
  14422. && this._cache.alpha === this.alpha
  14423. && this._cache.beta === this.beta
  14424. && this._cache.radius === this.radius
  14425. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14426. };
  14427. // Methods
  14428. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14429. var _this = this;
  14430. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14431. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14432. this._useCtrlForPanning = useCtrlForPanning;
  14433. this._panningMouseButton = panningMouseButton;
  14434. this.inputs.attachElement(element, noPreventDefault);
  14435. this._reset = function () {
  14436. _this.inertialAlphaOffset = 0;
  14437. _this.inertialBetaOffset = 0;
  14438. _this.inertialRadiusOffset = 0;
  14439. };
  14440. };
  14441. ArcRotateCamera.prototype.detachControl = function (element) {
  14442. this.inputs.detachElement(element);
  14443. if (this._reset) {
  14444. this._reset();
  14445. }
  14446. };
  14447. ArcRotateCamera.prototype._checkInputs = function () {
  14448. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14449. if (this._collisionTriggered) {
  14450. return;
  14451. }
  14452. this.inputs.checkInputs();
  14453. // Inertia
  14454. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14455. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14456. this.beta += this.inertialBetaOffset;
  14457. this.radius -= this.inertialRadiusOffset;
  14458. this.inertialAlphaOffset *= this.inertia;
  14459. this.inertialBetaOffset *= this.inertia;
  14460. this.inertialRadiusOffset *= this.inertia;
  14461. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14462. this.inertialAlphaOffset = 0;
  14463. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14464. this.inertialBetaOffset = 0;
  14465. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14466. this.inertialRadiusOffset = 0;
  14467. }
  14468. // Panning inertia
  14469. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14470. if (!this._localDirection) {
  14471. this._localDirection = BABYLON.Vector3.Zero();
  14472. this._transformedDirection = BABYLON.Vector3.Zero();
  14473. }
  14474. this.inertialPanningX *= this.inertia;
  14475. this.inertialPanningY *= this.inertia;
  14476. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14477. this.inertialPanningX = 0;
  14478. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14479. this.inertialPanningY = 0;
  14480. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14481. this._localDirection.multiplyInPlace(this.panningAxis);
  14482. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14483. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14484. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14485. if (!this.panningAxis.y) {
  14486. this._transformedDirection.y = 0;
  14487. }
  14488. if (!this.target.getAbsolutePosition) {
  14489. this.target.addInPlace(this._transformedDirection);
  14490. }
  14491. }
  14492. // Limits
  14493. this._checkLimits();
  14494. _super.prototype._checkInputs.call(this);
  14495. };
  14496. ArcRotateCamera.prototype._checkLimits = function () {
  14497. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14498. if (this.allowUpsideDown && this.beta > Math.PI) {
  14499. this.beta = this.beta - (2 * Math.PI);
  14500. }
  14501. }
  14502. else {
  14503. if (this.beta < this.lowerBetaLimit) {
  14504. this.beta = this.lowerBetaLimit;
  14505. }
  14506. }
  14507. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14508. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14509. this.beta = this.beta + (2 * Math.PI);
  14510. }
  14511. }
  14512. else {
  14513. if (this.beta > this.upperBetaLimit) {
  14514. this.beta = this.upperBetaLimit;
  14515. }
  14516. }
  14517. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14518. this.alpha = this.lowerAlphaLimit;
  14519. }
  14520. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14521. this.alpha = this.upperAlphaLimit;
  14522. }
  14523. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14524. this.radius = this.lowerRadiusLimit;
  14525. }
  14526. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14527. this.radius = this.upperRadiusLimit;
  14528. }
  14529. };
  14530. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14531. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14532. this.radius = radiusv3.length();
  14533. // Alpha
  14534. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14535. if (radiusv3.z < 0) {
  14536. this.alpha = 2 * Math.PI - this.alpha;
  14537. }
  14538. // Beta
  14539. this.beta = Math.acos(radiusv3.y / this.radius);
  14540. this._checkLimits();
  14541. };
  14542. ArcRotateCamera.prototype.setPosition = function (position) {
  14543. if (this.position.equals(position)) {
  14544. return;
  14545. }
  14546. this.position.copyFrom(position);
  14547. this.rebuildAnglesAndRadius();
  14548. };
  14549. ArcRotateCamera.prototype.setTarget = function (target) {
  14550. if (this._getTargetPosition().equals(target)) {
  14551. return;
  14552. }
  14553. this.target = target;
  14554. this.rebuildAnglesAndRadius();
  14555. };
  14556. ArcRotateCamera.prototype._getViewMatrix = function () {
  14557. // Compute
  14558. var cosa = Math.cos(this.alpha);
  14559. var sina = Math.sin(this.alpha);
  14560. var cosb = Math.cos(this.beta);
  14561. var sinb = Math.sin(this.beta);
  14562. if (sinb === 0) {
  14563. sinb = 0.0001;
  14564. }
  14565. var target = this._getTargetPosition();
  14566. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14567. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14568. this._collider.radius = this.collisionRadius;
  14569. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14570. this._collisionTriggered = true;
  14571. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14572. }
  14573. else {
  14574. this.position.copyFrom(this._newPosition);
  14575. var up = this.upVector;
  14576. if (this.allowUpsideDown && this.beta < 0) {
  14577. up = up.clone();
  14578. up = up.negate();
  14579. }
  14580. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14581. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14582. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14583. }
  14584. return this._viewMatrix;
  14585. };
  14586. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14587. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14588. meshes = meshes || this.getScene().meshes;
  14589. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14590. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14591. this.radius = distance * this.zoomOnFactor;
  14592. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14593. };
  14594. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14595. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14596. var meshesOrMinMaxVector;
  14597. var distance;
  14598. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14599. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14600. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14601. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14602. }
  14603. else {
  14604. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14605. distance = meshesOrMinMaxVectorAndDistance.distance;
  14606. }
  14607. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14608. if (!doNotUpdateMaxZ) {
  14609. this.maxZ = distance * 2;
  14610. }
  14611. };
  14612. /**
  14613. * @override
  14614. * Override Camera.createRigCamera
  14615. */
  14616. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14617. var alphaShift;
  14618. switch (this.cameraRigMode) {
  14619. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14620. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14621. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14622. case BABYLON.Camera.RIG_MODE_VR:
  14623. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14624. break;
  14625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14626. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14627. break;
  14628. }
  14629. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14630. rigCam._cameraRigParams = {};
  14631. return rigCam;
  14632. };
  14633. /**
  14634. * @override
  14635. * Override Camera._updateRigCameras
  14636. */
  14637. ArcRotateCamera.prototype._updateRigCameras = function () {
  14638. var camLeft = this._rigCameras[0];
  14639. var camRight = this._rigCameras[1];
  14640. camLeft.beta = camRight.beta = this.beta;
  14641. camLeft.radius = camRight.radius = this.radius;
  14642. switch (this.cameraRigMode) {
  14643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14646. case BABYLON.Camera.RIG_MODE_VR:
  14647. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14648. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14649. break;
  14650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14651. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14652. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14653. break;
  14654. }
  14655. _super.prototype._updateRigCameras.call(this);
  14656. };
  14657. ArcRotateCamera.prototype.dispose = function () {
  14658. this.inputs.clear();
  14659. _super.prototype.dispose.call(this);
  14660. };
  14661. ArcRotateCamera.prototype.getTypeName = function () {
  14662. return "ArcRotateCamera";
  14663. };
  14664. __decorate([
  14665. BABYLON.serialize()
  14666. ], ArcRotateCamera.prototype, "alpha", void 0);
  14667. __decorate([
  14668. BABYLON.serialize()
  14669. ], ArcRotateCamera.prototype, "beta", void 0);
  14670. __decorate([
  14671. BABYLON.serialize()
  14672. ], ArcRotateCamera.prototype, "radius", void 0);
  14673. __decorate([
  14674. BABYLON.serializeAsVector3()
  14675. ], ArcRotateCamera.prototype, "target", void 0);
  14676. __decorate([
  14677. BABYLON.serialize()
  14678. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14682. __decorate([
  14683. BABYLON.serialize()
  14684. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14685. __decorate([
  14686. BABYLON.serialize()
  14687. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14688. __decorate([
  14689. BABYLON.serialize()
  14690. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14691. __decorate([
  14692. BABYLON.serialize()
  14693. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14694. __decorate([
  14695. BABYLON.serialize()
  14696. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14697. __decorate([
  14698. BABYLON.serialize()
  14699. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14700. __decorate([
  14701. BABYLON.serialize()
  14702. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14703. __decorate([
  14704. BABYLON.serialize()
  14705. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14706. __decorate([
  14707. BABYLON.serialize()
  14708. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14709. __decorate([
  14710. BABYLON.serialize()
  14711. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14712. __decorate([
  14713. BABYLON.serialize()
  14714. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14715. return ArcRotateCamera;
  14716. }(BABYLON.TargetCamera));
  14717. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14718. })(BABYLON || (BABYLON = {}));
  14719. var BABYLON;
  14720. (function (BABYLON) {
  14721. var ArcRotateCameraInputsManager = (function (_super) {
  14722. __extends(ArcRotateCameraInputsManager, _super);
  14723. function ArcRotateCameraInputsManager(camera) {
  14724. _super.call(this, camera);
  14725. }
  14726. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14727. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14728. return this;
  14729. };
  14730. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14731. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14732. return this;
  14733. };
  14734. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14735. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14736. return this;
  14737. };
  14738. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14739. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14740. return this;
  14741. };
  14742. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14743. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14744. return this;
  14745. };
  14746. return ArcRotateCameraInputsManager;
  14747. }(BABYLON.CameraInputsManager));
  14748. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14749. })(BABYLON || (BABYLON = {}));
  14750. var BABYLON;
  14751. (function (BABYLON) {
  14752. var RenderingManager = (function () {
  14753. function RenderingManager(scene) {
  14754. this._renderingGroups = new Array();
  14755. this._scene = scene;
  14756. }
  14757. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14758. if (this._scene._activeParticleSystems.length === 0) {
  14759. return;
  14760. }
  14761. // Particles
  14762. var activeCamera = this._scene.activeCamera;
  14763. this._scene._particlesDuration.beginMonitoring();
  14764. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14765. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14766. if (particleSystem.renderingGroupId !== index) {
  14767. continue;
  14768. }
  14769. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14770. continue;
  14771. }
  14772. this._clearDepthBuffer();
  14773. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14774. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14775. }
  14776. }
  14777. this._scene._particlesDuration.endMonitoring(false);
  14778. };
  14779. RenderingManager.prototype._renderSprites = function (index) {
  14780. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14781. return;
  14782. }
  14783. // Sprites
  14784. var activeCamera = this._scene.activeCamera;
  14785. this._scene._spritesDuration.beginMonitoring();
  14786. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14787. var spriteManager = this._scene.spriteManagers[id];
  14788. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14789. this._clearDepthBuffer();
  14790. spriteManager.render();
  14791. }
  14792. }
  14793. this._scene._spritesDuration.endMonitoring(false);
  14794. };
  14795. RenderingManager.prototype._clearDepthBuffer = function () {
  14796. if (this._depthBufferAlreadyCleaned) {
  14797. return;
  14798. }
  14799. this._scene.getEngine().clear(0, false, true);
  14800. this._depthBufferAlreadyCleaned = true;
  14801. };
  14802. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14803. if (this._currentRenderSprites) {
  14804. this._renderSprites(this._currentIndex);
  14805. }
  14806. if (this._currentRenderParticles) {
  14807. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14808. }
  14809. };
  14810. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14811. this._currentActiveMeshes = activeMeshes;
  14812. this._currentRenderParticles = renderParticles;
  14813. this._currentRenderSprites = renderSprites;
  14814. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14815. this._depthBufferAlreadyCleaned = index === 0;
  14816. var renderingGroup = this._renderingGroups[index];
  14817. var needToStepBack = false;
  14818. this._currentIndex = index;
  14819. if (renderingGroup) {
  14820. this._clearDepthBuffer();
  14821. if (!renderingGroup.onBeforeTransparentRendering) {
  14822. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14823. }
  14824. if (!renderingGroup.render(customRenderFunction)) {
  14825. this._renderingGroups.splice(index, 1);
  14826. needToStepBack = true;
  14827. this._renderSpritesAndParticles();
  14828. }
  14829. }
  14830. else {
  14831. this._renderSpritesAndParticles();
  14832. }
  14833. if (needToStepBack) {
  14834. index--;
  14835. }
  14836. }
  14837. };
  14838. RenderingManager.prototype.reset = function () {
  14839. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14840. if (renderingGroup) {
  14841. renderingGroup.prepare();
  14842. }
  14843. });
  14844. };
  14845. RenderingManager.prototype.dispatch = function (subMesh) {
  14846. var mesh = subMesh.getMesh();
  14847. var renderingGroupId = mesh.renderingGroupId || 0;
  14848. if (!this._renderingGroups[renderingGroupId]) {
  14849. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14850. }
  14851. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14852. };
  14853. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14854. return RenderingManager;
  14855. }());
  14856. BABYLON.RenderingManager = RenderingManager;
  14857. })(BABYLON || (BABYLON = {}));
  14858. var BABYLON;
  14859. (function (BABYLON) {
  14860. var RenderingGroup = (function () {
  14861. function RenderingGroup(index, scene) {
  14862. this.index = index;
  14863. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14864. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14865. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14866. this._scene = scene;
  14867. }
  14868. RenderingGroup.prototype.render = function (customRenderFunction) {
  14869. if (customRenderFunction) {
  14870. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14871. return true;
  14872. }
  14873. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14874. if (this.onBeforeTransparentRendering) {
  14875. this.onBeforeTransparentRendering();
  14876. }
  14877. return false;
  14878. }
  14879. var engine = this._scene.getEngine();
  14880. // Opaque
  14881. var subIndex;
  14882. var submesh;
  14883. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14884. submesh = this._opaqueSubMeshes.data[subIndex];
  14885. submesh.render(false);
  14886. }
  14887. // Alpha test
  14888. engine.setAlphaTesting(true);
  14889. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14890. submesh = this._alphaTestSubMeshes.data[subIndex];
  14891. submesh.render(false);
  14892. }
  14893. engine.setAlphaTesting(false);
  14894. if (this.onBeforeTransparentRendering) {
  14895. this.onBeforeTransparentRendering();
  14896. }
  14897. // Transparent
  14898. if (this._transparentSubMeshes.length) {
  14899. // Sorting
  14900. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14901. submesh = this._transparentSubMeshes.data[subIndex];
  14902. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14903. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14904. }
  14905. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14906. sortedArray.sort(function (a, b) {
  14907. // Alpha index first
  14908. if (a._alphaIndex > b._alphaIndex) {
  14909. return 1;
  14910. }
  14911. if (a._alphaIndex < b._alphaIndex) {
  14912. return -1;
  14913. }
  14914. // Then distance to camera
  14915. if (a._distanceToCamera < b._distanceToCamera) {
  14916. return 1;
  14917. }
  14918. if (a._distanceToCamera > b._distanceToCamera) {
  14919. return -1;
  14920. }
  14921. return 0;
  14922. });
  14923. // Rendering
  14924. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14925. submesh = sortedArray[subIndex];
  14926. submesh.render(true);
  14927. }
  14928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14929. }
  14930. return true;
  14931. };
  14932. RenderingGroup.prototype.prepare = function () {
  14933. this._opaqueSubMeshes.reset();
  14934. this._transparentSubMeshes.reset();
  14935. this._alphaTestSubMeshes.reset();
  14936. };
  14937. RenderingGroup.prototype.dispatch = function (subMesh) {
  14938. var material = subMesh.getMaterial();
  14939. var mesh = subMesh.getMesh();
  14940. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14941. this._transparentSubMeshes.push(subMesh);
  14942. }
  14943. else if (material.needAlphaTesting()) {
  14944. this._alphaTestSubMeshes.push(subMesh);
  14945. }
  14946. else {
  14947. this._opaqueSubMeshes.push(subMesh); // Opaque
  14948. }
  14949. };
  14950. return RenderingGroup;
  14951. }());
  14952. BABYLON.RenderingGroup = RenderingGroup;
  14953. })(BABYLON || (BABYLON = {}));
  14954. var BABYLON;
  14955. (function (BABYLON) {
  14956. var PointerEventTypes = (function () {
  14957. function PointerEventTypes() {
  14958. }
  14959. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14960. get: function () {
  14961. return PointerEventTypes._POINTERDOWN;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14967. get: function () {
  14968. return PointerEventTypes._POINTERUP;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14974. get: function () {
  14975. return PointerEventTypes._POINTERMOVE;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14981. get: function () {
  14982. return PointerEventTypes._POINTERWHEEL;
  14983. },
  14984. enumerable: true,
  14985. configurable: true
  14986. });
  14987. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14988. get: function () {
  14989. return PointerEventTypes._POINTERPICK;
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. PointerEventTypes._POINTERDOWN = 0x01;
  14995. PointerEventTypes._POINTERUP = 0x02;
  14996. PointerEventTypes._POINTERMOVE = 0x04;
  14997. PointerEventTypes._POINTERWHEEL = 0x08;
  14998. PointerEventTypes._POINTERPICK = 0x10;
  14999. return PointerEventTypes;
  15000. }());
  15001. BABYLON.PointerEventTypes = PointerEventTypes;
  15002. var PointerInfoBase = (function () {
  15003. function PointerInfoBase(type, event) {
  15004. this.type = type;
  15005. this.event = event;
  15006. }
  15007. return PointerInfoBase;
  15008. }());
  15009. BABYLON.PointerInfoBase = PointerInfoBase;
  15010. /**
  15011. * This class is used to store pointer related info for the onPrePointerObservable event.
  15012. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15013. */
  15014. var PointerInfoPre = (function (_super) {
  15015. __extends(PointerInfoPre, _super);
  15016. function PointerInfoPre(type, event, localX, localY) {
  15017. _super.call(this, type, event);
  15018. this.skipOnPointerObservable = false;
  15019. this.localPosition = new BABYLON.Vector2(localX, localY);
  15020. }
  15021. return PointerInfoPre;
  15022. }(PointerInfoBase));
  15023. BABYLON.PointerInfoPre = PointerInfoPre;
  15024. /**
  15025. * This type contains all the data related to a pointer event in Babylon.js.
  15026. * 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.
  15027. */
  15028. var PointerInfo = (function (_super) {
  15029. __extends(PointerInfo, _super);
  15030. function PointerInfo(type, event, pickInfo) {
  15031. _super.call(this, type, event);
  15032. this.pickInfo = pickInfo;
  15033. }
  15034. return PointerInfo;
  15035. }(PointerInfoBase));
  15036. BABYLON.PointerInfo = PointerInfo;
  15037. /**
  15038. * Represents a scene to be rendered by the engine.
  15039. * @see http://doc.babylonjs.com/page.php?p=21911
  15040. */
  15041. var Scene = (function () {
  15042. /**
  15043. * @constructor
  15044. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15045. */
  15046. function Scene(engine) {
  15047. // Members
  15048. this.autoClear = true;
  15049. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15050. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15051. this.forceWireframe = false;
  15052. this.forcePointsCloud = false;
  15053. this.forceShowBoundingBoxes = false;
  15054. this.animationsEnabled = true;
  15055. this.constantlyUpdateMeshUnderPointer = false;
  15056. this.hoverCursor = "pointer";
  15057. // Events
  15058. /**
  15059. * An event triggered when the scene is disposed.
  15060. * @type {BABYLON.Observable}
  15061. */
  15062. this.onDisposeObservable = new BABYLON.Observable();
  15063. /**
  15064. * An event triggered before rendering the scene
  15065. * @type {BABYLON.Observable}
  15066. */
  15067. this.onBeforeRenderObservable = new BABYLON.Observable();
  15068. /**
  15069. * An event triggered after rendering the scene
  15070. * @type {BABYLON.Observable}
  15071. */
  15072. this.onAfterRenderObservable = new BABYLON.Observable();
  15073. /**
  15074. * An event triggered when the scene is ready
  15075. * @type {BABYLON.Observable}
  15076. */
  15077. this.onReadyObservable = new BABYLON.Observable();
  15078. /**
  15079. * An event triggered before rendering a camera
  15080. * @type {BABYLON.Observable}
  15081. */
  15082. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15083. /**
  15084. * An event triggered after rendering a camera
  15085. * @type {BABYLON.Observable}
  15086. */
  15087. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15088. /**
  15089. * An event triggered when a camera is created
  15090. * @type {BABYLON.Observable}
  15091. */
  15092. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15093. /**
  15094. * An event triggered when a camera is removed
  15095. * @type {BABYLON.Observable}
  15096. */
  15097. this.onCameraRemovedObservable = new BABYLON.Observable();
  15098. /**
  15099. * An event triggered when a light is created
  15100. * @type {BABYLON.Observable}
  15101. */
  15102. this.onNewLightAddedObservable = new BABYLON.Observable();
  15103. /**
  15104. * An event triggered when a light is removed
  15105. * @type {BABYLON.Observable}
  15106. */
  15107. this.onLightRemovedObservable = new BABYLON.Observable();
  15108. /**
  15109. * An event triggered when a geometry is created
  15110. * @type {BABYLON.Observable}
  15111. */
  15112. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15113. /**
  15114. * An event triggered when a geometry is removed
  15115. * @type {BABYLON.Observable}
  15116. */
  15117. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15118. /**
  15119. * An event triggered when a mesh is created
  15120. * @type {BABYLON.Observable}
  15121. */
  15122. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15123. /**
  15124. * An event triggered when a mesh is removed
  15125. * @type {BABYLON.Observable}
  15126. */
  15127. this.onMeshRemovedObservable = new BABYLON.Observable();
  15128. // Animations
  15129. this.animations = [];
  15130. /**
  15131. * 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).
  15132. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15133. */
  15134. this.onPrePointerObservable = new BABYLON.Observable();
  15135. /**
  15136. * Observable event triggered each time an input event is received from the rendering canvas
  15137. */
  15138. this.onPointerObservable = new BABYLON.Observable();
  15139. 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
  15140. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15141. this._startingPointerTime = 0;
  15142. // Fog
  15143. /**
  15144. * is fog enabled on this scene.
  15145. * @type {boolean}
  15146. */
  15147. this.fogEnabled = true;
  15148. this.fogMode = Scene.FOGMODE_NONE;
  15149. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15150. this.fogDensity = 0.1;
  15151. this.fogStart = 0;
  15152. this.fogEnd = 1000.0;
  15153. // Lights
  15154. /**
  15155. * is shadow enabled on this scene.
  15156. * @type {boolean}
  15157. */
  15158. this.shadowsEnabled = true;
  15159. /**
  15160. * is light enabled on this scene.
  15161. * @type {boolean}
  15162. */
  15163. this.lightsEnabled = true;
  15164. /**
  15165. * All of the lights added to this scene.
  15166. * @see BABYLON.Light
  15167. * @type {BABYLON.Light[]}
  15168. */
  15169. this.lights = new Array();
  15170. // Cameras
  15171. /**
  15172. * All of the cameras added to this scene.
  15173. * @see BABYLON.Camera
  15174. * @type {BABYLON.Camera[]}
  15175. */
  15176. this.cameras = new Array();
  15177. this.activeCameras = new Array();
  15178. // Meshes
  15179. /**
  15180. * All of the (abstract) meshes added to this scene.
  15181. * @see BABYLON.AbstractMesh
  15182. * @type {BABYLON.AbstractMesh[]}
  15183. */
  15184. this.meshes = new Array();
  15185. // Geometries
  15186. this._geometries = new Array();
  15187. this.materials = new Array();
  15188. this.multiMaterials = new Array();
  15189. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15190. // Textures
  15191. this.texturesEnabled = true;
  15192. this.textures = new Array();
  15193. // Particles
  15194. this.particlesEnabled = true;
  15195. this.particleSystems = new Array();
  15196. // Sprites
  15197. this.spritesEnabled = true;
  15198. this.spriteManagers = new Array();
  15199. // Layers
  15200. this.layers = new Array();
  15201. // Skeletons
  15202. this.skeletonsEnabled = true;
  15203. this.skeletons = new Array();
  15204. // Lens flares
  15205. this.lensFlaresEnabled = true;
  15206. this.lensFlareSystems = new Array();
  15207. // Collisions
  15208. this.collisionsEnabled = true;
  15209. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15210. // Postprocesses
  15211. this.postProcessesEnabled = true;
  15212. // Customs render targets
  15213. this.renderTargetsEnabled = true;
  15214. this.dumpNextRenderTargets = false;
  15215. this.customRenderTargets = new Array();
  15216. // Imported meshes
  15217. this.importedMeshesFiles = new Array();
  15218. // Probes
  15219. this.probesEnabled = true;
  15220. this.reflectionProbes = new Array();
  15221. this._actionManagers = new Array();
  15222. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15223. // Procedural textures
  15224. this.proceduralTexturesEnabled = true;
  15225. this._proceduralTextures = new Array();
  15226. this.soundTracks = new Array();
  15227. this._audioEnabled = true;
  15228. this._headphone = false;
  15229. // Performance counters
  15230. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15231. this._totalLightsCounter = new BABYLON.PerfCounter();
  15232. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15233. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15234. this._totalVertices = new BABYLON.PerfCounter();
  15235. this._activeIndices = new BABYLON.PerfCounter();
  15236. this._activeParticles = new BABYLON.PerfCounter();
  15237. this._lastFrameDuration = new BABYLON.PerfCounter();
  15238. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15239. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15240. this._particlesDuration = new BABYLON.PerfCounter();
  15241. this._renderDuration = new BABYLON.PerfCounter();
  15242. this._spritesDuration = new BABYLON.PerfCounter();
  15243. this._activeBones = new BABYLON.PerfCounter();
  15244. this._renderId = 0;
  15245. this._executeWhenReadyTimeoutId = -1;
  15246. this._intermediateRendering = false;
  15247. this._toBeDisposed = new BABYLON.SmartArray(256);
  15248. this._pendingData = []; //ANY
  15249. this._activeMeshes = new BABYLON.SmartArray(256);
  15250. this._processedMaterials = new BABYLON.SmartArray(256);
  15251. this._renderTargets = new BABYLON.SmartArray(256);
  15252. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15253. this._activeSkeletons = new BABYLON.SmartArray(32);
  15254. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15255. this._activeAnimatables = new Array();
  15256. this._transformMatrix = BABYLON.Matrix.Zero();
  15257. this._edgesRenderers = new BABYLON.SmartArray(16);
  15258. this._uniqueIdCounter = 0;
  15259. this._engine = engine;
  15260. engine.scenes.push(this);
  15261. this._renderingManager = new BABYLON.RenderingManager(this);
  15262. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15263. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15264. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15265. if (BABYLON.OutlineRenderer) {
  15266. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15267. }
  15268. this.attachControl();
  15269. if (BABYLON.SoundTrack) {
  15270. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15271. }
  15272. //simplification queue
  15273. if (BABYLON.SimplificationQueue) {
  15274. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15275. }
  15276. //collision coordinator initialization. For now legacy per default.
  15277. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15278. }
  15279. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15280. get: function () {
  15281. return Scene._FOGMODE_NONE;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15287. get: function () {
  15288. return Scene._FOGMODE_EXP;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15294. get: function () {
  15295. return Scene._FOGMODE_EXP2;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15301. get: function () {
  15302. return Scene._FOGMODE_LINEAR;
  15303. },
  15304. enumerable: true,
  15305. configurable: true
  15306. });
  15307. Object.defineProperty(Scene.prototype, "onDispose", {
  15308. set: function (callback) {
  15309. if (this._onDisposeObserver) {
  15310. this.onDisposeObservable.remove(this._onDisposeObserver);
  15311. }
  15312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15313. },
  15314. enumerable: true,
  15315. configurable: true
  15316. });
  15317. Object.defineProperty(Scene.prototype, "beforeRender", {
  15318. set: function (callback) {
  15319. if (this._onBeforeRenderObserver) {
  15320. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15321. }
  15322. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15323. },
  15324. enumerable: true,
  15325. configurable: true
  15326. });
  15327. Object.defineProperty(Scene.prototype, "afterRender", {
  15328. set: function (callback) {
  15329. if (this._onAfterRenderObserver) {
  15330. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15331. }
  15332. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15333. },
  15334. enumerable: true,
  15335. configurable: true
  15336. });
  15337. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15338. set: function (callback) {
  15339. if (this._onBeforeCameraRenderObserver) {
  15340. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15341. }
  15342. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15343. },
  15344. enumerable: true,
  15345. configurable: true
  15346. });
  15347. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15348. set: function (callback) {
  15349. if (this._onAfterCameraRenderObserver) {
  15350. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15351. }
  15352. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15353. },
  15354. enumerable: true,
  15355. configurable: true
  15356. });
  15357. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15358. get: function () {
  15359. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15360. },
  15361. enumerable: true,
  15362. configurable: true
  15363. });
  15364. Object.defineProperty(Scene.prototype, "debugLayer", {
  15365. // Properties
  15366. get: function () {
  15367. if (!this._debugLayer) {
  15368. this._debugLayer = new BABYLON.DebugLayer(this);
  15369. }
  15370. return this._debugLayer;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15376. get: function () {
  15377. return this._workerCollisions;
  15378. },
  15379. set: function (enabled) {
  15380. enabled = (enabled && !!Worker);
  15381. this._workerCollisions = enabled;
  15382. if (this.collisionCoordinator) {
  15383. this.collisionCoordinator.destroy();
  15384. }
  15385. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15386. this.collisionCoordinator.init(this);
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15392. get: function () {
  15393. return this._selectionOctree;
  15394. },
  15395. enumerable: true,
  15396. configurable: true
  15397. });
  15398. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15399. /**
  15400. * The mesh that is currently under the pointer.
  15401. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15402. */
  15403. get: function () {
  15404. return this._pointerOverMesh;
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. Object.defineProperty(Scene.prototype, "pointerX", {
  15410. /**
  15411. * Current on-screen X position of the pointer
  15412. * @return {number} X position of the pointer
  15413. */
  15414. get: function () {
  15415. return this._pointerX;
  15416. },
  15417. enumerable: true,
  15418. configurable: true
  15419. });
  15420. Object.defineProperty(Scene.prototype, "pointerY", {
  15421. /**
  15422. * Current on-screen Y position of the pointer
  15423. * @return {number} Y position of the pointer
  15424. */
  15425. get: function () {
  15426. return this._pointerY;
  15427. },
  15428. enumerable: true,
  15429. configurable: true
  15430. });
  15431. Scene.prototype.getCachedMaterial = function () {
  15432. return this._cachedMaterial;
  15433. };
  15434. Scene.prototype.getBoundingBoxRenderer = function () {
  15435. return this._boundingBoxRenderer;
  15436. };
  15437. Scene.prototype.getOutlineRenderer = function () {
  15438. return this._outlineRenderer;
  15439. };
  15440. Scene.prototype.getEngine = function () {
  15441. return this._engine;
  15442. };
  15443. Scene.prototype.getTotalVertices = function () {
  15444. return this._totalVertices.current;
  15445. };
  15446. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15447. get: function () {
  15448. return this._totalVertices;
  15449. },
  15450. enumerable: true,
  15451. configurable: true
  15452. });
  15453. Scene.prototype.getActiveIndices = function () {
  15454. return this._activeIndices.current;
  15455. };
  15456. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15457. get: function () {
  15458. return this._activeIndices;
  15459. },
  15460. enumerable: true,
  15461. configurable: true
  15462. });
  15463. Scene.prototype.getActiveParticles = function () {
  15464. return this._activeParticles.current;
  15465. };
  15466. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15467. get: function () {
  15468. return this._activeParticles;
  15469. },
  15470. enumerable: true,
  15471. configurable: true
  15472. });
  15473. Scene.prototype.getActiveBones = function () {
  15474. return this._activeBones.current;
  15475. };
  15476. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15477. get: function () {
  15478. return this._activeBones;
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. // Stats
  15484. Scene.prototype.getLastFrameDuration = function () {
  15485. return this._lastFrameDuration.current;
  15486. };
  15487. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15488. get: function () {
  15489. return this._lastFrameDuration;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15495. return this._evaluateActiveMeshesDuration.current;
  15496. };
  15497. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15498. get: function () {
  15499. return this._evaluateActiveMeshesDuration;
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. Scene.prototype.getActiveMeshes = function () {
  15505. return this._activeMeshes;
  15506. };
  15507. Scene.prototype.getRenderTargetsDuration = function () {
  15508. return this._renderTargetsDuration.current;
  15509. };
  15510. Scene.prototype.getRenderDuration = function () {
  15511. return this._renderDuration.current;
  15512. };
  15513. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15514. get: function () {
  15515. return this._renderDuration;
  15516. },
  15517. enumerable: true,
  15518. configurable: true
  15519. });
  15520. Scene.prototype.getParticlesDuration = function () {
  15521. return this._particlesDuration.current;
  15522. };
  15523. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15524. get: function () {
  15525. return this._particlesDuration;
  15526. },
  15527. enumerable: true,
  15528. configurable: true
  15529. });
  15530. Scene.prototype.getSpritesDuration = function () {
  15531. return this._spritesDuration.current;
  15532. };
  15533. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15534. get: function () {
  15535. return this._spritesDuration;
  15536. },
  15537. enumerable: true,
  15538. configurable: true
  15539. });
  15540. Scene.prototype.getAnimationRatio = function () {
  15541. return this._animationRatio;
  15542. };
  15543. Scene.prototype.getRenderId = function () {
  15544. return this._renderId;
  15545. };
  15546. Scene.prototype.incrementRenderId = function () {
  15547. this._renderId++;
  15548. };
  15549. Scene.prototype._updatePointerPosition = function (evt) {
  15550. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15551. this._pointerX = evt.clientX - canvasRect.left;
  15552. this._pointerY = evt.clientY - canvasRect.top;
  15553. this._unTranslatedPointerX = this._pointerX;
  15554. this._unTranslatedPointerY = this._pointerY;
  15555. if (this.cameraToUseForPointers) {
  15556. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15557. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15558. }
  15559. };
  15560. // Pointers handling
  15561. /**
  15562. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15563. * @param attachUp defines if you want to attach events to pointerup
  15564. * @param attachDown defines if you want to attach events to pointerdown
  15565. * @param attachMove defines if you want to attach events to pointermove
  15566. */
  15567. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15568. var _this = this;
  15569. if (attachUp === void 0) { attachUp = true; }
  15570. if (attachDown === void 0) { attachDown = true; }
  15571. if (attachMove === void 0) { attachMove = true; }
  15572. var spritePredicate = function (sprite) {
  15573. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15574. };
  15575. this._onPointerMove = function (evt) {
  15576. _this._updatePointerPosition(evt);
  15577. // PreObservable support
  15578. if (_this.onPrePointerObservable.hasObservers()) {
  15579. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15580. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15581. _this.onPrePointerObservable.notifyObservers(pi, type);
  15582. if (pi.skipOnPointerObservable) {
  15583. return;
  15584. }
  15585. }
  15586. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15587. return;
  15588. }
  15589. var canvas = _this._engine.getRenderingCanvas();
  15590. if (!_this.pointerMovePredicate) {
  15591. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15592. }
  15593. // Meshes
  15594. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15595. if (pickResult.hit && pickResult.pickedMesh) {
  15596. _this.setPointerOverSprite(null);
  15597. _this.setPointerOverMesh(pickResult.pickedMesh);
  15598. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15599. canvas.style.cursor = _this.hoverCursor;
  15600. }
  15601. else {
  15602. canvas.style.cursor = "";
  15603. }
  15604. }
  15605. else {
  15606. _this.setPointerOverMesh(null);
  15607. // Sprites
  15608. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15609. if (pickResult.hit && pickResult.pickedSprite) {
  15610. canvas.style.cursor = _this.hoverCursor;
  15611. _this.setPointerOverSprite(pickResult.pickedSprite);
  15612. }
  15613. else {
  15614. _this.setPointerOverSprite(null);
  15615. // Restore pointer
  15616. canvas.style.cursor = "";
  15617. }
  15618. }
  15619. if (_this.onPointerMove) {
  15620. _this.onPointerMove(evt, pickResult);
  15621. }
  15622. if (_this.onPointerObservable.hasObservers()) {
  15623. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15624. var pi = new PointerInfo(type, evt, pickResult);
  15625. _this.onPointerObservable.notifyObservers(pi, type);
  15626. }
  15627. };
  15628. this._onPointerDown = function (evt) {
  15629. _this._updatePointerPosition(evt);
  15630. // PreObservable support
  15631. if (_this.onPrePointerObservable.hasObservers()) {
  15632. var type = PointerEventTypes.POINTERDOWN;
  15633. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15634. _this.onPrePointerObservable.notifyObservers(pi, type);
  15635. if (pi.skipOnPointerObservable) {
  15636. return;
  15637. }
  15638. }
  15639. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15640. return;
  15641. }
  15642. _this._startingPointerPosition.x = _this._pointerX;
  15643. _this._startingPointerPosition.y = _this._pointerY;
  15644. _this._startingPointerTime = new Date().getTime();
  15645. if (!_this.pointerDownPredicate) {
  15646. _this.pointerDownPredicate = function (mesh) {
  15647. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15648. };
  15649. }
  15650. // Meshes
  15651. _this._pickedDownMesh = null;
  15652. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15653. if (pickResult.hit && pickResult.pickedMesh) {
  15654. if (pickResult.pickedMesh.actionManager) {
  15655. _this._pickedDownMesh = pickResult.pickedMesh;
  15656. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15657. switch (evt.button) {
  15658. case 0:
  15659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15660. break;
  15661. case 1:
  15662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15663. break;
  15664. case 2:
  15665. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15666. break;
  15667. }
  15668. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15669. }
  15670. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15671. var that = _this;
  15672. window.setTimeout(function () {
  15673. 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);
  15674. if (pickResult.hit && pickResult.pickedMesh) {
  15675. if (pickResult.pickedMesh.actionManager) {
  15676. 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)) {
  15677. that._startingPointerTime = 0;
  15678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15679. }
  15680. }
  15681. }
  15682. }, BABYLON.ActionManager.LongPressDelay);
  15683. }
  15684. }
  15685. }
  15686. if (_this.onPointerDown) {
  15687. _this.onPointerDown(evt, pickResult);
  15688. }
  15689. if (_this.onPointerObservable.hasObservers()) {
  15690. var type = PointerEventTypes.POINTERDOWN;
  15691. var pi = new PointerInfo(type, evt, pickResult);
  15692. _this.onPointerObservable.notifyObservers(pi, type);
  15693. }
  15694. // Sprites
  15695. _this._pickedDownSprite = null;
  15696. if (_this.spriteManagers.length > 0) {
  15697. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15698. if (pickResult.hit && pickResult.pickedSprite) {
  15699. if (pickResult.pickedSprite.actionManager) {
  15700. _this._pickedDownSprite = pickResult.pickedSprite;
  15701. switch (evt.button) {
  15702. case 0:
  15703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15704. break;
  15705. case 1:
  15706. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15707. break;
  15708. case 2:
  15709. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15710. break;
  15711. }
  15712. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15713. }
  15714. }
  15715. }
  15716. };
  15717. this._onPointerUp = function (evt) {
  15718. _this._updatePointerPosition(evt);
  15719. // PreObservable support
  15720. if (_this.onPrePointerObservable.hasObservers()) {
  15721. var type = PointerEventTypes.POINTERUP;
  15722. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15723. _this.onPrePointerObservable.notifyObservers(pi, type);
  15724. if (pi.skipOnPointerObservable) {
  15725. return;
  15726. }
  15727. }
  15728. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15729. return;
  15730. }
  15731. if (!_this.pointerUpPredicate) {
  15732. _this.pointerUpPredicate = function (mesh) {
  15733. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15734. };
  15735. }
  15736. // Meshes
  15737. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15738. if (pickResult.hit && pickResult.pickedMesh) {
  15739. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15740. if (_this.onPointerPick) {
  15741. _this.onPointerPick(evt, pickResult);
  15742. }
  15743. if (_this.onPointerObservable.hasObservers()) {
  15744. var type = PointerEventTypes.POINTERPICK;
  15745. var pi = new PointerInfo(type, evt, pickResult);
  15746. _this.onPointerObservable.notifyObservers(pi, type);
  15747. }
  15748. }
  15749. if (pickResult.pickedMesh.actionManager) {
  15750. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15751. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15752. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15753. }
  15754. }
  15755. }
  15756. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15757. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15758. }
  15759. if (_this.onPointerUp) {
  15760. _this.onPointerUp(evt, pickResult);
  15761. }
  15762. if (_this.onPointerObservable.hasObservers()) {
  15763. var type = PointerEventTypes.POINTERUP;
  15764. var pi = new PointerInfo(type, evt, pickResult);
  15765. _this.onPointerObservable.notifyObservers(pi, type);
  15766. }
  15767. _this._startingPointerTime = 0;
  15768. // Sprites
  15769. if (_this.spriteManagers.length > 0) {
  15770. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15771. if (pickResult.hit && pickResult.pickedSprite) {
  15772. if (pickResult.pickedSprite.actionManager) {
  15773. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15774. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15775. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15776. }
  15777. }
  15778. }
  15779. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15780. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15781. }
  15782. }
  15783. };
  15784. this._onKeyDown = function (evt) {
  15785. if (_this.actionManager) {
  15786. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15787. }
  15788. };
  15789. this._onKeyUp = function (evt) {
  15790. if (_this.actionManager) {
  15791. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15792. }
  15793. };
  15794. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15795. var canvas = this._engine.getRenderingCanvas();
  15796. if (attachMove) {
  15797. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15798. // Wheel
  15799. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15800. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15801. }
  15802. if (attachDown) {
  15803. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15804. }
  15805. if (attachUp) {
  15806. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15807. }
  15808. canvas.tabIndex = 1;
  15809. canvas.addEventListener("keydown", this._onKeyDown, false);
  15810. canvas.addEventListener("keyup", this._onKeyUp, false);
  15811. };
  15812. Scene.prototype.detachControl = function () {
  15813. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15814. var canvas = this._engine.getRenderingCanvas();
  15815. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15816. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15817. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15818. // Wheel
  15819. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15820. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15821. canvas.removeEventListener("keydown", this._onKeyDown);
  15822. canvas.removeEventListener("keyup", this._onKeyUp);
  15823. };
  15824. // Ready
  15825. Scene.prototype.isReady = function () {
  15826. if (this._pendingData.length > 0) {
  15827. return false;
  15828. }
  15829. var index;
  15830. for (index = 0; index < this._geometries.length; index++) {
  15831. var geometry = this._geometries[index];
  15832. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15833. return false;
  15834. }
  15835. }
  15836. for (index = 0; index < this.meshes.length; index++) {
  15837. var mesh = this.meshes[index];
  15838. if (!mesh.isReady()) {
  15839. return false;
  15840. }
  15841. var mat = mesh.material;
  15842. if (mat) {
  15843. if (!mat.isReady(mesh)) {
  15844. return false;
  15845. }
  15846. }
  15847. }
  15848. return true;
  15849. };
  15850. Scene.prototype.resetCachedMaterial = function () {
  15851. this._cachedMaterial = null;
  15852. };
  15853. Scene.prototype.registerBeforeRender = function (func) {
  15854. this.onBeforeRenderObservable.add(func);
  15855. };
  15856. Scene.prototype.unregisterBeforeRender = function (func) {
  15857. this.onBeforeRenderObservable.removeCallback(func);
  15858. };
  15859. Scene.prototype.registerAfterRender = function (func) {
  15860. this.onAfterRenderObservable.add(func);
  15861. };
  15862. Scene.prototype.unregisterAfterRender = function (func) {
  15863. this.onAfterRenderObservable.removeCallback(func);
  15864. };
  15865. Scene.prototype._addPendingData = function (data) {
  15866. this._pendingData.push(data);
  15867. };
  15868. Scene.prototype._removePendingData = function (data) {
  15869. var index = this._pendingData.indexOf(data);
  15870. if (index !== -1) {
  15871. this._pendingData.splice(index, 1);
  15872. }
  15873. };
  15874. Scene.prototype.getWaitingItemsCount = function () {
  15875. return this._pendingData.length;
  15876. };
  15877. /**
  15878. * Registers a function to be executed when the scene is ready.
  15879. * @param {Function} func - the function to be executed.
  15880. */
  15881. Scene.prototype.executeWhenReady = function (func) {
  15882. var _this = this;
  15883. this.onReadyObservable.add(func);
  15884. if (this._executeWhenReadyTimeoutId !== -1) {
  15885. return;
  15886. }
  15887. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15888. _this._checkIsReady();
  15889. }, 150);
  15890. };
  15891. Scene.prototype._checkIsReady = function () {
  15892. var _this = this;
  15893. if (this.isReady()) {
  15894. this.onReadyObservable.notifyObservers(this);
  15895. this.onReadyObservable.clear();
  15896. this._executeWhenReadyTimeoutId = -1;
  15897. return;
  15898. }
  15899. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15900. _this._checkIsReady();
  15901. }, 150);
  15902. };
  15903. // Animations
  15904. /**
  15905. * Will start the animation sequence of a given target
  15906. * @param target - the target
  15907. * @param {number} from - from which frame should animation start
  15908. * @param {number} to - till which frame should animation run.
  15909. * @param {boolean} [loop] - should the animation loop
  15910. * @param {number} [speedRatio] - the speed in which to run the animation
  15911. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15912. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15913. * @return {BABYLON.Animatable} the animatable object created for this animation
  15914. * @see BABYLON.Animatable
  15915. * @see http://doc.babylonjs.com/page.php?p=22081
  15916. */
  15917. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15918. if (speedRatio === void 0) { speedRatio = 1.0; }
  15919. this.stopAnimation(target);
  15920. if (!animatable) {
  15921. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15922. }
  15923. // Local animations
  15924. if (target.animations) {
  15925. animatable.appendAnimations(target, target.animations);
  15926. }
  15927. // Children animations
  15928. if (target.getAnimatables) {
  15929. var animatables = target.getAnimatables();
  15930. for (var index = 0; index < animatables.length; index++) {
  15931. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15932. }
  15933. }
  15934. animatable.reset();
  15935. return animatable;
  15936. };
  15937. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15938. if (speedRatio === undefined) {
  15939. speedRatio = 1.0;
  15940. }
  15941. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15942. return animatable;
  15943. };
  15944. Scene.prototype.getAnimatableByTarget = function (target) {
  15945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15946. if (this._activeAnimatables[index].target === target) {
  15947. return this._activeAnimatables[index];
  15948. }
  15949. }
  15950. return null;
  15951. };
  15952. Object.defineProperty(Scene.prototype, "Animatables", {
  15953. get: function () {
  15954. return this._activeAnimatables;
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. /**
  15960. * Will stop the animation of the given target
  15961. * @param target - the target
  15962. * @see beginAnimation
  15963. */
  15964. Scene.prototype.stopAnimation = function (target) {
  15965. var animatable = this.getAnimatableByTarget(target);
  15966. if (animatable) {
  15967. animatable.stop();
  15968. }
  15969. };
  15970. Scene.prototype._animate = function () {
  15971. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15972. return;
  15973. }
  15974. if (!this._animationStartDate) {
  15975. if (this._pendingData.length > 0) {
  15976. return;
  15977. }
  15978. this._animationStartDate = BABYLON.Tools.Now;
  15979. }
  15980. // Getting time
  15981. var now = BABYLON.Tools.Now;
  15982. var delay = now - this._animationStartDate;
  15983. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15984. this._activeAnimatables[index]._animate(delay);
  15985. }
  15986. };
  15987. // Matrix
  15988. Scene.prototype.getViewMatrix = function () {
  15989. return this._viewMatrix;
  15990. };
  15991. Scene.prototype.getProjectionMatrix = function () {
  15992. return this._projectionMatrix;
  15993. };
  15994. Scene.prototype.getTransformMatrix = function () {
  15995. return this._transformMatrix;
  15996. };
  15997. Scene.prototype.setTransformMatrix = function (view, projection) {
  15998. this._viewMatrix = view;
  15999. this._projectionMatrix = projection;
  16000. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16001. // Update frustum
  16002. if (!this._frustumPlanes) {
  16003. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16004. }
  16005. else {
  16006. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16007. }
  16008. };
  16009. // Methods
  16010. Scene.prototype.addMesh = function (newMesh) {
  16011. newMesh.uniqueId = this._uniqueIdCounter++;
  16012. var position = this.meshes.push(newMesh);
  16013. //notify the collision coordinator
  16014. this.collisionCoordinator.onMeshAdded(newMesh);
  16015. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16016. };
  16017. Scene.prototype.removeMesh = function (toRemove) {
  16018. var index = this.meshes.indexOf(toRemove);
  16019. if (index !== -1) {
  16020. // Remove from the scene if mesh found
  16021. this.meshes.splice(index, 1);
  16022. }
  16023. //notify the collision coordinator
  16024. this.collisionCoordinator.onMeshRemoved(toRemove);
  16025. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16026. return index;
  16027. };
  16028. Scene.prototype.removeSkeleton = function (toRemove) {
  16029. var index = this.skeletons.indexOf(toRemove);
  16030. if (index !== -1) {
  16031. // Remove from the scene if mesh found
  16032. this.skeletons.splice(index, 1);
  16033. }
  16034. return index;
  16035. };
  16036. Scene.prototype.removeLight = function (toRemove) {
  16037. var index = this.lights.indexOf(toRemove);
  16038. if (index !== -1) {
  16039. // Remove from the scene if mesh found
  16040. this.lights.splice(index, 1);
  16041. }
  16042. this.onLightRemovedObservable.notifyObservers(toRemove);
  16043. return index;
  16044. };
  16045. Scene.prototype.removeCamera = function (toRemove) {
  16046. var index = this.cameras.indexOf(toRemove);
  16047. if (index !== -1) {
  16048. // Remove from the scene if mesh found
  16049. this.cameras.splice(index, 1);
  16050. }
  16051. // Remove from activeCameras
  16052. var index2 = this.activeCameras.indexOf(toRemove);
  16053. if (index2 !== -1) {
  16054. // Remove from the scene if mesh found
  16055. this.activeCameras.splice(index2, 1);
  16056. }
  16057. // Reset the activeCamera
  16058. if (this.activeCamera === toRemove) {
  16059. if (this.cameras.length > 0) {
  16060. this.activeCamera = this.cameras[0];
  16061. }
  16062. else {
  16063. this.activeCamera = null;
  16064. }
  16065. }
  16066. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16067. return index;
  16068. };
  16069. Scene.prototype.addLight = function (newLight) {
  16070. newLight.uniqueId = this._uniqueIdCounter++;
  16071. var position = this.lights.push(newLight);
  16072. this.onNewLightAddedObservable.notifyObservers(newLight);
  16073. };
  16074. Scene.prototype.addCamera = function (newCamera) {
  16075. newCamera.uniqueId = this._uniqueIdCounter++;
  16076. var position = this.cameras.push(newCamera);
  16077. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16078. };
  16079. /**
  16080. * Switch active camera
  16081. * @param {Camera} newCamera - new active camera
  16082. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16083. */
  16084. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16085. if (attachControl === void 0) { attachControl = true; }
  16086. var canvas = this._engine.getRenderingCanvas();
  16087. this.activeCamera.detachControl(canvas);
  16088. this.activeCamera = newCamera;
  16089. if (attachControl) {
  16090. newCamera.attachControl(canvas);
  16091. }
  16092. };
  16093. /**
  16094. * sets the active camera of the scene using its ID
  16095. * @param {string} id - the camera's ID
  16096. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16097. * @see activeCamera
  16098. */
  16099. Scene.prototype.setActiveCameraByID = function (id) {
  16100. var camera = this.getCameraByID(id);
  16101. if (camera) {
  16102. this.activeCamera = camera;
  16103. return camera;
  16104. }
  16105. return null;
  16106. };
  16107. /**
  16108. * sets the active camera of the scene using its name
  16109. * @param {string} name - the camera's name
  16110. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16111. * @see activeCamera
  16112. */
  16113. Scene.prototype.setActiveCameraByName = function (name) {
  16114. var camera = this.getCameraByName(name);
  16115. if (camera) {
  16116. this.activeCamera = camera;
  16117. return camera;
  16118. }
  16119. return null;
  16120. };
  16121. /**
  16122. * get a material using its id
  16123. * @param {string} the material's ID
  16124. * @return {BABYLON.Material|null} the material or null if none found.
  16125. */
  16126. Scene.prototype.getMaterialByID = function (id) {
  16127. for (var index = 0; index < this.materials.length; index++) {
  16128. if (this.materials[index].id === id) {
  16129. return this.materials[index];
  16130. }
  16131. }
  16132. return null;
  16133. };
  16134. /**
  16135. * get a material using its name
  16136. * @param {string} the material's name
  16137. * @return {BABYLON.Material|null} the material or null if none found.
  16138. */
  16139. Scene.prototype.getMaterialByName = function (name) {
  16140. for (var index = 0; index < this.materials.length; index++) {
  16141. if (this.materials[index].name === name) {
  16142. return this.materials[index];
  16143. }
  16144. }
  16145. return null;
  16146. };
  16147. Scene.prototype.getLensFlareSystemByName = function (name) {
  16148. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16149. if (this.lensFlareSystems[index].name === name) {
  16150. return this.lensFlareSystems[index];
  16151. }
  16152. }
  16153. return null;
  16154. };
  16155. Scene.prototype.getLensFlareSystemByID = function (id) {
  16156. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16157. if (this.lensFlareSystems[index].id === id) {
  16158. return this.lensFlareSystems[index];
  16159. }
  16160. }
  16161. return null;
  16162. };
  16163. Scene.prototype.getCameraByID = function (id) {
  16164. for (var index = 0; index < this.cameras.length; index++) {
  16165. if (this.cameras[index].id === id) {
  16166. return this.cameras[index];
  16167. }
  16168. }
  16169. return null;
  16170. };
  16171. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16172. for (var index = 0; index < this.cameras.length; index++) {
  16173. if (this.cameras[index].uniqueId === uniqueId) {
  16174. return this.cameras[index];
  16175. }
  16176. }
  16177. return null;
  16178. };
  16179. /**
  16180. * get a camera using its name
  16181. * @param {string} the camera's name
  16182. * @return {BABYLON.Camera|null} the camera or null if none found.
  16183. */
  16184. Scene.prototype.getCameraByName = function (name) {
  16185. for (var index = 0; index < this.cameras.length; index++) {
  16186. if (this.cameras[index].name === name) {
  16187. return this.cameras[index];
  16188. }
  16189. }
  16190. return null;
  16191. };
  16192. /**
  16193. * get a bone using its id
  16194. * @param {string} the bone's id
  16195. * @return {BABYLON.Bone|null} the bone or null if not found
  16196. */
  16197. Scene.prototype.getBoneByID = function (id) {
  16198. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16199. var skeleton = this.skeletons[skeletonIndex];
  16200. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16201. if (skeleton.bones[boneIndex].id === id) {
  16202. return skeleton.bones[boneIndex];
  16203. }
  16204. }
  16205. }
  16206. return null;
  16207. };
  16208. /**
  16209. * get a bone using its id
  16210. * @param {string} the bone's name
  16211. * @return {BABYLON.Bone|null} the bone or null if not found
  16212. */
  16213. Scene.prototype.getBoneByName = function (name) {
  16214. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16215. var skeleton = this.skeletons[skeletonIndex];
  16216. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16217. if (skeleton.bones[boneIndex].name === name) {
  16218. return skeleton.bones[boneIndex];
  16219. }
  16220. }
  16221. }
  16222. return null;
  16223. };
  16224. /**
  16225. * get a light node using its name
  16226. * @param {string} the light's name
  16227. * @return {BABYLON.Light|null} the light or null if none found.
  16228. */
  16229. Scene.prototype.getLightByName = function (name) {
  16230. for (var index = 0; index < this.lights.length; index++) {
  16231. if (this.lights[index].name === name) {
  16232. return this.lights[index];
  16233. }
  16234. }
  16235. return null;
  16236. };
  16237. /**
  16238. * get a light node using its ID
  16239. * @param {string} the light's id
  16240. * @return {BABYLON.Light|null} the light or null if none found.
  16241. */
  16242. Scene.prototype.getLightByID = function (id) {
  16243. for (var index = 0; index < this.lights.length; index++) {
  16244. if (this.lights[index].id === id) {
  16245. return this.lights[index];
  16246. }
  16247. }
  16248. return null;
  16249. };
  16250. /**
  16251. * get a light node using its scene-generated unique ID
  16252. * @param {number} the light's unique id
  16253. * @return {BABYLON.Light|null} the light or null if none found.
  16254. */
  16255. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16256. for (var index = 0; index < this.lights.length; index++) {
  16257. if (this.lights[index].uniqueId === uniqueId) {
  16258. return this.lights[index];
  16259. }
  16260. }
  16261. return null;
  16262. };
  16263. /**
  16264. * get a particle system by id
  16265. * @param id {number} the particle system id
  16266. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16267. */
  16268. Scene.prototype.getParticleSystemByID = function (id) {
  16269. for (var index = 0; index < this.particleSystems.length; index++) {
  16270. if (this.particleSystems[index].id === id) {
  16271. return this.particleSystems[index];
  16272. }
  16273. }
  16274. return null;
  16275. };
  16276. /**
  16277. * get a geometry using its ID
  16278. * @param {string} the geometry's id
  16279. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16280. */
  16281. Scene.prototype.getGeometryByID = function (id) {
  16282. for (var index = 0; index < this._geometries.length; index++) {
  16283. if (this._geometries[index].id === id) {
  16284. return this._geometries[index];
  16285. }
  16286. }
  16287. return null;
  16288. };
  16289. /**
  16290. * add a new geometry to this scene.
  16291. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16292. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16293. * @return {boolean} was the geometry added or not
  16294. */
  16295. Scene.prototype.pushGeometry = function (geometry, force) {
  16296. if (!force && this.getGeometryByID(geometry.id)) {
  16297. return false;
  16298. }
  16299. this._geometries.push(geometry);
  16300. //notify the collision coordinator
  16301. this.collisionCoordinator.onGeometryAdded(geometry);
  16302. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16303. return true;
  16304. };
  16305. /**
  16306. * Removes an existing geometry
  16307. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16308. * @return {boolean} was the geometry removed or not
  16309. */
  16310. Scene.prototype.removeGeometry = function (geometry) {
  16311. var index = this._geometries.indexOf(geometry);
  16312. if (index > -1) {
  16313. this._geometries.splice(index, 1);
  16314. //notify the collision coordinator
  16315. this.collisionCoordinator.onGeometryDeleted(geometry);
  16316. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16317. return true;
  16318. }
  16319. return false;
  16320. };
  16321. Scene.prototype.getGeometries = function () {
  16322. return this._geometries;
  16323. };
  16324. /**
  16325. * Get the first added mesh found of a given ID
  16326. * @param {string} id - the id to search for
  16327. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16328. */
  16329. Scene.prototype.getMeshByID = function (id) {
  16330. for (var index = 0; index < this.meshes.length; index++) {
  16331. if (this.meshes[index].id === id) {
  16332. return this.meshes[index];
  16333. }
  16334. }
  16335. return null;
  16336. };
  16337. Scene.prototype.getMeshesByID = function (id) {
  16338. return this.meshes.filter(function (m) {
  16339. return m.id === id;
  16340. });
  16341. };
  16342. /**
  16343. * Get a mesh with its auto-generated unique id
  16344. * @param {number} uniqueId - the unique id to search for
  16345. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16346. */
  16347. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16348. for (var index = 0; index < this.meshes.length; index++) {
  16349. if (this.meshes[index].uniqueId === uniqueId) {
  16350. return this.meshes[index];
  16351. }
  16352. }
  16353. return null;
  16354. };
  16355. /**
  16356. * Get a the last added mesh found of a given ID
  16357. * @param {string} id - the id to search for
  16358. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16359. */
  16360. Scene.prototype.getLastMeshByID = function (id) {
  16361. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16362. if (this.meshes[index].id === id) {
  16363. return this.meshes[index];
  16364. }
  16365. }
  16366. return null;
  16367. };
  16368. /**
  16369. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16370. * @param {string} id - the id to search for
  16371. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16372. */
  16373. Scene.prototype.getLastEntryByID = function (id) {
  16374. var index;
  16375. for (index = this.meshes.length - 1; index >= 0; index--) {
  16376. if (this.meshes[index].id === id) {
  16377. return this.meshes[index];
  16378. }
  16379. }
  16380. for (index = this.cameras.length - 1; index >= 0; index--) {
  16381. if (this.cameras[index].id === id) {
  16382. return this.cameras[index];
  16383. }
  16384. }
  16385. for (index = this.lights.length - 1; index >= 0; index--) {
  16386. if (this.lights[index].id === id) {
  16387. return this.lights[index];
  16388. }
  16389. }
  16390. return null;
  16391. };
  16392. Scene.prototype.getNodeByID = function (id) {
  16393. var mesh = this.getMeshByID(id);
  16394. if (mesh) {
  16395. return mesh;
  16396. }
  16397. var light = this.getLightByID(id);
  16398. if (light) {
  16399. return light;
  16400. }
  16401. var camera = this.getCameraByID(id);
  16402. if (camera) {
  16403. return camera;
  16404. }
  16405. var bone = this.getBoneByID(id);
  16406. return bone;
  16407. };
  16408. Scene.prototype.getNodeByName = function (name) {
  16409. var mesh = this.getMeshByName(name);
  16410. if (mesh) {
  16411. return mesh;
  16412. }
  16413. var light = this.getLightByName(name);
  16414. if (light) {
  16415. return light;
  16416. }
  16417. var camera = this.getCameraByName(name);
  16418. if (camera) {
  16419. return camera;
  16420. }
  16421. var bone = this.getBoneByName(name);
  16422. return bone;
  16423. };
  16424. Scene.prototype.getMeshByName = function (name) {
  16425. for (var index = 0; index < this.meshes.length; index++) {
  16426. if (this.meshes[index].name === name) {
  16427. return this.meshes[index];
  16428. }
  16429. }
  16430. return null;
  16431. };
  16432. Scene.prototype.getSoundByName = function (name) {
  16433. var index;
  16434. if (BABYLON.AudioEngine) {
  16435. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16436. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16437. return this.mainSoundTrack.soundCollection[index];
  16438. }
  16439. }
  16440. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16441. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16442. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16443. return this.soundTracks[sdIndex].soundCollection[index];
  16444. }
  16445. }
  16446. }
  16447. }
  16448. return null;
  16449. };
  16450. Scene.prototype.getLastSkeletonByID = function (id) {
  16451. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16452. if (this.skeletons[index].id === id) {
  16453. return this.skeletons[index];
  16454. }
  16455. }
  16456. return null;
  16457. };
  16458. Scene.prototype.getSkeletonById = function (id) {
  16459. for (var index = 0; index < this.skeletons.length; index++) {
  16460. if (this.skeletons[index].id === id) {
  16461. return this.skeletons[index];
  16462. }
  16463. }
  16464. return null;
  16465. };
  16466. Scene.prototype.getSkeletonByName = function (name) {
  16467. for (var index = 0; index < this.skeletons.length; index++) {
  16468. if (this.skeletons[index].name === name) {
  16469. return this.skeletons[index];
  16470. }
  16471. }
  16472. return null;
  16473. };
  16474. Scene.prototype.isActiveMesh = function (mesh) {
  16475. return (this._activeMeshes.indexOf(mesh) !== -1);
  16476. };
  16477. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16478. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16479. var material = subMesh.getMaterial();
  16480. if (mesh.showSubMeshesBoundingBox) {
  16481. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16482. }
  16483. if (material) {
  16484. // Render targets
  16485. if (material.getRenderTargetTextures) {
  16486. if (this._processedMaterials.indexOf(material) === -1) {
  16487. this._processedMaterials.push(material);
  16488. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16489. }
  16490. }
  16491. // Dispatch
  16492. this._activeIndices.addCount(subMesh.indexCount, false);
  16493. this._renderingManager.dispatch(subMesh);
  16494. }
  16495. }
  16496. };
  16497. Scene.prototype._isInIntermediateRendering = function () {
  16498. return this._intermediateRendering;
  16499. };
  16500. Scene.prototype._evaluateActiveMeshes = function () {
  16501. this.activeCamera._activeMeshes.reset();
  16502. this._activeMeshes.reset();
  16503. this._renderingManager.reset();
  16504. this._processedMaterials.reset();
  16505. this._activeParticleSystems.reset();
  16506. this._activeSkeletons.reset();
  16507. this._softwareSkinnedMeshes.reset();
  16508. this._boundingBoxRenderer.reset();
  16509. this._edgesRenderers.reset();
  16510. // Meshes
  16511. var meshes;
  16512. var len;
  16513. if (this._selectionOctree) {
  16514. var selection = this._selectionOctree.select(this._frustumPlanes);
  16515. meshes = selection.data;
  16516. len = selection.length;
  16517. }
  16518. else {
  16519. len = this.meshes.length;
  16520. meshes = this.meshes;
  16521. }
  16522. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16523. var mesh = meshes[meshIndex];
  16524. if (mesh.isBlocked) {
  16525. continue;
  16526. }
  16527. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16528. if (!mesh.isReady() || !mesh.isEnabled()) {
  16529. continue;
  16530. }
  16531. mesh.computeWorldMatrix();
  16532. // Intersections
  16533. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16534. this._meshesForIntersections.pushNoDuplicate(mesh);
  16535. }
  16536. // Switch to current LOD
  16537. var meshLOD = mesh.getLOD(this.activeCamera);
  16538. if (!meshLOD) {
  16539. continue;
  16540. }
  16541. mesh._preActivate();
  16542. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16543. this._activeMeshes.push(mesh);
  16544. this.activeCamera._activeMeshes.push(mesh);
  16545. mesh._activate(this._renderId);
  16546. this._activeMesh(mesh, meshLOD);
  16547. }
  16548. }
  16549. // Particle systems
  16550. this._particlesDuration.beginMonitoring();
  16551. var beforeParticlesDate = BABYLON.Tools.Now;
  16552. if (this.particlesEnabled) {
  16553. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16554. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16555. var particleSystem = this.particleSystems[particleIndex];
  16556. if (!particleSystem.isStarted()) {
  16557. continue;
  16558. }
  16559. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16560. this._activeParticleSystems.push(particleSystem);
  16561. particleSystem.animate();
  16562. }
  16563. }
  16564. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16565. }
  16566. this._particlesDuration.endMonitoring(false);
  16567. };
  16568. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16569. if (mesh.skeleton && this.skeletonsEnabled) {
  16570. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16571. mesh.skeleton.prepare();
  16572. }
  16573. if (!mesh.computeBonesUsingShaders) {
  16574. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16575. }
  16576. }
  16577. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16578. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16579. }
  16580. if (sourceMesh._edgesRenderer) {
  16581. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16582. }
  16583. if (mesh && mesh.subMeshes) {
  16584. // Submeshes Octrees
  16585. var len;
  16586. var subMeshes;
  16587. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16588. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16589. len = intersections.length;
  16590. subMeshes = intersections.data;
  16591. }
  16592. else {
  16593. subMeshes = mesh.subMeshes;
  16594. len = subMeshes.length;
  16595. }
  16596. for (var subIndex = 0; subIndex < len; subIndex++) {
  16597. var subMesh = subMeshes[subIndex];
  16598. this._evaluateSubMesh(subMesh, mesh);
  16599. }
  16600. }
  16601. };
  16602. Scene.prototype.updateTransformMatrix = function (force) {
  16603. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16604. };
  16605. Scene.prototype._renderForCamera = function (camera) {
  16606. var engine = this._engine;
  16607. var startTime = BABYLON.Tools.Now;
  16608. this.activeCamera = camera;
  16609. if (!this.activeCamera)
  16610. throw new Error("Active camera not set");
  16611. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16612. // Viewport
  16613. engine.setViewport(this.activeCamera.viewport);
  16614. // Camera
  16615. this.resetCachedMaterial();
  16616. this._renderId++;
  16617. this.updateTransformMatrix();
  16618. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16619. // Meshes
  16620. this._evaluateActiveMeshesDuration.beginMonitoring();
  16621. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16622. this._evaluateActiveMeshes();
  16623. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16624. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16625. // Software skinning
  16626. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16627. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16628. mesh.applySkeleton(mesh.skeleton);
  16629. }
  16630. // Render targets
  16631. this._renderTargetsDuration.beginMonitoring();
  16632. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16633. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16634. this._intermediateRendering = true;
  16635. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16636. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16637. var renderTarget = this._renderTargets.data[renderIndex];
  16638. if (renderTarget._shouldRender()) {
  16639. this._renderId++;
  16640. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16641. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16642. }
  16643. }
  16644. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16645. this._intermediateRendering = false;
  16646. this._renderId++;
  16647. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16648. }
  16649. this._renderTargetsDuration.endMonitoring(false);
  16650. // Prepare Frame
  16651. this.postProcessManager._prepareFrame();
  16652. this._renderDuration.beginMonitoring();
  16653. // Backgrounds
  16654. var layerIndex;
  16655. var layer;
  16656. if (this.layers.length) {
  16657. engine.setDepthBuffer(false);
  16658. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16659. layer = this.layers[layerIndex];
  16660. if (layer.isBackground) {
  16661. layer.render();
  16662. }
  16663. }
  16664. engine.setDepthBuffer(true);
  16665. }
  16666. // Render
  16667. BABYLON.Tools.StartPerformanceCounter("Main render");
  16668. this._renderingManager.render(null, null, true, true);
  16669. BABYLON.Tools.EndPerformanceCounter("Main render");
  16670. // Bounding boxes
  16671. this._boundingBoxRenderer.render();
  16672. // Edges
  16673. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16674. this._edgesRenderers.data[edgesRendererIndex].render();
  16675. }
  16676. // Lens flares
  16677. if (this.lensFlaresEnabled) {
  16678. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16679. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16680. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16681. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16682. lensFlareSystem.render();
  16683. }
  16684. }
  16685. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16686. }
  16687. // Foregrounds
  16688. if (this.layers.length) {
  16689. engine.setDepthBuffer(false);
  16690. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16691. layer = this.layers[layerIndex];
  16692. if (!layer.isBackground) {
  16693. layer.render();
  16694. }
  16695. }
  16696. engine.setDepthBuffer(true);
  16697. }
  16698. this._renderDuration.endMonitoring(false);
  16699. // Finalize frame
  16700. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16701. // Update camera
  16702. this.activeCamera._updateFromScene();
  16703. // Reset some special arrays
  16704. this._renderTargets.reset();
  16705. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16706. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16707. };
  16708. Scene.prototype._processSubCameras = function (camera) {
  16709. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16710. this._renderForCamera(camera);
  16711. return;
  16712. }
  16713. // rig cameras
  16714. for (var index = 0; index < camera._rigCameras.length; index++) {
  16715. this._renderForCamera(camera._rigCameras[index]);
  16716. }
  16717. this.activeCamera = camera;
  16718. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16719. // Update camera
  16720. this.activeCamera._updateFromScene();
  16721. };
  16722. Scene.prototype._checkIntersections = function () {
  16723. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16724. var sourceMesh = this._meshesForIntersections.data[index];
  16725. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16726. var action = sourceMesh.actionManager.actions[actionIndex];
  16727. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16728. var parameters = action.getTriggerParameter();
  16729. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16730. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16731. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16732. if (areIntersecting && currentIntersectionInProgress === -1) {
  16733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16734. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16735. sourceMesh._intersectionsInProgress.push(otherMesh);
  16736. }
  16737. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16738. sourceMesh._intersectionsInProgress.push(otherMesh);
  16739. }
  16740. }
  16741. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16742. //They intersected, and now they don't.
  16743. //is this trigger an exit trigger? execute an event.
  16744. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16745. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16746. }
  16747. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16748. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16749. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16750. }
  16751. }
  16752. }
  16753. }
  16754. }
  16755. };
  16756. Scene.prototype.render = function () {
  16757. this._lastFrameDuration.beginMonitoring();
  16758. this._particlesDuration.fetchNewFrame();
  16759. this._spritesDuration.fetchNewFrame();
  16760. this._activeParticles.fetchNewFrame();
  16761. this._renderDuration.fetchNewFrame();
  16762. this._renderTargetsDuration.fetchNewFrame();
  16763. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16764. this._totalVertices.fetchNewFrame();
  16765. this._activeIndices.fetchNewFrame();
  16766. this._activeBones.fetchNewFrame();
  16767. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16768. this._meshesForIntersections.reset();
  16769. this.resetCachedMaterial();
  16770. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16771. // Actions
  16772. if (this.actionManager) {
  16773. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16774. }
  16775. //Simplification Queue
  16776. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16777. this.simplificationQueue.executeNext();
  16778. }
  16779. // Animations
  16780. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16781. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16782. this._animate();
  16783. // Physics
  16784. if (this._physicsEngine) {
  16785. BABYLON.Tools.StartPerformanceCounter("Physics");
  16786. this._physicsEngine._step(deltaTime / 1000.0);
  16787. BABYLON.Tools.EndPerformanceCounter("Physics");
  16788. }
  16789. // Before render
  16790. this.onBeforeRenderObservable.notifyObservers(this);
  16791. // Customs render targets
  16792. this._renderTargetsDuration.beginMonitoring();
  16793. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16794. var engine = this.getEngine();
  16795. var currentActiveCamera = this.activeCamera;
  16796. if (this.renderTargetsEnabled) {
  16797. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16798. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16799. var renderTarget = this.customRenderTargets[customIndex];
  16800. if (renderTarget._shouldRender()) {
  16801. this._renderId++;
  16802. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16803. if (!this.activeCamera)
  16804. throw new Error("Active camera not set");
  16805. // Viewport
  16806. engine.setViewport(this.activeCamera.viewport);
  16807. // Camera
  16808. this.updateTransformMatrix();
  16809. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16810. }
  16811. }
  16812. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16813. this._renderId++;
  16814. }
  16815. if (this.customRenderTargets.length > 0) {
  16816. engine.restoreDefaultFramebuffer();
  16817. }
  16818. this._renderTargetsDuration.endMonitoring();
  16819. this.activeCamera = currentActiveCamera;
  16820. // Procedural textures
  16821. if (this.proceduralTexturesEnabled) {
  16822. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16823. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16824. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16825. if (proceduralTexture._shouldRender()) {
  16826. proceduralTexture.render();
  16827. }
  16828. }
  16829. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16830. }
  16831. // Clear
  16832. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16833. // Shadows
  16834. if (this.shadowsEnabled) {
  16835. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16836. var light = this.lights[lightIndex];
  16837. var shadowGenerator = light.getShadowGenerator();
  16838. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16839. this._renderTargets.push(shadowGenerator.getShadowMap());
  16840. }
  16841. }
  16842. }
  16843. // Depth renderer
  16844. if (this._depthRenderer) {
  16845. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16846. }
  16847. // RenderPipeline
  16848. this.postProcessRenderPipelineManager.update();
  16849. // Multi-cameras?
  16850. if (this.activeCameras.length > 0) {
  16851. var currentRenderId = this._renderId;
  16852. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16853. this._renderId = currentRenderId;
  16854. if (cameraIndex > 0) {
  16855. this._engine.clear(0, false, true);
  16856. }
  16857. this._processSubCameras(this.activeCameras[cameraIndex]);
  16858. }
  16859. }
  16860. else {
  16861. if (!this.activeCamera) {
  16862. throw new Error("No camera defined");
  16863. }
  16864. this._processSubCameras(this.activeCamera);
  16865. }
  16866. // Intersection checks
  16867. this._checkIntersections();
  16868. // Update the audio listener attached to the camera
  16869. if (BABYLON.AudioEngine) {
  16870. this._updateAudioParameters();
  16871. }
  16872. // After render
  16873. if (this.afterRender) {
  16874. this.afterRender();
  16875. }
  16876. this.onAfterRenderObservable.notifyObservers(this);
  16877. // Cleaning
  16878. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16879. this._toBeDisposed.data[index].dispose();
  16880. this._toBeDisposed[index] = null;
  16881. }
  16882. this._toBeDisposed.reset();
  16883. if (this.dumpNextRenderTargets) {
  16884. this.dumpNextRenderTargets = false;
  16885. }
  16886. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16887. this._lastFrameDuration.endMonitoring();
  16888. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16889. this._totalLightsCounter.addCount(this.lights.length, true);
  16890. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16891. this._totalTexturesCounter.addCount(this.textures.length, true);
  16892. this._activeBones.addCount(0, true);
  16893. this._activeIndices.addCount(0, true);
  16894. this._activeParticles.addCount(0, true);
  16895. };
  16896. Scene.prototype._updateAudioParameters = function () {
  16897. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16898. return;
  16899. }
  16900. var listeningCamera;
  16901. var audioEngine = BABYLON.Engine.audioEngine;
  16902. if (this.activeCameras.length > 0) {
  16903. listeningCamera = this.activeCameras[0];
  16904. }
  16905. else {
  16906. listeningCamera = this.activeCamera;
  16907. }
  16908. if (listeningCamera && audioEngine.canUseWebAudio) {
  16909. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16910. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16911. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16912. cameraDirection.normalize();
  16913. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16914. var i;
  16915. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16916. var sound = this.mainSoundTrack.soundCollection[i];
  16917. if (sound.useCustomAttenuation) {
  16918. sound.updateDistanceFromListener();
  16919. }
  16920. }
  16921. for (i = 0; i < this.soundTracks.length; i++) {
  16922. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16923. sound = this.soundTracks[i].soundCollection[j];
  16924. if (sound.useCustomAttenuation) {
  16925. sound.updateDistanceFromListener();
  16926. }
  16927. }
  16928. }
  16929. }
  16930. };
  16931. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16932. // Audio
  16933. get: function () {
  16934. return this._audioEnabled;
  16935. },
  16936. set: function (value) {
  16937. this._audioEnabled = value;
  16938. if (BABYLON.AudioEngine) {
  16939. if (this._audioEnabled) {
  16940. this._enableAudio();
  16941. }
  16942. else {
  16943. this._disableAudio();
  16944. }
  16945. }
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. Scene.prototype._disableAudio = function () {
  16951. var i;
  16952. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16953. this.mainSoundTrack.soundCollection[i].pause();
  16954. }
  16955. for (i = 0; i < this.soundTracks.length; i++) {
  16956. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16957. this.soundTracks[i].soundCollection[j].pause();
  16958. }
  16959. }
  16960. };
  16961. Scene.prototype._enableAudio = function () {
  16962. var i;
  16963. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16964. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16965. this.mainSoundTrack.soundCollection[i].play();
  16966. }
  16967. }
  16968. for (i = 0; i < this.soundTracks.length; i++) {
  16969. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16970. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16971. this.soundTracks[i].soundCollection[j].play();
  16972. }
  16973. }
  16974. }
  16975. };
  16976. Object.defineProperty(Scene.prototype, "headphone", {
  16977. get: function () {
  16978. return this._headphone;
  16979. },
  16980. set: function (value) {
  16981. this._headphone = value;
  16982. if (BABYLON.AudioEngine) {
  16983. if (this._headphone) {
  16984. this._switchAudioModeForHeadphones();
  16985. }
  16986. else {
  16987. this._switchAudioModeForNormalSpeakers();
  16988. }
  16989. }
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Scene.prototype._switchAudioModeForHeadphones = function () {
  16995. this.mainSoundTrack.switchPanningModelToHRTF();
  16996. for (var i = 0; i < this.soundTracks.length; i++) {
  16997. this.soundTracks[i].switchPanningModelToHRTF();
  16998. }
  16999. };
  17000. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17001. this.mainSoundTrack.switchPanningModelToEqualPower();
  17002. for (var i = 0; i < this.soundTracks.length; i++) {
  17003. this.soundTracks[i].switchPanningModelToEqualPower();
  17004. }
  17005. };
  17006. Scene.prototype.enableDepthRenderer = function () {
  17007. if (this._depthRenderer) {
  17008. return this._depthRenderer;
  17009. }
  17010. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17011. return this._depthRenderer;
  17012. };
  17013. Scene.prototype.disableDepthRenderer = function () {
  17014. if (!this._depthRenderer) {
  17015. return;
  17016. }
  17017. this._depthRenderer.dispose();
  17018. this._depthRenderer = null;
  17019. };
  17020. Scene.prototype.freezeMaterials = function () {
  17021. for (var i = 0; i < this.materials.length; i++) {
  17022. this.materials[i].freeze();
  17023. }
  17024. };
  17025. Scene.prototype.unfreezeMaterials = function () {
  17026. for (var i = 0; i < this.materials.length; i++) {
  17027. this.materials[i].unfreeze();
  17028. }
  17029. };
  17030. Scene.prototype.dispose = function () {
  17031. this.beforeRender = null;
  17032. this.afterRender = null;
  17033. this.skeletons = [];
  17034. this._boundingBoxRenderer.dispose();
  17035. if (this._depthRenderer) {
  17036. this._depthRenderer.dispose();
  17037. }
  17038. // Debug layer
  17039. if (this._debugLayer) {
  17040. this._debugLayer.hide();
  17041. }
  17042. // Events
  17043. this.onDisposeObservable.notifyObservers(this);
  17044. this.onDisposeObservable.clear();
  17045. this.onBeforeRenderObservable.clear();
  17046. this.onAfterRenderObservable.clear();
  17047. this.detachControl();
  17048. // Release sounds & sounds tracks
  17049. if (BABYLON.AudioEngine) {
  17050. this.disposeSounds();
  17051. }
  17052. // Detach cameras
  17053. var canvas = this._engine.getRenderingCanvas();
  17054. var index;
  17055. for (index = 0; index < this.cameras.length; index++) {
  17056. this.cameras[index].detachControl(canvas);
  17057. }
  17058. // Release lights
  17059. while (this.lights.length) {
  17060. this.lights[0].dispose();
  17061. }
  17062. // Release meshes
  17063. while (this.meshes.length) {
  17064. this.meshes[0].dispose(true);
  17065. }
  17066. // Release cameras
  17067. while (this.cameras.length) {
  17068. this.cameras[0].dispose();
  17069. }
  17070. // Release materials
  17071. while (this.materials.length) {
  17072. this.materials[0].dispose();
  17073. }
  17074. // Release particles
  17075. while (this.particleSystems.length) {
  17076. this.particleSystems[0].dispose();
  17077. }
  17078. // Release sprites
  17079. while (this.spriteManagers.length) {
  17080. this.spriteManagers[0].dispose();
  17081. }
  17082. // Release layers
  17083. while (this.layers.length) {
  17084. this.layers[0].dispose();
  17085. }
  17086. // Release textures
  17087. while (this.textures.length) {
  17088. this.textures[0].dispose();
  17089. }
  17090. // Post-processes
  17091. this.postProcessManager.dispose();
  17092. // Physics
  17093. if (this._physicsEngine) {
  17094. this.disablePhysicsEngine();
  17095. }
  17096. // Remove from engine
  17097. index = this._engine.scenes.indexOf(this);
  17098. if (index > -1) {
  17099. this._engine.scenes.splice(index, 1);
  17100. }
  17101. this._engine.wipeCaches();
  17102. };
  17103. // Release sounds & sounds tracks
  17104. Scene.prototype.disposeSounds = function () {
  17105. this.mainSoundTrack.dispose();
  17106. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17107. this.soundTracks[scIndex].dispose();
  17108. }
  17109. };
  17110. // Octrees
  17111. Scene.prototype.getWorldExtends = function () {
  17112. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17113. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17114. for (var index = 0; index < this.meshes.length; index++) {
  17115. var mesh = this.meshes[index];
  17116. mesh.computeWorldMatrix(true);
  17117. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17118. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17119. BABYLON.Tools.CheckExtends(minBox, min, max);
  17120. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17121. }
  17122. return {
  17123. min: min,
  17124. max: max
  17125. };
  17126. };
  17127. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17128. if (maxCapacity === void 0) { maxCapacity = 64; }
  17129. if (maxDepth === void 0) { maxDepth = 2; }
  17130. if (!this._selectionOctree) {
  17131. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17132. }
  17133. var worldExtends = this.getWorldExtends();
  17134. // Update octree
  17135. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17136. return this._selectionOctree;
  17137. };
  17138. // Picking
  17139. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17140. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17141. var engine = this._engine;
  17142. if (!camera) {
  17143. if (!this.activeCamera)
  17144. throw new Error("Active camera not set");
  17145. camera = this.activeCamera;
  17146. }
  17147. var cameraViewport = camera.viewport;
  17148. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17149. // Moving coordinates to local viewport world
  17150. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17151. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17152. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17153. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17154. };
  17155. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17156. var engine = this._engine;
  17157. if (!camera) {
  17158. if (!this.activeCamera)
  17159. throw new Error("Active camera not set");
  17160. camera = this.activeCamera;
  17161. }
  17162. var cameraViewport = camera.viewport;
  17163. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17164. var identity = BABYLON.Matrix.Identity();
  17165. // Moving coordinates to local viewport world
  17166. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17167. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17168. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17169. };
  17170. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17171. var pickingInfo = null;
  17172. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17173. var mesh = this.meshes[meshIndex];
  17174. if (predicate) {
  17175. if (!predicate(mesh)) {
  17176. continue;
  17177. }
  17178. }
  17179. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17180. continue;
  17181. }
  17182. var world = mesh.getWorldMatrix();
  17183. var ray = rayFunction(world);
  17184. var result = mesh.intersects(ray, fastCheck);
  17185. if (!result || !result.hit)
  17186. continue;
  17187. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17188. continue;
  17189. pickingInfo = result;
  17190. if (fastCheck) {
  17191. break;
  17192. }
  17193. }
  17194. return pickingInfo || new BABYLON.PickingInfo();
  17195. };
  17196. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17197. var pickingInfo = null;
  17198. camera = camera || this.activeCamera;
  17199. if (this.spriteManagers.length > 0) {
  17200. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17201. var spriteManager = this.spriteManagers[spriteIndex];
  17202. if (!spriteManager.isPickable) {
  17203. continue;
  17204. }
  17205. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17206. if (!result || !result.hit)
  17207. continue;
  17208. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17209. continue;
  17210. pickingInfo = result;
  17211. if (fastCheck) {
  17212. break;
  17213. }
  17214. }
  17215. }
  17216. return pickingInfo || new BABYLON.PickingInfo();
  17217. };
  17218. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17219. var _this = this;
  17220. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17221. /// <param name="x">X position on screen</param>
  17222. /// <param name="y">Y position on screen</param>
  17223. /// <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>
  17224. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17225. /// <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>
  17226. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17227. };
  17228. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17229. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17230. /// <param name="x">X position on screen</param>
  17231. /// <param name="y">Y position on screen</param>
  17232. /// <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>
  17233. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17234. /// <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>
  17235. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17236. };
  17237. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17238. var _this = this;
  17239. return this._internalPick(function (world) {
  17240. if (!_this._pickWithRayInverseMatrix) {
  17241. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17242. }
  17243. world.invertToRef(_this._pickWithRayInverseMatrix);
  17244. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17245. }, predicate, fastCheck);
  17246. };
  17247. Scene.prototype.setPointerOverMesh = function (mesh) {
  17248. if (this._pointerOverMesh === mesh) {
  17249. return;
  17250. }
  17251. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17252. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17253. }
  17254. this._pointerOverMesh = mesh;
  17255. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17256. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17257. }
  17258. };
  17259. Scene.prototype.getPointerOverMesh = function () {
  17260. return this._pointerOverMesh;
  17261. };
  17262. Scene.prototype.setPointerOverSprite = function (sprite) {
  17263. if (this._pointerOverSprite === sprite) {
  17264. return;
  17265. }
  17266. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17267. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17268. }
  17269. this._pointerOverSprite = sprite;
  17270. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17271. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17272. }
  17273. };
  17274. Scene.prototype.getPointerOverSprite = function () {
  17275. return this._pointerOverSprite;
  17276. };
  17277. // Physics
  17278. Scene.prototype.getPhysicsEngine = function () {
  17279. return this._physicsEngine;
  17280. };
  17281. /**
  17282. * Enables physics to the current scene
  17283. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17284. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17285. * @return {boolean} was the physics engine initialized
  17286. */
  17287. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17288. if (this._physicsEngine) {
  17289. return true;
  17290. }
  17291. try {
  17292. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17293. return true;
  17294. }
  17295. catch (e) {
  17296. BABYLON.Tools.Error(e.message);
  17297. return false;
  17298. }
  17299. };
  17300. Scene.prototype.disablePhysicsEngine = function () {
  17301. if (!this._physicsEngine) {
  17302. return;
  17303. }
  17304. this._physicsEngine.dispose();
  17305. this._physicsEngine = undefined;
  17306. };
  17307. Scene.prototype.isPhysicsEnabled = function () {
  17308. return this._physicsEngine !== undefined;
  17309. };
  17310. /**
  17311. *
  17312. * Sets the gravity of the physics engine (and NOT of the scene)
  17313. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17314. */
  17315. Scene.prototype.setGravity = function (gravity) {
  17316. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17317. if (!this._physicsEngine) {
  17318. return;
  17319. }
  17320. this._physicsEngine.setGravity(gravity);
  17321. };
  17322. /**
  17323. * Legacy support, using the new API
  17324. * @Deprecated
  17325. */
  17326. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17327. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17328. if (parts.parts) {
  17329. options = parts;
  17330. parts = parts.parts;
  17331. }
  17332. var mainMesh = parts[0].mesh;
  17333. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17334. for (var index = 1; index < parts.length; index++) {
  17335. var mesh = parts[index].mesh;
  17336. if (mesh.parent !== mainMesh) {
  17337. mesh.position = mesh.position.subtract(mainMesh.position);
  17338. mesh.parent = mainMesh;
  17339. }
  17340. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17341. }
  17342. mainMesh.physicsImpostor.forceUpdate();
  17343. };
  17344. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17345. var mesh = compound.parts[0].mesh;
  17346. mesh.physicsImpostor.dispose();
  17347. mesh.physicsImpostor = null;
  17348. };
  17349. // Misc.
  17350. Scene.prototype.createDefaultCameraOrLight = function () {
  17351. // Light
  17352. if (this.lights.length === 0) {
  17353. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17354. }
  17355. // Camera
  17356. if (!this.activeCamera) {
  17357. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17358. // Compute position
  17359. var worldExtends = this.getWorldExtends();
  17360. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17361. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17362. camera.setTarget(worldCenter);
  17363. this.activeCamera = camera;
  17364. }
  17365. };
  17366. // Tags
  17367. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17368. if (tagsQuery === undefined) {
  17369. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17370. return list;
  17371. }
  17372. var listByTags = [];
  17373. forEach = forEach || (function (item) { return; });
  17374. for (var i in list) {
  17375. var item = list[i];
  17376. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17377. listByTags.push(item);
  17378. forEach(item);
  17379. }
  17380. }
  17381. return listByTags;
  17382. };
  17383. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17384. return this._getByTags(this.meshes, tagsQuery, forEach);
  17385. };
  17386. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17387. return this._getByTags(this.cameras, tagsQuery, forEach);
  17388. };
  17389. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17390. return this._getByTags(this.lights, tagsQuery, forEach);
  17391. };
  17392. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17393. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17394. };
  17395. // Statics
  17396. Scene._FOGMODE_NONE = 0;
  17397. Scene._FOGMODE_EXP = 1;
  17398. Scene._FOGMODE_EXP2 = 2;
  17399. Scene._FOGMODE_LINEAR = 3;
  17400. Scene.MinDeltaTime = 1.0;
  17401. Scene.MaxDeltaTime = 1000.0;
  17402. return Scene;
  17403. }());
  17404. BABYLON.Scene = Scene;
  17405. })(BABYLON || (BABYLON = {}));
  17406. var BABYLON;
  17407. (function (BABYLON) {
  17408. var Buffer = (function () {
  17409. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17410. if (engine instanceof BABYLON.Mesh) {
  17411. this._engine = engine.getScene().getEngine();
  17412. }
  17413. else {
  17414. this._engine = engine;
  17415. }
  17416. this._updatable = updatable;
  17417. this._data = data;
  17418. this._strideSize = stride;
  17419. if (!postponeInternalCreation) {
  17420. this.create();
  17421. }
  17422. this._instanced = instanced;
  17423. }
  17424. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17425. // a lot of these parameters are ignored as they are overriden by the buffer
  17426. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17427. };
  17428. // Properties
  17429. Buffer.prototype.isUpdatable = function () {
  17430. return this._updatable;
  17431. };
  17432. Buffer.prototype.getData = function () {
  17433. return this._data;
  17434. };
  17435. Buffer.prototype.getBuffer = function () {
  17436. return this._buffer;
  17437. };
  17438. Buffer.prototype.getStrideSize = function () {
  17439. return this._strideSize;
  17440. };
  17441. Buffer.prototype.getIsInstanced = function () {
  17442. return this._instanced;
  17443. };
  17444. // Methods
  17445. Buffer.prototype.create = function (data) {
  17446. if (!data && this._buffer) {
  17447. return; // nothing to do
  17448. }
  17449. data = data || this._data;
  17450. if (!this._buffer) {
  17451. if (this._updatable) {
  17452. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17453. this._data = data;
  17454. }
  17455. else {
  17456. this._buffer = this._engine.createVertexBuffer(data);
  17457. }
  17458. }
  17459. else if (this._updatable) {
  17460. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17461. this._data = data;
  17462. }
  17463. };
  17464. Buffer.prototype.update = function (data) {
  17465. this.create(data);
  17466. };
  17467. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17468. if (!this._buffer) {
  17469. return;
  17470. }
  17471. if (this._updatable) {
  17472. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17473. this._data = null;
  17474. }
  17475. };
  17476. Buffer.prototype.dispose = function () {
  17477. if (!this._buffer) {
  17478. return;
  17479. }
  17480. if (this._engine._releaseBuffer(this._buffer)) {
  17481. this._buffer = null;
  17482. }
  17483. };
  17484. return Buffer;
  17485. }());
  17486. BABYLON.Buffer = Buffer;
  17487. })(BABYLON || (BABYLON = {}));
  17488. var BABYLON;
  17489. (function (BABYLON) {
  17490. var VertexBuffer = (function () {
  17491. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17492. if (!stride) {
  17493. // Deduce stride from kind
  17494. switch (kind) {
  17495. case VertexBuffer.PositionKind:
  17496. stride = 3;
  17497. break;
  17498. case VertexBuffer.NormalKind:
  17499. stride = 3;
  17500. break;
  17501. case VertexBuffer.UVKind:
  17502. case VertexBuffer.UV2Kind:
  17503. case VertexBuffer.UV3Kind:
  17504. case VertexBuffer.UV4Kind:
  17505. case VertexBuffer.UV5Kind:
  17506. case VertexBuffer.UV6Kind:
  17507. stride = 2;
  17508. break;
  17509. case VertexBuffer.ColorKind:
  17510. stride = 4;
  17511. break;
  17512. case VertexBuffer.MatricesIndicesKind:
  17513. case VertexBuffer.MatricesIndicesExtraKind:
  17514. stride = 4;
  17515. break;
  17516. case VertexBuffer.MatricesWeightsKind:
  17517. case VertexBuffer.MatricesWeightsExtraKind:
  17518. stride = 4;
  17519. break;
  17520. }
  17521. }
  17522. if (data instanceof BABYLON.Buffer) {
  17523. if (!stride) {
  17524. stride = data.getStrideSize();
  17525. }
  17526. this._buffer = data;
  17527. this._ownsBuffer = false;
  17528. }
  17529. else {
  17530. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17531. this._ownsBuffer = true;
  17532. }
  17533. this._stride = stride;
  17534. this._offset = offset ? offset : 0;
  17535. this._size = size ? size : stride;
  17536. this._kind = kind;
  17537. }
  17538. VertexBuffer.prototype.getKind = function () {
  17539. return this._kind;
  17540. };
  17541. // Properties
  17542. VertexBuffer.prototype.isUpdatable = function () {
  17543. return this._buffer.isUpdatable();
  17544. };
  17545. VertexBuffer.prototype.getData = function () {
  17546. return this._buffer.getData();
  17547. };
  17548. VertexBuffer.prototype.getBuffer = function () {
  17549. return this._buffer.getBuffer();
  17550. };
  17551. VertexBuffer.prototype.getStrideSize = function () {
  17552. return this._stride;
  17553. };
  17554. VertexBuffer.prototype.getOffset = function () {
  17555. return this._offset;
  17556. };
  17557. VertexBuffer.prototype.getSize = function () {
  17558. return this._size;
  17559. };
  17560. VertexBuffer.prototype.getIsInstanced = function () {
  17561. return this._buffer.getIsInstanced();
  17562. };
  17563. // Methods
  17564. VertexBuffer.prototype.create = function (data) {
  17565. return this._buffer.create(data);
  17566. };
  17567. VertexBuffer.prototype.update = function (data) {
  17568. return this._buffer.update(data);
  17569. };
  17570. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17571. return this._buffer.updateDirectly(data, offset);
  17572. };
  17573. VertexBuffer.prototype.dispose = function () {
  17574. if (this._ownsBuffer) {
  17575. this._buffer.dispose();
  17576. }
  17577. };
  17578. Object.defineProperty(VertexBuffer, "PositionKind", {
  17579. get: function () {
  17580. return VertexBuffer._PositionKind;
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. Object.defineProperty(VertexBuffer, "NormalKind", {
  17586. get: function () {
  17587. return VertexBuffer._NormalKind;
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(VertexBuffer, "UVKind", {
  17593. get: function () {
  17594. return VertexBuffer._UVKind;
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17600. get: function () {
  17601. return VertexBuffer._UV2Kind;
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17607. get: function () {
  17608. return VertexBuffer._UV3Kind;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17614. get: function () {
  17615. return VertexBuffer._UV4Kind;
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17621. get: function () {
  17622. return VertexBuffer._UV5Kind;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17628. get: function () {
  17629. return VertexBuffer._UV6Kind;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(VertexBuffer, "ColorKind", {
  17635. get: function () {
  17636. return VertexBuffer._ColorKind;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17642. get: function () {
  17643. return VertexBuffer._MatricesIndicesKind;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17649. get: function () {
  17650. return VertexBuffer._MatricesWeightsKind;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17656. get: function () {
  17657. return VertexBuffer._MatricesIndicesExtraKind;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17663. get: function () {
  17664. return VertexBuffer._MatricesWeightsExtraKind;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. // Enums
  17670. VertexBuffer._PositionKind = "position";
  17671. VertexBuffer._NormalKind = "normal";
  17672. VertexBuffer._UVKind = "uv";
  17673. VertexBuffer._UV2Kind = "uv2";
  17674. VertexBuffer._UV3Kind = "uv3";
  17675. VertexBuffer._UV4Kind = "uv4";
  17676. VertexBuffer._UV5Kind = "uv5";
  17677. VertexBuffer._UV6Kind = "uv6";
  17678. VertexBuffer._ColorKind = "color";
  17679. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17680. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17681. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17682. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17683. return VertexBuffer;
  17684. }());
  17685. BABYLON.VertexBuffer = VertexBuffer;
  17686. })(BABYLON || (BABYLON = {}));
  17687. var BABYLON;
  17688. (function (BABYLON) {
  17689. /**
  17690. * Creates an instance based on a source mesh.
  17691. */
  17692. var InstancedMesh = (function (_super) {
  17693. __extends(InstancedMesh, _super);
  17694. function InstancedMesh(name, source) {
  17695. _super.call(this, name, source.getScene());
  17696. source.instances.push(this);
  17697. this._sourceMesh = source;
  17698. this.position.copyFrom(source.position);
  17699. this.rotation.copyFrom(source.rotation);
  17700. this.scaling.copyFrom(source.scaling);
  17701. if (source.rotationQuaternion) {
  17702. this.rotationQuaternion = source.rotationQuaternion.clone();
  17703. }
  17704. this.infiniteDistance = source.infiniteDistance;
  17705. this.setPivotMatrix(source.getPivotMatrix());
  17706. this.refreshBoundingInfo();
  17707. this._syncSubMeshes();
  17708. }
  17709. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17710. // Methods
  17711. get: function () {
  17712. return this._sourceMesh.receiveShadows;
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. Object.defineProperty(InstancedMesh.prototype, "material", {
  17718. get: function () {
  17719. return this._sourceMesh.material;
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17725. get: function () {
  17726. return this._sourceMesh.visibility;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17732. get: function () {
  17733. return this._sourceMesh.skeleton;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17739. get: function () {
  17740. return this._sourceMesh.renderingGroupId;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. InstancedMesh.prototype.getTotalVertices = function () {
  17746. return this._sourceMesh.getTotalVertices();
  17747. };
  17748. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17749. get: function () {
  17750. return this._sourceMesh;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17756. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17757. };
  17758. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17759. return this._sourceMesh.isVerticesDataPresent(kind);
  17760. };
  17761. InstancedMesh.prototype.getIndices = function () {
  17762. return this._sourceMesh.getIndices();
  17763. };
  17764. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17765. get: function () {
  17766. return this._sourceMesh._positions;
  17767. },
  17768. enumerable: true,
  17769. configurable: true
  17770. });
  17771. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17772. var meshBB = this._sourceMesh.getBoundingInfo();
  17773. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17774. this._updateBoundingInfo();
  17775. };
  17776. InstancedMesh.prototype._preActivate = function () {
  17777. if (this._currentLOD) {
  17778. this._currentLOD._preActivate();
  17779. }
  17780. };
  17781. InstancedMesh.prototype._activate = function (renderId) {
  17782. if (this._currentLOD) {
  17783. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17784. }
  17785. };
  17786. InstancedMesh.prototype.getLOD = function (camera) {
  17787. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17788. if (this._currentLOD === this.sourceMesh) {
  17789. return this;
  17790. }
  17791. return this._currentLOD;
  17792. };
  17793. InstancedMesh.prototype._syncSubMeshes = function () {
  17794. this.releaseSubMeshes();
  17795. if (this._sourceMesh.subMeshes) {
  17796. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17797. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17798. }
  17799. }
  17800. };
  17801. InstancedMesh.prototype._generatePointsArray = function () {
  17802. return this._sourceMesh._generatePointsArray();
  17803. };
  17804. // Clone
  17805. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17806. var result = this._sourceMesh.createInstance(name);
  17807. // Deep copy
  17808. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17809. // Bounding info
  17810. this.refreshBoundingInfo();
  17811. // Parent
  17812. if (newParent) {
  17813. result.parent = newParent;
  17814. }
  17815. if (!doNotCloneChildren) {
  17816. // Children
  17817. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17818. var mesh = this.getScene().meshes[index];
  17819. if (mesh.parent === this) {
  17820. mesh.clone(mesh.name, result);
  17821. }
  17822. }
  17823. }
  17824. result.computeWorldMatrix(true);
  17825. return result;
  17826. };
  17827. // Dispoe
  17828. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17829. // Remove from mesh
  17830. var index = this._sourceMesh.instances.indexOf(this);
  17831. this._sourceMesh.instances.splice(index, 1);
  17832. _super.prototype.dispose.call(this, doNotRecurse);
  17833. };
  17834. return InstancedMesh;
  17835. }(BABYLON.AbstractMesh));
  17836. BABYLON.InstancedMesh = InstancedMesh;
  17837. })(BABYLON || (BABYLON = {}));
  17838. var BABYLON;
  17839. (function (BABYLON) {
  17840. var _InstancesBatch = (function () {
  17841. function _InstancesBatch() {
  17842. this.mustReturn = false;
  17843. this.visibleInstances = new Array();
  17844. this.renderSelf = new Array();
  17845. }
  17846. return _InstancesBatch;
  17847. }());
  17848. BABYLON._InstancesBatch = _InstancesBatch;
  17849. var Mesh = (function (_super) {
  17850. __extends(Mesh, _super);
  17851. /**
  17852. * @constructor
  17853. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17854. * @param {Scene} scene The scene to add this mesh to.
  17855. * @param {Node} parent The parent of this mesh, if it has one
  17856. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17857. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17858. * When false, achieved by calling a clone(), also passing False.
  17859. * This will make creation of children, recursive.
  17860. */
  17861. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17862. if (parent === void 0) { parent = null; }
  17863. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17864. _super.call(this, name, scene);
  17865. // Events
  17866. /**
  17867. * An event triggered before rendering the mesh
  17868. * @type {BABYLON.Observable}
  17869. */
  17870. this.onBeforeRenderObservable = new BABYLON.Observable();
  17871. /**
  17872. * An event triggered after rendering the mesh
  17873. * @type {BABYLON.Observable}
  17874. */
  17875. this.onAfterRenderObservable = new BABYLON.Observable();
  17876. /**
  17877. * An event triggered before drawing the mesh
  17878. * @type {BABYLON.Observable}
  17879. */
  17880. this.onBeforeDrawObservable = new BABYLON.Observable();
  17881. // Members
  17882. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17883. this.instances = new Array();
  17884. this._LODLevels = new Array();
  17885. this._visibleInstances = {};
  17886. this._renderIdForInstances = new Array();
  17887. this._batchCache = new _InstancesBatch();
  17888. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17889. this._sideOrientation = Mesh._DEFAULTSIDE;
  17890. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17891. if (source) {
  17892. // Geometry
  17893. if (source._geometry) {
  17894. source._geometry.applyToMesh(this);
  17895. }
  17896. // Deep copy
  17897. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17898. // Pivot
  17899. this.setPivotMatrix(source.getPivotMatrix());
  17900. this.id = name + "." + source.id;
  17901. // Material
  17902. this.material = source.material;
  17903. var index;
  17904. if (!doNotCloneChildren) {
  17905. // Children
  17906. for (index = 0; index < scene.meshes.length; index++) {
  17907. var mesh = scene.meshes[index];
  17908. if (mesh.parent === source) {
  17909. // doNotCloneChildren is always going to be False
  17910. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17911. }
  17912. }
  17913. }
  17914. // Physics clone
  17915. var physicsEngine = this.getScene().getPhysicsEngine();
  17916. if (clonePhysicsImpostor && physicsEngine) {
  17917. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17918. if (impostor) {
  17919. this.physicsImpostor = impostor.clone(this);
  17920. }
  17921. }
  17922. // Particles
  17923. for (index = 0; index < scene.particleSystems.length; index++) {
  17924. var system = scene.particleSystems[index];
  17925. if (system.emitter === source) {
  17926. system.clone(system.name, this);
  17927. }
  17928. }
  17929. this.computeWorldMatrix(true);
  17930. }
  17931. // Parent
  17932. if (parent !== null) {
  17933. this.parent = parent;
  17934. }
  17935. }
  17936. Object.defineProperty(Mesh, "FRONTSIDE", {
  17937. /**
  17938. * Mesh side orientation : usually the external or front surface
  17939. */
  17940. get: function () {
  17941. return Mesh._FRONTSIDE;
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. Object.defineProperty(Mesh, "BACKSIDE", {
  17947. /**
  17948. * Mesh side orientation : usually the internal or back surface
  17949. */
  17950. get: function () {
  17951. return Mesh._BACKSIDE;
  17952. },
  17953. enumerable: true,
  17954. configurable: true
  17955. });
  17956. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17957. /**
  17958. * Mesh side orientation : both internal and external or front and back surfaces
  17959. */
  17960. get: function () {
  17961. return Mesh._DOUBLESIDE;
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17967. /**
  17968. * Mesh side orientation : by default, `FRONTSIDE`
  17969. */
  17970. get: function () {
  17971. return Mesh._DEFAULTSIDE;
  17972. },
  17973. enumerable: true,
  17974. configurable: true
  17975. });
  17976. Object.defineProperty(Mesh, "NO_CAP", {
  17977. /**
  17978. * Mesh cap setting : no cap
  17979. */
  17980. get: function () {
  17981. return Mesh._NO_CAP;
  17982. },
  17983. enumerable: true,
  17984. configurable: true
  17985. });
  17986. Object.defineProperty(Mesh, "CAP_START", {
  17987. /**
  17988. * Mesh cap setting : one cap at the beginning of the mesh
  17989. */
  17990. get: function () {
  17991. return Mesh._CAP_START;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Mesh, "CAP_END", {
  17997. /**
  17998. * Mesh cap setting : one cap at the end of the mesh
  17999. */
  18000. get: function () {
  18001. return Mesh._CAP_END;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. Object.defineProperty(Mesh, "CAP_ALL", {
  18007. /**
  18008. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18009. */
  18010. get: function () {
  18011. return Mesh._CAP_ALL;
  18012. },
  18013. enumerable: true,
  18014. configurable: true
  18015. });
  18016. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18017. set: function (callback) {
  18018. if (this._onBeforeDrawObserver) {
  18019. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18020. }
  18021. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. // Methods
  18027. /**
  18028. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18029. */
  18030. Mesh.prototype.toString = function (fullDetails) {
  18031. var ret = _super.prototype.toString.call(this, fullDetails);
  18032. ret += ", n vertices: " + this.getTotalVertices();
  18033. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18034. if (this.animations) {
  18035. for (var i = 0; i < this.animations.length; i++) {
  18036. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18037. }
  18038. }
  18039. if (fullDetails) {
  18040. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18041. }
  18042. return ret;
  18043. };
  18044. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18045. get: function () {
  18046. return this._LODLevels.length > 0;
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Mesh.prototype._sortLODLevels = function () {
  18052. this._LODLevels.sort(function (a, b) {
  18053. if (a.distance < b.distance) {
  18054. return 1;
  18055. }
  18056. if (a.distance > b.distance) {
  18057. return -1;
  18058. }
  18059. return 0;
  18060. });
  18061. };
  18062. /**
  18063. * Add a mesh as LOD level triggered at the given distance.
  18064. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18065. * @param {number} distance The distance from the center of the object to show this level
  18066. * @param {Mesh} mesh The mesh to be added as LOD level
  18067. * @return {Mesh} This mesh (for chaining)
  18068. */
  18069. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18070. if (mesh && mesh._masterMesh) {
  18071. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18072. return this;
  18073. }
  18074. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18075. this._LODLevels.push(level);
  18076. if (mesh) {
  18077. mesh._masterMesh = this;
  18078. }
  18079. this._sortLODLevels();
  18080. return this;
  18081. };
  18082. /**
  18083. * Returns the LOD level mesh at the passed distance or null if not found.
  18084. * It is related to the method `addLODLevel(distance, mesh)`.
  18085. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18086. */
  18087. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18088. for (var index = 0; index < this._LODLevels.length; index++) {
  18089. var level = this._LODLevels[index];
  18090. if (level.distance === distance) {
  18091. return level.mesh;
  18092. }
  18093. }
  18094. return null;
  18095. };
  18096. /**
  18097. * Remove a mesh from the LOD array
  18098. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18099. * @param {Mesh} mesh The mesh to be removed.
  18100. * @return {Mesh} This mesh (for chaining)
  18101. */
  18102. Mesh.prototype.removeLODLevel = function (mesh) {
  18103. for (var index = 0; index < this._LODLevels.length; index++) {
  18104. if (this._LODLevels[index].mesh === mesh) {
  18105. this._LODLevels.splice(index, 1);
  18106. if (mesh) {
  18107. mesh._masterMesh = null;
  18108. }
  18109. }
  18110. }
  18111. this._sortLODLevels();
  18112. return this;
  18113. };
  18114. /**
  18115. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18116. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18117. */
  18118. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18119. if (!this._LODLevels || this._LODLevels.length === 0) {
  18120. return this;
  18121. }
  18122. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18123. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18124. if (this.onLODLevelSelection) {
  18125. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18126. }
  18127. return this;
  18128. }
  18129. for (var index = 0; index < this._LODLevels.length; index++) {
  18130. var level = this._LODLevels[index];
  18131. if (level.distance < distanceToCamera) {
  18132. if (level.mesh) {
  18133. level.mesh._preActivate();
  18134. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18135. }
  18136. if (this.onLODLevelSelection) {
  18137. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18138. }
  18139. return level.mesh;
  18140. }
  18141. }
  18142. if (this.onLODLevelSelection) {
  18143. this.onLODLevelSelection(distanceToCamera, this, this);
  18144. }
  18145. return this;
  18146. };
  18147. Object.defineProperty(Mesh.prototype, "geometry", {
  18148. /**
  18149. * Returns the mesh internal Geometry object.
  18150. */
  18151. get: function () {
  18152. return this._geometry;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. /**
  18158. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18159. */
  18160. Mesh.prototype.getTotalVertices = function () {
  18161. if (!this._geometry) {
  18162. return 0;
  18163. }
  18164. return this._geometry.getTotalVertices();
  18165. };
  18166. /**
  18167. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18168. * 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.
  18169. * Returns null if the mesh has no geometry or no vertex buffer.
  18170. * Possible `kind` values :
  18171. * - BABYLON.VertexBuffer.PositionKind
  18172. * - BABYLON.VertexBuffer.UVKind
  18173. * - BABYLON.VertexBuffer.UV2Kind
  18174. * - BABYLON.VertexBuffer.UV3Kind
  18175. * - BABYLON.VertexBuffer.UV4Kind
  18176. * - BABYLON.VertexBuffer.UV5Kind
  18177. * - BABYLON.VertexBuffer.UV6Kind
  18178. * - BABYLON.VertexBuffer.ColorKind
  18179. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18180. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18181. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18182. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18183. */
  18184. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18185. if (!this._geometry) {
  18186. return null;
  18187. }
  18188. return this._geometry.getVerticesData(kind, copyWhenShared);
  18189. };
  18190. /**
  18191. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18192. * Returns `undefined` if the mesh has no geometry.
  18193. * Possible `kind` values :
  18194. * - BABYLON.VertexBuffer.PositionKind
  18195. * - BABYLON.VertexBuffer.UVKind
  18196. * - BABYLON.VertexBuffer.UV2Kind
  18197. * - BABYLON.VertexBuffer.UV3Kind
  18198. * - BABYLON.VertexBuffer.UV4Kind
  18199. * - BABYLON.VertexBuffer.UV5Kind
  18200. * - BABYLON.VertexBuffer.UV6Kind
  18201. * - BABYLON.VertexBuffer.ColorKind
  18202. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18203. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18204. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18205. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18206. */
  18207. Mesh.prototype.getVertexBuffer = function (kind) {
  18208. if (!this._geometry) {
  18209. return undefined;
  18210. }
  18211. return this._geometry.getVertexBuffer(kind);
  18212. };
  18213. /**
  18214. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18215. * Possible `kind` values :
  18216. * - BABYLON.VertexBuffer.PositionKind
  18217. * - BABYLON.VertexBuffer.UVKind
  18218. * - BABYLON.VertexBuffer.UV2Kind
  18219. * - BABYLON.VertexBuffer.UV3Kind
  18220. * - BABYLON.VertexBuffer.UV4Kind
  18221. * - BABYLON.VertexBuffer.UV5Kind
  18222. * - BABYLON.VertexBuffer.UV6Kind
  18223. * - BABYLON.VertexBuffer.ColorKind
  18224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18228. */
  18229. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18230. if (!this._geometry) {
  18231. if (this._delayInfo) {
  18232. return this._delayInfo.indexOf(kind) !== -1;
  18233. }
  18234. return false;
  18235. }
  18236. return this._geometry.isVerticesDataPresent(kind);
  18237. };
  18238. /**
  18239. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18240. * Possible `kind` values :
  18241. * - BABYLON.VertexBuffer.PositionKind
  18242. * - BABYLON.VertexBuffer.UVKind
  18243. * - BABYLON.VertexBuffer.UV2Kind
  18244. * - BABYLON.VertexBuffer.UV3Kind
  18245. * - BABYLON.VertexBuffer.UV4Kind
  18246. * - BABYLON.VertexBuffer.UV5Kind
  18247. * - BABYLON.VertexBuffer.UV6Kind
  18248. * - BABYLON.VertexBuffer.ColorKind
  18249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18253. */
  18254. Mesh.prototype.getVerticesDataKinds = function () {
  18255. if (!this._geometry) {
  18256. var result = [];
  18257. if (this._delayInfo) {
  18258. for (var kind in this._delayInfo) {
  18259. result.push(kind);
  18260. }
  18261. }
  18262. return result;
  18263. }
  18264. return this._geometry.getVerticesDataKinds();
  18265. };
  18266. /**
  18267. * Returns a positive integer : the total number of indices in this mesh geometry.
  18268. * Returns zero if the mesh has no geometry.
  18269. */
  18270. Mesh.prototype.getTotalIndices = function () {
  18271. if (!this._geometry) {
  18272. return 0;
  18273. }
  18274. return this._geometry.getTotalIndices();
  18275. };
  18276. /**
  18277. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18278. * 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.
  18279. * Returns an empty array if the mesh has no geometry.
  18280. */
  18281. Mesh.prototype.getIndices = function (copyWhenShared) {
  18282. if (!this._geometry) {
  18283. return [];
  18284. }
  18285. return this._geometry.getIndices(copyWhenShared);
  18286. };
  18287. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18288. get: function () {
  18289. return this._masterMesh !== null && this._masterMesh !== undefined;
  18290. },
  18291. enumerable: true,
  18292. configurable: true
  18293. });
  18294. /**
  18295. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18296. */
  18297. Mesh.prototype.isReady = function () {
  18298. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18299. return false;
  18300. }
  18301. return _super.prototype.isReady.call(this);
  18302. };
  18303. /**
  18304. * Boolean : true if the mesh has been disposed.
  18305. */
  18306. Mesh.prototype.isDisposed = function () {
  18307. return this._isDisposed;
  18308. };
  18309. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18310. get: function () {
  18311. return this._sideOrientation;
  18312. },
  18313. /**
  18314. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18315. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18316. */
  18317. set: function (sideO) {
  18318. this._sideOrientation = sideO;
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18324. /**
  18325. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18326. * This property is pertinent only for updatable parametric shapes.
  18327. */
  18328. get: function () {
  18329. return this._areNormalsFrozen;
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. /**
  18335. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18336. * It has no effect at all on other shapes.
  18337. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18338. */
  18339. Mesh.prototype.freezeNormals = function () {
  18340. this._areNormalsFrozen = true;
  18341. };
  18342. /**
  18343. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18344. * It has no effect at all on other shapes.
  18345. * It reactivates the mesh normals computation if it was previously frozen.
  18346. */
  18347. Mesh.prototype.unfreezeNormals = function () {
  18348. this._areNormalsFrozen = false;
  18349. };
  18350. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18351. /**
  18352. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18353. */
  18354. set: function (count) {
  18355. this._overridenInstanceCount = count;
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. // Methods
  18361. Mesh.prototype._preActivate = function () {
  18362. var sceneRenderId = this.getScene().getRenderId();
  18363. if (this._preActivateId === sceneRenderId) {
  18364. return;
  18365. }
  18366. this._preActivateId = sceneRenderId;
  18367. this._visibleInstances = null;
  18368. };
  18369. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18370. if (this._visibleInstances) {
  18371. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18372. }
  18373. };
  18374. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18375. if (!this._visibleInstances) {
  18376. this._visibleInstances = {};
  18377. this._visibleInstances.defaultRenderId = renderId;
  18378. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18379. }
  18380. if (!this._visibleInstances[renderId]) {
  18381. this._visibleInstances[renderId] = new Array();
  18382. }
  18383. this._visibleInstances[renderId].push(instance);
  18384. };
  18385. /**
  18386. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18387. * This means the mesh underlying bounding box and sphere are recomputed.
  18388. */
  18389. Mesh.prototype.refreshBoundingInfo = function () {
  18390. if (this._boundingInfo.isLocked) {
  18391. return;
  18392. }
  18393. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18394. if (data) {
  18395. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18396. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18397. }
  18398. if (this.subMeshes) {
  18399. for (var index = 0; index < this.subMeshes.length; index++) {
  18400. this.subMeshes[index].refreshBoundingInfo();
  18401. }
  18402. }
  18403. this._updateBoundingInfo();
  18404. };
  18405. Mesh.prototype._createGlobalSubMesh = function () {
  18406. var totalVertices = this.getTotalVertices();
  18407. if (!totalVertices || !this.getIndices()) {
  18408. return null;
  18409. }
  18410. this.releaseSubMeshes();
  18411. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18412. };
  18413. Mesh.prototype.subdivide = function (count) {
  18414. if (count < 1) {
  18415. return;
  18416. }
  18417. var totalIndices = this.getTotalIndices();
  18418. var subdivisionSize = (totalIndices / count) | 0;
  18419. var offset = 0;
  18420. // Ensure that subdivisionSize is a multiple of 3
  18421. while (subdivisionSize % 3 !== 0) {
  18422. subdivisionSize++;
  18423. }
  18424. this.releaseSubMeshes();
  18425. for (var index = 0; index < count; index++) {
  18426. if (offset >= totalIndices) {
  18427. break;
  18428. }
  18429. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18430. offset += subdivisionSize;
  18431. }
  18432. this.synchronizeInstances();
  18433. };
  18434. /**
  18435. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18436. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18437. * The `data` are either a numeric array either a Float32Array.
  18438. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18439. * 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).
  18440. * Note that a new underlying VertexBuffer object is created each call.
  18441. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18442. *
  18443. * Possible `kind` values :
  18444. * - BABYLON.VertexBuffer.PositionKind
  18445. * - BABYLON.VertexBuffer.UVKind
  18446. * - BABYLON.VertexBuffer.UV2Kind
  18447. * - BABYLON.VertexBuffer.UV3Kind
  18448. * - BABYLON.VertexBuffer.UV4Kind
  18449. * - BABYLON.VertexBuffer.UV5Kind
  18450. * - BABYLON.VertexBuffer.UV6Kind
  18451. * - BABYLON.VertexBuffer.ColorKind
  18452. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18453. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18454. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18455. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18456. */
  18457. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18458. if (!this._geometry) {
  18459. var vertexData = new BABYLON.VertexData();
  18460. vertexData.set(data, kind);
  18461. var scene = this.getScene();
  18462. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18463. }
  18464. else {
  18465. this._geometry.setVerticesData(kind, data, updatable, stride);
  18466. }
  18467. };
  18468. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18469. if (!this._geometry) {
  18470. var scene = this.getScene();
  18471. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18472. }
  18473. this._geometry.setVerticesBuffer(buffer);
  18474. };
  18475. /**
  18476. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18477. * If the mesh has no geometry, it is simply returned as it is.
  18478. * The `data` are either a numeric array either a Float32Array.
  18479. * No new underlying VertexBuffer object is created.
  18480. * 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.
  18481. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18482. *
  18483. * Possible `kind` values :
  18484. * - BABYLON.VertexBuffer.PositionKind
  18485. * - BABYLON.VertexBuffer.UVKind
  18486. * - BABYLON.VertexBuffer.UV2Kind
  18487. * - BABYLON.VertexBuffer.UV3Kind
  18488. * - BABYLON.VertexBuffer.UV4Kind
  18489. * - BABYLON.VertexBuffer.UV5Kind
  18490. * - BABYLON.VertexBuffer.UV6Kind
  18491. * - BABYLON.VertexBuffer.ColorKind
  18492. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18493. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18494. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18495. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18496. */
  18497. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18498. if (!this._geometry) {
  18499. return;
  18500. }
  18501. if (!makeItUnique) {
  18502. this._geometry.updateVerticesData(kind, data, updateExtends);
  18503. }
  18504. else {
  18505. this.makeGeometryUnique();
  18506. this.updateVerticesData(kind, data, updateExtends, false);
  18507. }
  18508. };
  18509. /**
  18510. * Deprecated since BabylonJS v2.3
  18511. */
  18512. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18513. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18514. if (!this._geometry) {
  18515. return;
  18516. }
  18517. if (!makeItUnique) {
  18518. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18519. }
  18520. else {
  18521. this.makeGeometryUnique();
  18522. this.updateVerticesDataDirectly(kind, data, offset, false);
  18523. }
  18524. };
  18525. /**
  18526. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18527. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18528. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18529. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18530. */
  18531. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18532. if (computeNormals === void 0) { computeNormals = true; }
  18533. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18534. positionFunction(positions);
  18535. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18536. if (computeNormals) {
  18537. var indices = this.getIndices();
  18538. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18539. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18540. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18541. }
  18542. };
  18543. Mesh.prototype.makeGeometryUnique = function () {
  18544. if (!this._geometry) {
  18545. return;
  18546. }
  18547. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18548. geometry.applyToMesh(this);
  18549. };
  18550. /**
  18551. * Sets the mesh indices.
  18552. * Expects an array populated with integers or a Int32Array.
  18553. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18554. * This method creates a new index buffer each call.
  18555. */
  18556. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18557. if (!this._geometry) {
  18558. var vertexData = new BABYLON.VertexData();
  18559. vertexData.indices = indices;
  18560. var scene = this.getScene();
  18561. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18562. }
  18563. else {
  18564. this._geometry.setIndices(indices, totalVertices);
  18565. }
  18566. };
  18567. /**
  18568. * Invert the geometry to move from a right handed system to a left handed one.
  18569. */
  18570. Mesh.prototype.toLeftHanded = function () {
  18571. if (!this._geometry) {
  18572. return;
  18573. }
  18574. this._geometry.toLeftHanded();
  18575. };
  18576. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18577. var engine = this.getScene().getEngine();
  18578. // Wireframe
  18579. var indexToBind;
  18580. if (this._unIndexed) {
  18581. indexToBind = null;
  18582. }
  18583. else {
  18584. switch (fillMode) {
  18585. case BABYLON.Material.PointFillMode:
  18586. indexToBind = null;
  18587. break;
  18588. case BABYLON.Material.WireFrameFillMode:
  18589. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18590. break;
  18591. default:
  18592. case BABYLON.Material.TriangleFillMode:
  18593. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18594. break;
  18595. }
  18596. }
  18597. // VBOs
  18598. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18599. };
  18600. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18601. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18602. return;
  18603. }
  18604. this.onBeforeDrawObservable.notifyObservers(this);
  18605. var engine = this.getScene().getEngine();
  18606. // Draw order
  18607. switch (fillMode) {
  18608. case BABYLON.Material.PointFillMode:
  18609. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18610. break;
  18611. case BABYLON.Material.WireFrameFillMode:
  18612. if (this._unIndexed) {
  18613. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18614. }
  18615. else {
  18616. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18617. }
  18618. break;
  18619. default:
  18620. if (this._unIndexed) {
  18621. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18622. }
  18623. else {
  18624. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18625. }
  18626. }
  18627. };
  18628. /**
  18629. * Registers for this mesh a javascript function called just before the rendering process.
  18630. * This function is passed the current mesh and doesn't return anything.
  18631. */
  18632. Mesh.prototype.registerBeforeRender = function (func) {
  18633. this.onBeforeRenderObservable.add(func);
  18634. };
  18635. /**
  18636. * Disposes a previously registered javascript function called before the rendering.
  18637. * This function is passed the current mesh and doesn't return anything.
  18638. */
  18639. Mesh.prototype.unregisterBeforeRender = function (func) {
  18640. this.onBeforeRenderObservable.removeCallback(func);
  18641. };
  18642. /**
  18643. * Registers for this mesh a javascript function called just after the rendering is complete.
  18644. * This function is passed the current mesh and doesn't return anything.
  18645. */
  18646. Mesh.prototype.registerAfterRender = function (func) {
  18647. this.onAfterRenderObservable.add(func);
  18648. };
  18649. /**
  18650. * Disposes a previously registered javascript function called after the rendering.
  18651. * This function is passed the current mesh and doesn't return anything.
  18652. */
  18653. Mesh.prototype.unregisterAfterRender = function (func) {
  18654. this.onAfterRenderObservable.removeCallback(func);
  18655. };
  18656. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18657. var scene = this.getScene();
  18658. this._batchCache.mustReturn = false;
  18659. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18660. this._batchCache.visibleInstances[subMeshId] = null;
  18661. if (this._visibleInstances) {
  18662. var currentRenderId = scene.getRenderId();
  18663. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18664. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18665. var selfRenderId = this._renderId;
  18666. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18667. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18668. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18669. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18670. }
  18671. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18672. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18673. this._batchCache.mustReturn = true;
  18674. return this._batchCache;
  18675. }
  18676. if (currentRenderId !== selfRenderId) {
  18677. this._batchCache.renderSelf[subMeshId] = false;
  18678. }
  18679. }
  18680. this._renderIdForInstances[subMeshId] = currentRenderId;
  18681. }
  18682. return this._batchCache;
  18683. };
  18684. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18685. var visibleInstances = batch.visibleInstances[subMesh._id];
  18686. var matricesCount = visibleInstances.length + 1;
  18687. var bufferSize = matricesCount * 16 * 4;
  18688. var currentInstancesBufferSize = this._instancesBufferSize;
  18689. var instancesBuffer = this._instancesBuffer;
  18690. while (this._instancesBufferSize < bufferSize) {
  18691. this._instancesBufferSize *= 2;
  18692. }
  18693. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18694. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18695. }
  18696. var offset = 0;
  18697. var instancesCount = 0;
  18698. var world = this.getWorldMatrix();
  18699. if (batch.renderSelf[subMesh._id]) {
  18700. world.copyToArray(this._instancesData, offset);
  18701. offset += 16;
  18702. instancesCount++;
  18703. }
  18704. if (visibleInstances) {
  18705. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18706. var instance = visibleInstances[instanceIndex];
  18707. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18708. offset += 16;
  18709. instancesCount++;
  18710. }
  18711. }
  18712. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18713. if (instancesBuffer) {
  18714. instancesBuffer.dispose();
  18715. }
  18716. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18717. this._instancesBuffer = instancesBuffer;
  18718. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18719. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18720. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18721. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18722. }
  18723. else {
  18724. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18725. }
  18726. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18727. this._draw(subMesh, fillMode, instancesCount);
  18728. engine.unbindInstanceAttributes();
  18729. };
  18730. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18731. var scene = this.getScene();
  18732. var engine = scene.getEngine();
  18733. if (hardwareInstancedRendering) {
  18734. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18735. }
  18736. else {
  18737. if (batch.renderSelf[subMesh._id]) {
  18738. // Draw
  18739. if (onBeforeDraw) {
  18740. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18741. }
  18742. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18743. }
  18744. if (batch.visibleInstances[subMesh._id]) {
  18745. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18746. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18747. // World
  18748. var world = instance.getWorldMatrix();
  18749. if (onBeforeDraw) {
  18750. onBeforeDraw(true, world, effectiveMaterial);
  18751. }
  18752. // Draw
  18753. this._draw(subMesh, fillMode);
  18754. }
  18755. }
  18756. }
  18757. };
  18758. /**
  18759. * Triggers the draw call for the mesh.
  18760. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18761. */
  18762. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18763. var scene = this.getScene();
  18764. // Managing instances
  18765. var batch = this._getInstancesRenderList(subMesh._id);
  18766. if (batch.mustReturn) {
  18767. return;
  18768. }
  18769. // Checking geometry state
  18770. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18771. return;
  18772. }
  18773. var callbackIndex;
  18774. this.onBeforeRenderObservable.notifyObservers(this);
  18775. var engine = scene.getEngine();
  18776. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18777. // Material
  18778. var effectiveMaterial = subMesh.getMaterial();
  18779. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18780. return;
  18781. }
  18782. // Outline - step 1
  18783. var savedDepthWrite = engine.getDepthWrite();
  18784. if (this.renderOutline) {
  18785. engine.setDepthWrite(false);
  18786. scene.getOutlineRenderer().render(subMesh, batch);
  18787. engine.setDepthWrite(savedDepthWrite);
  18788. }
  18789. effectiveMaterial._preBind();
  18790. var effect = effectiveMaterial.getEffect();
  18791. // Bind
  18792. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18793. this._bind(subMesh, effect, fillMode);
  18794. var world = this.getWorldMatrix();
  18795. effectiveMaterial.bind(world, this);
  18796. // Alpha mode
  18797. if (enableAlphaMode) {
  18798. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18799. }
  18800. // Draw
  18801. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18802. // Unbind
  18803. effectiveMaterial.unbind();
  18804. // Outline - step 2
  18805. if (this.renderOutline && savedDepthWrite) {
  18806. engine.setDepthWrite(true);
  18807. engine.setColorWrite(false);
  18808. scene.getOutlineRenderer().render(subMesh, batch);
  18809. engine.setColorWrite(true);
  18810. }
  18811. // Overlay
  18812. if (this.renderOverlay) {
  18813. var currentMode = engine.getAlphaMode();
  18814. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18815. scene.getOutlineRenderer().render(subMesh, batch, true);
  18816. engine.setAlphaMode(currentMode);
  18817. }
  18818. this.onAfterRenderObservable.notifyObservers(this);
  18819. };
  18820. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18821. if (isInstance) {
  18822. effectiveMaterial.bindOnlyWorldMatrix(world);
  18823. }
  18824. };
  18825. /**
  18826. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18827. */
  18828. Mesh.prototype.getEmittedParticleSystems = function () {
  18829. var results = new Array();
  18830. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18831. var particleSystem = this.getScene().particleSystems[index];
  18832. if (particleSystem.emitter === this) {
  18833. results.push(particleSystem);
  18834. }
  18835. }
  18836. return results;
  18837. };
  18838. /**
  18839. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18840. */
  18841. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18842. var results = new Array();
  18843. var descendants = this.getDescendants();
  18844. descendants.push(this);
  18845. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18846. var particleSystem = this.getScene().particleSystems[index];
  18847. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18848. results.push(particleSystem);
  18849. }
  18850. }
  18851. return results;
  18852. };
  18853. Mesh.prototype._checkDelayState = function () {
  18854. var scene = this.getScene();
  18855. if (this._geometry) {
  18856. this._geometry.load(scene);
  18857. }
  18858. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18860. this._queueLoad(this, scene);
  18861. }
  18862. };
  18863. Mesh.prototype._queueLoad = function (mesh, scene) {
  18864. var _this = this;
  18865. scene._addPendingData(mesh);
  18866. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18867. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18868. if (data instanceof ArrayBuffer) {
  18869. _this._delayLoadingFunction(data, _this);
  18870. }
  18871. else {
  18872. _this._delayLoadingFunction(JSON.parse(data), _this);
  18873. }
  18874. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18875. scene._removePendingData(_this);
  18876. }, function () { }, scene.database, getBinaryData);
  18877. };
  18878. /**
  18879. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18880. */
  18881. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18882. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18883. return false;
  18884. }
  18885. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18886. return false;
  18887. }
  18888. this._checkDelayState();
  18889. return true;
  18890. };
  18891. /**
  18892. * Sets the mesh material by the material or multiMaterial `id` property.
  18893. * The material `id` is a string identifying the material or the multiMaterial.
  18894. * This method returns nothing.
  18895. */
  18896. Mesh.prototype.setMaterialByID = function (id) {
  18897. var materials = this.getScene().materials;
  18898. var index;
  18899. for (index = 0; index < materials.length; index++) {
  18900. if (materials[index].id === id) {
  18901. this.material = materials[index];
  18902. return;
  18903. }
  18904. }
  18905. // Multi
  18906. var multiMaterials = this.getScene().multiMaterials;
  18907. for (index = 0; index < multiMaterials.length; index++) {
  18908. if (multiMaterials[index].id === id) {
  18909. this.material = multiMaterials[index];
  18910. return;
  18911. }
  18912. }
  18913. };
  18914. /**
  18915. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18916. */
  18917. Mesh.prototype.getAnimatables = function () {
  18918. var results = [];
  18919. if (this.material) {
  18920. results.push(this.material);
  18921. }
  18922. if (this.skeleton) {
  18923. results.push(this.skeleton);
  18924. }
  18925. return results;
  18926. };
  18927. /**
  18928. * Modifies the mesh geometry according to the passed transformation matrix.
  18929. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18930. * The mesh normals are modified accordingly the same transformation.
  18931. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18932. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18933. */
  18934. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18935. // Position
  18936. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18937. return;
  18938. }
  18939. var submeshes = this.subMeshes.splice(0);
  18940. this._resetPointsArrayCache();
  18941. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18942. var temp = [];
  18943. var index;
  18944. for (index = 0; index < data.length; index += 3) {
  18945. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18946. }
  18947. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18948. // Normals
  18949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18950. return;
  18951. }
  18952. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18953. temp = [];
  18954. for (index = 0; index < data.length; index += 3) {
  18955. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18956. }
  18957. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18958. // flip faces?
  18959. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18960. this.flipFaces();
  18961. }
  18962. // Restore submeshes
  18963. this.releaseSubMeshes();
  18964. this.subMeshes = submeshes;
  18965. };
  18966. /**
  18967. * Modifies the mesh geometry according to its own current World Matrix.
  18968. * The mesh World Matrix is then reset.
  18969. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18970. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18971. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18972. */
  18973. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18974. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18975. this.scaling.copyFromFloats(1, 1, 1);
  18976. this.position.copyFromFloats(0, 0, 0);
  18977. this.rotation.copyFromFloats(0, 0, 0);
  18978. //only if quaternion is already set
  18979. if (this.rotationQuaternion) {
  18980. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18981. }
  18982. this._worldMatrix = BABYLON.Matrix.Identity();
  18983. };
  18984. // Cache
  18985. Mesh.prototype._resetPointsArrayCache = function () {
  18986. this._positions = null;
  18987. };
  18988. Mesh.prototype._generatePointsArray = function () {
  18989. if (this._positions)
  18990. return true;
  18991. this._positions = [];
  18992. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18993. if (!data) {
  18994. return false;
  18995. }
  18996. for (var index = 0; index < data.length; index += 3) {
  18997. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18998. }
  18999. return true;
  19000. };
  19001. /**
  19002. * Returns a new Mesh object generated from the current mesh properties.
  19003. * This method must not get confused with createInstance().
  19004. * The parameter `name` is a string, the name given to the new mesh.
  19005. * The optional parameter `newParent` can be any Node object (default `null`).
  19006. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19007. * 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.
  19008. */
  19009. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19010. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19011. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19012. };
  19013. /**
  19014. * Disposes the mesh.
  19015. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19016. */
  19017. Mesh.prototype.dispose = function (doNotRecurse) {
  19018. if (this._geometry) {
  19019. this._geometry.releaseForMesh(this, true);
  19020. }
  19021. // Instances
  19022. if (this._instancesBuffer) {
  19023. this._instancesBuffer.dispose();
  19024. this._instancesBuffer = null;
  19025. }
  19026. while (this.instances.length) {
  19027. this.instances[0].dispose();
  19028. }
  19029. _super.prototype.dispose.call(this, doNotRecurse);
  19030. };
  19031. /**
  19032. * Modifies the mesh geometry according to a displacement map.
  19033. * 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.
  19034. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19035. * This method returns nothing.
  19036. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19037. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19038. * 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.
  19039. */
  19040. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19041. var _this = this;
  19042. var scene = this.getScene();
  19043. var onload = function (img) {
  19044. // Getting height map data
  19045. var canvas = document.createElement("canvas");
  19046. var context = canvas.getContext("2d");
  19047. var heightMapWidth = img.width;
  19048. var heightMapHeight = img.height;
  19049. canvas.width = heightMapWidth;
  19050. canvas.height = heightMapHeight;
  19051. context.drawImage(img, 0, 0);
  19052. // Create VertexData from map data
  19053. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19054. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19055. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19056. //execute success callback, if set
  19057. if (onSuccess) {
  19058. onSuccess(_this);
  19059. }
  19060. };
  19061. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19062. };
  19063. /**
  19064. * Modifies the mesh geometry according to a displacementMap buffer.
  19065. * 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.
  19066. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19067. * This method returns nothing.
  19068. * 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.
  19069. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19070. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19071. */
  19072. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19073. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19074. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19075. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19076. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19077. return;
  19078. }
  19079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19080. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19081. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19082. var position = BABYLON.Vector3.Zero();
  19083. var normal = BABYLON.Vector3.Zero();
  19084. var uv = BABYLON.Vector2.Zero();
  19085. for (var index = 0; index < positions.length; index += 3) {
  19086. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19087. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19088. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19089. // Compute height
  19090. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19091. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19092. var pos = (u + v * heightMapWidth) * 4;
  19093. var r = buffer[pos] / 255.0;
  19094. var g = buffer[pos + 1] / 255.0;
  19095. var b = buffer[pos + 2] / 255.0;
  19096. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19097. normal.normalize();
  19098. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19099. position = position.add(normal);
  19100. position.toArray(positions, index);
  19101. }
  19102. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19103. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19104. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19105. };
  19106. /**
  19107. * Modify the mesh to get a flat shading rendering.
  19108. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19109. * This method returns nothing.
  19110. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19111. */
  19112. Mesh.prototype.convertToFlatShadedMesh = function () {
  19113. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19114. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19115. var kinds = this.getVerticesDataKinds();
  19116. var vbs = [];
  19117. var data = [];
  19118. var newdata = [];
  19119. var updatableNormals = false;
  19120. var kindIndex;
  19121. var kind;
  19122. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19123. kind = kinds[kindIndex];
  19124. var vertexBuffer = this.getVertexBuffer(kind);
  19125. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19126. updatableNormals = vertexBuffer.isUpdatable();
  19127. kinds.splice(kindIndex, 1);
  19128. kindIndex--;
  19129. continue;
  19130. }
  19131. vbs[kind] = vertexBuffer;
  19132. data[kind] = vbs[kind].getData();
  19133. newdata[kind] = [];
  19134. }
  19135. // Save previous submeshes
  19136. var previousSubmeshes = this.subMeshes.slice(0);
  19137. var indices = this.getIndices();
  19138. var totalIndices = this.getTotalIndices();
  19139. // Generating unique vertices per face
  19140. var index;
  19141. for (index = 0; index < totalIndices; index++) {
  19142. var vertexIndex = indices[index];
  19143. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19144. kind = kinds[kindIndex];
  19145. var stride = vbs[kind].getStrideSize();
  19146. for (var offset = 0; offset < stride; offset++) {
  19147. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19148. }
  19149. }
  19150. }
  19151. // Updating faces & normal
  19152. var normals = [];
  19153. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19154. for (index = 0; index < totalIndices; index += 3) {
  19155. indices[index] = index;
  19156. indices[index + 1] = index + 1;
  19157. indices[index + 2] = index + 2;
  19158. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19159. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19160. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19161. var p1p2 = p1.subtract(p2);
  19162. var p3p2 = p3.subtract(p2);
  19163. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19164. // Store same normals for every vertex
  19165. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19166. normals.push(normal.x);
  19167. normals.push(normal.y);
  19168. normals.push(normal.z);
  19169. }
  19170. }
  19171. this.setIndices(indices);
  19172. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19173. // Updating vertex buffers
  19174. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19175. kind = kinds[kindIndex];
  19176. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19177. }
  19178. // Updating submeshes
  19179. this.releaseSubMeshes();
  19180. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19181. var previousOne = previousSubmeshes[submeshIndex];
  19182. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19183. }
  19184. this.synchronizeInstances();
  19185. };
  19186. /**
  19187. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19188. * In other words, more vertices, no more indices and a single bigger VBO.
  19189. * This method returns nothing.
  19190. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19191. *
  19192. */
  19193. Mesh.prototype.convertToUnIndexedMesh = function () {
  19194. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19195. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19196. var kinds = this.getVerticesDataKinds();
  19197. var vbs = [];
  19198. var data = [];
  19199. var newdata = [];
  19200. var updatableNormals = false;
  19201. var kindIndex;
  19202. var kind;
  19203. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19204. kind = kinds[kindIndex];
  19205. var vertexBuffer = this.getVertexBuffer(kind);
  19206. vbs[kind] = vertexBuffer;
  19207. data[kind] = vbs[kind].getData();
  19208. newdata[kind] = [];
  19209. }
  19210. // Save previous submeshes
  19211. var previousSubmeshes = this.subMeshes.slice(0);
  19212. var indices = this.getIndices();
  19213. var totalIndices = this.getTotalIndices();
  19214. // Generating unique vertices per face
  19215. var index;
  19216. for (index = 0; index < totalIndices; index++) {
  19217. var vertexIndex = indices[index];
  19218. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19219. kind = kinds[kindIndex];
  19220. var stride = vbs[kind].getStrideSize();
  19221. for (var offset = 0; offset < stride; offset++) {
  19222. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19223. }
  19224. }
  19225. }
  19226. // Updating indices
  19227. for (index = 0; index < totalIndices; index += 3) {
  19228. indices[index] = index;
  19229. indices[index + 1] = index + 1;
  19230. indices[index + 2] = index + 2;
  19231. }
  19232. this.setIndices(indices);
  19233. // Updating vertex buffers
  19234. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19235. kind = kinds[kindIndex];
  19236. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19237. }
  19238. // Updating submeshes
  19239. this.releaseSubMeshes();
  19240. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19241. var previousOne = previousSubmeshes[submeshIndex];
  19242. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19243. }
  19244. this._unIndexed = true;
  19245. this.synchronizeInstances();
  19246. };
  19247. /**
  19248. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19249. * This method returns nothing.
  19250. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19251. */
  19252. Mesh.prototype.flipFaces = function (flipNormals) {
  19253. if (flipNormals === void 0) { flipNormals = false; }
  19254. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19255. var i;
  19256. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19257. for (i = 0; i < vertex_data.normals.length; i++) {
  19258. vertex_data.normals[i] *= -1;
  19259. }
  19260. }
  19261. var temp;
  19262. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19263. // reassign indices
  19264. temp = vertex_data.indices[i + 1];
  19265. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19266. vertex_data.indices[i + 2] = temp;
  19267. }
  19268. vertex_data.applyToMesh(this);
  19269. };
  19270. // Instances
  19271. /**
  19272. * Creates a new InstancedMesh object from the mesh model.
  19273. * An instance shares the same properties and the same material than its model.
  19274. * Only these properties of each instance can then be set individually :
  19275. * - position
  19276. * - rotation
  19277. * - rotationQuaternion
  19278. * - setPivotMatrix
  19279. * - scaling
  19280. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19281. * Warning : this method is not supported for Line mesh and LineSystem
  19282. */
  19283. Mesh.prototype.createInstance = function (name) {
  19284. return new BABYLON.InstancedMesh(name, this);
  19285. };
  19286. /**
  19287. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19288. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19289. * This method returns nothing.
  19290. */
  19291. Mesh.prototype.synchronizeInstances = function () {
  19292. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19293. var instance = this.instances[instanceIndex];
  19294. instance._syncSubMeshes();
  19295. }
  19296. };
  19297. /**
  19298. * Simplify the mesh according to the given array of settings.
  19299. * Function will return immediately and will simplify async. It returns nothing.
  19300. * @param settings a collection of simplification settings.
  19301. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19302. * @param type the type of simplification to run.
  19303. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19304. */
  19305. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19306. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19307. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19308. this.getScene().simplificationQueue.addTask({
  19309. settings: settings,
  19310. parallelProcessing: parallelProcessing,
  19311. mesh: this,
  19312. simplificationType: simplificationType,
  19313. successCallback: successCallback
  19314. });
  19315. };
  19316. /**
  19317. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19318. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19319. * This should be used together with the simplification to avoid disappearing triangles.
  19320. * @param successCallback an optional success callback to be called after the optimization finished.
  19321. */
  19322. Mesh.prototype.optimizeIndices = function (successCallback) {
  19323. var _this = this;
  19324. var indices = this.getIndices();
  19325. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19326. var vectorPositions = [];
  19327. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19328. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19329. }
  19330. var dupes = [];
  19331. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19332. var realPos = vectorPositions.length - 1 - iteration;
  19333. var testedPosition = vectorPositions[realPos];
  19334. for (var j = 0; j < realPos; ++j) {
  19335. var againstPosition = vectorPositions[j];
  19336. if (testedPosition.equals(againstPosition)) {
  19337. dupes[realPos] = j;
  19338. break;
  19339. }
  19340. }
  19341. }, function () {
  19342. for (var i = 0; i < indices.length; ++i) {
  19343. indices[i] = dupes[indices[i]] || indices[i];
  19344. }
  19345. //indices are now reordered
  19346. var originalSubMeshes = _this.subMeshes.slice(0);
  19347. _this.setIndices(indices);
  19348. _this.subMeshes = originalSubMeshes;
  19349. if (successCallback) {
  19350. successCallback(_this);
  19351. }
  19352. });
  19353. };
  19354. // Statics
  19355. /**
  19356. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19357. * The parameter `parsedMesh` is the mesh to be copied.
  19358. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19359. */
  19360. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19361. var mesh = new Mesh(parsedMesh.name, scene);
  19362. mesh.id = parsedMesh.id;
  19363. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19364. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19365. if (parsedMesh.rotationQuaternion) {
  19366. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19367. }
  19368. else if (parsedMesh.rotation) {
  19369. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19370. }
  19371. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19372. if (parsedMesh.localMatrix) {
  19373. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19374. }
  19375. else if (parsedMesh.pivotMatrix) {
  19376. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19377. }
  19378. mesh.setEnabled(parsedMesh.isEnabled);
  19379. mesh.isVisible = parsedMesh.isVisible;
  19380. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19381. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19382. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19383. if (parsedMesh.applyFog !== undefined) {
  19384. mesh.applyFog = parsedMesh.applyFog;
  19385. }
  19386. if (parsedMesh.pickable !== undefined) {
  19387. mesh.isPickable = parsedMesh.pickable;
  19388. }
  19389. if (parsedMesh.alphaIndex !== undefined) {
  19390. mesh.alphaIndex = parsedMesh.alphaIndex;
  19391. }
  19392. mesh.receiveShadows = parsedMesh.receiveShadows;
  19393. mesh.billboardMode = parsedMesh.billboardMode;
  19394. if (parsedMesh.visibility !== undefined) {
  19395. mesh.visibility = parsedMesh.visibility;
  19396. }
  19397. mesh.checkCollisions = parsedMesh.checkCollisions;
  19398. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19399. // freezeWorldMatrix
  19400. if (parsedMesh.freezeWorldMatrix) {
  19401. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19402. }
  19403. // Parent
  19404. if (parsedMesh.parentId) {
  19405. mesh._waitingParentId = parsedMesh.parentId;
  19406. }
  19407. // Actions
  19408. if (parsedMesh.actions !== undefined) {
  19409. mesh._waitingActions = parsedMesh.actions;
  19410. }
  19411. // Geometry
  19412. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19413. if (parsedMesh.delayLoadingFile) {
  19414. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19415. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19416. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19417. if (parsedMesh._binaryInfo) {
  19418. mesh._binaryInfo = parsedMesh._binaryInfo;
  19419. }
  19420. mesh._delayInfo = [];
  19421. if (parsedMesh.hasUVs) {
  19422. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19423. }
  19424. if (parsedMesh.hasUVs2) {
  19425. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19426. }
  19427. if (parsedMesh.hasUVs3) {
  19428. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19429. }
  19430. if (parsedMesh.hasUVs4) {
  19431. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19432. }
  19433. if (parsedMesh.hasUVs5) {
  19434. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19435. }
  19436. if (parsedMesh.hasUVs6) {
  19437. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19438. }
  19439. if (parsedMesh.hasColors) {
  19440. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19441. }
  19442. if (parsedMesh.hasMatricesIndices) {
  19443. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19444. }
  19445. if (parsedMesh.hasMatricesWeights) {
  19446. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19447. }
  19448. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19449. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19450. mesh._checkDelayState();
  19451. }
  19452. }
  19453. else {
  19454. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19455. }
  19456. // Material
  19457. if (parsedMesh.materialId) {
  19458. mesh.setMaterialByID(parsedMesh.materialId);
  19459. }
  19460. else {
  19461. mesh.material = null;
  19462. }
  19463. // Skeleton
  19464. if (parsedMesh.skeletonId > -1) {
  19465. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19466. if (parsedMesh.numBoneInfluencers) {
  19467. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19468. }
  19469. }
  19470. // Animations
  19471. if (parsedMesh.animations) {
  19472. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19473. var parsedAnimation = parsedMesh.animations[animationIndex];
  19474. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19475. }
  19476. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19477. }
  19478. if (parsedMesh.autoAnimate) {
  19479. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19480. }
  19481. // Layer Mask
  19482. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19483. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19484. }
  19485. else {
  19486. mesh.layerMask = 0x0FFFFFFF;
  19487. }
  19488. //(Deprecated) physics
  19489. if (parsedMesh.physicsImpostor) {
  19490. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19491. mass: parsedMesh.physicsMass,
  19492. friction: parsedMesh.physicsFriction,
  19493. restitution: parsedMesh.physicsRestitution
  19494. }, scene);
  19495. }
  19496. // Instances
  19497. if (parsedMesh.instances) {
  19498. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19499. var parsedInstance = parsedMesh.instances[index];
  19500. var instance = mesh.createInstance(parsedInstance.name);
  19501. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19502. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19503. if (parsedInstance.rotationQuaternion) {
  19504. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19505. }
  19506. else if (parsedInstance.rotation) {
  19507. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19508. }
  19509. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19510. instance.checkCollisions = mesh.checkCollisions;
  19511. if (parsedMesh.animations) {
  19512. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19513. parsedAnimation = parsedMesh.animations[animationIndex];
  19514. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19515. }
  19516. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19517. }
  19518. }
  19519. }
  19520. return mesh;
  19521. };
  19522. /**
  19523. * Creates a ribbon mesh.
  19524. * Please consider using the same method from the MeshBuilder class instead.
  19525. * 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.
  19526. *
  19527. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19528. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19529. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19530. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19531. * 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.
  19532. * 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.
  19533. * 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
  19534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19537. */
  19538. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19539. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19540. pathArray: pathArray,
  19541. closeArray: closeArray,
  19542. closePath: closePath,
  19543. offset: offset,
  19544. updatable: updatable,
  19545. sideOrientation: sideOrientation,
  19546. instance: instance
  19547. }, scene);
  19548. };
  19549. /**
  19550. * Creates a plane polygonal mesh. By default, this is a disc.
  19551. * Please consider using the same method from the MeshBuilder class instead.
  19552. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19553. * 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.
  19554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19557. */
  19558. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19559. var options = {
  19560. radius: radius,
  19561. tessellation: tessellation,
  19562. sideOrientation: sideOrientation,
  19563. updatable: updatable
  19564. };
  19565. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19566. };
  19567. /**
  19568. * Creates a box mesh.
  19569. * Please consider using the same method from the MeshBuilder class instead.
  19570. * The parameter `size` sets the size (float) of each box side (default 1).
  19571. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19574. */
  19575. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19576. var options = {
  19577. size: size,
  19578. sideOrientation: sideOrientation,
  19579. updatable: updatable
  19580. };
  19581. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19582. };
  19583. /**
  19584. * Creates a sphere mesh.
  19585. * Please consider using the same method from the MeshBuilder class instead.
  19586. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19587. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19591. */
  19592. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19593. var options = {
  19594. segments: segments,
  19595. diameterX: diameter,
  19596. diameterY: diameter,
  19597. diameterZ: diameter,
  19598. sideOrientation: sideOrientation,
  19599. updatable: updatable
  19600. };
  19601. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19602. };
  19603. /**
  19604. * Creates a cylinder or a cone mesh.
  19605. * Please consider using the same method from the MeshBuilder class instead.
  19606. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19607. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19608. * 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.
  19609. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19610. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19614. */
  19615. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19616. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19617. if (scene !== undefined) {
  19618. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19619. updatable = scene;
  19620. }
  19621. scene = subdivisions;
  19622. subdivisions = 1;
  19623. }
  19624. var options = {
  19625. height: height,
  19626. diameterTop: diameterTop,
  19627. diameterBottom: diameterBottom,
  19628. tessellation: tessellation,
  19629. subdivisions: subdivisions,
  19630. sideOrientation: sideOrientation,
  19631. updatable: updatable
  19632. };
  19633. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19634. };
  19635. // Torus (Code from SharpDX.org)
  19636. /**
  19637. * Creates a torus mesh.
  19638. * Please consider using the same method from the MeshBuilder class instead.
  19639. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19640. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19641. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19645. */
  19646. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19647. var options = {
  19648. diameter: diameter,
  19649. thickness: thickness,
  19650. tessellation: tessellation,
  19651. sideOrientation: sideOrientation,
  19652. updatable: updatable
  19653. };
  19654. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19655. };
  19656. /**
  19657. * Creates a torus knot mesh.
  19658. * Please consider using the same method from the MeshBuilder class instead.
  19659. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19660. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19661. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19662. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19666. */
  19667. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19668. var options = {
  19669. radius: radius,
  19670. tube: tube,
  19671. radialSegments: radialSegments,
  19672. tubularSegments: tubularSegments,
  19673. p: p,
  19674. q: q,
  19675. sideOrientation: sideOrientation,
  19676. updatable: updatable
  19677. };
  19678. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19679. };
  19680. /**
  19681. * Creates a line mesh.
  19682. * Please consider using the same method from the MeshBuilder class instead.
  19683. * 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.
  19684. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19685. * The parameter `points` is an array successive Vector3.
  19686. * 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
  19687. * When updating an instance, remember that only point positions can change, not the number of points.
  19688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19689. */
  19690. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19691. var options = {
  19692. points: points,
  19693. updatable: updatable,
  19694. instance: instance
  19695. };
  19696. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19697. };
  19698. /**
  19699. * Creates a dashed line mesh.
  19700. * Please consider using the same method from the MeshBuilder class instead.
  19701. * 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.
  19702. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19703. * The parameter `points` is an array successive Vector3.
  19704. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19705. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19706. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19707. * 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
  19708. * When updating an instance, remember that only point positions can change, not the number of points.
  19709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19710. */
  19711. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19712. var options = {
  19713. points: points,
  19714. dashSize: dashSize,
  19715. gapSize: gapSize,
  19716. dashNb: dashNb,
  19717. updatable: updatable,
  19718. instance: instance
  19719. };
  19720. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19721. };
  19722. /**
  19723. * Creates an extruded shape mesh.
  19724. * 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.
  19725. * Please consider using the same method from the MeshBuilder class instead.
  19726. *
  19727. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19728. * 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
  19729. * extruded along the Z axis.
  19730. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19731. * 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.
  19732. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19733. * 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
  19734. * 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
  19735. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19736. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19739. */
  19740. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19741. var options = {
  19742. shape: shape,
  19743. path: path,
  19744. scale: scale,
  19745. rotation: rotation,
  19746. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19747. sideOrientation: sideOrientation,
  19748. instance: instance,
  19749. updatable: updatable
  19750. };
  19751. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19752. };
  19753. /**
  19754. * Creates an custom extruded shape mesh.
  19755. * 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.
  19756. * Please consider using the same method from the MeshBuilder class instead.
  19757. *
  19758. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19759. * 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
  19760. * extruded along the Z axis.
  19761. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19762. * 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
  19763. * and the distance of this point from the begining of the path :
  19764. * ```javascript
  19765. * var rotationFunction = function(i, distance) {
  19766. * // do things
  19767. * return rotationValue; }
  19768. * ```
  19769. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19770. * 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
  19771. * and the distance of this point from the begining of the path :
  19772. * ```javascript
  19773. * var scaleFunction = function(i, distance) {
  19774. * // do things
  19775. * return scaleValue;}
  19776. * ```
  19777. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19778. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19779. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19780. * 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
  19781. * 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
  19782. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19786. */
  19787. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19788. var options = {
  19789. shape: shape,
  19790. path: path,
  19791. scaleFunction: scaleFunction,
  19792. rotationFunction: rotationFunction,
  19793. ribbonCloseArray: ribbonCloseArray,
  19794. ribbonClosePath: ribbonClosePath,
  19795. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19796. sideOrientation: sideOrientation,
  19797. instance: instance,
  19798. updatable: updatable
  19799. };
  19800. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19801. };
  19802. /**
  19803. * Creates lathe mesh.
  19804. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19805. * Please consider using the same method from the MeshBuilder class instead.
  19806. * 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
  19807. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19808. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19809. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19813. */
  19814. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19815. var options = {
  19816. shape: shape,
  19817. radius: radius,
  19818. tessellation: tessellation,
  19819. sideOrientation: sideOrientation,
  19820. updatable: updatable
  19821. };
  19822. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19823. };
  19824. /**
  19825. * Creates a plane mesh.
  19826. * Please consider using the same method from the MeshBuilder class instead.
  19827. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19831. */
  19832. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19833. var options = {
  19834. size: size,
  19835. width: size,
  19836. height: size,
  19837. sideOrientation: sideOrientation,
  19838. updatable: updatable
  19839. };
  19840. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19841. };
  19842. /**
  19843. * Creates a ground mesh.
  19844. * Please consider using the same method from the MeshBuilder class instead.
  19845. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19846. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19848. */
  19849. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19850. var options = {
  19851. width: width,
  19852. height: height,
  19853. subdivisions: subdivisions,
  19854. updatable: updatable
  19855. };
  19856. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19857. };
  19858. /**
  19859. * Creates a tiled ground mesh.
  19860. * Please consider using the same method from the MeshBuilder class instead.
  19861. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19862. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19863. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19864. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19865. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19866. * numbers of subdivisions on the ground width and height of each tile.
  19867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19868. */
  19869. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19870. var options = {
  19871. xmin: xmin,
  19872. zmin: zmin,
  19873. xmax: xmax,
  19874. zmax: zmax,
  19875. subdivisions: subdivisions,
  19876. precision: precision,
  19877. updatable: updatable
  19878. };
  19879. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19880. };
  19881. /**
  19882. * Creates a ground mesh from a height map.
  19883. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19884. * Please consider using the same method from the MeshBuilder class instead.
  19885. * The parameter `url` sets the URL of the height map image resource.
  19886. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19887. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19888. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19889. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19890. * 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).
  19891. * This function is passed the newly built mesh :
  19892. * ```javascript
  19893. * function(mesh) { // do things
  19894. * return; }
  19895. * ```
  19896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19897. */
  19898. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19899. var options = {
  19900. width: width,
  19901. height: height,
  19902. subdivisions: subdivisions,
  19903. minHeight: minHeight,
  19904. maxHeight: maxHeight,
  19905. updatable: updatable,
  19906. onReady: onReady
  19907. };
  19908. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19909. };
  19910. /**
  19911. * Creates a tube mesh.
  19912. * 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.
  19913. * Please consider using the same method from the MeshBuilder class instead.
  19914. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19915. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19916. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19917. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19918. * 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.
  19919. * It must return a radius value (positive float) :
  19920. * ```javascript
  19921. * var radiusFunction = function(i, distance) {
  19922. * // do things
  19923. * return radius; }
  19924. * ```
  19925. * 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
  19926. * 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
  19927. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19930. */
  19931. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19932. var options = {
  19933. path: path,
  19934. radius: radius,
  19935. tessellation: tessellation,
  19936. radiusFunction: radiusFunction,
  19937. arc: 1,
  19938. cap: cap,
  19939. updatable: updatable,
  19940. sideOrientation: sideOrientation,
  19941. instance: instance
  19942. };
  19943. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19944. };
  19945. /**
  19946. * Creates a polyhedron mesh.
  19947. * Please consider using the same method from the MeshBuilder class instead.
  19948. * 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
  19949. * to choose the wanted type.
  19950. * The parameter `size` (positive float, default 1) sets the polygon size.
  19951. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19952. * 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`.
  19953. * 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
  19954. * 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)`).
  19955. * 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
  19956. * 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.
  19957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19960. */
  19961. Mesh.CreatePolyhedron = function (name, options, scene) {
  19962. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19963. };
  19964. /**
  19965. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19966. * Please consider using the same method from the MeshBuilder class instead.
  19967. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19968. * 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`).
  19969. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19970. * 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.
  19971. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19974. */
  19975. Mesh.CreateIcoSphere = function (name, options, scene) {
  19976. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19977. };
  19978. /**
  19979. * Creates a decal mesh.
  19980. * Please consider using the same method from the MeshBuilder class instead.
  19981. * 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.
  19982. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19983. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19984. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19985. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19986. */
  19987. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19988. var options = {
  19989. position: position,
  19990. normal: normal,
  19991. size: size,
  19992. angle: angle
  19993. };
  19994. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19995. };
  19996. // Skeletons
  19997. /**
  19998. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19999. */
  20000. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20001. var source;
  20002. if (!this._sourcePositions) {
  20003. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20004. this._sourcePositions = new Float32Array(source);
  20005. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20006. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20007. }
  20008. }
  20009. return this._sourcePositions;
  20010. };
  20011. /**
  20012. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20013. */
  20014. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20015. var source;
  20016. if (!this._sourceNormals) {
  20017. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20018. this._sourceNormals = new Float32Array(source);
  20019. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20020. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20021. }
  20022. }
  20023. return this._sourceNormals;
  20024. };
  20025. /**
  20026. * Update the vertex buffers by applying transformation from the bones
  20027. * @param {skeleton} skeleton to apply
  20028. */
  20029. Mesh.prototype.applySkeleton = function (skeleton) {
  20030. if (!this.geometry) {
  20031. return;
  20032. }
  20033. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20034. return;
  20035. }
  20036. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20038. return this;
  20039. }
  20040. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20041. return this;
  20042. }
  20043. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20044. return this;
  20045. }
  20046. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20047. return this;
  20048. }
  20049. if (!this._sourcePositions) {
  20050. this.setPositionsForCPUSkinning();
  20051. }
  20052. if (!this._sourceNormals) {
  20053. this.setNormalsForCPUSkinning();
  20054. }
  20055. // positionsData checks for not being Float32Array will only pass at most once
  20056. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20057. if (!(positionsData instanceof Float32Array)) {
  20058. positionsData = new Float32Array(positionsData);
  20059. }
  20060. // normalsData checks for not being Float32Array will only pass at most once
  20061. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20062. if (!(normalsData instanceof Float32Array)) {
  20063. normalsData = new Float32Array(normalsData);
  20064. }
  20065. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20066. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20067. var needExtras = this.numBoneInfluencers > 4;
  20068. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20069. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20070. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20071. var tempVector3 = BABYLON.Vector3.Zero();
  20072. var finalMatrix = new BABYLON.Matrix();
  20073. var tempMatrix = new BABYLON.Matrix();
  20074. var matWeightIdx = 0;
  20075. var inf;
  20076. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20077. var weight;
  20078. for (inf = 0; inf < 4; inf++) {
  20079. weight = matricesWeightsData[matWeightIdx + inf];
  20080. if (weight > 0) {
  20081. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20082. finalMatrix.addToSelf(tempMatrix);
  20083. }
  20084. else
  20085. break;
  20086. }
  20087. if (needExtras) {
  20088. for (inf = 0; inf < 4; inf++) {
  20089. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20090. if (weight > 0) {
  20091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20092. finalMatrix.addToSelf(tempMatrix);
  20093. }
  20094. else
  20095. break;
  20096. }
  20097. }
  20098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20099. tempVector3.toArray(positionsData, index);
  20100. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20101. tempVector3.toArray(normalsData, index);
  20102. finalMatrix.reset();
  20103. }
  20104. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20105. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20106. return this;
  20107. };
  20108. // Tools
  20109. /**
  20110. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20111. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20112. */
  20113. Mesh.MinMax = function (meshes) {
  20114. var minVector = null;
  20115. var maxVector = null;
  20116. for (var i in meshes) {
  20117. var mesh = meshes[i];
  20118. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20119. if (!minVector) {
  20120. minVector = boundingBox.minimumWorld;
  20121. maxVector = boundingBox.maximumWorld;
  20122. continue;
  20123. }
  20124. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20125. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20126. }
  20127. return {
  20128. min: minVector,
  20129. max: maxVector
  20130. };
  20131. };
  20132. /**
  20133. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20134. */
  20135. Mesh.Center = function (meshesOrMinMaxVector) {
  20136. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20137. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20138. };
  20139. /**
  20140. * Merge the array of meshes into a single mesh for performance reasons.
  20141. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20142. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20143. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20144. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20145. */
  20146. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20147. if (disposeSource === void 0) { disposeSource = true; }
  20148. var index;
  20149. if (!allow32BitsIndices) {
  20150. var totalVertices = 0;
  20151. // Counting vertices
  20152. for (index = 0; index < meshes.length; index++) {
  20153. if (meshes[index]) {
  20154. totalVertices += meshes[index].getTotalVertices();
  20155. if (totalVertices > 65536) {
  20156. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20157. return null;
  20158. }
  20159. }
  20160. }
  20161. }
  20162. // Merge
  20163. var vertexData;
  20164. var otherVertexData;
  20165. var source;
  20166. for (index = 0; index < meshes.length; index++) {
  20167. if (meshes[index]) {
  20168. meshes[index].computeWorldMatrix(true);
  20169. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20170. otherVertexData.transform(meshes[index].getWorldMatrix());
  20171. if (vertexData) {
  20172. vertexData.merge(otherVertexData);
  20173. }
  20174. else {
  20175. vertexData = otherVertexData;
  20176. source = meshes[index];
  20177. }
  20178. }
  20179. }
  20180. if (!meshSubclass) {
  20181. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20182. }
  20183. vertexData.applyToMesh(meshSubclass);
  20184. // Setting properties
  20185. meshSubclass.material = source.material;
  20186. meshSubclass.checkCollisions = source.checkCollisions;
  20187. // Cleaning
  20188. if (disposeSource) {
  20189. for (index = 0; index < meshes.length; index++) {
  20190. if (meshes[index]) {
  20191. meshes[index].dispose();
  20192. }
  20193. }
  20194. }
  20195. return meshSubclass;
  20196. };
  20197. // Consts
  20198. Mesh._FRONTSIDE = 0;
  20199. Mesh._BACKSIDE = 1;
  20200. Mesh._DOUBLESIDE = 2;
  20201. Mesh._DEFAULTSIDE = 0;
  20202. Mesh._NO_CAP = 0;
  20203. Mesh._CAP_START = 1;
  20204. Mesh._CAP_END = 2;
  20205. Mesh._CAP_ALL = 3;
  20206. return Mesh;
  20207. }(BABYLON.AbstractMesh));
  20208. BABYLON.Mesh = Mesh;
  20209. })(BABYLON || (BABYLON = {}));
  20210. var BABYLON;
  20211. (function (BABYLON) {
  20212. var SubMesh = (function () {
  20213. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20214. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20215. this.materialIndex = materialIndex;
  20216. this.verticesStart = verticesStart;
  20217. this.verticesCount = verticesCount;
  20218. this.indexStart = indexStart;
  20219. this.indexCount = indexCount;
  20220. this._renderId = 0;
  20221. this._mesh = mesh;
  20222. this._renderingMesh = renderingMesh || mesh;
  20223. mesh.subMeshes.push(this);
  20224. this._trianglePlanes = [];
  20225. this._id = mesh.subMeshes.length - 1;
  20226. if (createBoundingBox) {
  20227. this.refreshBoundingInfo();
  20228. mesh.computeWorldMatrix(true);
  20229. }
  20230. }
  20231. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20232. get: function () {
  20233. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. SubMesh.prototype.getBoundingInfo = function () {
  20239. if (this.IsGlobal) {
  20240. return this._mesh.getBoundingInfo();
  20241. }
  20242. return this._boundingInfo;
  20243. };
  20244. SubMesh.prototype.getMesh = function () {
  20245. return this._mesh;
  20246. };
  20247. SubMesh.prototype.getRenderingMesh = function () {
  20248. return this._renderingMesh;
  20249. };
  20250. SubMesh.prototype.getMaterial = function () {
  20251. var rootMaterial = this._renderingMesh.material;
  20252. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20253. var multiMaterial = rootMaterial;
  20254. return multiMaterial.getSubMaterial(this.materialIndex);
  20255. }
  20256. if (!rootMaterial) {
  20257. return this._mesh.getScene().defaultMaterial;
  20258. }
  20259. return rootMaterial;
  20260. };
  20261. // Methods
  20262. SubMesh.prototype.refreshBoundingInfo = function () {
  20263. this._lastColliderWorldVertices = null;
  20264. if (this.IsGlobal) {
  20265. return;
  20266. }
  20267. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20268. if (!data) {
  20269. this._boundingInfo = this._mesh._boundingInfo;
  20270. return;
  20271. }
  20272. var indices = this._renderingMesh.getIndices();
  20273. var extend;
  20274. //is this the only submesh?
  20275. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20276. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20277. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20278. }
  20279. else {
  20280. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20281. }
  20282. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20283. };
  20284. SubMesh.prototype._checkCollision = function (collider) {
  20285. return this.getBoundingInfo()._checkCollision(collider);
  20286. };
  20287. SubMesh.prototype.updateBoundingInfo = function (world) {
  20288. if (!this.getBoundingInfo()) {
  20289. this.refreshBoundingInfo();
  20290. }
  20291. this.getBoundingInfo().update(world);
  20292. };
  20293. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20294. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20295. };
  20296. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20297. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20298. };
  20299. SubMesh.prototype.render = function (enableAlphaMode) {
  20300. this._renderingMesh.render(this, enableAlphaMode);
  20301. };
  20302. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20303. if (!this._linesIndexBuffer) {
  20304. var linesIndices = [];
  20305. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20306. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20307. }
  20308. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20309. this.linesIndexCount = linesIndices.length;
  20310. }
  20311. return this._linesIndexBuffer;
  20312. };
  20313. SubMesh.prototype.canIntersects = function (ray) {
  20314. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20315. };
  20316. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20317. var intersectInfo = null;
  20318. // LineMesh first as it's also a Mesh...
  20319. if (this._mesh instanceof BABYLON.LinesMesh) {
  20320. var lineMesh = this._mesh;
  20321. // Line test
  20322. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20323. var p0 = positions[indices[index]];
  20324. var p1 = positions[indices[index + 1]];
  20325. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20326. if (length < 0) {
  20327. continue;
  20328. }
  20329. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20330. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20331. if (fastCheck) {
  20332. break;
  20333. }
  20334. }
  20335. }
  20336. }
  20337. else {
  20338. // Triangles test
  20339. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20340. var p0 = positions[indices[index]];
  20341. var p1 = positions[indices[index + 1]];
  20342. var p2 = positions[indices[index + 2]];
  20343. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20344. if (currentIntersectInfo) {
  20345. if (currentIntersectInfo.distance < 0) {
  20346. continue;
  20347. }
  20348. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20349. intersectInfo = currentIntersectInfo;
  20350. intersectInfo.faceId = index / 3;
  20351. if (fastCheck) {
  20352. break;
  20353. }
  20354. }
  20355. }
  20356. }
  20357. }
  20358. return intersectInfo;
  20359. };
  20360. // Clone
  20361. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20362. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20363. if (!this.IsGlobal) {
  20364. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20365. }
  20366. return result;
  20367. };
  20368. // Dispose
  20369. SubMesh.prototype.dispose = function () {
  20370. if (this._linesIndexBuffer) {
  20371. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20372. this._linesIndexBuffer = null;
  20373. }
  20374. // Remove from mesh
  20375. var index = this._mesh.subMeshes.indexOf(this);
  20376. this._mesh.subMeshes.splice(index, 1);
  20377. };
  20378. // Statics
  20379. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20380. var minVertexIndex = Number.MAX_VALUE;
  20381. var maxVertexIndex = -Number.MAX_VALUE;
  20382. renderingMesh = renderingMesh || mesh;
  20383. var indices = renderingMesh.getIndices();
  20384. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20385. var vertexIndex = indices[index];
  20386. if (vertexIndex < minVertexIndex)
  20387. minVertexIndex = vertexIndex;
  20388. if (vertexIndex > maxVertexIndex)
  20389. maxVertexIndex = vertexIndex;
  20390. }
  20391. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20392. };
  20393. return SubMesh;
  20394. }());
  20395. BABYLON.SubMesh = SubMesh;
  20396. })(BABYLON || (BABYLON = {}));
  20397. var BABYLON;
  20398. (function (BABYLON) {
  20399. var MeshBuilder = (function () {
  20400. function MeshBuilder() {
  20401. }
  20402. /**
  20403. * Creates a box mesh.
  20404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20405. * The parameter `size` sets the size (float) of each box side (default 1).
  20406. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20407. * 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).
  20408. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20412. */
  20413. MeshBuilder.CreateBox = function (name, options, scene) {
  20414. var box = new BABYLON.Mesh(name, scene);
  20415. var vertexData = BABYLON.VertexData.CreateBox(options);
  20416. vertexData.applyToMesh(box, options.updatable);
  20417. return box;
  20418. };
  20419. /**
  20420. * Creates a sphere mesh.
  20421. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20422. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20423. * 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`).
  20424. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20425. * 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
  20426. * 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).
  20427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20430. */
  20431. MeshBuilder.CreateSphere = function (name, options, scene) {
  20432. var sphere = new BABYLON.Mesh(name, scene);
  20433. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20434. vertexData.applyToMesh(sphere, options.updatable);
  20435. return sphere;
  20436. };
  20437. /**
  20438. * Creates a plane polygonal mesh. By default, this is a disc.
  20439. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20440. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20441. * 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.
  20442. * 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
  20443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20446. */
  20447. MeshBuilder.CreateDisc = function (name, options, scene) {
  20448. var disc = new BABYLON.Mesh(name, scene);
  20449. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20450. vertexData.applyToMesh(disc, options.updatable);
  20451. return disc;
  20452. };
  20453. /**
  20454. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20456. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20457. * 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`).
  20458. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20459. * 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.
  20460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20463. */
  20464. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20465. var sphere = new BABYLON.Mesh(name, scene);
  20466. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20467. vertexData.applyToMesh(sphere, options.updatable);
  20468. return sphere;
  20469. };
  20470. ;
  20471. /**
  20472. * Creates a ribbon mesh.
  20473. * 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.
  20474. *
  20475. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20476. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20477. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20478. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20479. * 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.
  20480. * 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.
  20481. * 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
  20482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20484. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20486. */
  20487. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20488. var pathArray = options.pathArray;
  20489. var closeArray = options.closeArray;
  20490. var closePath = options.closePath;
  20491. var offset = options.offset;
  20492. var sideOrientation = options.sideOrientation;
  20493. var instance = options.instance;
  20494. var updatable = options.updatable;
  20495. if (instance) {
  20496. // positionFunction : ribbon case
  20497. // only pathArray and sideOrientation parameters are taken into account for positions update
  20498. var positionFunction = function (positions) {
  20499. var minlg = pathArray[0].length;
  20500. var i = 0;
  20501. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20502. for (var si = 1; si <= ns; si++) {
  20503. for (var p = 0; p < pathArray.length; p++) {
  20504. var path = pathArray[p];
  20505. var l = path.length;
  20506. minlg = (minlg < l) ? minlg : l;
  20507. var j = 0;
  20508. while (j < minlg) {
  20509. positions[i] = path[j].x;
  20510. positions[i + 1] = path[j].y;
  20511. positions[i + 2] = path[j].z;
  20512. j++;
  20513. i += 3;
  20514. }
  20515. if (instance._closePath) {
  20516. positions[i] = path[0].x;
  20517. positions[i + 1] = path[0].y;
  20518. positions[i + 2] = path[0].z;
  20519. i += 3;
  20520. }
  20521. }
  20522. }
  20523. };
  20524. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20525. positionFunction(positions);
  20526. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20527. if (!(instance.areNormalsFrozen)) {
  20528. var indices = instance.getIndices();
  20529. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20530. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20531. if (instance._closePath) {
  20532. var indexFirst = 0;
  20533. var indexLast = 0;
  20534. for (var p = 0; p < pathArray.length; p++) {
  20535. indexFirst = instance._idx[p] * 3;
  20536. if (p + 1 < pathArray.length) {
  20537. indexLast = (instance._idx[p + 1] - 1) * 3;
  20538. }
  20539. else {
  20540. indexLast = normals.length - 3;
  20541. }
  20542. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20543. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20544. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20545. normals[indexLast] = normals[indexFirst];
  20546. normals[indexLast + 1] = normals[indexFirst + 1];
  20547. normals[indexLast + 2] = normals[indexFirst + 2];
  20548. }
  20549. }
  20550. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20551. }
  20552. return instance;
  20553. }
  20554. else {
  20555. var ribbon = new BABYLON.Mesh(name, scene);
  20556. ribbon.sideOrientation = sideOrientation;
  20557. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20558. if (closePath) {
  20559. ribbon._idx = vertexData._idx;
  20560. }
  20561. ribbon._closePath = closePath;
  20562. ribbon._closeArray = closeArray;
  20563. vertexData.applyToMesh(ribbon, updatable);
  20564. return ribbon;
  20565. }
  20566. };
  20567. /**
  20568. * Creates a cylinder or a cone mesh.
  20569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20570. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20571. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20572. * 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.
  20573. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20574. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20575. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20576. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20577. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20578. * 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).
  20579. * 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
  20580. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20581. * 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
  20582. * 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.
  20583. * If `enclose` is false, a ring surface is one element.
  20584. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20585. * 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
  20586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20589. */
  20590. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20591. var cylinder = new BABYLON.Mesh(name, scene);
  20592. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20593. vertexData.applyToMesh(cylinder, options.updatable);
  20594. return cylinder;
  20595. };
  20596. /**
  20597. * Creates a torus mesh.
  20598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20599. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20600. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20601. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20605. */
  20606. MeshBuilder.CreateTorus = function (name, options, scene) {
  20607. var torus = new BABYLON.Mesh(name, scene);
  20608. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20609. vertexData.applyToMesh(torus, options.updatable);
  20610. return torus;
  20611. };
  20612. /**
  20613. * Creates a torus knot mesh.
  20614. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20615. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20616. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20617. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20618. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20622. */
  20623. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20624. var torusKnot = new BABYLON.Mesh(name, scene);
  20625. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20626. vertexData.applyToMesh(torusKnot, options.updatable);
  20627. return torusKnot;
  20628. };
  20629. /**
  20630. * Creates a line system mesh.
  20631. * A line system is a pool of many lines gathered in a single mesh.
  20632. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20633. * 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.
  20634. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20635. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20636. * 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
  20637. * 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
  20638. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20640. */
  20641. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20642. var instance = options.instance;
  20643. var lines = options.lines;
  20644. if (instance) {
  20645. var positionFunction = function (positions) {
  20646. var i = 0;
  20647. for (var l = 0; l < lines.length; l++) {
  20648. var points = lines[l];
  20649. for (var p = 0; p < points.length; p++) {
  20650. positions[i] = points[p].x;
  20651. positions[i + 1] = points[p].y;
  20652. positions[i + 2] = points[p].z;
  20653. i += 3;
  20654. }
  20655. }
  20656. };
  20657. instance.updateMeshPositions(positionFunction, false);
  20658. return instance;
  20659. }
  20660. // line system creation
  20661. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20662. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20663. vertexData.applyToMesh(lineSystem, options.updatable);
  20664. return lineSystem;
  20665. };
  20666. /**
  20667. * Creates a line mesh.
  20668. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20669. * 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.
  20670. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20671. * The parameter `points` is an array successive Vector3.
  20672. * 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
  20673. * When updating an instance, remember that only point positions can change, not the number of points.
  20674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20675. */
  20676. MeshBuilder.CreateLines = function (name, options, scene) {
  20677. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20678. return lines;
  20679. };
  20680. /**
  20681. * Creates a dashed line mesh.
  20682. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20683. * 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.
  20684. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20685. * The parameter `points` is an array successive Vector3.
  20686. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20687. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20688. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20689. * 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
  20690. * When updating an instance, remember that only point positions can change, not the number of points.
  20691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20692. */
  20693. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20694. var points = options.points;
  20695. var instance = options.instance;
  20696. var gapSize = options.gapSize;
  20697. var dashNb = options.dashNb;
  20698. var dashSize = options.dashSize;
  20699. if (instance) {
  20700. var positionFunction = function (positions) {
  20701. var curvect = BABYLON.Vector3.Zero();
  20702. var nbSeg = positions.length / 6;
  20703. var lg = 0;
  20704. var nb = 0;
  20705. var shft = 0;
  20706. var dashshft = 0;
  20707. var curshft = 0;
  20708. var p = 0;
  20709. var i = 0;
  20710. var j = 0;
  20711. for (i = 0; i < points.length - 1; i++) {
  20712. points[i + 1].subtractToRef(points[i], curvect);
  20713. lg += curvect.length();
  20714. }
  20715. shft = lg / nbSeg;
  20716. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20717. for (i = 0; i < points.length - 1; i++) {
  20718. points[i + 1].subtractToRef(points[i], curvect);
  20719. nb = Math.floor(curvect.length() / shft);
  20720. curvect.normalize();
  20721. j = 0;
  20722. while (j < nb && p < positions.length) {
  20723. curshft = shft * j;
  20724. positions[p] = points[i].x + curshft * curvect.x;
  20725. positions[p + 1] = points[i].y + curshft * curvect.y;
  20726. positions[p + 2] = points[i].z + curshft * curvect.z;
  20727. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20728. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20729. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20730. p += 6;
  20731. j++;
  20732. }
  20733. }
  20734. while (p < positions.length) {
  20735. positions[p] = points[i].x;
  20736. positions[p + 1] = points[i].y;
  20737. positions[p + 2] = points[i].z;
  20738. p += 3;
  20739. }
  20740. };
  20741. instance.updateMeshPositions(positionFunction, false);
  20742. return instance;
  20743. }
  20744. // dashed lines creation
  20745. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20746. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20747. vertexData.applyToMesh(dashedLines, options.updatable);
  20748. dashedLines.dashSize = dashSize;
  20749. dashedLines.gapSize = gapSize;
  20750. return dashedLines;
  20751. };
  20752. /**
  20753. * Creates an extruded shape mesh.
  20754. * 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.
  20755. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20756. *
  20757. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20758. * 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
  20759. * extruded along the Z axis.
  20760. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20761. * 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.
  20762. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20763. * 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
  20764. * 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
  20765. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20768. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20770. */
  20771. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20772. var path = options.path;
  20773. var shape = options.shape;
  20774. var scale = options.scale || 1;
  20775. var rotation = options.rotation || 0;
  20776. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20777. var updatable = options.updatable;
  20778. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20779. var instance = options.instance;
  20780. var invertUV = options.invertUV || false;
  20781. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20782. };
  20783. /**
  20784. * Creates an custom extruded shape mesh.
  20785. * 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.
  20786. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20787. *
  20788. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20789. * 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
  20790. * extruded along the Z axis.
  20791. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20792. * 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
  20793. * and the distance of this point from the begining of the path :
  20794. * ```javascript
  20795. * var rotationFunction = function(i, distance) {
  20796. * // do things
  20797. * return rotationValue; }
  20798. * ```
  20799. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20800. * 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
  20801. * and the distance of this point from the begining of the path :
  20802. * ```javascript
  20803. * var scaleFunction = function(i, distance) {
  20804. * // do things
  20805. * return scaleValue;}
  20806. * ```
  20807. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20808. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20809. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20810. * 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
  20811. * 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
  20812. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20815. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20817. */
  20818. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20819. var path = options.path;
  20820. var shape = options.shape;
  20821. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20822. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20823. var ribbonCloseArray = options.ribbonCloseArray || false;
  20824. var ribbonClosePath = options.ribbonClosePath || false;
  20825. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20826. var updatable = options.updatable;
  20827. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20828. var instance = options.instance;
  20829. var invertUV = options.invertUV || false;
  20830. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20831. };
  20832. /**
  20833. * Creates lathe mesh.
  20834. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20835. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20836. *
  20837. * 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
  20838. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20839. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20840. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20841. * 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.
  20842. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20843. * 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
  20844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20846. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20848. */
  20849. MeshBuilder.CreateLathe = function (name, options, scene) {
  20850. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20851. var closed = (options.closed === undefined) ? true : options.closed;
  20852. var shape = options.shape;
  20853. var radius = options.radius || 1;
  20854. var tessellation = options.tessellation || 64;
  20855. var updatable = options.updatable;
  20856. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20857. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20858. var pi2 = Math.PI * 2;
  20859. var paths = new Array();
  20860. var invertUV = options.invertUV || false;
  20861. var i = 0;
  20862. var p = 0;
  20863. var step = pi2 / tessellation * arc;
  20864. var rotated;
  20865. var path = new Array();
  20866. ;
  20867. for (i = 0; i <= tessellation; i++) {
  20868. var path = [];
  20869. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20870. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20871. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20872. }
  20873. for (p = 0; p < shape.length; p++) {
  20874. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20875. path.push(rotated);
  20876. }
  20877. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20878. 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));
  20879. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20880. }
  20881. paths.push(path);
  20882. }
  20883. // lathe ribbon
  20884. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20885. return lathe;
  20886. };
  20887. /**
  20888. * Creates a plane mesh.
  20889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20890. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20891. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20892. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20894. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20896. */
  20897. MeshBuilder.CreatePlane = function (name, options, scene) {
  20898. var plane = new BABYLON.Mesh(name, scene);
  20899. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20900. vertexData.applyToMesh(plane, options.updatable);
  20901. if (options.sourcePlane) {
  20902. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20903. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20904. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20905. plane.rotate(vectorProduct, product);
  20906. }
  20907. return plane;
  20908. };
  20909. /**
  20910. * Creates a ground mesh.
  20911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20912. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20913. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20915. */
  20916. MeshBuilder.CreateGround = function (name, options, scene) {
  20917. var ground = new BABYLON.GroundMesh(name, scene);
  20918. ground._setReady(false);
  20919. ground._subdivisions = options.subdivisions || 1;
  20920. ground._width = options.width || 1;
  20921. ground._height = options.height || 1;
  20922. ground._maxX = ground._width / 2;
  20923. ground._maxZ = ground._height / 2;
  20924. ground._minX = -ground._maxX;
  20925. ground._minZ = -ground._maxZ;
  20926. var vertexData = BABYLON.VertexData.CreateGround(options);
  20927. vertexData.applyToMesh(ground, options.updatable);
  20928. ground._setReady(true);
  20929. return ground;
  20930. };
  20931. /**
  20932. * Creates a tiled ground mesh.
  20933. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20934. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20935. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20936. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20937. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20938. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20939. * numbers of subdivisions on the ground width and height of each tile.
  20940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20941. */
  20942. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20943. var tiledGround = new BABYLON.Mesh(name, scene);
  20944. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20945. vertexData.applyToMesh(tiledGround, options.updatable);
  20946. return tiledGround;
  20947. };
  20948. /**
  20949. * Creates a ground mesh from a height map.
  20950. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20952. * The parameter `url` sets the URL of the height map image resource.
  20953. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20954. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20955. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20956. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20957. * 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).
  20958. * This function is passed the newly built mesh :
  20959. * ```javascript
  20960. * function(mesh) { // do things
  20961. * return; }
  20962. * ```
  20963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20964. */
  20965. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20966. var width = options.width || 10.0;
  20967. var height = options.height || 10.0;
  20968. var subdivisions = options.subdivisions || 1 | 0;
  20969. var minHeight = options.minHeight || 0.0;
  20970. var maxHeight = options.maxHeight || 10.0;
  20971. var updatable = options.updatable;
  20972. var onReady = options.onReady;
  20973. var ground = new BABYLON.GroundMesh(name, scene);
  20974. ground._subdivisions = subdivisions;
  20975. ground._width = width;
  20976. ground._height = height;
  20977. ground._maxX = ground._width / 2.0;
  20978. ground._maxZ = ground._height / 2.0;
  20979. ground._minX = -ground._maxX;
  20980. ground._minZ = -ground._maxZ;
  20981. ground._setReady(false);
  20982. var onload = function (img) {
  20983. // Getting height map data
  20984. var canvas = document.createElement("canvas");
  20985. var context = canvas.getContext("2d");
  20986. var bufferWidth = img.width;
  20987. var bufferHeight = img.height;
  20988. canvas.width = bufferWidth;
  20989. canvas.height = bufferHeight;
  20990. context.drawImage(img, 0, 0);
  20991. // Create VertexData from map data
  20992. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20993. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20994. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20995. width: width, height: height,
  20996. subdivisions: subdivisions,
  20997. minHeight: minHeight, maxHeight: maxHeight,
  20998. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20999. });
  21000. vertexData.applyToMesh(ground, updatable);
  21001. ground._setReady(true);
  21002. //execute ready callback, if set
  21003. if (onReady) {
  21004. onReady(ground);
  21005. }
  21006. };
  21007. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21008. return ground;
  21009. };
  21010. /**
  21011. * Creates a tube mesh.
  21012. * 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.
  21013. *
  21014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21015. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21016. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21017. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21018. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21019. * 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.
  21020. * It must return a radius value (positive float) :
  21021. * ```javascript
  21022. * var radiusFunction = function(i, distance) {
  21023. * // do things
  21024. * return radius; }
  21025. * ```
  21026. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21027. * 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
  21028. * 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
  21029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21031. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21033. */
  21034. MeshBuilder.CreateTube = function (name, options, scene) {
  21035. var path = options.path;
  21036. var radius = options.radius || 1.0;
  21037. var tessellation = options.tessellation || 64 | 0;
  21038. var radiusFunction = options.radiusFunction;
  21039. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21040. var invertUV = options.invertUV || false;
  21041. var updatable = options.updatable;
  21042. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21043. var instance = options.instance;
  21044. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21045. // tube geometry
  21046. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21047. var tangents = path3D.getTangents();
  21048. var normals = path3D.getNormals();
  21049. var distances = path3D.getDistances();
  21050. var pi2 = Math.PI * 2;
  21051. var step = pi2 / tessellation * arc;
  21052. var returnRadius = function () { return radius; };
  21053. var radiusFunctionFinal = radiusFunction || returnRadius;
  21054. var circlePath;
  21055. var rad;
  21056. var normal;
  21057. var rotated;
  21058. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21059. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21060. for (var i = 0; i < path.length; i++) {
  21061. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21062. circlePath = Array(); // current circle array
  21063. normal = normals[i]; // current normal
  21064. for (var t = 0; t < tessellation; t++) {
  21065. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21066. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21067. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21068. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21069. circlePath[t] = rotated;
  21070. }
  21071. circlePaths[index] = circlePath;
  21072. index++;
  21073. }
  21074. // cap
  21075. var capPath = function (nbPoints, pathIndex) {
  21076. var pointCap = Array();
  21077. for (var i = 0; i < nbPoints; i++) {
  21078. pointCap.push(path[pathIndex]);
  21079. }
  21080. return pointCap;
  21081. };
  21082. switch (cap) {
  21083. case BABYLON.Mesh.NO_CAP:
  21084. break;
  21085. case BABYLON.Mesh.CAP_START:
  21086. circlePaths[0] = capPath(tessellation, 0);
  21087. circlePaths[1] = circlePaths[2].slice(0);
  21088. break;
  21089. case BABYLON.Mesh.CAP_END:
  21090. circlePaths[index] = circlePaths[index - 1].slice(0);
  21091. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21092. break;
  21093. case BABYLON.Mesh.CAP_ALL:
  21094. circlePaths[0] = capPath(tessellation, 0);
  21095. circlePaths[1] = circlePaths[2].slice(0);
  21096. circlePaths[index] = circlePaths[index - 1].slice(0);
  21097. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21098. break;
  21099. default:
  21100. break;
  21101. }
  21102. return circlePaths;
  21103. };
  21104. var path3D;
  21105. var pathArray;
  21106. if (instance) {
  21107. var arc = options.arc || instance.arc;
  21108. path3D = (instance.path3D).update(path);
  21109. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21110. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21111. instance.path3D = path3D;
  21112. instance.pathArray = pathArray;
  21113. instance.arc = arc;
  21114. return instance;
  21115. }
  21116. // tube creation
  21117. path3D = new BABYLON.Path3D(path);
  21118. var newPathArray = new Array();
  21119. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21120. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21121. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21122. tube.pathArray = pathArray;
  21123. tube.path3D = path3D;
  21124. tube.tessellation = tessellation;
  21125. tube.cap = cap;
  21126. tube.arc = options.arc;
  21127. return tube;
  21128. };
  21129. /**
  21130. * Creates a polyhedron mesh.
  21131. *
  21132. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21133. * 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
  21134. * to choose the wanted type.
  21135. * The parameter `size` (positive float, default 1) sets the polygon size.
  21136. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21137. * 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`.
  21138. * 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
  21139. * 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)`).
  21140. * 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
  21141. * 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.
  21142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21143. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21145. */
  21146. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21147. var polyhedron = new BABYLON.Mesh(name, scene);
  21148. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21149. vertexData.applyToMesh(polyhedron, options.updatable);
  21150. return polyhedron;
  21151. };
  21152. /**
  21153. * Creates a decal mesh.
  21154. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21155. * 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.
  21156. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21157. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21158. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21159. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21160. */
  21161. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21162. var indices = sourceMesh.getIndices();
  21163. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21164. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21165. var position = options.position || BABYLON.Vector3.Zero();
  21166. var normal = options.normal || BABYLON.Vector3.Up();
  21167. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21168. var angle = options.angle || 0;
  21169. // Getting correct rotation
  21170. if (!normal) {
  21171. var target = new BABYLON.Vector3(0, 0, 1);
  21172. var camera = sourceMesh.getScene().activeCamera;
  21173. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21174. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21175. }
  21176. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21177. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21178. var pitch = Math.atan2(normal.y, len);
  21179. // Matrix
  21180. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21181. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21182. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21183. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21184. var vertexData = new BABYLON.VertexData();
  21185. vertexData.indices = [];
  21186. vertexData.positions = [];
  21187. vertexData.normals = [];
  21188. vertexData.uvs = [];
  21189. var currentVertexDataIndex = 0;
  21190. var extractDecalVector3 = function (indexId) {
  21191. var vertexId = indices[indexId];
  21192. var result = new BABYLON.PositionNormalVertex();
  21193. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21194. // Send vector to decal local world
  21195. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21196. // Get normal
  21197. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21198. return result;
  21199. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21200. var clip = function (vertices, axis) {
  21201. if (vertices.length === 0) {
  21202. return vertices;
  21203. }
  21204. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21205. var clipVertices = function (v0, v1) {
  21206. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21207. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21208. };
  21209. var result = new Array();
  21210. for (var index = 0; index < vertices.length; index += 3) {
  21211. var v1Out;
  21212. var v2Out;
  21213. var v3Out;
  21214. var total = 0;
  21215. var nV1, nV2, nV3, nV4;
  21216. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21217. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21218. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21219. v1Out = d1 > 0;
  21220. v2Out = d2 > 0;
  21221. v3Out = d3 > 0;
  21222. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21223. switch (total) {
  21224. case 0:
  21225. result.push(vertices[index]);
  21226. result.push(vertices[index + 1]);
  21227. result.push(vertices[index + 2]);
  21228. break;
  21229. case 1:
  21230. if (v1Out) {
  21231. nV1 = vertices[index + 1];
  21232. nV2 = vertices[index + 2];
  21233. nV3 = clipVertices(vertices[index], nV1);
  21234. nV4 = clipVertices(vertices[index], nV2);
  21235. }
  21236. if (v2Out) {
  21237. nV1 = vertices[index];
  21238. nV2 = vertices[index + 2];
  21239. nV3 = clipVertices(vertices[index + 1], nV1);
  21240. nV4 = clipVertices(vertices[index + 1], nV2);
  21241. result.push(nV3);
  21242. result.push(nV2.clone());
  21243. result.push(nV1.clone());
  21244. result.push(nV2.clone());
  21245. result.push(nV3.clone());
  21246. result.push(nV4);
  21247. break;
  21248. }
  21249. if (v3Out) {
  21250. nV1 = vertices[index];
  21251. nV2 = vertices[index + 1];
  21252. nV3 = clipVertices(vertices[index + 2], nV1);
  21253. nV4 = clipVertices(vertices[index + 2], nV2);
  21254. }
  21255. result.push(nV1.clone());
  21256. result.push(nV2.clone());
  21257. result.push(nV3);
  21258. result.push(nV4);
  21259. result.push(nV3.clone());
  21260. result.push(nV2.clone());
  21261. break;
  21262. case 2:
  21263. if (!v1Out) {
  21264. nV1 = vertices[index].clone();
  21265. nV2 = clipVertices(nV1, vertices[index + 1]);
  21266. nV3 = clipVertices(nV1, vertices[index + 2]);
  21267. result.push(nV1);
  21268. result.push(nV2);
  21269. result.push(nV3);
  21270. }
  21271. if (!v2Out) {
  21272. nV1 = vertices[index + 1].clone();
  21273. nV2 = clipVertices(nV1, vertices[index + 2]);
  21274. nV3 = clipVertices(nV1, vertices[index]);
  21275. result.push(nV1);
  21276. result.push(nV2);
  21277. result.push(nV3);
  21278. }
  21279. if (!v3Out) {
  21280. nV1 = vertices[index + 2].clone();
  21281. nV2 = clipVertices(nV1, vertices[index]);
  21282. nV3 = clipVertices(nV1, vertices[index + 1]);
  21283. result.push(nV1);
  21284. result.push(nV2);
  21285. result.push(nV3);
  21286. }
  21287. break;
  21288. case 3:
  21289. break;
  21290. }
  21291. }
  21292. return result;
  21293. };
  21294. for (var index = 0; index < indices.length; index += 3) {
  21295. var faceVertices = new Array();
  21296. faceVertices.push(extractDecalVector3(index));
  21297. faceVertices.push(extractDecalVector3(index + 1));
  21298. faceVertices.push(extractDecalVector3(index + 2));
  21299. // Clip
  21300. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21301. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21302. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21303. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21304. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21305. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21306. if (faceVertices.length === 0) {
  21307. continue;
  21308. }
  21309. // Add UVs and get back to world
  21310. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21311. var vertex = faceVertices[vIndex];
  21312. //TODO check for Int32Array
  21313. vertexData.indices.push(currentVertexDataIndex);
  21314. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21315. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21316. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21317. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21318. currentVertexDataIndex++;
  21319. }
  21320. }
  21321. // Return mesh
  21322. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21323. vertexData.applyToMesh(decal);
  21324. decal.position = position.clone();
  21325. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21326. return decal;
  21327. };
  21328. // Privates
  21329. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21330. // extrusion geometry
  21331. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21332. var tangents = path3D.getTangents();
  21333. var normals = path3D.getNormals();
  21334. var binormals = path3D.getBinormals();
  21335. var distances = path3D.getDistances();
  21336. var angle = 0;
  21337. var returnScale = function () { return scale; };
  21338. var returnRotation = function () { return rotation; };
  21339. var rotate = custom ? rotateFunction : returnRotation;
  21340. var scl = custom ? scaleFunction : returnScale;
  21341. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21342. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21343. for (var i = 0; i < curve.length; i++) {
  21344. var shapePath = new Array();
  21345. var angleStep = rotate(i, distances[i]);
  21346. var scaleRatio = scl(i, distances[i]);
  21347. for (var p = 0; p < shape.length; p++) {
  21348. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21349. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21350. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21351. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21352. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21353. shapePath[p] = rotated;
  21354. }
  21355. shapePaths[index] = shapePath;
  21356. angle += angleStep;
  21357. index++;
  21358. }
  21359. // cap
  21360. var capPath = function (shapePath) {
  21361. var pointCap = Array();
  21362. var barycenter = BABYLON.Vector3.Zero();
  21363. var i;
  21364. for (i = 0; i < shapePath.length; i++) {
  21365. barycenter.addInPlace(shapePath[i]);
  21366. }
  21367. barycenter.scaleInPlace(1 / shapePath.length);
  21368. for (i = 0; i < shapePath.length; i++) {
  21369. pointCap.push(barycenter);
  21370. }
  21371. return pointCap;
  21372. };
  21373. switch (cap) {
  21374. case BABYLON.Mesh.NO_CAP:
  21375. break;
  21376. case BABYLON.Mesh.CAP_START:
  21377. shapePaths[0] = capPath(shapePaths[2]);
  21378. shapePaths[1] = shapePaths[2].slice(0);
  21379. break;
  21380. case BABYLON.Mesh.CAP_END:
  21381. shapePaths[index] = shapePaths[index - 1];
  21382. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21383. break;
  21384. case BABYLON.Mesh.CAP_ALL:
  21385. shapePaths[0] = capPath(shapePaths[2]);
  21386. shapePaths[1] = shapePaths[2].slice(0);
  21387. shapePaths[index] = shapePaths[index - 1];
  21388. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21389. break;
  21390. default:
  21391. break;
  21392. }
  21393. return shapePaths;
  21394. };
  21395. var path3D;
  21396. var pathArray;
  21397. if (instance) {
  21398. path3D = (instance.path3D).update(curve);
  21399. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21400. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21401. return instance;
  21402. }
  21403. // extruded shape creation
  21404. path3D = new BABYLON.Path3D(curve);
  21405. var newShapePaths = new Array();
  21406. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21407. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21408. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21409. extrudedGeneric.pathArray = pathArray;
  21410. extrudedGeneric.path3D = path3D;
  21411. extrudedGeneric.cap = cap;
  21412. return extrudedGeneric;
  21413. };
  21414. return MeshBuilder;
  21415. }());
  21416. BABYLON.MeshBuilder = MeshBuilder;
  21417. })(BABYLON || (BABYLON = {}));
  21418. var BABYLON;
  21419. (function (BABYLON) {
  21420. var BaseTexture = (function () {
  21421. function BaseTexture(scene) {
  21422. this.hasAlpha = false;
  21423. this.getAlphaFromRGB = false;
  21424. this.level = 1;
  21425. this.coordinatesIndex = 0;
  21426. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21427. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21428. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21429. this.anisotropicFilteringLevel = 4;
  21430. this.isCube = false;
  21431. this.isRenderTarget = false;
  21432. this.animations = new Array();
  21433. /**
  21434. * An event triggered when the texture is disposed.
  21435. * @type {BABYLON.Observable}
  21436. */
  21437. this.onDisposeObservable = new BABYLON.Observable();
  21438. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21439. this._scene = scene;
  21440. this._scene.textures.push(this);
  21441. }
  21442. BaseTexture.prototype.toString = function () {
  21443. return this.name;
  21444. };
  21445. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21446. set: function (callback) {
  21447. if (this._onDisposeObserver) {
  21448. this.onDisposeObservable.remove(this._onDisposeObserver);
  21449. }
  21450. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. BaseTexture.prototype.getScene = function () {
  21456. return this._scene;
  21457. };
  21458. BaseTexture.prototype.getTextureMatrix = function () {
  21459. return null;
  21460. };
  21461. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21462. return null;
  21463. };
  21464. BaseTexture.prototype.getInternalTexture = function () {
  21465. return this._texture;
  21466. };
  21467. BaseTexture.prototype.isReady = function () {
  21468. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21469. return true;
  21470. }
  21471. if (this._texture) {
  21472. return this._texture.isReady;
  21473. }
  21474. return false;
  21475. };
  21476. BaseTexture.prototype.getSize = function () {
  21477. if (this._texture._width) {
  21478. return new BABYLON.Size(this._texture._width, this._texture._height);
  21479. }
  21480. if (this._texture._size) {
  21481. return new BABYLON.Size(this._texture._size, this._texture._size);
  21482. }
  21483. return BABYLON.Size.Zero();
  21484. };
  21485. BaseTexture.prototype.getBaseSize = function () {
  21486. if (!this.isReady() || !this._texture)
  21487. return BABYLON.Size.Zero();
  21488. if (this._texture._size) {
  21489. return new BABYLON.Size(this._texture._size, this._texture._size);
  21490. }
  21491. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  21492. };
  21493. BaseTexture.prototype.scale = function (ratio) {
  21494. };
  21495. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21496. get: function () {
  21497. return false;
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21503. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21504. for (var index = 0; index < texturesCache.length; index++) {
  21505. var texturesCacheEntry = texturesCache[index];
  21506. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21507. texturesCache.splice(index, 1);
  21508. return;
  21509. }
  21510. }
  21511. };
  21512. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21513. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21514. for (var index = 0; index < texturesCache.length; index++) {
  21515. var texturesCacheEntry = texturesCache[index];
  21516. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21517. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21518. texturesCacheEntry.references++;
  21519. return texturesCacheEntry;
  21520. }
  21521. }
  21522. }
  21523. return null;
  21524. };
  21525. BaseTexture.prototype.delayLoad = function () {
  21526. };
  21527. BaseTexture.prototype.clone = function () {
  21528. return null;
  21529. };
  21530. BaseTexture.prototype.releaseInternalTexture = function () {
  21531. if (this._texture) {
  21532. this._scene.getEngine().releaseInternalTexture(this._texture);
  21533. delete this._texture;
  21534. }
  21535. };
  21536. BaseTexture.prototype.dispose = function () {
  21537. // Animations
  21538. this.getScene().stopAnimation(this);
  21539. // Remove from scene
  21540. var index = this._scene.textures.indexOf(this);
  21541. if (index >= 0) {
  21542. this._scene.textures.splice(index, 1);
  21543. }
  21544. if (this._texture === undefined) {
  21545. return;
  21546. }
  21547. // Release
  21548. this.releaseInternalTexture();
  21549. // Callback
  21550. this.onDisposeObservable.notifyObservers(this);
  21551. this.onDisposeObservable.clear();
  21552. };
  21553. BaseTexture.prototype.serialize = function () {
  21554. if (!this.name) {
  21555. return null;
  21556. }
  21557. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21558. // Animations
  21559. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21560. return serializationObject;
  21561. };
  21562. __decorate([
  21563. BABYLON.serialize()
  21564. ], BaseTexture.prototype, "name", void 0);
  21565. __decorate([
  21566. BABYLON.serialize()
  21567. ], BaseTexture.prototype, "hasAlpha", void 0);
  21568. __decorate([
  21569. BABYLON.serialize()
  21570. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21571. __decorate([
  21572. BABYLON.serialize()
  21573. ], BaseTexture.prototype, "level", void 0);
  21574. __decorate([
  21575. BABYLON.serialize()
  21576. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21577. __decorate([
  21578. BABYLON.serialize()
  21579. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21580. __decorate([
  21581. BABYLON.serialize()
  21582. ], BaseTexture.prototype, "wrapU", void 0);
  21583. __decorate([
  21584. BABYLON.serialize()
  21585. ], BaseTexture.prototype, "wrapV", void 0);
  21586. __decorate([
  21587. BABYLON.serialize()
  21588. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21589. __decorate([
  21590. BABYLON.serialize()
  21591. ], BaseTexture.prototype, "isCube", void 0);
  21592. __decorate([
  21593. BABYLON.serialize()
  21594. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21595. return BaseTexture;
  21596. }());
  21597. BABYLON.BaseTexture = BaseTexture;
  21598. })(BABYLON || (BABYLON = {}));
  21599. var BABYLON;
  21600. (function (BABYLON) {
  21601. var Texture = (function (_super) {
  21602. __extends(Texture, _super);
  21603. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21604. var _this = this;
  21605. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21606. if (onLoad === void 0) { onLoad = null; }
  21607. if (onError === void 0) { onError = null; }
  21608. if (buffer === void 0) { buffer = null; }
  21609. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21610. _super.call(this, scene);
  21611. this.uOffset = 0;
  21612. this.vOffset = 0;
  21613. this.uScale = 1.0;
  21614. this.vScale = 1.0;
  21615. this.uAng = 0;
  21616. this.vAng = 0;
  21617. this.wAng = 0;
  21618. this.name = url;
  21619. this.url = url;
  21620. this._noMipmap = noMipmap;
  21621. this._invertY = invertY;
  21622. this._samplingMode = samplingMode;
  21623. this._buffer = buffer;
  21624. this._deleteBuffer = deleteBuffer;
  21625. if (!url) {
  21626. return;
  21627. }
  21628. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21629. var load = function () {
  21630. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  21631. _this.onLoadObservable.notifyObservers(true);
  21632. }
  21633. if (onLoad) {
  21634. onLoad();
  21635. }
  21636. };
  21637. if (!this._texture) {
  21638. if (!scene.useDelayedTextureLoading) {
  21639. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  21640. if (deleteBuffer) {
  21641. delete this._buffer;
  21642. }
  21643. }
  21644. else {
  21645. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21646. this._delayedOnLoad = load;
  21647. this._delayedOnError = onError;
  21648. }
  21649. }
  21650. else {
  21651. BABYLON.Tools.SetImmediate(function () { return load(); });
  21652. }
  21653. }
  21654. Object.defineProperty(Texture.prototype, "noMipmap", {
  21655. get: function () {
  21656. return this._noMipmap;
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. Texture.prototype.delayLoad = function () {
  21662. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21663. return;
  21664. }
  21665. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21666. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21667. if (!this._texture) {
  21668. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21669. if (this._deleteBuffer) {
  21670. delete this._buffer;
  21671. }
  21672. }
  21673. };
  21674. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21675. if (!this._texture) {
  21676. return;
  21677. }
  21678. this._samplingMode = samplingMode;
  21679. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21680. };
  21681. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21682. x *= this.uScale;
  21683. y *= this.vScale;
  21684. x -= 0.5 * this.uScale;
  21685. y -= 0.5 * this.vScale;
  21686. z -= 0.5;
  21687. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21688. t.x += 0.5 * this.uScale + this.uOffset;
  21689. t.y += 0.5 * this.vScale + this.vOffset;
  21690. t.z += 0.5;
  21691. };
  21692. Texture.prototype.getTextureMatrix = function () {
  21693. if (this.uOffset === this._cachedUOffset &&
  21694. this.vOffset === this._cachedVOffset &&
  21695. this.uScale === this._cachedUScale &&
  21696. this.vScale === this._cachedVScale &&
  21697. this.uAng === this._cachedUAng &&
  21698. this.vAng === this._cachedVAng &&
  21699. this.wAng === this._cachedWAng) {
  21700. return this._cachedTextureMatrix;
  21701. }
  21702. this._cachedUOffset = this.uOffset;
  21703. this._cachedVOffset = this.vOffset;
  21704. this._cachedUScale = this.uScale;
  21705. this._cachedVScale = this.vScale;
  21706. this._cachedUAng = this.uAng;
  21707. this._cachedVAng = this.vAng;
  21708. this._cachedWAng = this.wAng;
  21709. if (!this._cachedTextureMatrix) {
  21710. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21711. this._rowGenerationMatrix = new BABYLON.Matrix();
  21712. this._t0 = BABYLON.Vector3.Zero();
  21713. this._t1 = BABYLON.Vector3.Zero();
  21714. this._t2 = BABYLON.Vector3.Zero();
  21715. }
  21716. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21717. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21718. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21719. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21720. this._t1.subtractInPlace(this._t0);
  21721. this._t2.subtractInPlace(this._t0);
  21722. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21723. this._cachedTextureMatrix.m[0] = this._t1.x;
  21724. this._cachedTextureMatrix.m[1] = this._t1.y;
  21725. this._cachedTextureMatrix.m[2] = this._t1.z;
  21726. this._cachedTextureMatrix.m[4] = this._t2.x;
  21727. this._cachedTextureMatrix.m[5] = this._t2.y;
  21728. this._cachedTextureMatrix.m[6] = this._t2.z;
  21729. this._cachedTextureMatrix.m[8] = this._t0.x;
  21730. this._cachedTextureMatrix.m[9] = this._t0.y;
  21731. this._cachedTextureMatrix.m[10] = this._t0.z;
  21732. return this._cachedTextureMatrix;
  21733. };
  21734. Texture.prototype.getReflectionTextureMatrix = function () {
  21735. if (this.uOffset === this._cachedUOffset &&
  21736. this.vOffset === this._cachedVOffset &&
  21737. this.uScale === this._cachedUScale &&
  21738. this.vScale === this._cachedVScale &&
  21739. this.coordinatesMode === this._cachedCoordinatesMode) {
  21740. return this._cachedTextureMatrix;
  21741. }
  21742. if (!this._cachedTextureMatrix) {
  21743. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21744. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21745. }
  21746. this._cachedCoordinatesMode = this.coordinatesMode;
  21747. switch (this.coordinatesMode) {
  21748. case Texture.PLANAR_MODE:
  21749. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21750. this._cachedTextureMatrix[0] = this.uScale;
  21751. this._cachedTextureMatrix[5] = this.vScale;
  21752. this._cachedTextureMatrix[12] = this.uOffset;
  21753. this._cachedTextureMatrix[13] = this.vOffset;
  21754. break;
  21755. case Texture.PROJECTION_MODE:
  21756. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21757. this._projectionModeMatrix.m[0] = 0.5;
  21758. this._projectionModeMatrix.m[5] = -0.5;
  21759. this._projectionModeMatrix.m[10] = 0.0;
  21760. this._projectionModeMatrix.m[12] = 0.5;
  21761. this._projectionModeMatrix.m[13] = 0.5;
  21762. this._projectionModeMatrix.m[14] = 1.0;
  21763. this._projectionModeMatrix.m[15] = 1.0;
  21764. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21765. break;
  21766. default:
  21767. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21768. break;
  21769. }
  21770. return this._cachedTextureMatrix;
  21771. };
  21772. Texture.prototype.clone = function () {
  21773. var _this = this;
  21774. return BABYLON.SerializationHelper.Clone(function () {
  21775. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21776. }, this);
  21777. };
  21778. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21779. get: function () {
  21780. if (!this._onLoadObservarble) {
  21781. this._onLoadObservarble = new BABYLON.Observable();
  21782. }
  21783. return this._onLoadObservarble;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. // Statics
  21789. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21790. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21791. if (onLoad === void 0) { onLoad = null; }
  21792. if (onError === void 0) { onError = null; }
  21793. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21794. };
  21795. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21796. if (parsedTexture.isCube) {
  21797. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21798. }
  21799. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21800. return null;
  21801. }
  21802. var texture = BABYLON.SerializationHelper.Parse(function () {
  21803. if (parsedTexture.mirrorPlane) {
  21804. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21805. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21806. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21807. return mirrorTexture;
  21808. }
  21809. else if (parsedTexture.isRenderTarget) {
  21810. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21811. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21812. return renderTargetTexture;
  21813. }
  21814. else {
  21815. var texture;
  21816. if (parsedTexture.base64String) {
  21817. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21818. }
  21819. else {
  21820. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21821. }
  21822. return texture;
  21823. }
  21824. }, parsedTexture, scene);
  21825. // Animations
  21826. if (parsedTexture.animations) {
  21827. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21828. var parsedAnimation = parsedTexture.animations[animationIndex];
  21829. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21830. }
  21831. }
  21832. return texture;
  21833. };
  21834. // Constants
  21835. Texture.NEAREST_SAMPLINGMODE = 1;
  21836. Texture.BILINEAR_SAMPLINGMODE = 2;
  21837. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21838. Texture.EXPLICIT_MODE = 0;
  21839. Texture.SPHERICAL_MODE = 1;
  21840. Texture.PLANAR_MODE = 2;
  21841. Texture.CUBIC_MODE = 3;
  21842. Texture.PROJECTION_MODE = 4;
  21843. Texture.SKYBOX_MODE = 5;
  21844. Texture.INVCUBIC_MODE = 6;
  21845. Texture.EQUIRECTANGULAR_MODE = 7;
  21846. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21847. Texture.CLAMP_ADDRESSMODE = 0;
  21848. Texture.WRAP_ADDRESSMODE = 1;
  21849. Texture.MIRROR_ADDRESSMODE = 2;
  21850. __decorate([
  21851. BABYLON.serialize()
  21852. ], Texture.prototype, "url", void 0);
  21853. __decorate([
  21854. BABYLON.serialize()
  21855. ], Texture.prototype, "uOffset", void 0);
  21856. __decorate([
  21857. BABYLON.serialize()
  21858. ], Texture.prototype, "vOffset", void 0);
  21859. __decorate([
  21860. BABYLON.serialize()
  21861. ], Texture.prototype, "uScale", void 0);
  21862. __decorate([
  21863. BABYLON.serialize()
  21864. ], Texture.prototype, "vScale", void 0);
  21865. __decorate([
  21866. BABYLON.serialize()
  21867. ], Texture.prototype, "uAng", void 0);
  21868. __decorate([
  21869. BABYLON.serialize()
  21870. ], Texture.prototype, "vAng", void 0);
  21871. __decorate([
  21872. BABYLON.serialize()
  21873. ], Texture.prototype, "wAng", void 0);
  21874. return Texture;
  21875. }(BABYLON.BaseTexture));
  21876. BABYLON.Texture = Texture;
  21877. })(BABYLON || (BABYLON = {}));
  21878. var BABYLON;
  21879. (function (BABYLON) {
  21880. var CubeTexture = (function (_super) {
  21881. __extends(CubeTexture, _super);
  21882. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21883. _super.call(this, scene);
  21884. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21885. this.name = rootUrl;
  21886. this.url = rootUrl;
  21887. this._noMipmap = noMipmap;
  21888. this.hasAlpha = false;
  21889. if (!rootUrl && !files) {
  21890. return;
  21891. }
  21892. this._texture = this._getFromCache(rootUrl, noMipmap);
  21893. if (!files) {
  21894. if (!extensions) {
  21895. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21896. }
  21897. files = [];
  21898. for (var index = 0; index < extensions.length; index++) {
  21899. files.push(rootUrl + extensions[index]);
  21900. }
  21901. this._extensions = extensions;
  21902. }
  21903. this._files = files;
  21904. if (!this._texture) {
  21905. if (!scene.useDelayedTextureLoading) {
  21906. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21907. }
  21908. else {
  21909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21910. }
  21911. }
  21912. this.isCube = true;
  21913. this._textureMatrix = BABYLON.Matrix.Identity();
  21914. }
  21915. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21916. return new CubeTexture("", scene, null, noMipmap, files);
  21917. };
  21918. // Methods
  21919. CubeTexture.prototype.delayLoad = function () {
  21920. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21921. return;
  21922. }
  21923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21924. this._texture = this._getFromCache(this.url, this._noMipmap);
  21925. if (!this._texture) {
  21926. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  21927. }
  21928. };
  21929. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21930. return this._textureMatrix;
  21931. };
  21932. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21933. var texture = BABYLON.SerializationHelper.Parse(function () {
  21934. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21935. }, parsedTexture, scene);
  21936. // Animations
  21937. if (parsedTexture.animations) {
  21938. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21939. var parsedAnimation = parsedTexture.animations[animationIndex];
  21940. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21941. }
  21942. }
  21943. return texture;
  21944. };
  21945. CubeTexture.prototype.clone = function () {
  21946. var _this = this;
  21947. return BABYLON.SerializationHelper.Clone(function () {
  21948. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21949. }, this);
  21950. };
  21951. return CubeTexture;
  21952. }(BABYLON.BaseTexture));
  21953. BABYLON.CubeTexture = CubeTexture;
  21954. })(BABYLON || (BABYLON = {}));
  21955. var BABYLON;
  21956. (function (BABYLON) {
  21957. var RenderTargetTexture = (function (_super) {
  21958. __extends(RenderTargetTexture, _super);
  21959. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21960. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21961. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21962. if (isCube === void 0) { isCube = false; }
  21963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21964. _super.call(this, null, scene, !generateMipMaps);
  21965. this.isCube = isCube;
  21966. /**
  21967. * Use this list to define the list of mesh you want to render.
  21968. */
  21969. this.renderList = new Array();
  21970. this.renderParticles = true;
  21971. this.renderSprites = false;
  21972. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21973. // Events
  21974. /**
  21975. * An event triggered when the texture is unbind.
  21976. * @type {BABYLON.Observable}
  21977. */
  21978. this.onAfterUnbindObservable = new BABYLON.Observable();
  21979. /**
  21980. * An event triggered before rendering the texture
  21981. * @type {BABYLON.Observable}
  21982. */
  21983. this.onBeforeRenderObservable = new BABYLON.Observable();
  21984. /**
  21985. * An event triggered after rendering the texture
  21986. * @type {BABYLON.Observable}
  21987. */
  21988. this.onAfterRenderObservable = new BABYLON.Observable();
  21989. /**
  21990. * An event triggered after the texture clear
  21991. * @type {BABYLON.Observable}
  21992. */
  21993. this.onClearObservable = new BABYLON.Observable();
  21994. this._currentRefreshId = -1;
  21995. this._refreshRate = 1;
  21996. this.name = name;
  21997. this.isRenderTarget = true;
  21998. this._size = size;
  21999. this._generateMipMaps = generateMipMaps;
  22000. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22001. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22002. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22003. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22004. }
  22005. if (isCube) {
  22006. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  22007. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22008. this._textureMatrix = BABYLON.Matrix.Identity();
  22009. }
  22010. else {
  22011. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  22012. }
  22013. // Rendering groups
  22014. this._renderingManager = new BABYLON.RenderingManager(scene);
  22015. }
  22016. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22017. get: function () {
  22018. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22024. get: function () {
  22025. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22031. get: function () {
  22032. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22033. },
  22034. enumerable: true,
  22035. configurable: true
  22036. });
  22037. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22038. set: function (callback) {
  22039. if (this._onAfterUnbindObserver) {
  22040. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22041. }
  22042. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22048. set: function (callback) {
  22049. if (this._onBeforeRenderObserver) {
  22050. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22051. }
  22052. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22053. },
  22054. enumerable: true,
  22055. configurable: true
  22056. });
  22057. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22058. set: function (callback) {
  22059. if (this._onAfterRenderObserver) {
  22060. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22061. }
  22062. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22068. set: function (callback) {
  22069. if (this._onClearObserver) {
  22070. this.onClearObservable.remove(this._onClearObserver);
  22071. }
  22072. this._onClearObserver = this.onClearObservable.add(callback);
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22078. this._currentRefreshId = -1;
  22079. };
  22080. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22081. get: function () {
  22082. return this._refreshRate;
  22083. },
  22084. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22085. set: function (value) {
  22086. this._refreshRate = value;
  22087. this.resetRefreshCounter();
  22088. },
  22089. enumerable: true,
  22090. configurable: true
  22091. });
  22092. RenderTargetTexture.prototype._shouldRender = function () {
  22093. if (this._currentRefreshId === -1) {
  22094. this._currentRefreshId = 1;
  22095. return true;
  22096. }
  22097. if (this.refreshRate === this._currentRefreshId) {
  22098. this._currentRefreshId = 1;
  22099. return true;
  22100. }
  22101. this._currentRefreshId++;
  22102. return false;
  22103. };
  22104. RenderTargetTexture.prototype.isReady = function () {
  22105. if (!this.getScene().renderTargetsEnabled) {
  22106. return false;
  22107. }
  22108. return _super.prototype.isReady.call(this);
  22109. };
  22110. RenderTargetTexture.prototype.getRenderSize = function () {
  22111. return this._size;
  22112. };
  22113. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22114. get: function () {
  22115. return true;
  22116. },
  22117. enumerable: true,
  22118. configurable: true
  22119. });
  22120. RenderTargetTexture.prototype.scale = function (ratio) {
  22121. var newSize = this._size * ratio;
  22122. this.resize(newSize, this._generateMipMaps);
  22123. };
  22124. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22125. if (this.isCube) {
  22126. return this._textureMatrix;
  22127. }
  22128. return _super.prototype.getReflectionTextureMatrix.call(this);
  22129. };
  22130. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22131. this.releaseInternalTexture();
  22132. if (this.isCube) {
  22133. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22134. }
  22135. else {
  22136. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22137. }
  22138. };
  22139. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22140. var scene = this.getScene();
  22141. if (this.useCameraPostProcesses !== undefined) {
  22142. useCameraPostProcess = this.useCameraPostProcesses;
  22143. }
  22144. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22145. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22146. }
  22147. if (this._waitingRenderList) {
  22148. this.renderList = [];
  22149. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22150. var id = this._waitingRenderList[index];
  22151. this.renderList.push(scene.getMeshByID(id));
  22152. }
  22153. delete this._waitingRenderList;
  22154. }
  22155. // Is predicate defined?
  22156. if (this.renderListPredicate) {
  22157. this.renderList.splice(0); // Clear previous renderList
  22158. var sceneMeshes = this.getScene().meshes;
  22159. for (var index = 0; index < sceneMeshes.length; index++) {
  22160. var mesh = sceneMeshes[index];
  22161. if (this.renderListPredicate(mesh)) {
  22162. this.renderList.push(mesh);
  22163. }
  22164. }
  22165. }
  22166. if (this.renderList && this.renderList.length === 0) {
  22167. return;
  22168. }
  22169. // Prepare renderingManager
  22170. this._renderingManager.reset();
  22171. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22172. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22173. var sceneRenderId = scene.getRenderId();
  22174. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22175. var mesh = currentRenderList[meshIndex];
  22176. if (mesh) {
  22177. if (!mesh.isReady()) {
  22178. // Reset _currentRefreshId
  22179. this.resetRefreshCounter();
  22180. continue;
  22181. }
  22182. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22183. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22184. mesh._activate(sceneRenderId);
  22185. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22186. var subMesh = mesh.subMeshes[subIndex];
  22187. scene._activeIndices.addCount(subMesh.indexCount, false);
  22188. this._renderingManager.dispatch(subMesh);
  22189. }
  22190. }
  22191. }
  22192. }
  22193. if (this.isCube) {
  22194. for (var face = 0; face < 6; face++) {
  22195. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22196. scene.incrementRenderId();
  22197. scene.resetCachedMaterial();
  22198. }
  22199. }
  22200. else {
  22201. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22202. }
  22203. this.onAfterUnbindObservable.notifyObservers(this);
  22204. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22205. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22206. }
  22207. scene.resetCachedMaterial();
  22208. };
  22209. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22210. var scene = this.getScene();
  22211. var engine = scene.getEngine();
  22212. // Bind
  22213. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22214. if (this.isCube) {
  22215. engine.bindFramebuffer(this._texture, faceIndex);
  22216. }
  22217. else {
  22218. engine.bindFramebuffer(this._texture);
  22219. }
  22220. }
  22221. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22222. // Clear
  22223. if (this.onClearObservable.hasObservers()) {
  22224. this.onClearObservable.notifyObservers(engine);
  22225. }
  22226. else {
  22227. engine.clear(scene.clearColor, true, true);
  22228. }
  22229. if (!this._doNotChangeAspectRatio) {
  22230. scene.updateTransformMatrix(true);
  22231. }
  22232. // Render
  22233. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22234. if (useCameraPostProcess) {
  22235. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22236. }
  22237. if (!this._doNotChangeAspectRatio) {
  22238. scene.updateTransformMatrix(true);
  22239. }
  22240. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22241. // Dump ?
  22242. if (dumpForDebug) {
  22243. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22244. }
  22245. // Unbind
  22246. if (!this.isCube || faceIndex === 5) {
  22247. if (this.isCube) {
  22248. if (faceIndex === 5) {
  22249. engine.generateMipMapsForCubemap(this._texture);
  22250. }
  22251. }
  22252. engine.unBindFramebuffer(this._texture, this.isCube);
  22253. }
  22254. };
  22255. RenderTargetTexture.prototype.clone = function () {
  22256. var textureSize = this.getSize();
  22257. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22258. // Base texture
  22259. newTexture.hasAlpha = this.hasAlpha;
  22260. newTexture.level = this.level;
  22261. // RenderTarget Texture
  22262. newTexture.coordinatesMode = this.coordinatesMode;
  22263. newTexture.renderList = this.renderList.slice(0);
  22264. return newTexture;
  22265. };
  22266. RenderTargetTexture.prototype.serialize = function () {
  22267. if (!this.name) {
  22268. return null;
  22269. }
  22270. var serializationObject = _super.prototype.serialize.call(this);
  22271. serializationObject.renderTargetSize = this.getRenderSize();
  22272. serializationObject.renderList = [];
  22273. for (var index = 0; index < this.renderList.length; index++) {
  22274. serializationObject.renderList.push(this.renderList[index].id);
  22275. }
  22276. return serializationObject;
  22277. };
  22278. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22279. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22280. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22281. return RenderTargetTexture;
  22282. }(BABYLON.Texture));
  22283. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22284. })(BABYLON || (BABYLON = {}));
  22285. var BABYLON;
  22286. (function (BABYLON) {
  22287. var ProceduralTexture = (function (_super) {
  22288. __extends(ProceduralTexture, _super);
  22289. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22290. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22291. if (isCube === void 0) { isCube = false; }
  22292. _super.call(this, null, scene, !generateMipMaps);
  22293. this.isCube = isCube;
  22294. this.isEnabled = true;
  22295. this._currentRefreshId = -1;
  22296. this._refreshRate = 1;
  22297. this._vertexBuffers = {};
  22298. this._uniforms = new Array();
  22299. this._samplers = new Array();
  22300. this._textures = new Array();
  22301. this._floats = new Array();
  22302. this._floatsArrays = {};
  22303. this._colors3 = new Array();
  22304. this._colors4 = new Array();
  22305. this._vectors2 = new Array();
  22306. this._vectors3 = new Array();
  22307. this._matrices = new Array();
  22308. this._fallbackTextureUsed = false;
  22309. scene._proceduralTextures.push(this);
  22310. this.name = name;
  22311. this.isRenderTarget = true;
  22312. this._size = size;
  22313. this._generateMipMaps = generateMipMaps;
  22314. this.setFragment(fragment);
  22315. this._fallbackTexture = fallbackTexture;
  22316. var engine = scene.getEngine();
  22317. if (isCube) {
  22318. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22319. this.setFloat("face", 0);
  22320. }
  22321. else {
  22322. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22323. }
  22324. // VBO
  22325. var vertices = [];
  22326. vertices.push(1, 1);
  22327. vertices.push(-1, 1);
  22328. vertices.push(-1, -1);
  22329. vertices.push(1, -1);
  22330. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22331. // Indices
  22332. var indices = [];
  22333. indices.push(0);
  22334. indices.push(1);
  22335. indices.push(2);
  22336. indices.push(0);
  22337. indices.push(2);
  22338. indices.push(3);
  22339. this._indexBuffer = engine.createIndexBuffer(indices);
  22340. }
  22341. ProceduralTexture.prototype.reset = function () {
  22342. if (this._effect === undefined) {
  22343. return;
  22344. }
  22345. var engine = this.getScene().getEngine();
  22346. engine._releaseEffect(this._effect);
  22347. };
  22348. ProceduralTexture.prototype.isReady = function () {
  22349. var _this = this;
  22350. var engine = this.getScene().getEngine();
  22351. var shaders;
  22352. if (!this._fragment) {
  22353. return false;
  22354. }
  22355. if (this._fallbackTextureUsed) {
  22356. return true;
  22357. }
  22358. if (this._fragment.fragmentElement !== undefined) {
  22359. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22360. }
  22361. else {
  22362. shaders = { vertex: "procedural", fragment: this._fragment };
  22363. }
  22364. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22365. _this.releaseInternalTexture();
  22366. if (_this._fallbackTexture) {
  22367. _this._texture = _this._fallbackTexture._texture;
  22368. _this._texture.references++;
  22369. }
  22370. _this._fallbackTextureUsed = true;
  22371. });
  22372. return this._effect.isReady();
  22373. };
  22374. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22375. this._currentRefreshId = -1;
  22376. };
  22377. ProceduralTexture.prototype.setFragment = function (fragment) {
  22378. this._fragment = fragment;
  22379. };
  22380. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22381. get: function () {
  22382. return this._refreshRate;
  22383. },
  22384. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22385. set: function (value) {
  22386. this._refreshRate = value;
  22387. this.resetRefreshCounter();
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. ProceduralTexture.prototype._shouldRender = function () {
  22393. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22394. return false;
  22395. }
  22396. if (this._fallbackTextureUsed) {
  22397. return false;
  22398. }
  22399. if (this._currentRefreshId === -1) {
  22400. this._currentRefreshId = 1;
  22401. return true;
  22402. }
  22403. if (this.refreshRate === this._currentRefreshId) {
  22404. this._currentRefreshId = 1;
  22405. return true;
  22406. }
  22407. this._currentRefreshId++;
  22408. return false;
  22409. };
  22410. ProceduralTexture.prototype.getRenderSize = function () {
  22411. return this._size;
  22412. };
  22413. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22414. if (this._fallbackTextureUsed) {
  22415. return;
  22416. }
  22417. this.releaseInternalTexture();
  22418. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22419. };
  22420. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22421. if (this._uniforms.indexOf(uniformName) === -1) {
  22422. this._uniforms.push(uniformName);
  22423. }
  22424. };
  22425. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22426. if (this._samplers.indexOf(name) === -1) {
  22427. this._samplers.push(name);
  22428. }
  22429. this._textures[name] = texture;
  22430. return this;
  22431. };
  22432. ProceduralTexture.prototype.setFloat = function (name, value) {
  22433. this._checkUniform(name);
  22434. this._floats[name] = value;
  22435. return this;
  22436. };
  22437. ProceduralTexture.prototype.setFloats = function (name, value) {
  22438. this._checkUniform(name);
  22439. this._floatsArrays[name] = value;
  22440. return this;
  22441. };
  22442. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22443. this._checkUniform(name);
  22444. this._colors3[name] = value;
  22445. return this;
  22446. };
  22447. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22448. this._checkUniform(name);
  22449. this._colors4[name] = value;
  22450. return this;
  22451. };
  22452. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22453. this._checkUniform(name);
  22454. this._vectors2[name] = value;
  22455. return this;
  22456. };
  22457. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22458. this._checkUniform(name);
  22459. this._vectors3[name] = value;
  22460. return this;
  22461. };
  22462. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22463. this._checkUniform(name);
  22464. this._matrices[name] = value;
  22465. return this;
  22466. };
  22467. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22468. var scene = this.getScene();
  22469. var engine = scene.getEngine();
  22470. // Render
  22471. engine.enableEffect(this._effect);
  22472. engine.setState(false);
  22473. // Texture
  22474. for (var name in this._textures) {
  22475. this._effect.setTexture(name, this._textures[name]);
  22476. }
  22477. // Float
  22478. for (name in this._floats) {
  22479. this._effect.setFloat(name, this._floats[name]);
  22480. }
  22481. // Floats
  22482. for (name in this._floatsArrays) {
  22483. this._effect.setArray(name, this._floatsArrays[name]);
  22484. }
  22485. // Color3
  22486. for (name in this._colors3) {
  22487. this._effect.setColor3(name, this._colors3[name]);
  22488. }
  22489. // Color4
  22490. for (name in this._colors4) {
  22491. var color = this._colors4[name];
  22492. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22493. }
  22494. // Vector2
  22495. for (name in this._vectors2) {
  22496. this._effect.setVector2(name, this._vectors2[name]);
  22497. }
  22498. // Vector3
  22499. for (name in this._vectors3) {
  22500. this._effect.setVector3(name, this._vectors3[name]);
  22501. }
  22502. // Matrix
  22503. for (name in this._matrices) {
  22504. this._effect.setMatrix(name, this._matrices[name]);
  22505. }
  22506. // VBOs
  22507. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22508. if (this.isCube) {
  22509. for (var face = 0; face < 6; face++) {
  22510. engine.bindFramebuffer(this._texture, face);
  22511. this._effect.setFloat("face", face);
  22512. // Clear
  22513. engine.clear(scene.clearColor, true, true);
  22514. // Draw order
  22515. engine.draw(true, 0, 6);
  22516. // Mipmaps
  22517. if (face === 5) {
  22518. engine.generateMipMapsForCubemap(this._texture);
  22519. }
  22520. }
  22521. }
  22522. else {
  22523. engine.bindFramebuffer(this._texture);
  22524. // Clear
  22525. engine.clear(scene.clearColor, true, true);
  22526. // Draw order
  22527. engine.draw(true, 0, 6);
  22528. }
  22529. // Unbind
  22530. engine.unBindFramebuffer(this._texture, this.isCube);
  22531. if (this.onGenerated) {
  22532. this.onGenerated();
  22533. }
  22534. };
  22535. ProceduralTexture.prototype.clone = function () {
  22536. var textureSize = this.getSize();
  22537. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22538. // Base texture
  22539. newTexture.hasAlpha = this.hasAlpha;
  22540. newTexture.level = this.level;
  22541. // RenderTarget Texture
  22542. newTexture.coordinatesMode = this.coordinatesMode;
  22543. return newTexture;
  22544. };
  22545. ProceduralTexture.prototype.dispose = function () {
  22546. var index = this.getScene()._proceduralTextures.indexOf(this);
  22547. if (index >= 0) {
  22548. this.getScene()._proceduralTextures.splice(index, 1);
  22549. }
  22550. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22551. if (vertexBuffer) {
  22552. vertexBuffer.dispose();
  22553. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22554. }
  22555. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22556. this._indexBuffer = null;
  22557. }
  22558. _super.prototype.dispose.call(this);
  22559. };
  22560. return ProceduralTexture;
  22561. }(BABYLON.Texture));
  22562. BABYLON.ProceduralTexture = ProceduralTexture;
  22563. })(BABYLON || (BABYLON = {}));
  22564. var BABYLON;
  22565. (function (BABYLON) {
  22566. var MirrorTexture = (function (_super) {
  22567. __extends(MirrorTexture, _super);
  22568. function MirrorTexture(name, size, scene, generateMipMaps) {
  22569. var _this = this;
  22570. _super.call(this, name, size, scene, generateMipMaps, true);
  22571. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22572. this._transformMatrix = BABYLON.Matrix.Zero();
  22573. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22574. this.onBeforeRenderObservable.add(function () {
  22575. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22576. _this._savedViewMatrix = scene.getViewMatrix();
  22577. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22578. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22579. scene.clipPlane = _this.mirrorPlane;
  22580. scene.getEngine().cullBackFaces = false;
  22581. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22582. });
  22583. this.onAfterRenderObservable.add(function () {
  22584. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22585. scene.getEngine().cullBackFaces = true;
  22586. scene._mirroredCameraPosition = null;
  22587. delete scene.clipPlane;
  22588. });
  22589. }
  22590. MirrorTexture.prototype.clone = function () {
  22591. var textureSize = this.getSize();
  22592. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22593. // Base texture
  22594. newTexture.hasAlpha = this.hasAlpha;
  22595. newTexture.level = this.level;
  22596. // Mirror Texture
  22597. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22598. newTexture.renderList = this.renderList.slice(0);
  22599. return newTexture;
  22600. };
  22601. MirrorTexture.prototype.serialize = function () {
  22602. if (!this.name) {
  22603. return null;
  22604. }
  22605. var serializationObject = _super.prototype.serialize.call(this);
  22606. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22607. return serializationObject;
  22608. };
  22609. return MirrorTexture;
  22610. }(BABYLON.RenderTargetTexture));
  22611. BABYLON.MirrorTexture = MirrorTexture;
  22612. })(BABYLON || (BABYLON = {}));
  22613. var BABYLON;
  22614. (function (BABYLON) {
  22615. /**
  22616. * Creates a refraction texture used by refraction channel of the standard material.
  22617. * @param name the texture name
  22618. * @param size size of the underlying texture
  22619. * @param scene root scene
  22620. */
  22621. var RefractionTexture = (function (_super) {
  22622. __extends(RefractionTexture, _super);
  22623. function RefractionTexture(name, size, scene, generateMipMaps) {
  22624. var _this = this;
  22625. _super.call(this, name, size, scene, generateMipMaps, true);
  22626. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22627. this.depth = 2.0;
  22628. this.onBeforeRenderObservable.add(function () {
  22629. scene.clipPlane = _this.refractionPlane;
  22630. });
  22631. this.onAfterRenderObservable.add(function () {
  22632. delete scene.clipPlane;
  22633. });
  22634. }
  22635. RefractionTexture.prototype.clone = function () {
  22636. var textureSize = this.getSize();
  22637. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22638. // Base texture
  22639. newTexture.hasAlpha = this.hasAlpha;
  22640. newTexture.level = this.level;
  22641. // Refraction Texture
  22642. newTexture.refractionPlane = this.refractionPlane.clone();
  22643. newTexture.renderList = this.renderList.slice(0);
  22644. newTexture.depth = this.depth;
  22645. return newTexture;
  22646. };
  22647. RefractionTexture.prototype.serialize = function () {
  22648. if (!this.name) {
  22649. return null;
  22650. }
  22651. var serializationObject = _super.prototype.serialize.call(this);
  22652. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22653. serializationObject.depth = this.depth;
  22654. return serializationObject;
  22655. };
  22656. return RefractionTexture;
  22657. }(BABYLON.RenderTargetTexture));
  22658. BABYLON.RefractionTexture = RefractionTexture;
  22659. })(BABYLON || (BABYLON = {}));
  22660. var BABYLON;
  22661. (function (BABYLON) {
  22662. var DynamicTexture = (function (_super) {
  22663. __extends(DynamicTexture, _super);
  22664. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22666. _super.call(this, null, scene, !generateMipMaps);
  22667. this.name = name;
  22668. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22669. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22670. this._generateMipMaps = generateMipMaps;
  22671. if (options.getContext) {
  22672. this._canvas = options;
  22673. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22674. }
  22675. else {
  22676. this._canvas = document.createElement("canvas");
  22677. if (options.width) {
  22678. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22679. }
  22680. else {
  22681. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22682. }
  22683. }
  22684. var textureSize = this.getSize();
  22685. this._canvas.width = textureSize.width;
  22686. this._canvas.height = textureSize.height;
  22687. this._context = this._canvas.getContext("2d");
  22688. }
  22689. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22690. get: function () {
  22691. return true;
  22692. },
  22693. enumerable: true,
  22694. configurable: true
  22695. });
  22696. DynamicTexture.prototype.scale = function (ratio) {
  22697. var textureSize = this.getSize();
  22698. textureSize.width *= ratio;
  22699. textureSize.height *= ratio;
  22700. this._canvas.width = textureSize.width;
  22701. this._canvas.height = textureSize.height;
  22702. this.releaseInternalTexture();
  22703. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22704. };
  22705. DynamicTexture.prototype.getContext = function () {
  22706. return this._context;
  22707. };
  22708. DynamicTexture.prototype.clear = function () {
  22709. var size = this.getSize();
  22710. this._context.fillRect(0, 0, size.width, size.height);
  22711. };
  22712. DynamicTexture.prototype.update = function (invertY) {
  22713. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22714. };
  22715. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22716. if (update === void 0) { update = true; }
  22717. var size = this.getSize();
  22718. if (clearColor) {
  22719. this._context.fillStyle = clearColor;
  22720. this._context.fillRect(0, 0, size.width, size.height);
  22721. }
  22722. this._context.font = font;
  22723. if (x === null) {
  22724. var textSize = this._context.measureText(text);
  22725. x = (size.width - textSize.width) / 2;
  22726. }
  22727. this._context.fillStyle = color;
  22728. this._context.fillText(text, x, y);
  22729. if (update) {
  22730. this.update(invertY);
  22731. }
  22732. };
  22733. DynamicTexture.prototype.clone = function () {
  22734. var textureSize = this.getSize();
  22735. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22736. // Base texture
  22737. newTexture.hasAlpha = this.hasAlpha;
  22738. newTexture.level = this.level;
  22739. // Dynamic Texture
  22740. newTexture.wrapU = this.wrapU;
  22741. newTexture.wrapV = this.wrapV;
  22742. return newTexture;
  22743. };
  22744. return DynamicTexture;
  22745. }(BABYLON.Texture));
  22746. BABYLON.DynamicTexture = DynamicTexture;
  22747. })(BABYLON || (BABYLON = {}));
  22748. var BABYLON;
  22749. (function (BABYLON) {
  22750. var VideoTexture = (function (_super) {
  22751. __extends(VideoTexture, _super);
  22752. /**
  22753. * Creates a video texture.
  22754. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22755. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22756. * @param {BABYLON.Scene} scene is obviously the current scene.
  22757. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22758. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22759. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22760. */
  22761. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22762. var _this = this;
  22763. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22764. if (invertY === void 0) { invertY = false; }
  22765. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22766. _super.call(this, null, scene, !generateMipMaps, invertY);
  22767. this._autoLaunch = true;
  22768. var urls;
  22769. this.name = name;
  22770. if (urlsOrVideo instanceof HTMLVideoElement) {
  22771. this.video = urlsOrVideo;
  22772. }
  22773. else {
  22774. urls = urlsOrVideo;
  22775. this.video = document.createElement("video");
  22776. this.video.autoplay = false;
  22777. this.video.loop = true;
  22778. }
  22779. this._generateMipMaps = generateMipMaps;
  22780. this._samplingMode = samplingMode;
  22781. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22782. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22783. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22784. }
  22785. else {
  22786. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22787. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22788. this._generateMipMaps = false;
  22789. }
  22790. if (urls) {
  22791. this.video.addEventListener("canplaythrough", function () {
  22792. _this._createTexture();
  22793. });
  22794. urls.forEach(function (url) {
  22795. var source = document.createElement("source");
  22796. source.src = url;
  22797. _this.video.appendChild(source);
  22798. });
  22799. }
  22800. else {
  22801. this._createTexture();
  22802. }
  22803. this._lastUpdate = BABYLON.Tools.Now;
  22804. }
  22805. VideoTexture.prototype._createTexture = function () {
  22806. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22807. this._texture.isReady = true;
  22808. };
  22809. VideoTexture.prototype.update = function () {
  22810. if (this._autoLaunch) {
  22811. this._autoLaunch = false;
  22812. this.video.play();
  22813. }
  22814. var now = BABYLON.Tools.Now;
  22815. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22816. return false;
  22817. }
  22818. this._lastUpdate = now;
  22819. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22820. return true;
  22821. };
  22822. return VideoTexture;
  22823. }(BABYLON.Texture));
  22824. BABYLON.VideoTexture = VideoTexture;
  22825. })(BABYLON || (BABYLON = {}));
  22826. var BABYLON;
  22827. (function (BABYLON) {
  22828. var CustomProceduralTexture = (function (_super) {
  22829. __extends(CustomProceduralTexture, _super);
  22830. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22831. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22832. this._animate = true;
  22833. this._time = 0;
  22834. this._texturePath = texturePath;
  22835. //Try to load json
  22836. this.loadJson(texturePath);
  22837. this.refreshRate = 1;
  22838. }
  22839. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22840. var _this = this;
  22841. var that = this;
  22842. function noConfigFile() {
  22843. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22844. try {
  22845. that.setFragment(that._texturePath);
  22846. }
  22847. catch (ex) {
  22848. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22849. }
  22850. }
  22851. var configFileUrl = jsonUrl + "/config.json";
  22852. var xhr = new XMLHttpRequest();
  22853. xhr.open("GET", configFileUrl, true);
  22854. xhr.addEventListener("load", function () {
  22855. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22856. try {
  22857. _this._config = JSON.parse(xhr.response);
  22858. _this.updateShaderUniforms();
  22859. _this.updateTextures();
  22860. _this.setFragment(_this._texturePath + "/custom");
  22861. _this._animate = _this._config.animate;
  22862. _this.refreshRate = _this._config.refreshrate;
  22863. }
  22864. catch (ex) {
  22865. noConfigFile();
  22866. }
  22867. }
  22868. else {
  22869. noConfigFile();
  22870. }
  22871. }, false);
  22872. xhr.addEventListener("error", function () {
  22873. noConfigFile();
  22874. }, false);
  22875. try {
  22876. xhr.send();
  22877. }
  22878. catch (ex) {
  22879. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22880. }
  22881. };
  22882. CustomProceduralTexture.prototype.isReady = function () {
  22883. if (!_super.prototype.isReady.call(this)) {
  22884. return false;
  22885. }
  22886. for (var name in this._textures) {
  22887. var texture = this._textures[name];
  22888. if (!texture.isReady()) {
  22889. return false;
  22890. }
  22891. }
  22892. return true;
  22893. };
  22894. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22895. if (this._animate) {
  22896. this._time += this.getScene().getAnimationRatio() * 0.03;
  22897. this.updateShaderUniforms();
  22898. }
  22899. _super.prototype.render.call(this, useCameraPostProcess);
  22900. };
  22901. CustomProceduralTexture.prototype.updateTextures = function () {
  22902. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22903. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22904. }
  22905. };
  22906. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22907. if (this._config) {
  22908. for (var j = 0; j < this._config.uniforms.length; j++) {
  22909. var uniform = this._config.uniforms[j];
  22910. switch (uniform.type) {
  22911. case "float":
  22912. this.setFloat(uniform.name, uniform.value);
  22913. break;
  22914. case "color3":
  22915. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22916. break;
  22917. case "color4":
  22918. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22919. break;
  22920. case "vector2":
  22921. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22922. break;
  22923. case "vector3":
  22924. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22925. break;
  22926. }
  22927. }
  22928. }
  22929. this.setFloat("time", this._time);
  22930. };
  22931. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22932. get: function () {
  22933. return this._animate;
  22934. },
  22935. set: function (value) {
  22936. this._animate = value;
  22937. },
  22938. enumerable: true,
  22939. configurable: true
  22940. });
  22941. return CustomProceduralTexture;
  22942. }(BABYLON.ProceduralTexture));
  22943. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22944. })(BABYLON || (BABYLON = {}));
  22945. var BABYLON;
  22946. (function (BABYLON) {
  22947. var EffectFallbacks = (function () {
  22948. function EffectFallbacks() {
  22949. this._defines = {};
  22950. this._currentRank = 32;
  22951. this._maxRank = -1;
  22952. }
  22953. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22954. if (!this._defines[rank]) {
  22955. if (rank < this._currentRank) {
  22956. this._currentRank = rank;
  22957. }
  22958. if (rank > this._maxRank) {
  22959. this._maxRank = rank;
  22960. }
  22961. this._defines[rank] = new Array();
  22962. }
  22963. this._defines[rank].push(define);
  22964. };
  22965. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22966. this._meshRank = rank;
  22967. this._mesh = mesh;
  22968. if (rank > this._maxRank) {
  22969. this._maxRank = rank;
  22970. }
  22971. };
  22972. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22973. get: function () {
  22974. return this._currentRank <= this._maxRank;
  22975. },
  22976. enumerable: true,
  22977. configurable: true
  22978. });
  22979. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22980. var currentFallbacks = this._defines[this._currentRank];
  22981. for (var index = 0; index < currentFallbacks.length; index++) {
  22982. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22983. }
  22984. if (this._mesh && this._currentRank === this._meshRank) {
  22985. this._mesh.computeBonesUsingShaders = false;
  22986. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22987. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22988. }
  22989. this._currentRank++;
  22990. return currentDefines;
  22991. };
  22992. return EffectFallbacks;
  22993. }());
  22994. BABYLON.EffectFallbacks = EffectFallbacks;
  22995. var Effect = (function () {
  22996. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22997. var _this = this;
  22998. this._isReady = false;
  22999. this._compilationError = "";
  23000. this._valueCache = {};
  23001. this._engine = engine;
  23002. this.name = baseName;
  23003. this.defines = defines;
  23004. this._uniformsNames = uniformsNames.concat(samplers);
  23005. this._samplers = samplers;
  23006. this._attributesNames = attributesNames;
  23007. this.onError = onError;
  23008. this.onCompiled = onCompiled;
  23009. this._indexParameters = indexParameters;
  23010. var vertexSource;
  23011. var fragmentSource;
  23012. if (baseName.vertexElement) {
  23013. vertexSource = document.getElementById(baseName.vertexElement);
  23014. if (!vertexSource) {
  23015. vertexSource = baseName.vertexElement;
  23016. }
  23017. }
  23018. else {
  23019. vertexSource = baseName.vertex || baseName;
  23020. }
  23021. if (baseName.fragmentElement) {
  23022. fragmentSource = document.getElementById(baseName.fragmentElement);
  23023. if (!fragmentSource) {
  23024. fragmentSource = baseName.fragmentElement;
  23025. }
  23026. }
  23027. else {
  23028. fragmentSource = baseName.fragment || baseName;
  23029. }
  23030. this._loadVertexShader(vertexSource, function (vertexCode) {
  23031. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23032. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23033. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23034. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23035. });
  23036. });
  23037. });
  23038. });
  23039. }
  23040. // Properties
  23041. Effect.prototype.isReady = function () {
  23042. return this._isReady;
  23043. };
  23044. Effect.prototype.getProgram = function () {
  23045. return this._program;
  23046. };
  23047. Effect.prototype.getAttributesNames = function () {
  23048. return this._attributesNames;
  23049. };
  23050. Effect.prototype.getAttributeLocation = function (index) {
  23051. return this._attributes[index];
  23052. };
  23053. Effect.prototype.getAttributeLocationByName = function (name) {
  23054. var index = this._attributesNames.indexOf(name);
  23055. return this._attributes[index];
  23056. };
  23057. Effect.prototype.getAttributesCount = function () {
  23058. return this._attributes.length;
  23059. };
  23060. Effect.prototype.getUniformIndex = function (uniformName) {
  23061. return this._uniformsNames.indexOf(uniformName);
  23062. };
  23063. Effect.prototype.getUniform = function (uniformName) {
  23064. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23065. };
  23066. Effect.prototype.getSamplers = function () {
  23067. return this._samplers;
  23068. };
  23069. Effect.prototype.getCompilationError = function () {
  23070. return this._compilationError;
  23071. };
  23072. // Methods
  23073. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23074. // DOM element ?
  23075. if (vertex instanceof HTMLElement) {
  23076. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23077. callback(vertexCode);
  23078. return;
  23079. }
  23080. // Is in local store ?
  23081. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23082. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23083. return;
  23084. }
  23085. var vertexShaderUrl;
  23086. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23087. vertexShaderUrl = vertex;
  23088. }
  23089. else {
  23090. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23091. }
  23092. // Vertex shader
  23093. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23094. };
  23095. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23096. // DOM element ?
  23097. if (fragment instanceof HTMLElement) {
  23098. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23099. callback(fragmentCode);
  23100. return;
  23101. }
  23102. // Is in local store ?
  23103. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23104. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23105. return;
  23106. }
  23107. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23108. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23109. return;
  23110. }
  23111. var fragmentShaderUrl;
  23112. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23113. fragmentShaderUrl = fragment;
  23114. }
  23115. else {
  23116. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23117. }
  23118. // Fragment shader
  23119. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23120. };
  23121. Effect.prototype._dumpShadersName = function () {
  23122. if (this.name.vertexElement) {
  23123. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23124. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23125. }
  23126. else if (this.name.vertex) {
  23127. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23128. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23129. }
  23130. else {
  23131. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23132. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23133. }
  23134. };
  23135. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23136. var _this = this;
  23137. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23138. var match = regex.exec(sourceCode);
  23139. var returnValue = new String(sourceCode);
  23140. while (match != null) {
  23141. var includeFile = match[1];
  23142. if (Effect.IncludesShadersStore[includeFile]) {
  23143. // Substitution
  23144. var includeContent = Effect.IncludesShadersStore[includeFile];
  23145. if (match[2]) {
  23146. var splits = match[3].split(",");
  23147. for (var index = 0; index < splits.length; index += 2) {
  23148. var source = new RegExp(splits[index], "g");
  23149. var dest = splits[index + 1];
  23150. includeContent = includeContent.replace(source, dest);
  23151. }
  23152. }
  23153. if (match[4]) {
  23154. var indexString = match[5];
  23155. if (indexString.indexOf("..") !== -1) {
  23156. var indexSplits = indexString.split("..");
  23157. var minIndex = parseInt(indexSplits[0]);
  23158. var maxIndex = parseInt(indexSplits[1]);
  23159. var sourceIncludeContent = includeContent.slice(0);
  23160. includeContent = "";
  23161. if (isNaN(maxIndex)) {
  23162. maxIndex = this._indexParameters[indexSplits[1]];
  23163. }
  23164. for (var i = minIndex; i <= maxIndex; i++) {
  23165. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23166. }
  23167. }
  23168. else {
  23169. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23170. }
  23171. }
  23172. // Replace
  23173. returnValue = returnValue.replace(match[0], includeContent);
  23174. }
  23175. else {
  23176. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23177. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23178. Effect.IncludesShadersStore[includeFile] = fileContent;
  23179. _this._processIncludes(returnValue, callback);
  23180. });
  23181. return;
  23182. }
  23183. match = regex.exec(sourceCode);
  23184. }
  23185. callback(returnValue);
  23186. };
  23187. Effect.prototype._processPrecision = function (source) {
  23188. if (source.indexOf("precision highp float") === -1) {
  23189. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23190. source = "precision mediump float;\n" + source;
  23191. }
  23192. else {
  23193. source = "precision highp float;\n" + source;
  23194. }
  23195. }
  23196. else {
  23197. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23198. source = source.replace("precision highp float", "precision mediump float");
  23199. }
  23200. }
  23201. return source;
  23202. };
  23203. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23204. try {
  23205. var engine = this._engine;
  23206. // Precision
  23207. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23208. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23209. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23210. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23211. this._attributes = engine.getAttributes(this._program, attributesNames);
  23212. var index;
  23213. for (index = 0; index < this._samplers.length; index++) {
  23214. var sampler = this.getUniform(this._samplers[index]);
  23215. if (sampler == null) {
  23216. this._samplers.splice(index, 1);
  23217. index--;
  23218. }
  23219. }
  23220. engine.bindSamplers(this);
  23221. this._isReady = true;
  23222. if (this.onCompiled) {
  23223. this.onCompiled(this);
  23224. }
  23225. }
  23226. catch (e) {
  23227. // Let's go through fallbacks then
  23228. if (fallbacks && fallbacks.isMoreFallbacks) {
  23229. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23230. this._dumpShadersName();
  23231. defines = fallbacks.reduce(defines);
  23232. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23233. }
  23234. else {
  23235. BABYLON.Tools.Error("Unable to compile effect: ");
  23236. this._dumpShadersName();
  23237. BABYLON.Tools.Error("Defines: " + defines);
  23238. BABYLON.Tools.Error("Error: " + e.message);
  23239. this._compilationError = e.message;
  23240. if (this.onError) {
  23241. this.onError(this, this._compilationError);
  23242. }
  23243. }
  23244. }
  23245. };
  23246. Object.defineProperty(Effect.prototype, "isSupported", {
  23247. get: function () {
  23248. return this._compilationError === "";
  23249. },
  23250. enumerable: true,
  23251. configurable: true
  23252. });
  23253. Effect.prototype._bindTexture = function (channel, texture) {
  23254. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23255. };
  23256. Effect.prototype.setTexture = function (channel, texture) {
  23257. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23258. };
  23259. Effect.prototype.setTextureArray = function (channel, textures) {
  23260. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23261. var initialPos = this._samplers.indexOf(channel);
  23262. for (var index = 1; index < textures.length; index++) {
  23263. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23264. }
  23265. }
  23266. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23267. };
  23268. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23269. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23270. };
  23271. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23272. var changed = false;
  23273. var cache = this._valueCache[uniformName];
  23274. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23275. changed = true;
  23276. cache = new BABYLON.Matrix();
  23277. }
  23278. var tm = cache.m;
  23279. var om = matrix.m;
  23280. for (var index = 0; index < 16; index++) {
  23281. if (tm[index] !== om[index]) {
  23282. tm[index] = om[index];
  23283. changed = true;
  23284. }
  23285. }
  23286. this._valueCache[uniformName] = cache;
  23287. return changed;
  23288. };
  23289. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23290. var cache = this._valueCache[uniformName];
  23291. if (!cache) {
  23292. cache = [x, y];
  23293. this._valueCache[uniformName] = cache;
  23294. return true;
  23295. }
  23296. var changed = false;
  23297. if (cache[0] !== x) {
  23298. cache[0] = x;
  23299. changed = true;
  23300. }
  23301. if (cache[1] !== y) {
  23302. cache[1] = y;
  23303. changed = true;
  23304. }
  23305. return changed;
  23306. };
  23307. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23308. var cache = this._valueCache[uniformName];
  23309. if (!cache) {
  23310. cache = [x, y, z];
  23311. this._valueCache[uniformName] = cache;
  23312. return true;
  23313. }
  23314. var changed = false;
  23315. if (cache[0] !== x) {
  23316. cache[0] = x;
  23317. changed = true;
  23318. }
  23319. if (cache[1] !== y) {
  23320. cache[1] = y;
  23321. changed = true;
  23322. }
  23323. if (cache[2] !== z) {
  23324. cache[2] = z;
  23325. changed = true;
  23326. }
  23327. return changed;
  23328. };
  23329. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23330. var cache = this._valueCache[uniformName];
  23331. if (!cache) {
  23332. cache = [x, y, z, w];
  23333. this._valueCache[uniformName] = cache;
  23334. return true;
  23335. }
  23336. var changed = false;
  23337. if (cache[0] !== x) {
  23338. cache[0] = x;
  23339. changed = true;
  23340. }
  23341. if (cache[1] !== y) {
  23342. cache[1] = y;
  23343. changed = true;
  23344. }
  23345. if (cache[2] !== z) {
  23346. cache[2] = z;
  23347. changed = true;
  23348. }
  23349. if (cache[3] !== w) {
  23350. cache[3] = w;
  23351. changed = true;
  23352. }
  23353. return changed;
  23354. };
  23355. Effect.prototype.setArray = function (uniformName, array) {
  23356. this._valueCache[uniformName] = null;
  23357. this._engine.setArray(this.getUniform(uniformName), array);
  23358. return this;
  23359. };
  23360. Effect.prototype.setArray2 = function (uniformName, array) {
  23361. this._valueCache[uniformName] = null;
  23362. this._engine.setArray2(this.getUniform(uniformName), array);
  23363. return this;
  23364. };
  23365. Effect.prototype.setArray3 = function (uniformName, array) {
  23366. this._valueCache[uniformName] = null;
  23367. this._engine.setArray3(this.getUniform(uniformName), array);
  23368. return this;
  23369. };
  23370. Effect.prototype.setArray4 = function (uniformName, array) {
  23371. this._valueCache[uniformName] = null;
  23372. this._engine.setArray4(this.getUniform(uniformName), array);
  23373. return this;
  23374. };
  23375. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23376. this._valueCache[uniformName] = null;
  23377. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23378. return this;
  23379. };
  23380. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23381. if (this._cacheMatrix(uniformName, matrix)) {
  23382. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23383. }
  23384. return this;
  23385. };
  23386. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23387. this._valueCache[uniformName] = null;
  23388. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23389. return this;
  23390. };
  23391. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23392. this._valueCache[uniformName] = null;
  23393. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23394. return this;
  23395. };
  23396. Effect.prototype.setFloat = function (uniformName, value) {
  23397. var cache = this._valueCache[uniformName];
  23398. if (cache !== undefined && cache === value)
  23399. return this;
  23400. this._valueCache[uniformName] = value;
  23401. this._engine.setFloat(this.getUniform(uniformName), value);
  23402. return this;
  23403. };
  23404. Effect.prototype.setBool = function (uniformName, bool) {
  23405. var cache = this._valueCache[uniformName];
  23406. if (cache !== undefined && cache === bool)
  23407. return this;
  23408. this._valueCache[uniformName] = bool;
  23409. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23410. return this;
  23411. };
  23412. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23413. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23414. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23415. }
  23416. return this;
  23417. };
  23418. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23419. if (this._cacheFloat2(uniformName, x, y)) {
  23420. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23421. }
  23422. return this;
  23423. };
  23424. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23425. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23426. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23427. }
  23428. return this;
  23429. };
  23430. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23431. if (this._cacheFloat3(uniformName, x, y, z)) {
  23432. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23433. }
  23434. return this;
  23435. };
  23436. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23437. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23438. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23439. }
  23440. return this;
  23441. };
  23442. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23443. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23444. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23445. }
  23446. return this;
  23447. };
  23448. Effect.prototype.setColor3 = function (uniformName, color3) {
  23449. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23450. this._engine.setColor3(this.getUniform(uniformName), color3);
  23451. }
  23452. return this;
  23453. };
  23454. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23455. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23456. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23457. }
  23458. return this;
  23459. };
  23460. // Statics
  23461. Effect.ShadersStore = {};
  23462. Effect.IncludesShadersStore = {};
  23463. return Effect;
  23464. }());
  23465. BABYLON.Effect = Effect;
  23466. })(BABYLON || (BABYLON = {}));
  23467. var BABYLON;
  23468. (function (BABYLON) {
  23469. var MaterialHelper = (function () {
  23470. function MaterialHelper() {
  23471. }
  23472. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23473. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23474. var lightIndex = 0;
  23475. var needNormals = false;
  23476. var needRebuild = false;
  23477. var needShadows = false;
  23478. for (var index = 0; index < scene.lights.length; index++) {
  23479. var light = scene.lights[index];
  23480. if (!light.isEnabled()) {
  23481. continue;
  23482. }
  23483. // Excluded check
  23484. if (light._excludedMeshesIds.length > 0) {
  23485. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23486. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23487. if (excludedMesh) {
  23488. light.excludedMeshes.push(excludedMesh);
  23489. }
  23490. }
  23491. light._excludedMeshesIds = [];
  23492. }
  23493. // Included check
  23494. if (light._includedOnlyMeshesIds.length > 0) {
  23495. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23496. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23497. if (includedOnlyMesh) {
  23498. light.includedOnlyMeshes.push(includedOnlyMesh);
  23499. }
  23500. }
  23501. light._includedOnlyMeshesIds = [];
  23502. }
  23503. if (!light.canAffectMesh(mesh)) {
  23504. continue;
  23505. }
  23506. needNormals = true;
  23507. if (defines["LIGHT" + lightIndex] === undefined) {
  23508. needRebuild = true;
  23509. }
  23510. defines["LIGHT" + lightIndex] = true;
  23511. var type;
  23512. if (light instanceof BABYLON.SpotLight) {
  23513. type = "SPOTLIGHT" + lightIndex;
  23514. }
  23515. else if (light instanceof BABYLON.HemisphericLight) {
  23516. type = "HEMILIGHT" + lightIndex;
  23517. }
  23518. else if (light instanceof BABYLON.PointLight) {
  23519. type = "POINTLIGHT" + lightIndex;
  23520. }
  23521. else {
  23522. type = "DIRLIGHT" + lightIndex;
  23523. }
  23524. if (defines[type] === undefined) {
  23525. needRebuild = true;
  23526. }
  23527. defines[type] = true;
  23528. // Specular
  23529. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23530. defines["SPECULARTERM"] = true;
  23531. }
  23532. // Shadows
  23533. if (scene.shadowsEnabled) {
  23534. var shadowGenerator = light.getShadowGenerator();
  23535. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23536. if (defines["SHADOW" + lightIndex] === undefined) {
  23537. needRebuild = true;
  23538. }
  23539. defines["SHADOW" + lightIndex] = true;
  23540. defines["SHADOWS"] = true;
  23541. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23542. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23543. needRebuild = true;
  23544. }
  23545. defines["SHADOWVSM" + lightIndex] = true;
  23546. }
  23547. if (shadowGenerator.usePoissonSampling) {
  23548. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23549. needRebuild = true;
  23550. }
  23551. defines["SHADOWPCF" + lightIndex] = true;
  23552. }
  23553. needShadows = true;
  23554. }
  23555. }
  23556. lightIndex++;
  23557. if (lightIndex === maxSimultaneousLights)
  23558. break;
  23559. }
  23560. var caps = scene.getEngine().getCaps();
  23561. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  23562. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23563. needRebuild = true;
  23564. }
  23565. defines["SHADOWFULLFLOAT"] = true;
  23566. }
  23567. if (needRebuild) {
  23568. defines.rebuild();
  23569. }
  23570. return needNormals;
  23571. };
  23572. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23573. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23574. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23575. if (!defines["LIGHT" + lightIndex]) {
  23576. break;
  23577. }
  23578. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23579. samplersList.push("shadowSampler" + lightIndex);
  23580. }
  23581. };
  23582. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23583. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23584. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23585. if (!defines["LIGHT" + lightIndex]) {
  23586. break;
  23587. }
  23588. if (lightIndex > 0) {
  23589. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23590. }
  23591. if (defines["SHADOW" + lightIndex]) {
  23592. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23593. }
  23594. if (defines["SHADOWPCF" + lightIndex]) {
  23595. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23596. }
  23597. if (defines["SHADOWVSM" + lightIndex]) {
  23598. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23599. }
  23600. }
  23601. };
  23602. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23603. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23604. fallbacks.addCPUSkinningFallback(0, mesh);
  23605. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23606. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23607. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23608. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23609. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23610. }
  23611. }
  23612. };
  23613. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23614. if (defines["INSTANCES"]) {
  23615. attribs.push("world0");
  23616. attribs.push("world1");
  23617. attribs.push("world2");
  23618. attribs.push("world3");
  23619. }
  23620. };
  23621. // Bindings
  23622. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23623. var shadowGenerator = light.getShadowGenerator();
  23624. if (mesh.receiveShadows && shadowGenerator) {
  23625. if (!light.needCube()) {
  23626. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23627. }
  23628. else {
  23629. if (!depthValuesAlreadySet) {
  23630. depthValuesAlreadySet = true;
  23631. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23632. }
  23633. }
  23634. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23635. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23636. }
  23637. return depthValuesAlreadySet;
  23638. };
  23639. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23640. if (light instanceof BABYLON.PointLight) {
  23641. // Point Light
  23642. light.transferToEffect(effect, "vLightData" + lightIndex);
  23643. }
  23644. else if (light instanceof BABYLON.DirectionalLight) {
  23645. // Directional Light
  23646. light.transferToEffect(effect, "vLightData" + lightIndex);
  23647. }
  23648. else if (light instanceof BABYLON.SpotLight) {
  23649. // Spot Light
  23650. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23651. }
  23652. else if (light instanceof BABYLON.HemisphericLight) {
  23653. // Hemispheric Light
  23654. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23655. }
  23656. };
  23657. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23658. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23659. var lightIndex = 0;
  23660. var depthValuesAlreadySet = false;
  23661. for (var index = 0; index < scene.lights.length; index++) {
  23662. var light = scene.lights[index];
  23663. if (!light.isEnabled()) {
  23664. continue;
  23665. }
  23666. if (!light.canAffectMesh(mesh)) {
  23667. continue;
  23668. }
  23669. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23670. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23671. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23672. if (defines["SPECULARTERM"]) {
  23673. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23674. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23675. }
  23676. // Shadows
  23677. if (scene.shadowsEnabled) {
  23678. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23679. }
  23680. lightIndex++;
  23681. if (lightIndex === maxSimultaneousLights)
  23682. break;
  23683. }
  23684. };
  23685. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23686. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23687. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23688. effect.setColor3("vFogColor", scene.fogColor);
  23689. }
  23690. };
  23691. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23692. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23693. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23694. }
  23695. };
  23696. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23697. if (defines["LOGARITHMICDEPTH"]) {
  23698. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23699. }
  23700. };
  23701. MaterialHelper.BindClipPlane = function (effect, scene) {
  23702. if (scene.clipPlane) {
  23703. var clipPlane = scene.clipPlane;
  23704. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23705. }
  23706. };
  23707. return MaterialHelper;
  23708. }());
  23709. BABYLON.MaterialHelper = MaterialHelper;
  23710. })(BABYLON || (BABYLON = {}));
  23711. var BABYLON;
  23712. (function (BABYLON) {
  23713. var FresnelParameters = (function () {
  23714. function FresnelParameters() {
  23715. this.isEnabled = true;
  23716. this.leftColor = BABYLON.Color3.White();
  23717. this.rightColor = BABYLON.Color3.Black();
  23718. this.bias = 0;
  23719. this.power = 1;
  23720. }
  23721. FresnelParameters.prototype.clone = function () {
  23722. var newFresnelParameters = new FresnelParameters();
  23723. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23724. return new FresnelParameters;
  23725. };
  23726. FresnelParameters.prototype.serialize = function () {
  23727. var serializationObject = {};
  23728. serializationObject.isEnabled = this.isEnabled;
  23729. serializationObject.leftColor = this.leftColor;
  23730. serializationObject.rightColor = this.rightColor;
  23731. serializationObject.bias = this.bias;
  23732. serializationObject.power = this.power;
  23733. return serializationObject;
  23734. };
  23735. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23736. var fresnelParameters = new FresnelParameters();
  23737. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23738. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23739. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23740. fresnelParameters.bias = parsedFresnelParameters.bias;
  23741. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23742. return fresnelParameters;
  23743. };
  23744. return FresnelParameters;
  23745. }());
  23746. BABYLON.FresnelParameters = FresnelParameters;
  23747. })(BABYLON || (BABYLON = {}));
  23748. var BABYLON;
  23749. (function (BABYLON) {
  23750. var MaterialDefines = (function () {
  23751. function MaterialDefines() {
  23752. }
  23753. MaterialDefines.prototype.rebuild = function () {
  23754. if (this._keys) {
  23755. delete this._keys;
  23756. }
  23757. this._keys = Object.keys(this);
  23758. };
  23759. MaterialDefines.prototype.isEqual = function (other) {
  23760. if (this._keys.length !== other._keys.length) {
  23761. return false;
  23762. }
  23763. for (var index = 0; index < this._keys.length; index++) {
  23764. var prop = this._keys[index];
  23765. if (this[prop] !== other[prop]) {
  23766. return false;
  23767. }
  23768. }
  23769. return true;
  23770. };
  23771. MaterialDefines.prototype.cloneTo = function (other) {
  23772. if (this._keys.length !== other._keys.length) {
  23773. other._keys = this._keys.slice(0);
  23774. }
  23775. for (var index = 0; index < this._keys.length; index++) {
  23776. var prop = this._keys[index];
  23777. other[prop] = this[prop];
  23778. }
  23779. };
  23780. MaterialDefines.prototype.reset = function () {
  23781. for (var index = 0; index < this._keys.length; index++) {
  23782. var prop = this._keys[index];
  23783. if (typeof (this[prop]) === "number") {
  23784. this[prop] = 0;
  23785. }
  23786. else {
  23787. this[prop] = false;
  23788. }
  23789. }
  23790. };
  23791. MaterialDefines.prototype.toString = function () {
  23792. var result = "";
  23793. for (var index = 0; index < this._keys.length; index++) {
  23794. var prop = this._keys[index];
  23795. if (typeof (this[prop]) === "number") {
  23796. result += "#define " + prop + " " + this[prop] + "\n";
  23797. }
  23798. else if (this[prop]) {
  23799. result += "#define " + prop + "\n";
  23800. }
  23801. }
  23802. return result;
  23803. };
  23804. return MaterialDefines;
  23805. }());
  23806. BABYLON.MaterialDefines = MaterialDefines;
  23807. var Material = (function () {
  23808. function Material(name, scene, doNotAdd) {
  23809. this.name = name;
  23810. this.checkReadyOnEveryCall = false;
  23811. this.checkReadyOnlyOnce = false;
  23812. this.state = "";
  23813. this.alpha = 1.0;
  23814. this.backFaceCulling = true;
  23815. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23816. /**
  23817. * An event triggered when the material is disposed.
  23818. * @type {BABYLON.Observable}
  23819. */
  23820. this.onDisposeObservable = new BABYLON.Observable();
  23821. /**
  23822. * An event triggered when the material is compiled.
  23823. * @type {BABYLON.Observable}
  23824. */
  23825. this.onBindObservable = new BABYLON.Observable();
  23826. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23827. this.disableDepthWrite = false;
  23828. this.fogEnabled = true;
  23829. this.pointSize = 1.0;
  23830. this.zOffset = 0;
  23831. this._wasPreviouslyReady = false;
  23832. this._fillMode = Material.TriangleFillMode;
  23833. this.id = name;
  23834. this._scene = scene;
  23835. if (!doNotAdd) {
  23836. scene.materials.push(this);
  23837. }
  23838. }
  23839. Object.defineProperty(Material, "TriangleFillMode", {
  23840. get: function () {
  23841. return Material._TriangleFillMode;
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. Object.defineProperty(Material, "WireFrameFillMode", {
  23847. get: function () {
  23848. return Material._WireFrameFillMode;
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. Object.defineProperty(Material, "PointFillMode", {
  23854. get: function () {
  23855. return Material._PointFillMode;
  23856. },
  23857. enumerable: true,
  23858. configurable: true
  23859. });
  23860. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23861. get: function () {
  23862. return Material._ClockWiseSideOrientation;
  23863. },
  23864. enumerable: true,
  23865. configurable: true
  23866. });
  23867. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23868. get: function () {
  23869. return Material._CounterClockWiseSideOrientation;
  23870. },
  23871. enumerable: true,
  23872. configurable: true
  23873. });
  23874. Object.defineProperty(Material.prototype, "onDispose", {
  23875. set: function (callback) {
  23876. if (this._onDisposeObserver) {
  23877. this.onDisposeObservable.remove(this._onDisposeObserver);
  23878. }
  23879. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23880. },
  23881. enumerable: true,
  23882. configurable: true
  23883. });
  23884. Object.defineProperty(Material.prototype, "onBind", {
  23885. set: function (callback) {
  23886. if (this._onBindObserver) {
  23887. this.onBindObservable.remove(this._onBindObserver);
  23888. }
  23889. this._onBindObserver = this.onBindObservable.add(callback);
  23890. },
  23891. enumerable: true,
  23892. configurable: true
  23893. });
  23894. Object.defineProperty(Material.prototype, "wireframe", {
  23895. get: function () {
  23896. return this._fillMode === Material.WireFrameFillMode;
  23897. },
  23898. set: function (value) {
  23899. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23900. },
  23901. enumerable: true,
  23902. configurable: true
  23903. });
  23904. Object.defineProperty(Material.prototype, "pointsCloud", {
  23905. get: function () {
  23906. return this._fillMode === Material.PointFillMode;
  23907. },
  23908. set: function (value) {
  23909. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23910. },
  23911. enumerable: true,
  23912. configurable: true
  23913. });
  23914. Object.defineProperty(Material.prototype, "fillMode", {
  23915. get: function () {
  23916. return this._fillMode;
  23917. },
  23918. set: function (value) {
  23919. this._fillMode = value;
  23920. },
  23921. enumerable: true,
  23922. configurable: true
  23923. });
  23924. /**
  23925. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23926. * subclasses should override adding information pertainent to themselves
  23927. */
  23928. Material.prototype.toString = function (fullDetails) {
  23929. var ret = "Name: " + this.name;
  23930. if (fullDetails) {
  23931. }
  23932. return ret;
  23933. };
  23934. Object.defineProperty(Material.prototype, "isFrozen", {
  23935. get: function () {
  23936. return this.checkReadyOnlyOnce;
  23937. },
  23938. enumerable: true,
  23939. configurable: true
  23940. });
  23941. Material.prototype.freeze = function () {
  23942. this.checkReadyOnlyOnce = true;
  23943. };
  23944. Material.prototype.unfreeze = function () {
  23945. this.checkReadyOnlyOnce = false;
  23946. };
  23947. Material.prototype.isReady = function (mesh, useInstances) {
  23948. return true;
  23949. };
  23950. Material.prototype.getEffect = function () {
  23951. return this._effect;
  23952. };
  23953. Material.prototype.getScene = function () {
  23954. return this._scene;
  23955. };
  23956. Material.prototype.needAlphaBlending = function () {
  23957. return (this.alpha < 1.0);
  23958. };
  23959. Material.prototype.needAlphaTesting = function () {
  23960. return false;
  23961. };
  23962. Material.prototype.getAlphaTestTexture = function () {
  23963. return null;
  23964. };
  23965. Material.prototype.markDirty = function () {
  23966. this._wasPreviouslyReady = false;
  23967. };
  23968. Material.prototype._preBind = function () {
  23969. var engine = this._scene.getEngine();
  23970. engine.enableEffect(this._effect);
  23971. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23972. };
  23973. Material.prototype.bind = function (world, mesh) {
  23974. this._scene._cachedMaterial = this;
  23975. this.onBindObservable.notifyObservers(mesh);
  23976. if (this.disableDepthWrite) {
  23977. var engine = this._scene.getEngine();
  23978. this._cachedDepthWriteState = engine.getDepthWrite();
  23979. engine.setDepthWrite(false);
  23980. }
  23981. };
  23982. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23983. };
  23984. Material.prototype.unbind = function () {
  23985. if (this.disableDepthWrite) {
  23986. var engine = this._scene.getEngine();
  23987. engine.setDepthWrite(this._cachedDepthWriteState);
  23988. }
  23989. };
  23990. Material.prototype.clone = function (name) {
  23991. return null;
  23992. };
  23993. Material.prototype.getBindedMeshes = function () {
  23994. var result = new Array();
  23995. for (var index = 0; index < this._scene.meshes.length; index++) {
  23996. var mesh = this._scene.meshes[index];
  23997. if (mesh.material === this) {
  23998. result.push(mesh);
  23999. }
  24000. }
  24001. return result;
  24002. };
  24003. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24004. // Animations
  24005. this.getScene().stopAnimation(this);
  24006. // Remove from scene
  24007. var index = this._scene.materials.indexOf(this);
  24008. if (index >= 0) {
  24009. this._scene.materials.splice(index, 1);
  24010. }
  24011. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24012. if (forceDisposeEffect && this._effect) {
  24013. this._scene.getEngine()._releaseEffect(this._effect);
  24014. this._effect = null;
  24015. }
  24016. // Remove from meshes
  24017. for (index = 0; index < this._scene.meshes.length; index++) {
  24018. var mesh = this._scene.meshes[index];
  24019. if (mesh.material === this) {
  24020. mesh.material = null;
  24021. }
  24022. }
  24023. // Callback
  24024. this.onDisposeObservable.notifyObservers(this);
  24025. this.onDisposeObservable.clear();
  24026. this.onBindObservable.clear();
  24027. };
  24028. Material.prototype.serialize = function () {
  24029. return BABYLON.SerializationHelper.Serialize(this);
  24030. };
  24031. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24032. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24033. multiMaterial.id = parsedMultiMaterial.id;
  24034. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24035. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24036. var subMatId = parsedMultiMaterial.materials[matIndex];
  24037. if (subMatId) {
  24038. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24039. }
  24040. else {
  24041. multiMaterial.subMaterials.push(null);
  24042. }
  24043. }
  24044. return multiMaterial;
  24045. };
  24046. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24047. if (!parsedMaterial.customType) {
  24048. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24049. }
  24050. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24051. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24052. ;
  24053. };
  24054. Material._TriangleFillMode = 0;
  24055. Material._WireFrameFillMode = 1;
  24056. Material._PointFillMode = 2;
  24057. Material._ClockWiseSideOrientation = 0;
  24058. Material._CounterClockWiseSideOrientation = 1;
  24059. __decorate([
  24060. BABYLON.serialize()
  24061. ], Material.prototype, "id", void 0);
  24062. __decorate([
  24063. BABYLON.serialize()
  24064. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24065. __decorate([
  24066. BABYLON.serialize()
  24067. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24068. __decorate([
  24069. BABYLON.serialize()
  24070. ], Material.prototype, "state", void 0);
  24071. __decorate([
  24072. BABYLON.serialize()
  24073. ], Material.prototype, "alpha", void 0);
  24074. __decorate([
  24075. BABYLON.serialize()
  24076. ], Material.prototype, "backFaceCulling", void 0);
  24077. __decorate([
  24078. BABYLON.serialize()
  24079. ], Material.prototype, "sideOrientation", void 0);
  24080. __decorate([
  24081. BABYLON.serialize()
  24082. ], Material.prototype, "alphaMode", void 0);
  24083. __decorate([
  24084. BABYLON.serialize()
  24085. ], Material.prototype, "disableDepthWrite", void 0);
  24086. __decorate([
  24087. BABYLON.serialize()
  24088. ], Material.prototype, "fogEnabled", void 0);
  24089. __decorate([
  24090. BABYLON.serialize()
  24091. ], Material.prototype, "pointSize", void 0);
  24092. __decorate([
  24093. BABYLON.serialize()
  24094. ], Material.prototype, "zOffset", void 0);
  24095. __decorate([
  24096. BABYLON.serialize()
  24097. ], Material.prototype, "wireframe", null);
  24098. __decorate([
  24099. BABYLON.serialize()
  24100. ], Material.prototype, "pointsCloud", null);
  24101. __decorate([
  24102. BABYLON.serialize()
  24103. ], Material.prototype, "fillMode", null);
  24104. return Material;
  24105. }());
  24106. BABYLON.Material = Material;
  24107. })(BABYLON || (BABYLON = {}));
  24108. var BABYLON;
  24109. (function (BABYLON) {
  24110. var StandardMaterialDefines = (function (_super) {
  24111. __extends(StandardMaterialDefines, _super);
  24112. function StandardMaterialDefines() {
  24113. _super.call(this);
  24114. this.DIFFUSE = false;
  24115. this.AMBIENT = false;
  24116. this.OPACITY = false;
  24117. this.OPACITYRGB = false;
  24118. this.REFLECTION = false;
  24119. this.EMISSIVE = false;
  24120. this.SPECULAR = false;
  24121. this.BUMP = false;
  24122. this.PARALLAX = false;
  24123. this.PARALLAXOCCLUSION = false;
  24124. this.SPECULAROVERALPHA = false;
  24125. this.CLIPPLANE = false;
  24126. this.ALPHATEST = false;
  24127. this.ALPHAFROMDIFFUSE = false;
  24128. this.POINTSIZE = false;
  24129. this.FOG = false;
  24130. this.SPECULARTERM = false;
  24131. this.DIFFUSEFRESNEL = false;
  24132. this.OPACITYFRESNEL = false;
  24133. this.REFLECTIONFRESNEL = false;
  24134. this.REFRACTIONFRESNEL = false;
  24135. this.EMISSIVEFRESNEL = false;
  24136. this.FRESNEL = false;
  24137. this.NORMAL = false;
  24138. this.UV1 = false;
  24139. this.UV2 = false;
  24140. this.VERTEXCOLOR = false;
  24141. this.VERTEXALPHA = false;
  24142. this.NUM_BONE_INFLUENCERS = 0;
  24143. this.BonesPerMesh = 0;
  24144. this.INSTANCES = false;
  24145. this.GLOSSINESS = false;
  24146. this.ROUGHNESS = false;
  24147. this.EMISSIVEASILLUMINATION = false;
  24148. this.LINKEMISSIVEWITHDIFFUSE = false;
  24149. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24150. this.LIGHTMAP = false;
  24151. this.USELIGHTMAPASSHADOWMAP = false;
  24152. this.REFLECTIONMAP_3D = false;
  24153. this.REFLECTIONMAP_SPHERICAL = false;
  24154. this.REFLECTIONMAP_PLANAR = false;
  24155. this.REFLECTIONMAP_CUBIC = false;
  24156. this.REFLECTIONMAP_PROJECTION = false;
  24157. this.REFLECTIONMAP_SKYBOX = false;
  24158. this.REFLECTIONMAP_EXPLICIT = false;
  24159. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24160. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24161. this.INVERTCUBICMAP = false;
  24162. this.LOGARITHMICDEPTH = false;
  24163. this.REFRACTION = false;
  24164. this.REFRACTIONMAP_3D = false;
  24165. this.REFLECTIONOVERALPHA = false;
  24166. this.INVERTNORMALMAPX = false;
  24167. this.INVERTNORMALMAPY = false;
  24168. this.SHADOWFULLFLOAT = false;
  24169. this.CAMERACOLORGRADING = false;
  24170. this.CAMERACOLORCURVES = false;
  24171. this.rebuild();
  24172. }
  24173. return StandardMaterialDefines;
  24174. }(BABYLON.MaterialDefines));
  24175. var StandardMaterial = (function (_super) {
  24176. __extends(StandardMaterial, _super);
  24177. function StandardMaterial(name, scene) {
  24178. var _this = this;
  24179. _super.call(this, name, scene);
  24180. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24181. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24182. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24183. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24184. this.specularPower = 64;
  24185. this.useAlphaFromDiffuseTexture = false;
  24186. this.useEmissiveAsIllumination = false;
  24187. this.linkEmissiveWithDiffuse = false;
  24188. this.useReflectionFresnelFromSpecular = false;
  24189. this.useSpecularOverAlpha = false;
  24190. this.useReflectionOverAlpha = false;
  24191. this.disableLighting = false;
  24192. this.useParallax = false;
  24193. this.useParallaxOcclusion = false;
  24194. this.parallaxScaleBias = 0.05;
  24195. this.roughness = 0;
  24196. this.indexOfRefraction = 0.98;
  24197. this.invertRefractionY = true;
  24198. this.useLightmapAsShadowmap = false;
  24199. this.useGlossinessFromSpecularMapAlpha = false;
  24200. this.maxSimultaneousLights = 4;
  24201. /**
  24202. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24203. */
  24204. this.invertNormalMapX = false;
  24205. /**
  24206. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24207. */
  24208. this.invertNormalMapY = false;
  24209. /**
  24210. * Color Grading 2D Lookup Texture.
  24211. * This allows special effects like sepia, black and white to sixties rendering style.
  24212. */
  24213. this.cameraColorGradingTexture = null;
  24214. /**
  24215. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24216. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24217. * 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;
  24218. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24219. */
  24220. this.cameraColorCurves = null;
  24221. this._renderTargets = new BABYLON.SmartArray(16);
  24222. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24223. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24224. this._defines = new StandardMaterialDefines();
  24225. this._cachedDefines = new StandardMaterialDefines();
  24226. this._cachedDefines.BonesPerMesh = -1;
  24227. this.getRenderTargetTextures = function () {
  24228. _this._renderTargets.reset();
  24229. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24230. _this._renderTargets.push(_this.reflectionTexture);
  24231. }
  24232. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24233. _this._renderTargets.push(_this.refractionTexture);
  24234. }
  24235. return _this._renderTargets;
  24236. };
  24237. }
  24238. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24239. get: function () {
  24240. return this._useLogarithmicDepth;
  24241. },
  24242. set: function (value) {
  24243. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. StandardMaterial.prototype.needAlphaBlending = function () {
  24249. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24250. };
  24251. StandardMaterial.prototype.needAlphaTesting = function () {
  24252. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24253. };
  24254. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24255. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24256. };
  24257. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24258. return this.diffuseTexture;
  24259. };
  24260. // Methods
  24261. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24262. if (!mesh) {
  24263. return true;
  24264. }
  24265. if (this._defines.INSTANCES !== useInstances) {
  24266. return false;
  24267. }
  24268. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24269. return true;
  24270. }
  24271. return false;
  24272. };
  24273. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24274. if (this.isFrozen) {
  24275. if (this._wasPreviouslyReady) {
  24276. return true;
  24277. }
  24278. }
  24279. var scene = this.getScene();
  24280. if (!this.checkReadyOnEveryCall) {
  24281. if (this._renderId === scene.getRenderId()) {
  24282. if (this._checkCache(scene, mesh, useInstances)) {
  24283. return true;
  24284. }
  24285. }
  24286. }
  24287. var engine = scene.getEngine();
  24288. var needNormals = false;
  24289. var needUVs = false;
  24290. this._defines.reset();
  24291. // Textures
  24292. if (scene.texturesEnabled) {
  24293. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24294. if (!this.diffuseTexture.isReady()) {
  24295. return false;
  24296. }
  24297. else {
  24298. needUVs = true;
  24299. this._defines.DIFFUSE = true;
  24300. }
  24301. }
  24302. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24303. if (!this.ambientTexture.isReady()) {
  24304. return false;
  24305. }
  24306. else {
  24307. needUVs = true;
  24308. this._defines.AMBIENT = true;
  24309. }
  24310. }
  24311. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24312. if (!this.opacityTexture.isReady()) {
  24313. return false;
  24314. }
  24315. else {
  24316. needUVs = true;
  24317. this._defines.OPACITY = true;
  24318. if (this.opacityTexture.getAlphaFromRGB) {
  24319. this._defines.OPACITYRGB = true;
  24320. }
  24321. }
  24322. }
  24323. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24324. if (!this.reflectionTexture.isReady()) {
  24325. return false;
  24326. }
  24327. else {
  24328. needNormals = true;
  24329. this._defines.REFLECTION = true;
  24330. if (this.roughness > 0) {
  24331. this._defines.ROUGHNESS = true;
  24332. }
  24333. if (this.useReflectionOverAlpha) {
  24334. this._defines.REFLECTIONOVERALPHA = true;
  24335. }
  24336. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24337. this._defines.INVERTCUBICMAP = true;
  24338. }
  24339. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24340. switch (this.reflectionTexture.coordinatesMode) {
  24341. case BABYLON.Texture.CUBIC_MODE:
  24342. case BABYLON.Texture.INVCUBIC_MODE:
  24343. this._defines.REFLECTIONMAP_CUBIC = true;
  24344. break;
  24345. case BABYLON.Texture.EXPLICIT_MODE:
  24346. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24347. break;
  24348. case BABYLON.Texture.PLANAR_MODE:
  24349. this._defines.REFLECTIONMAP_PLANAR = true;
  24350. break;
  24351. case BABYLON.Texture.PROJECTION_MODE:
  24352. this._defines.REFLECTIONMAP_PROJECTION = true;
  24353. break;
  24354. case BABYLON.Texture.SKYBOX_MODE:
  24355. this._defines.REFLECTIONMAP_SKYBOX = true;
  24356. break;
  24357. case BABYLON.Texture.SPHERICAL_MODE:
  24358. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24359. break;
  24360. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24361. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24362. break;
  24363. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24364. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24365. break;
  24366. }
  24367. }
  24368. }
  24369. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24370. if (!this.emissiveTexture.isReady()) {
  24371. return false;
  24372. }
  24373. else {
  24374. needUVs = true;
  24375. this._defines.EMISSIVE = true;
  24376. }
  24377. }
  24378. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24379. if (!this.lightmapTexture.isReady()) {
  24380. return false;
  24381. }
  24382. else {
  24383. needUVs = true;
  24384. this._defines.LIGHTMAP = true;
  24385. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24386. }
  24387. }
  24388. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24389. if (!this.specularTexture.isReady()) {
  24390. return false;
  24391. }
  24392. else {
  24393. needUVs = true;
  24394. this._defines.SPECULAR = true;
  24395. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24396. }
  24397. }
  24398. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24399. if (!this.bumpTexture.isReady()) {
  24400. return false;
  24401. }
  24402. else {
  24403. needUVs = true;
  24404. this._defines.BUMP = true;
  24405. if (this.useParallax) {
  24406. this._defines.PARALLAX = true;
  24407. if (this.useParallaxOcclusion) {
  24408. this._defines.PARALLAXOCCLUSION = true;
  24409. }
  24410. }
  24411. if (this.invertNormalMapX) {
  24412. this._defines.INVERTNORMALMAPX = true;
  24413. }
  24414. if (this.invertNormalMapY) {
  24415. this._defines.INVERTNORMALMAPY = true;
  24416. }
  24417. }
  24418. }
  24419. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24420. if (!this.refractionTexture.isReady()) {
  24421. return false;
  24422. }
  24423. else {
  24424. needUVs = true;
  24425. this._defines.REFRACTION = true;
  24426. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24427. }
  24428. }
  24429. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24430. if (!this.cameraColorGradingTexture.isReady()) {
  24431. return false;
  24432. }
  24433. else {
  24434. this._defines.CAMERACOLORGRADING = true;
  24435. }
  24436. }
  24437. }
  24438. // Effect
  24439. if (scene.clipPlane) {
  24440. this._defines.CLIPPLANE = true;
  24441. }
  24442. if (engine.getAlphaTesting()) {
  24443. this._defines.ALPHATEST = true;
  24444. }
  24445. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24446. this._defines.ALPHAFROMDIFFUSE = true;
  24447. }
  24448. if (this.useEmissiveAsIllumination) {
  24449. this._defines.EMISSIVEASILLUMINATION = true;
  24450. }
  24451. if (this.linkEmissiveWithDiffuse) {
  24452. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24453. }
  24454. if (this.useLogarithmicDepth) {
  24455. this._defines.LOGARITHMICDEPTH = true;
  24456. }
  24457. if (this.cameraColorCurves) {
  24458. this._defines.CAMERACOLORCURVES = true;
  24459. }
  24460. // Point size
  24461. if (this.pointsCloud || scene.forcePointsCloud) {
  24462. this._defines.POINTSIZE = true;
  24463. }
  24464. // Fog
  24465. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24466. this._defines.FOG = true;
  24467. }
  24468. if (scene.lightsEnabled && !this.disableLighting) {
  24469. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24470. }
  24471. if (StandardMaterial.FresnelEnabled) {
  24472. // Fresnel
  24473. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24474. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24475. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24476. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24477. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24478. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24479. this._defines.DIFFUSEFRESNEL = true;
  24480. }
  24481. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24482. this._defines.OPACITYFRESNEL = true;
  24483. }
  24484. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24485. this._defines.REFLECTIONFRESNEL = true;
  24486. if (this.useReflectionFresnelFromSpecular) {
  24487. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24488. }
  24489. }
  24490. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24491. this._defines.REFRACTIONFRESNEL = true;
  24492. }
  24493. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24494. this._defines.EMISSIVEFRESNEL = true;
  24495. }
  24496. needNormals = true;
  24497. this._defines.FRESNEL = true;
  24498. }
  24499. }
  24500. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24501. this._defines.SPECULAROVERALPHA = true;
  24502. }
  24503. // Attribs
  24504. if (mesh) {
  24505. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24506. this._defines.NORMAL = true;
  24507. }
  24508. if (needUVs) {
  24509. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24510. this._defines.UV1 = true;
  24511. }
  24512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24513. this._defines.UV2 = true;
  24514. }
  24515. }
  24516. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24517. this._defines.VERTEXCOLOR = true;
  24518. if (mesh.hasVertexAlpha) {
  24519. this._defines.VERTEXALPHA = true;
  24520. }
  24521. }
  24522. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24523. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24524. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24525. }
  24526. // Instances
  24527. if (useInstances) {
  24528. this._defines.INSTANCES = true;
  24529. }
  24530. }
  24531. // Get correct effect
  24532. if (!this._defines.isEqual(this._cachedDefines)) {
  24533. this._defines.cloneTo(this._cachedDefines);
  24534. scene.resetCachedMaterial();
  24535. // Fallbacks
  24536. var fallbacks = new BABYLON.EffectFallbacks();
  24537. if (this._defines.REFLECTION) {
  24538. fallbacks.addFallback(0, "REFLECTION");
  24539. }
  24540. if (this._defines.SPECULAR) {
  24541. fallbacks.addFallback(0, "SPECULAR");
  24542. }
  24543. if (this._defines.BUMP) {
  24544. fallbacks.addFallback(0, "BUMP");
  24545. }
  24546. if (this._defines.PARALLAX) {
  24547. fallbacks.addFallback(1, "PARALLAX");
  24548. }
  24549. if (this._defines.PARALLAXOCCLUSION) {
  24550. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24551. }
  24552. if (this._defines.SPECULAROVERALPHA) {
  24553. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24554. }
  24555. if (this._defines.FOG) {
  24556. fallbacks.addFallback(1, "FOG");
  24557. }
  24558. if (this._defines.POINTSIZE) {
  24559. fallbacks.addFallback(0, "POINTSIZE");
  24560. }
  24561. if (this._defines.LOGARITHMICDEPTH) {
  24562. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24563. }
  24564. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24565. if (this._defines.SPECULARTERM) {
  24566. fallbacks.addFallback(0, "SPECULARTERM");
  24567. }
  24568. if (this._defines.DIFFUSEFRESNEL) {
  24569. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24570. }
  24571. if (this._defines.OPACITYFRESNEL) {
  24572. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24573. }
  24574. if (this._defines.REFLECTIONFRESNEL) {
  24575. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24576. }
  24577. if (this._defines.EMISSIVEFRESNEL) {
  24578. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24579. }
  24580. if (this._defines.FRESNEL) {
  24581. fallbacks.addFallback(4, "FRESNEL");
  24582. }
  24583. //Attributes
  24584. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24585. if (this._defines.NORMAL) {
  24586. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24587. }
  24588. if (this._defines.UV1) {
  24589. attribs.push(BABYLON.VertexBuffer.UVKind);
  24590. }
  24591. if (this._defines.UV2) {
  24592. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24593. }
  24594. if (this._defines.VERTEXCOLOR) {
  24595. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24596. }
  24597. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24598. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24599. // Legacy browser patch
  24600. var shaderName = "default";
  24601. if (!scene.getEngine().getCaps().standardDerivatives) {
  24602. shaderName = "legacydefault";
  24603. }
  24604. var join = this._defines.toString();
  24605. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24606. "vFogInfos", "vFogColor", "pointSize",
  24607. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24608. "mBones",
  24609. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24610. "depthValues",
  24611. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24612. "logarithmicDepthConstant"
  24613. ];
  24614. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24615. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  24616. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  24617. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24618. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24619. }
  24620. if (!this._effect.isReady()) {
  24621. return false;
  24622. }
  24623. this._renderId = scene.getRenderId();
  24624. this._wasPreviouslyReady = true;
  24625. if (mesh) {
  24626. if (!mesh._materialDefines) {
  24627. mesh._materialDefines = new StandardMaterialDefines();
  24628. }
  24629. this._defines.cloneTo(mesh._materialDefines);
  24630. }
  24631. return true;
  24632. };
  24633. StandardMaterial.prototype.unbind = function () {
  24634. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24635. this._effect.setTexture("reflection2DSampler", null);
  24636. }
  24637. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24638. this._effect.setTexture("refraction2DSampler", null);
  24639. }
  24640. _super.prototype.unbind.call(this);
  24641. };
  24642. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24643. this._effect.setMatrix("world", world);
  24644. };
  24645. StandardMaterial.prototype.bind = function (world, mesh) {
  24646. var scene = this.getScene();
  24647. // Matrices
  24648. this.bindOnlyWorldMatrix(world);
  24649. // Bones
  24650. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24651. if (scene.getCachedMaterial() !== this) {
  24652. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24653. if (StandardMaterial.FresnelEnabled) {
  24654. // Fresnel
  24655. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24656. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24657. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24658. }
  24659. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24660. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24661. }
  24662. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24663. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24664. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24665. }
  24666. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24667. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24668. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24669. }
  24670. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24671. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24672. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24673. }
  24674. }
  24675. // Textures
  24676. if (scene.texturesEnabled) {
  24677. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24678. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24679. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24680. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24681. }
  24682. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24683. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24684. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24685. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24686. }
  24687. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24688. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24689. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24690. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24691. }
  24692. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24693. if (this.reflectionTexture.isCube) {
  24694. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24695. }
  24696. else {
  24697. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24698. }
  24699. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24700. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24701. }
  24702. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24703. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24704. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24705. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24706. }
  24707. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24708. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24709. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24710. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24711. }
  24712. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24713. this._effect.setTexture("specularSampler", this.specularTexture);
  24714. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24715. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24716. }
  24717. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24718. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24719. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24720. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24721. }
  24722. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24723. var depth = 1.0;
  24724. if (this.refractionTexture.isCube) {
  24725. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24726. }
  24727. else {
  24728. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24729. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24730. if (this.refractionTexture.depth) {
  24731. depth = this.refractionTexture.depth;
  24732. }
  24733. }
  24734. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24735. }
  24736. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24737. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  24738. }
  24739. }
  24740. // Clip plane
  24741. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24742. // Point size
  24743. if (this.pointsCloud) {
  24744. this._effect.setFloat("pointSize", this.pointSize);
  24745. }
  24746. // Colors
  24747. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24748. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24749. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24750. if (this._defines.SPECULARTERM) {
  24751. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24752. }
  24753. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24754. }
  24755. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24756. // Diffuse
  24757. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24758. // Lights
  24759. if (scene.lightsEnabled && !this.disableLighting) {
  24760. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24761. }
  24762. // View
  24763. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24764. this._effect.setMatrix("view", scene.getViewMatrix());
  24765. }
  24766. // Fog
  24767. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24768. // Log. depth
  24769. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24770. // Color Curves
  24771. if (this.cameraColorCurves) {
  24772. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  24773. }
  24774. }
  24775. _super.prototype.bind.call(this, world, mesh);
  24776. };
  24777. StandardMaterial.prototype.getAnimatables = function () {
  24778. var results = [];
  24779. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24780. results.push(this.diffuseTexture);
  24781. }
  24782. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24783. results.push(this.ambientTexture);
  24784. }
  24785. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24786. results.push(this.opacityTexture);
  24787. }
  24788. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24789. results.push(this.reflectionTexture);
  24790. }
  24791. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24792. results.push(this.emissiveTexture);
  24793. }
  24794. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24795. results.push(this.specularTexture);
  24796. }
  24797. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24798. results.push(this.bumpTexture);
  24799. }
  24800. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24801. results.push(this.lightmapTexture);
  24802. }
  24803. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24804. results.push(this.refractionTexture);
  24805. }
  24806. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  24807. results.push(this.cameraColorGradingTexture);
  24808. }
  24809. return results;
  24810. };
  24811. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24812. if (forceDisposeTextures) {
  24813. if (this.diffuseTexture) {
  24814. this.diffuseTexture.dispose();
  24815. }
  24816. if (this.ambientTexture) {
  24817. this.ambientTexture.dispose();
  24818. }
  24819. if (this.opacityTexture) {
  24820. this.opacityTexture.dispose();
  24821. }
  24822. if (this.reflectionTexture) {
  24823. this.reflectionTexture.dispose();
  24824. }
  24825. if (this.emissiveTexture) {
  24826. this.emissiveTexture.dispose();
  24827. }
  24828. if (this.specularTexture) {
  24829. this.specularTexture.dispose();
  24830. }
  24831. if (this.bumpTexture) {
  24832. this.bumpTexture.dispose();
  24833. }
  24834. if (this.lightmapTexture) {
  24835. this.lightmapTexture.dispose();
  24836. }
  24837. if (this.refractionTexture) {
  24838. this.refractionTexture.dispose();
  24839. }
  24840. if (this.cameraColorGradingTexture) {
  24841. this.cameraColorGradingTexture.dispose();
  24842. }
  24843. }
  24844. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24845. };
  24846. StandardMaterial.prototype.clone = function (name) {
  24847. var _this = this;
  24848. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24849. };
  24850. StandardMaterial.prototype.serialize = function () {
  24851. return BABYLON.SerializationHelper.Serialize(this);
  24852. };
  24853. // Statics
  24854. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24855. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24856. };
  24857. // Flags used to enable or disable a type of texture for all Standard Materials
  24858. StandardMaterial.DiffuseTextureEnabled = true;
  24859. StandardMaterial.AmbientTextureEnabled = true;
  24860. StandardMaterial.OpacityTextureEnabled = true;
  24861. StandardMaterial.ReflectionTextureEnabled = true;
  24862. StandardMaterial.EmissiveTextureEnabled = true;
  24863. StandardMaterial.SpecularTextureEnabled = true;
  24864. StandardMaterial.BumpTextureEnabled = true;
  24865. StandardMaterial.FresnelEnabled = true;
  24866. StandardMaterial.LightmapTextureEnabled = true;
  24867. StandardMaterial.RefractionTextureEnabled = true;
  24868. StandardMaterial.ColorGradingTextureEnabled = true;
  24869. __decorate([
  24870. BABYLON.serializeAsTexture()
  24871. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24872. __decorate([
  24873. BABYLON.serializeAsTexture()
  24874. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24875. __decorate([
  24876. BABYLON.serializeAsTexture()
  24877. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24878. __decorate([
  24879. BABYLON.serializeAsTexture()
  24880. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24881. __decorate([
  24882. BABYLON.serializeAsTexture()
  24883. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24884. __decorate([
  24885. BABYLON.serializeAsTexture()
  24886. ], StandardMaterial.prototype, "specularTexture", void 0);
  24887. __decorate([
  24888. BABYLON.serializeAsTexture()
  24889. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24890. __decorate([
  24891. BABYLON.serializeAsTexture()
  24892. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24893. __decorate([
  24894. BABYLON.serializeAsTexture()
  24895. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24896. __decorate([
  24897. BABYLON.serializeAsColor3("ambient")
  24898. ], StandardMaterial.prototype, "ambientColor", void 0);
  24899. __decorate([
  24900. BABYLON.serializeAsColor3("diffuse")
  24901. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24902. __decorate([
  24903. BABYLON.serializeAsColor3("specular")
  24904. ], StandardMaterial.prototype, "specularColor", void 0);
  24905. __decorate([
  24906. BABYLON.serializeAsColor3("emissive")
  24907. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24908. __decorate([
  24909. BABYLON.serialize()
  24910. ], StandardMaterial.prototype, "specularPower", void 0);
  24911. __decorate([
  24912. BABYLON.serialize()
  24913. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24914. __decorate([
  24915. BABYLON.serialize()
  24916. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24917. __decorate([
  24918. BABYLON.serialize()
  24919. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24920. __decorate([
  24921. BABYLON.serialize()
  24922. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24923. __decorate([
  24924. BABYLON.serialize()
  24925. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24926. __decorate([
  24927. BABYLON.serialize()
  24928. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24929. __decorate([
  24930. BABYLON.serialize()
  24931. ], StandardMaterial.prototype, "disableLighting", void 0);
  24932. __decorate([
  24933. BABYLON.serialize()
  24934. ], StandardMaterial.prototype, "useParallax", void 0);
  24935. __decorate([
  24936. BABYLON.serialize()
  24937. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24938. __decorate([
  24939. BABYLON.serialize()
  24940. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24941. __decorate([
  24942. BABYLON.serialize()
  24943. ], StandardMaterial.prototype, "roughness", void 0);
  24944. __decorate([
  24945. BABYLON.serialize()
  24946. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24947. __decorate([
  24948. BABYLON.serialize()
  24949. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24950. __decorate([
  24951. BABYLON.serialize()
  24952. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24953. __decorate([
  24954. BABYLON.serializeAsFresnelParameters()
  24955. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24956. __decorate([
  24957. BABYLON.serializeAsFresnelParameters()
  24958. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24959. __decorate([
  24960. BABYLON.serializeAsFresnelParameters()
  24961. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24962. __decorate([
  24963. BABYLON.serializeAsFresnelParameters()
  24964. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24965. __decorate([
  24966. BABYLON.serializeAsFresnelParameters()
  24967. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24968. __decorate([
  24969. BABYLON.serialize()
  24970. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24971. __decorate([
  24972. BABYLON.serialize()
  24973. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24974. __decorate([
  24975. BABYLON.serialize()
  24976. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24977. __decorate([
  24978. BABYLON.serialize()
  24979. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24980. __decorate([
  24981. BABYLON.serializeAsTexture()
  24982. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  24983. __decorate([
  24984. BABYLON.serializeAsColorCurves()
  24985. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  24986. __decorate([
  24987. BABYLON.serialize()
  24988. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24989. return StandardMaterial;
  24990. }(BABYLON.Material));
  24991. BABYLON.StandardMaterial = StandardMaterial;
  24992. })(BABYLON || (BABYLON = {}));
  24993. var BABYLON;
  24994. (function (BABYLON) {
  24995. var MultiMaterial = (function (_super) {
  24996. __extends(MultiMaterial, _super);
  24997. function MultiMaterial(name, scene) {
  24998. _super.call(this, name, scene, true);
  24999. this.subMaterials = new Array();
  25000. scene.multiMaterials.push(this);
  25001. }
  25002. // Properties
  25003. MultiMaterial.prototype.getSubMaterial = function (index) {
  25004. if (index < 0 || index >= this.subMaterials.length) {
  25005. return this.getScene().defaultMaterial;
  25006. }
  25007. return this.subMaterials[index];
  25008. };
  25009. // Methods
  25010. MultiMaterial.prototype.isReady = function (mesh) {
  25011. for (var index = 0; index < this.subMaterials.length; index++) {
  25012. var subMaterial = this.subMaterials[index];
  25013. if (subMaterial) {
  25014. if (!this.subMaterials[index].isReady(mesh)) {
  25015. return false;
  25016. }
  25017. }
  25018. }
  25019. return true;
  25020. };
  25021. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25022. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25023. for (var index = 0; index < this.subMaterials.length; index++) {
  25024. var subMaterial = null;
  25025. if (cloneChildren) {
  25026. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25027. }
  25028. else {
  25029. subMaterial = this.subMaterials[index];
  25030. }
  25031. newMultiMaterial.subMaterials.push(subMaterial);
  25032. }
  25033. return newMultiMaterial;
  25034. };
  25035. MultiMaterial.prototype.serialize = function () {
  25036. var serializationObject = {};
  25037. serializationObject.name = this.name;
  25038. serializationObject.id = this.id;
  25039. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25040. serializationObject.materials = [];
  25041. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25042. var subMat = this.subMaterials[matIndex];
  25043. if (subMat) {
  25044. serializationObject.materials.push(subMat.id);
  25045. }
  25046. else {
  25047. serializationObject.materials.push(null);
  25048. }
  25049. }
  25050. return serializationObject;
  25051. };
  25052. return MultiMaterial;
  25053. }(BABYLON.Material));
  25054. BABYLON.MultiMaterial = MultiMaterial;
  25055. })(BABYLON || (BABYLON = {}));
  25056. var BABYLON;
  25057. (function (BABYLON) {
  25058. var SceneLoader = (function () {
  25059. function SceneLoader() {
  25060. }
  25061. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25062. get: function () {
  25063. return 0;
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25069. get: function () {
  25070. return 1;
  25071. },
  25072. enumerable: true,
  25073. configurable: true
  25074. });
  25075. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25076. get: function () {
  25077. return 2;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25083. get: function () {
  25084. return 3;
  25085. },
  25086. enumerable: true,
  25087. configurable: true
  25088. });
  25089. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25090. get: function () {
  25091. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25092. },
  25093. set: function (value) {
  25094. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25095. },
  25096. enumerable: true,
  25097. configurable: true
  25098. });
  25099. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25100. get: function () {
  25101. return SceneLoader._ShowLoadingScreen;
  25102. },
  25103. set: function (value) {
  25104. SceneLoader._ShowLoadingScreen = value;
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. Object.defineProperty(SceneLoader, "loggingLevel", {
  25110. get: function () {
  25111. return SceneLoader._loggingLevel;
  25112. },
  25113. set: function (value) {
  25114. SceneLoader._loggingLevel = value;
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25120. var dotPosition = sceneFilename.lastIndexOf(".");
  25121. var queryStringPosition = sceneFilename.indexOf("?");
  25122. if (queryStringPosition === -1) {
  25123. queryStringPosition = sceneFilename.length;
  25124. }
  25125. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25126. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25127. var plugin = this._registeredPlugins[index];
  25128. if (plugin.extensions.indexOf(extension) !== -1) {
  25129. return plugin;
  25130. }
  25131. }
  25132. return this._registeredPlugins[0];
  25133. };
  25134. // Public functions
  25135. SceneLoader.GetPluginForExtension = function (extension) {
  25136. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25137. var plugin = this._registeredPlugins[index];
  25138. if (plugin.extensions.indexOf(extension) !== -1) {
  25139. return plugin;
  25140. }
  25141. }
  25142. return null;
  25143. };
  25144. SceneLoader.RegisterPlugin = function (plugin) {
  25145. plugin.extensions = plugin.extensions.toLowerCase();
  25146. SceneLoader._registeredPlugins.push(plugin);
  25147. };
  25148. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25149. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25150. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25151. return;
  25152. }
  25153. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25154. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25155. return;
  25156. }
  25157. var loadingToken = {};
  25158. scene._addPendingData(loadingToken);
  25159. var manifestChecked = function (success) {
  25160. scene.database = database;
  25161. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25162. var importMeshFromData = function (data) {
  25163. var meshes = [];
  25164. var particleSystems = [];
  25165. var skeletons = [];
  25166. try {
  25167. if (plugin.importMesh) {
  25168. var syncedPlugin = plugin;
  25169. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25170. if (onerror) {
  25171. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25172. }
  25173. scene._removePendingData(loadingToken);
  25174. return;
  25175. }
  25176. if (onsuccess) {
  25177. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25178. onsuccess(meshes, particleSystems, skeletons);
  25179. scene._removePendingData(loadingToken);
  25180. }
  25181. }
  25182. else {
  25183. var asyncedPlugin = plugin;
  25184. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25185. if (onsuccess) {
  25186. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25187. onsuccess(meshes, particleSystems, skeletons);
  25188. scene._removePendingData(loadingToken);
  25189. }
  25190. }, function () {
  25191. if (onerror) {
  25192. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25193. }
  25194. scene._removePendingData(loadingToken);
  25195. });
  25196. }
  25197. }
  25198. catch (e) {
  25199. if (onerror) {
  25200. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25201. }
  25202. scene._removePendingData(loadingToken);
  25203. }
  25204. };
  25205. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25206. // Direct load
  25207. importMeshFromData(sceneFilename.substr(5));
  25208. return;
  25209. }
  25210. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25211. importMeshFromData(data);
  25212. }, progressCallBack, database);
  25213. };
  25214. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25215. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25216. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25217. }
  25218. else {
  25219. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25220. manifestChecked(true);
  25221. }
  25222. };
  25223. /**
  25224. * Load a scene
  25225. * @param rootUrl a string that defines the root url for scene and resources
  25226. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25227. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25228. */
  25229. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25230. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25231. };
  25232. /**
  25233. * Append a scene
  25234. * @param rootUrl a string that defines the root url for scene and resources
  25235. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25236. * @param scene is the instance of BABYLON.Scene to append to
  25237. */
  25238. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25239. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25240. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25241. return;
  25242. }
  25243. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25244. var database;
  25245. var loadingToken = {};
  25246. scene._addPendingData(loadingToken);
  25247. if (SceneLoader.ShowLoadingScreen) {
  25248. scene.getEngine().displayLoadingUI();
  25249. }
  25250. var loadSceneFromData = function (data) {
  25251. scene.database = database;
  25252. if (plugin.load) {
  25253. var syncedPlugin = plugin;
  25254. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25255. if (onerror) {
  25256. onerror(scene);
  25257. }
  25258. scene._removePendingData(loadingToken);
  25259. scene.getEngine().hideLoadingUI();
  25260. return;
  25261. }
  25262. if (onsuccess) {
  25263. onsuccess(scene);
  25264. }
  25265. scene._removePendingData(loadingToken);
  25266. }
  25267. else {
  25268. var asyncedPlugin = plugin;
  25269. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25270. if (onsuccess) {
  25271. onsuccess(scene);
  25272. }
  25273. }, function () {
  25274. if (onerror) {
  25275. onerror(scene);
  25276. }
  25277. scene._removePendingData(loadingToken);
  25278. scene.getEngine().hideLoadingUI();
  25279. });
  25280. }
  25281. if (SceneLoader.ShowLoadingScreen) {
  25282. scene.executeWhenReady(function () {
  25283. scene.getEngine().hideLoadingUI();
  25284. });
  25285. }
  25286. };
  25287. var manifestChecked = function (success) {
  25288. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25289. };
  25290. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25291. // Direct load
  25292. loadSceneFromData(sceneFilename.substr(5));
  25293. return;
  25294. }
  25295. if (rootUrl.indexOf("file:") === -1) {
  25296. if (scene.getEngine().enableOfflineSupport) {
  25297. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25298. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25299. }
  25300. else {
  25301. manifestChecked(true);
  25302. }
  25303. }
  25304. else {
  25305. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25306. }
  25307. };
  25308. // Flags
  25309. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25310. SceneLoader._ShowLoadingScreen = true;
  25311. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25312. // Members
  25313. SceneLoader._registeredPlugins = new Array();
  25314. return SceneLoader;
  25315. }());
  25316. BABYLON.SceneLoader = SceneLoader;
  25317. ;
  25318. })(BABYLON || (BABYLON = {}));
  25319. var BABYLON;
  25320. (function (BABYLON) {
  25321. var Internals;
  25322. (function (Internals) {
  25323. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25324. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25325. var parsedMaterial = parsedData.materials[index];
  25326. if (parsedMaterial.id === id) {
  25327. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25328. }
  25329. }
  25330. return null;
  25331. };
  25332. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25333. names = (names instanceof Array) ? names : [names];
  25334. for (var i in names) {
  25335. if (mesh.name === names[i]) {
  25336. hierarchyIds.push(mesh.id);
  25337. return true;
  25338. }
  25339. }
  25340. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25341. hierarchyIds.push(mesh.id);
  25342. return true;
  25343. }
  25344. return false;
  25345. };
  25346. var logOperation = function (operation, producer) {
  25347. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25348. };
  25349. BABYLON.SceneLoader.RegisterPlugin({
  25350. extensions: ".babylon",
  25351. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25352. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25353. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25354. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25355. // and avoid problems with multiple concurrent .babylon loads.
  25356. var log = "importMesh has failed JSON parse";
  25357. try {
  25358. var parsedData = JSON.parse(data);
  25359. log = "";
  25360. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25361. var loadedSkeletonsIds = [];
  25362. var loadedMaterialsIds = [];
  25363. var hierarchyIds = [];
  25364. var index;
  25365. var cache;
  25366. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25367. var parsedMesh = parsedData.meshes[index];
  25368. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25369. if (meshesNames instanceof Array) {
  25370. // Remove found mesh name from list.
  25371. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25372. }
  25373. //Geometry?
  25374. if (parsedMesh.geometryId) {
  25375. //does the file contain geometries?
  25376. if (parsedData.geometries) {
  25377. //find the correct geometry and add it to the scene
  25378. var found = false;
  25379. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25380. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25381. return;
  25382. }
  25383. else {
  25384. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25385. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25386. switch (geometryType) {
  25387. case "boxes":
  25388. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25389. break;
  25390. case "spheres":
  25391. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25392. break;
  25393. case "cylinders":
  25394. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25395. break;
  25396. case "toruses":
  25397. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25398. break;
  25399. case "grounds":
  25400. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25401. break;
  25402. case "planes":
  25403. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25404. break;
  25405. case "torusKnots":
  25406. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25407. break;
  25408. case "vertexData":
  25409. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25410. break;
  25411. }
  25412. found = true;
  25413. }
  25414. });
  25415. }
  25416. });
  25417. if (!found) {
  25418. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25419. }
  25420. }
  25421. }
  25422. // Material ?
  25423. if (parsedMesh.materialId) {
  25424. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25425. if (!materialFound && parsedData.multiMaterials) {
  25426. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25427. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25428. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25429. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25430. var subMatId = parsedMultiMaterial.materials[matIndex];
  25431. loadedMaterialsIds.push(subMatId);
  25432. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25433. log += "\n\tMaterial " + mat.toString(fullDetails);
  25434. }
  25435. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25436. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25437. materialFound = true;
  25438. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25439. break;
  25440. }
  25441. }
  25442. }
  25443. if (!materialFound) {
  25444. loadedMaterialsIds.push(parsedMesh.materialId);
  25445. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25446. if (!mat) {
  25447. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25448. }
  25449. else {
  25450. log += "\n\tMaterial " + mat.toString(fullDetails);
  25451. }
  25452. }
  25453. }
  25454. // Skeleton ?
  25455. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25456. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25457. if (!skeletonAlreadyLoaded) {
  25458. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25459. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25460. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25461. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25462. skeletons.push(skeleton);
  25463. loadedSkeletonsIds.push(parsedSkeleton.id);
  25464. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25465. }
  25466. }
  25467. }
  25468. }
  25469. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25470. meshes.push(mesh);
  25471. log += "\n\tMesh " + mesh.toString(fullDetails);
  25472. }
  25473. }
  25474. // Connecting parents
  25475. var currentMesh;
  25476. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25477. currentMesh = scene.meshes[index];
  25478. if (currentMesh._waitingParentId) {
  25479. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25480. currentMesh._waitingParentId = undefined;
  25481. }
  25482. }
  25483. // freeze and compute world matrix application
  25484. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25485. currentMesh = scene.meshes[index];
  25486. if (currentMesh._waitingFreezeWorldMatrix) {
  25487. currentMesh.freezeWorldMatrix();
  25488. currentMesh._waitingFreezeWorldMatrix = undefined;
  25489. }
  25490. else {
  25491. currentMesh.computeWorldMatrix(true);
  25492. }
  25493. }
  25494. // Particles
  25495. if (parsedData.particleSystems) {
  25496. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25497. var parsedParticleSystem = parsedData.particleSystems[index];
  25498. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25499. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25500. }
  25501. }
  25502. }
  25503. return true;
  25504. }
  25505. catch (err) {
  25506. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25507. log = null;
  25508. throw err;
  25509. }
  25510. finally {
  25511. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25512. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25513. }
  25514. }
  25515. },
  25516. load: function (scene, data, rootUrl) {
  25517. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25518. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25519. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25520. // and avoid problems with multiple concurrent .babylon loads.
  25521. var log = "importScene has failed JSON parse";
  25522. try {
  25523. var parsedData = JSON.parse(data);
  25524. log = "";
  25525. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25526. // Scene
  25527. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25528. scene.autoClear = parsedData.autoClear;
  25529. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25530. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25531. if (parsedData.gravity) {
  25532. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25533. }
  25534. // Fog
  25535. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25536. scene.fogMode = parsedData.fogMode;
  25537. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25538. scene.fogStart = parsedData.fogStart;
  25539. scene.fogEnd = parsedData.fogEnd;
  25540. scene.fogDensity = parsedData.fogDensity;
  25541. log += "\tFog mode for scene: ";
  25542. switch (scene.fogMode) {
  25543. // getters not compiling, so using hardcoded
  25544. case 1:
  25545. log += "exp\n";
  25546. break;
  25547. case 2:
  25548. log += "exp2\n";
  25549. break;
  25550. case 3:
  25551. log += "linear\n";
  25552. break;
  25553. }
  25554. }
  25555. //Physics
  25556. if (parsedData.physicsEnabled) {
  25557. var physicsPlugin;
  25558. if (parsedData.physicsEngine === "cannon") {
  25559. physicsPlugin = new BABYLON.CannonJSPlugin();
  25560. }
  25561. else if (parsedData.physicsEngine === "oimo") {
  25562. physicsPlugin = new BABYLON.OimoJSPlugin();
  25563. }
  25564. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25565. //else - default engine, which is currently oimo
  25566. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25567. scene.enablePhysics(physicsGravity, physicsPlugin);
  25568. }
  25569. //collisions, if defined. otherwise, default is true
  25570. if (parsedData.collisionsEnabled != undefined) {
  25571. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25572. }
  25573. scene.workerCollisions = !!parsedData.workerCollisions;
  25574. var index;
  25575. var cache;
  25576. // Lights
  25577. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25578. var parsedLight = parsedData.lights[index];
  25579. var light = BABYLON.Light.Parse(parsedLight, scene);
  25580. log += (index === 0 ? "\n\tLights:" : "");
  25581. log += "\n\t\t" + light.toString(fullDetails);
  25582. }
  25583. // Animations
  25584. if (parsedData.animations) {
  25585. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25586. var parsedAnimation = parsedData.animations[index];
  25587. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25588. scene.animations.push(animation);
  25589. log += (index === 0 ? "\n\tAnimations:" : "");
  25590. log += "\n\t\t" + animation.toString(fullDetails);
  25591. }
  25592. }
  25593. if (parsedData.autoAnimate) {
  25594. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25595. }
  25596. // Materials
  25597. if (parsedData.materials) {
  25598. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25599. var parsedMaterial = parsedData.materials[index];
  25600. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25601. log += (index === 0 ? "\n\tMaterials:" : "");
  25602. log += "\n\t\t" + mat.toString(fullDetails);
  25603. }
  25604. }
  25605. if (parsedData.multiMaterials) {
  25606. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25607. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25608. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25609. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25610. log += "\n\t\t" + mmat.toString(fullDetails);
  25611. }
  25612. }
  25613. // Skeletons
  25614. if (parsedData.skeletons) {
  25615. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25616. var parsedSkeleton = parsedData.skeletons[index];
  25617. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25618. log += (index === 0 ? "\n\tSkeletons:" : "");
  25619. log += "\n\t\t" + skeleton.toString(fullDetails);
  25620. }
  25621. }
  25622. // Geometries
  25623. var geometries = parsedData.geometries;
  25624. if (geometries) {
  25625. // Boxes
  25626. var boxes = geometries.boxes;
  25627. if (boxes) {
  25628. for (index = 0, cache = boxes.length; index < cache; index++) {
  25629. var parsedBox = boxes[index];
  25630. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25631. }
  25632. }
  25633. // Spheres
  25634. var spheres = geometries.spheres;
  25635. if (spheres) {
  25636. for (index = 0, cache = spheres.length; index < cache; index++) {
  25637. var parsedSphere = spheres[index];
  25638. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25639. }
  25640. }
  25641. // Cylinders
  25642. var cylinders = geometries.cylinders;
  25643. if (cylinders) {
  25644. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25645. var parsedCylinder = cylinders[index];
  25646. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25647. }
  25648. }
  25649. // Toruses
  25650. var toruses = geometries.toruses;
  25651. if (toruses) {
  25652. for (index = 0, cache = toruses.length; index < cache; index++) {
  25653. var parsedTorus = toruses[index];
  25654. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25655. }
  25656. }
  25657. // Grounds
  25658. var grounds = geometries.grounds;
  25659. if (grounds) {
  25660. for (index = 0, cache = grounds.length; index < cache; index++) {
  25661. var parsedGround = grounds[index];
  25662. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25663. }
  25664. }
  25665. // Planes
  25666. var planes = geometries.planes;
  25667. if (planes) {
  25668. for (index = 0, cache = planes.length; index < cache; index++) {
  25669. var parsedPlane = planes[index];
  25670. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25671. }
  25672. }
  25673. // TorusKnots
  25674. var torusKnots = geometries.torusKnots;
  25675. if (torusKnots) {
  25676. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25677. var parsedTorusKnot = torusKnots[index];
  25678. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25679. }
  25680. }
  25681. // VertexData
  25682. var vertexData = geometries.vertexData;
  25683. if (vertexData) {
  25684. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25685. var parsedVertexData = vertexData[index];
  25686. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25687. }
  25688. }
  25689. }
  25690. // Meshes
  25691. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25692. var parsedMesh = parsedData.meshes[index];
  25693. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25694. log += (index === 0 ? "\n\tMeshes:" : "");
  25695. log += "\n\t\t" + mesh.toString(fullDetails);
  25696. }
  25697. // Cameras
  25698. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25699. var parsedCamera = parsedData.cameras[index];
  25700. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25701. log += (index === 0 ? "\n\tCameras:" : "");
  25702. log += "\n\t\t" + camera.toString(fullDetails);
  25703. }
  25704. if (parsedData.activeCameraID) {
  25705. scene.setActiveCameraByID(parsedData.activeCameraID);
  25706. }
  25707. // Browsing all the graph to connect the dots
  25708. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25709. var camera = scene.cameras[index];
  25710. if (camera._waitingParentId) {
  25711. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25712. camera._waitingParentId = undefined;
  25713. }
  25714. }
  25715. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25716. var light = scene.lights[index];
  25717. if (light._waitingParentId) {
  25718. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25719. light._waitingParentId = undefined;
  25720. }
  25721. }
  25722. // Sounds
  25723. var loadedSounds = [];
  25724. var loadedSound;
  25725. if (BABYLON.AudioEngine && parsedData.sounds) {
  25726. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25727. var parsedSound = parsedData.sounds[index];
  25728. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25729. if (!parsedSound.url)
  25730. parsedSound.url = parsedSound.name;
  25731. if (!loadedSounds[parsedSound.url]) {
  25732. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25733. loadedSounds[parsedSound.url] = loadedSound;
  25734. }
  25735. else {
  25736. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25737. }
  25738. }
  25739. else {
  25740. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25741. }
  25742. }
  25743. }
  25744. loadedSounds = [];
  25745. // Connect parents & children and parse actions
  25746. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25747. var mesh = scene.meshes[index];
  25748. if (mesh._waitingParentId) {
  25749. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25750. mesh._waitingParentId = undefined;
  25751. }
  25752. if (mesh._waitingActions) {
  25753. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25754. mesh._waitingActions = undefined;
  25755. }
  25756. }
  25757. // freeze world matrix application
  25758. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25759. var currentMesh = scene.meshes[index];
  25760. if (currentMesh._waitingFreezeWorldMatrix) {
  25761. currentMesh.freezeWorldMatrix();
  25762. currentMesh._waitingFreezeWorldMatrix = undefined;
  25763. }
  25764. else {
  25765. currentMesh.computeWorldMatrix(true);
  25766. }
  25767. }
  25768. // Particles Systems
  25769. if (parsedData.particleSystems) {
  25770. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25771. var parsedParticleSystem = parsedData.particleSystems[index];
  25772. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25773. }
  25774. }
  25775. // Lens flares
  25776. if (parsedData.lensFlareSystems) {
  25777. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25778. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25779. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25780. }
  25781. }
  25782. // Shadows
  25783. if (parsedData.shadowGenerators) {
  25784. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25785. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25786. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25787. }
  25788. }
  25789. // Actions (scene)
  25790. if (parsedData.actions) {
  25791. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25792. }
  25793. // Finish
  25794. return true;
  25795. }
  25796. catch (err) {
  25797. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25798. log = null;
  25799. throw err;
  25800. }
  25801. finally {
  25802. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25803. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25804. }
  25805. }
  25806. }
  25807. });
  25808. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25809. })(BABYLON || (BABYLON = {}));
  25810. var BABYLON;
  25811. (function (BABYLON) {
  25812. var SpriteManager = (function () {
  25813. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25815. this.name = name;
  25816. this.cellSize = cellSize;
  25817. this.sprites = new Array();
  25818. this.renderingGroupId = 0;
  25819. this.layerMask = 0x0FFFFFFF;
  25820. this.fogEnabled = true;
  25821. this.isPickable = false;
  25822. /**
  25823. * An event triggered when the manager is disposed.
  25824. * @type {BABYLON.Observable}
  25825. */
  25826. this.onDisposeObservable = new BABYLON.Observable();
  25827. this._vertexBuffers = {};
  25828. this._capacity = capacity;
  25829. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25830. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25831. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25832. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25833. this._scene = scene;
  25834. this._scene.spriteManagers.push(this);
  25835. var indices = [];
  25836. var index = 0;
  25837. for (var count = 0; count < capacity; count++) {
  25838. indices.push(index);
  25839. indices.push(index + 1);
  25840. indices.push(index + 2);
  25841. indices.push(index);
  25842. indices.push(index + 2);
  25843. indices.push(index + 3);
  25844. index += 4;
  25845. }
  25846. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25847. // VBO
  25848. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25849. this._vertexData = new Float32Array(capacity * 16 * 4);
  25850. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25851. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25852. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25853. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25854. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25856. this._vertexBuffers["options"] = options;
  25857. this._vertexBuffers["cellInfo"] = cellInfo;
  25858. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25859. // Effects
  25860. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25861. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25862. }
  25863. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25864. set: function (callback) {
  25865. if (this._onDisposeObserver) {
  25866. this.onDisposeObservable.remove(this._onDisposeObserver);
  25867. }
  25868. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(SpriteManager.prototype, "texture", {
  25874. get: function () {
  25875. return this._spriteTexture;
  25876. },
  25877. set: function (value) {
  25878. this._spriteTexture = value;
  25879. },
  25880. enumerable: true,
  25881. configurable: true
  25882. });
  25883. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25884. var arrayOffset = index * 16;
  25885. if (offsetX === 0)
  25886. offsetX = this._epsilon;
  25887. else if (offsetX === 1)
  25888. offsetX = 1 - this._epsilon;
  25889. if (offsetY === 0)
  25890. offsetY = this._epsilon;
  25891. else if (offsetY === 1)
  25892. offsetY = 1 - this._epsilon;
  25893. this._vertexData[arrayOffset] = sprite.position.x;
  25894. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25895. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25896. this._vertexData[arrayOffset + 3] = sprite.angle;
  25897. this._vertexData[arrayOffset + 4] = sprite.width;
  25898. this._vertexData[arrayOffset + 5] = sprite.height;
  25899. this._vertexData[arrayOffset + 6] = offsetX;
  25900. this._vertexData[arrayOffset + 7] = offsetY;
  25901. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25902. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25903. var offset = (sprite.cellIndex / rowSize) >> 0;
  25904. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25905. this._vertexData[arrayOffset + 11] = offset;
  25906. // Color
  25907. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25908. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25909. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25910. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25911. };
  25912. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25913. var count = Math.min(this._capacity, this.sprites.length);
  25914. var min = BABYLON.Vector3.Zero();
  25915. var max = BABYLON.Vector3.Zero();
  25916. var distance = Number.MAX_VALUE;
  25917. var currentSprite;
  25918. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25919. var cameraView = camera.getViewMatrix();
  25920. for (var index = 0; index < count; index++) {
  25921. var sprite = this.sprites[index];
  25922. if (!sprite) {
  25923. continue;
  25924. }
  25925. if (predicate) {
  25926. if (!predicate(sprite)) {
  25927. continue;
  25928. }
  25929. }
  25930. else if (!sprite.isPickable) {
  25931. continue;
  25932. }
  25933. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25934. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25935. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25936. if (ray.intersectsBoxMinMax(min, max)) {
  25937. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25938. if (distance > currentDistance) {
  25939. distance = currentDistance;
  25940. currentSprite = sprite;
  25941. if (fastCheck) {
  25942. break;
  25943. }
  25944. }
  25945. }
  25946. }
  25947. if (currentSprite) {
  25948. var result = new BABYLON.PickingInfo();
  25949. result.hit = true;
  25950. result.pickedSprite = currentSprite;
  25951. result.distance = distance;
  25952. return result;
  25953. }
  25954. return null;
  25955. };
  25956. SpriteManager.prototype.render = function () {
  25957. // Check
  25958. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25959. return;
  25960. var engine = this._scene.getEngine();
  25961. var baseSize = this._spriteTexture.getBaseSize();
  25962. // Sprites
  25963. var deltaTime = engine.getDeltaTime();
  25964. var max = Math.min(this._capacity, this.sprites.length);
  25965. var rowSize = baseSize.width / this.cellSize;
  25966. var offset = 0;
  25967. for (var index = 0; index < max; index++) {
  25968. var sprite = this.sprites[index];
  25969. if (!sprite) {
  25970. continue;
  25971. }
  25972. sprite._animate(deltaTime);
  25973. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25974. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25975. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25976. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25977. }
  25978. this._buffer.update(this._vertexData);
  25979. // Render
  25980. var effect = this._effectBase;
  25981. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25982. effect = this._effectFog;
  25983. }
  25984. engine.enableEffect(effect);
  25985. var viewMatrix = this._scene.getViewMatrix();
  25986. effect.setTexture("diffuseSampler", this._spriteTexture);
  25987. effect.setMatrix("view", viewMatrix);
  25988. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25989. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25990. // Fog
  25991. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25992. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25993. effect.setColor3("vFogColor", this._scene.fogColor);
  25994. }
  25995. // VBOs
  25996. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25997. // Draw order
  25998. engine.setDepthFunctionToLessOrEqual();
  25999. effect.setBool("alphaTest", true);
  26000. engine.setColorWrite(false);
  26001. engine.draw(true, 0, max * 6);
  26002. engine.setColorWrite(true);
  26003. effect.setBool("alphaTest", false);
  26004. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26005. engine.draw(true, 0, max * 6);
  26006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26007. };
  26008. SpriteManager.prototype.dispose = function () {
  26009. if (this._buffer) {
  26010. this._buffer.dispose();
  26011. this._buffer = null;
  26012. }
  26013. if (this._indexBuffer) {
  26014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26015. this._indexBuffer = null;
  26016. }
  26017. if (this._spriteTexture) {
  26018. this._spriteTexture.dispose();
  26019. this._spriteTexture = null;
  26020. }
  26021. // Remove from scene
  26022. var index = this._scene.spriteManagers.indexOf(this);
  26023. this._scene.spriteManagers.splice(index, 1);
  26024. // Callback
  26025. this.onDisposeObservable.notifyObservers(this);
  26026. this.onDisposeObservable.clear();
  26027. };
  26028. return SpriteManager;
  26029. }());
  26030. BABYLON.SpriteManager = SpriteManager;
  26031. })(BABYLON || (BABYLON = {}));
  26032. var BABYLON;
  26033. (function (BABYLON) {
  26034. var Sprite = (function () {
  26035. function Sprite(name, manager) {
  26036. this.name = name;
  26037. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26038. this.width = 1.0;
  26039. this.height = 1.0;
  26040. this.angle = 0;
  26041. this.cellIndex = 0;
  26042. this.invertU = 0;
  26043. this.invertV = 0;
  26044. this.animations = new Array();
  26045. this.isPickable = false;
  26046. this._animationStarted = false;
  26047. this._loopAnimation = false;
  26048. this._fromIndex = 0;
  26049. this._toIndex = 0;
  26050. this._delay = 0;
  26051. this._direction = 1;
  26052. this._frameCount = 0;
  26053. this._time = 0;
  26054. this._manager = manager;
  26055. this._manager.sprites.push(this);
  26056. this.position = BABYLON.Vector3.Zero();
  26057. }
  26058. Object.defineProperty(Sprite.prototype, "size", {
  26059. get: function () {
  26060. return this.width;
  26061. },
  26062. set: function (value) {
  26063. this.width = value;
  26064. this.height = value;
  26065. },
  26066. enumerable: true,
  26067. configurable: true
  26068. });
  26069. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26070. this._fromIndex = from;
  26071. this._toIndex = to;
  26072. this._loopAnimation = loop;
  26073. this._delay = delay;
  26074. this._animationStarted = true;
  26075. this._direction = from < to ? 1 : -1;
  26076. this.cellIndex = from;
  26077. this._time = 0;
  26078. };
  26079. Sprite.prototype.stopAnimation = function () {
  26080. this._animationStarted = false;
  26081. };
  26082. Sprite.prototype._animate = function (deltaTime) {
  26083. if (!this._animationStarted)
  26084. return;
  26085. this._time += deltaTime;
  26086. if (this._time > this._delay) {
  26087. this._time = this._time % this._delay;
  26088. this.cellIndex += this._direction;
  26089. if (this.cellIndex == this._toIndex) {
  26090. if (this._loopAnimation) {
  26091. this.cellIndex = this._fromIndex;
  26092. }
  26093. else {
  26094. this._animationStarted = false;
  26095. if (this.disposeWhenFinishedAnimating) {
  26096. this.dispose();
  26097. }
  26098. }
  26099. }
  26100. }
  26101. };
  26102. Sprite.prototype.dispose = function () {
  26103. for (var i = 0; i < this._manager.sprites.length; i++) {
  26104. if (this._manager.sprites[i] == this) {
  26105. this._manager.sprites.splice(i, 1);
  26106. }
  26107. }
  26108. };
  26109. return Sprite;
  26110. }());
  26111. BABYLON.Sprite = Sprite;
  26112. })(BABYLON || (BABYLON = {}));
  26113. var BABYLON;
  26114. (function (BABYLON) {
  26115. var Layer = (function () {
  26116. function Layer(name, imgUrl, scene, isBackground, color) {
  26117. this.name = name;
  26118. this.scale = new BABYLON.Vector2(1, 1);
  26119. this.offset = new BABYLON.Vector2(0, 0);
  26120. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26121. this._vertexBuffers = {};
  26122. // Events
  26123. /**
  26124. * An event triggered when the layer is disposed.
  26125. * @type {BABYLON.Observable}
  26126. */
  26127. this.onDisposeObservable = new BABYLON.Observable();
  26128. /**
  26129. * An event triggered before rendering the scene
  26130. * @type {BABYLON.Observable}
  26131. */
  26132. this.onBeforeRenderObservable = new BABYLON.Observable();
  26133. /**
  26134. * An event triggered after rendering the scene
  26135. * @type {BABYLON.Observable}
  26136. */
  26137. this.onAfterRenderObservable = new BABYLON.Observable();
  26138. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26139. this.isBackground = isBackground === undefined ? true : isBackground;
  26140. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26141. this._scene = scene;
  26142. this._scene.layers.push(this);
  26143. var engine = scene.getEngine();
  26144. // VBO
  26145. var vertices = [];
  26146. vertices.push(1, 1);
  26147. vertices.push(-1, 1);
  26148. vertices.push(-1, -1);
  26149. vertices.push(1, -1);
  26150. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26151. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26152. // Indices
  26153. var indices = [];
  26154. indices.push(0);
  26155. indices.push(1);
  26156. indices.push(2);
  26157. indices.push(0);
  26158. indices.push(2);
  26159. indices.push(3);
  26160. this._indexBuffer = engine.createIndexBuffer(indices);
  26161. // Effects
  26162. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26163. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26164. }
  26165. Object.defineProperty(Layer.prototype, "onDispose", {
  26166. set: function (callback) {
  26167. if (this._onDisposeObserver) {
  26168. this.onDisposeObservable.remove(this._onDisposeObserver);
  26169. }
  26170. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26171. },
  26172. enumerable: true,
  26173. configurable: true
  26174. });
  26175. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26176. set: function (callback) {
  26177. if (this._onBeforeRenderObserver) {
  26178. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26179. }
  26180. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26181. },
  26182. enumerable: true,
  26183. configurable: true
  26184. });
  26185. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26186. set: function (callback) {
  26187. if (this._onAfterRenderObserver) {
  26188. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26189. }
  26190. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26191. },
  26192. enumerable: true,
  26193. configurable: true
  26194. });
  26195. Layer.prototype.render = function () {
  26196. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26197. // Check
  26198. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26199. return;
  26200. var engine = this._scene.getEngine();
  26201. this.onBeforeRenderObservable.notifyObservers(this);
  26202. // Render
  26203. engine.enableEffect(currentEffect);
  26204. engine.setState(false);
  26205. // Texture
  26206. currentEffect.setTexture("textureSampler", this.texture);
  26207. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26208. // Color
  26209. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26210. // Scale / offset
  26211. currentEffect.setVector2("offset", this.offset);
  26212. currentEffect.setVector2("scale", this.scale);
  26213. // VBOs
  26214. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26215. // Draw order
  26216. if (!this._alphaTestEffect) {
  26217. engine.setAlphaMode(this.alphaBlendingMode);
  26218. engine.draw(true, 0, 6);
  26219. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26220. }
  26221. else {
  26222. engine.draw(true, 0, 6);
  26223. }
  26224. this.onAfterRenderObservable.notifyObservers(this);
  26225. };
  26226. Layer.prototype.dispose = function () {
  26227. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26228. if (vertexBuffer) {
  26229. vertexBuffer.dispose();
  26230. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26231. }
  26232. if (this._indexBuffer) {
  26233. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26234. this._indexBuffer = null;
  26235. }
  26236. if (this.texture) {
  26237. this.texture.dispose();
  26238. this.texture = null;
  26239. }
  26240. // Remove from scene
  26241. var index = this._scene.layers.indexOf(this);
  26242. this._scene.layers.splice(index, 1);
  26243. // Callback
  26244. this.onDisposeObservable.notifyObservers(this);
  26245. this.onDisposeObservable.clear();
  26246. this.onAfterRenderObservable.clear();
  26247. this.onBeforeRenderObservable.clear();
  26248. };
  26249. return Layer;
  26250. }());
  26251. BABYLON.Layer = Layer;
  26252. })(BABYLON || (BABYLON = {}));
  26253. var BABYLON;
  26254. (function (BABYLON) {
  26255. var Particle = (function () {
  26256. function Particle() {
  26257. this.position = BABYLON.Vector3.Zero();
  26258. this.direction = BABYLON.Vector3.Zero();
  26259. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26260. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26261. this.lifeTime = 1.0;
  26262. this.age = 0;
  26263. this.size = 0;
  26264. this.angle = 0;
  26265. this.angularSpeed = 0;
  26266. }
  26267. Particle.prototype.copyTo = function (other) {
  26268. other.position.copyFrom(this.position);
  26269. other.direction.copyFrom(this.direction);
  26270. other.color.copyFrom(this.color);
  26271. other.colorStep.copyFrom(this.colorStep);
  26272. other.lifeTime = this.lifeTime;
  26273. other.age = this.age;
  26274. other.size = this.size;
  26275. other.angle = this.angle;
  26276. other.angularSpeed = this.angularSpeed;
  26277. };
  26278. return Particle;
  26279. }());
  26280. BABYLON.Particle = Particle;
  26281. })(BABYLON || (BABYLON = {}));
  26282. var BABYLON;
  26283. (function (BABYLON) {
  26284. var randomNumber = function (min, max) {
  26285. if (min === max) {
  26286. return (min);
  26287. }
  26288. var random = Math.random();
  26289. return ((random * (max - min)) + min);
  26290. };
  26291. var ParticleSystem = (function () {
  26292. function ParticleSystem(name, capacity, scene, customEffect) {
  26293. var _this = this;
  26294. this.name = name;
  26295. // Members
  26296. this.animations = [];
  26297. this.renderingGroupId = 0;
  26298. this.emitter = null;
  26299. this.emitRate = 10;
  26300. this.manualEmitCount = -1;
  26301. this.updateSpeed = 0.01;
  26302. this.targetStopDuration = 0;
  26303. this.disposeOnStop = false;
  26304. this.minEmitPower = 1;
  26305. this.maxEmitPower = 1;
  26306. this.minLifeTime = 1;
  26307. this.maxLifeTime = 1;
  26308. this.minSize = 1;
  26309. this.maxSize = 1;
  26310. this.minAngularSpeed = 0;
  26311. this.maxAngularSpeed = 0;
  26312. this.layerMask = 0x0FFFFFFF;
  26313. /**
  26314. * An event triggered when the system is disposed.
  26315. * @type {BABYLON.Observable}
  26316. */
  26317. this.onDisposeObservable = new BABYLON.Observable();
  26318. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26319. this.forceDepthWrite = false;
  26320. this.gravity = BABYLON.Vector3.Zero();
  26321. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26322. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26323. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26324. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26325. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26326. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26327. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26328. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26329. this.particles = new Array();
  26330. this._stockParticles = new Array();
  26331. this._newPartsExcess = 0;
  26332. this._vertexBuffers = {};
  26333. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26334. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26335. this._scaledDirection = BABYLON.Vector3.Zero();
  26336. this._scaledGravity = BABYLON.Vector3.Zero();
  26337. this._currentRenderId = -1;
  26338. this._started = false;
  26339. this._stopped = false;
  26340. this._actualFrame = 0;
  26341. this.id = name;
  26342. this._capacity = capacity;
  26343. this._scene = scene;
  26344. this._customEffect = customEffect;
  26345. scene.particleSystems.push(this);
  26346. var indices = [];
  26347. var index = 0;
  26348. for (var count = 0; count < capacity; count++) {
  26349. indices.push(index);
  26350. indices.push(index + 1);
  26351. indices.push(index + 2);
  26352. indices.push(index);
  26353. indices.push(index + 2);
  26354. indices.push(index + 3);
  26355. index += 4;
  26356. }
  26357. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26358. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26359. this._vertexData = new Float32Array(capacity * 11 * 4);
  26360. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26361. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26362. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26363. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26364. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26365. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26366. this._vertexBuffers["options"] = options;
  26367. // Default behaviors
  26368. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26369. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26370. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26371. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26372. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26373. };
  26374. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26375. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26376. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26377. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26378. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26379. };
  26380. this.updateFunction = function (particles) {
  26381. for (var index = 0; index < particles.length; index++) {
  26382. var particle = particles[index];
  26383. particle.age += _this._scaledUpdateSpeed;
  26384. if (particle.age >= particle.lifeTime) {
  26385. _this.recycleParticle(particle);
  26386. index--;
  26387. continue;
  26388. }
  26389. else {
  26390. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26391. particle.color.addInPlace(_this._scaledColorStep);
  26392. if (particle.color.a < 0)
  26393. particle.color.a = 0;
  26394. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26395. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26396. particle.position.addInPlace(_this._scaledDirection);
  26397. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26398. particle.direction.addInPlace(_this._scaledGravity);
  26399. }
  26400. }
  26401. };
  26402. }
  26403. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26404. set: function (callback) {
  26405. if (this._onDisposeObserver) {
  26406. this.onDisposeObservable.remove(this._onDisposeObserver);
  26407. }
  26408. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. ParticleSystem.prototype.recycleParticle = function (particle) {
  26414. var lastParticle = this.particles.pop();
  26415. if (lastParticle !== particle) {
  26416. lastParticle.copyTo(particle);
  26417. this._stockParticles.push(lastParticle);
  26418. }
  26419. };
  26420. ParticleSystem.prototype.getCapacity = function () {
  26421. return this._capacity;
  26422. };
  26423. ParticleSystem.prototype.isAlive = function () {
  26424. return this._alive;
  26425. };
  26426. ParticleSystem.prototype.isStarted = function () {
  26427. return this._started;
  26428. };
  26429. ParticleSystem.prototype.start = function () {
  26430. this._started = true;
  26431. this._stopped = false;
  26432. this._actualFrame = 0;
  26433. };
  26434. ParticleSystem.prototype.stop = function () {
  26435. this._stopped = true;
  26436. };
  26437. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26438. var offset = index * 11;
  26439. this._vertexData[offset] = particle.position.x;
  26440. this._vertexData[offset + 1] = particle.position.y;
  26441. this._vertexData[offset + 2] = particle.position.z;
  26442. this._vertexData[offset + 3] = particle.color.r;
  26443. this._vertexData[offset + 4] = particle.color.g;
  26444. this._vertexData[offset + 5] = particle.color.b;
  26445. this._vertexData[offset + 6] = particle.color.a;
  26446. this._vertexData[offset + 7] = particle.angle;
  26447. this._vertexData[offset + 8] = particle.size;
  26448. this._vertexData[offset + 9] = offsetX;
  26449. this._vertexData[offset + 10] = offsetY;
  26450. };
  26451. ParticleSystem.prototype._update = function (newParticles) {
  26452. // Update current
  26453. this._alive = this.particles.length > 0;
  26454. this.updateFunction(this.particles);
  26455. // Add new ones
  26456. var worldMatrix;
  26457. if (this.emitter.position) {
  26458. worldMatrix = this.emitter.getWorldMatrix();
  26459. }
  26460. else {
  26461. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26462. }
  26463. var particle;
  26464. for (var index = 0; index < newParticles; index++) {
  26465. if (this.particles.length === this._capacity) {
  26466. break;
  26467. }
  26468. if (this._stockParticles.length !== 0) {
  26469. particle = this._stockParticles.pop();
  26470. particle.age = 0;
  26471. }
  26472. else {
  26473. particle = new BABYLON.Particle();
  26474. }
  26475. this.particles.push(particle);
  26476. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26477. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26478. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26479. particle.size = randomNumber(this.minSize, this.maxSize);
  26480. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26481. this.startPositionFunction(worldMatrix, particle.position, particle);
  26482. var step = randomNumber(0, 1.0);
  26483. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26484. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26485. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26486. }
  26487. };
  26488. ParticleSystem.prototype._getEffect = function () {
  26489. if (this._customEffect) {
  26490. return this._customEffect;
  26491. }
  26492. ;
  26493. var defines = [];
  26494. if (this._scene.clipPlane) {
  26495. defines.push("#define CLIPPLANE");
  26496. }
  26497. // Effect
  26498. var join = defines.join("\n");
  26499. if (this._cachedDefines !== join) {
  26500. this._cachedDefines = join;
  26501. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26502. }
  26503. return this._effect;
  26504. };
  26505. ParticleSystem.prototype.animate = function () {
  26506. if (!this._started)
  26507. return;
  26508. var effect = this._getEffect();
  26509. // Check
  26510. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26511. return;
  26512. if (this._currentRenderId === this._scene.getRenderId()) {
  26513. return;
  26514. }
  26515. this._currentRenderId = this._scene.getRenderId();
  26516. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26517. // determine the number of particles we need to create
  26518. var newParticles;
  26519. if (this.manualEmitCount > -1) {
  26520. newParticles = this.manualEmitCount;
  26521. this._newPartsExcess = 0;
  26522. this.manualEmitCount = 0;
  26523. }
  26524. else {
  26525. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26526. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26527. }
  26528. if (this._newPartsExcess > 1.0) {
  26529. newParticles += this._newPartsExcess >> 0;
  26530. this._newPartsExcess -= this._newPartsExcess >> 0;
  26531. }
  26532. this._alive = false;
  26533. if (!this._stopped) {
  26534. this._actualFrame += this._scaledUpdateSpeed;
  26535. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26536. this.stop();
  26537. }
  26538. else {
  26539. newParticles = 0;
  26540. }
  26541. this._update(newParticles);
  26542. // Stopped?
  26543. if (this._stopped) {
  26544. if (!this._alive) {
  26545. this._started = false;
  26546. if (this.disposeOnStop) {
  26547. this._scene._toBeDisposed.push(this);
  26548. }
  26549. }
  26550. }
  26551. // Update VBO
  26552. var offset = 0;
  26553. for (var index = 0; index < this.particles.length; index++) {
  26554. var particle = this.particles[index];
  26555. this._appendParticleVertex(offset++, particle, 0, 0);
  26556. this._appendParticleVertex(offset++, particle, 1, 0);
  26557. this._appendParticleVertex(offset++, particle, 1, 1);
  26558. this._appendParticleVertex(offset++, particle, 0, 1);
  26559. }
  26560. this._vertexBuffer.update(this._vertexData);
  26561. };
  26562. ParticleSystem.prototype.render = function () {
  26563. var effect = this._getEffect();
  26564. // Check
  26565. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26566. return 0;
  26567. var engine = this._scene.getEngine();
  26568. // Render
  26569. engine.enableEffect(effect);
  26570. engine.setState(false);
  26571. var viewMatrix = this._scene.getViewMatrix();
  26572. effect.setTexture("diffuseSampler", this.particleTexture);
  26573. effect.setMatrix("view", viewMatrix);
  26574. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26575. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26576. if (this._scene.clipPlane) {
  26577. var clipPlane = this._scene.clipPlane;
  26578. var invView = viewMatrix.clone();
  26579. invView.invert();
  26580. effect.setMatrix("invView", invView);
  26581. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26582. }
  26583. // VBOs
  26584. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26585. // Draw order
  26586. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26587. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26588. }
  26589. else {
  26590. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26591. }
  26592. if (this.forceDepthWrite) {
  26593. engine.setDepthWrite(true);
  26594. }
  26595. engine.draw(true, 0, this.particles.length * 6);
  26596. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26597. return this.particles.length;
  26598. };
  26599. ParticleSystem.prototype.dispose = function () {
  26600. if (this._vertexBuffer) {
  26601. this._vertexBuffer.dispose();
  26602. this._vertexBuffer = null;
  26603. }
  26604. if (this._indexBuffer) {
  26605. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26606. this._indexBuffer = null;
  26607. }
  26608. if (this.particleTexture) {
  26609. this.particleTexture.dispose();
  26610. this.particleTexture = null;
  26611. }
  26612. // Remove from scene
  26613. var index = this._scene.particleSystems.indexOf(this);
  26614. this._scene.particleSystems.splice(index, 1);
  26615. // Callback
  26616. this.onDisposeObservable.notifyObservers(this);
  26617. this.onDisposeObservable.clear();
  26618. };
  26619. // Clone
  26620. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26621. var result = new ParticleSystem(name, this._capacity, this._scene);
  26622. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26623. if (newEmitter === undefined) {
  26624. newEmitter = this.emitter;
  26625. }
  26626. result.emitter = newEmitter;
  26627. if (this.particleTexture) {
  26628. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26629. }
  26630. result.start();
  26631. return result;
  26632. };
  26633. ParticleSystem.prototype.serialize = function () {
  26634. var serializationObject = {};
  26635. serializationObject.name = this.name;
  26636. serializationObject.id = this.id;
  26637. // Emitter
  26638. if (this.emitter.position) {
  26639. serializationObject.emitterId = this.emitter.id;
  26640. }
  26641. else {
  26642. serializationObject.emitter = this.emitter.asArray();
  26643. }
  26644. serializationObject.capacity = this.getCapacity();
  26645. if (this.particleTexture) {
  26646. serializationObject.textureName = this.particleTexture.name;
  26647. }
  26648. // Animations
  26649. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26650. // Particle system
  26651. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26652. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26653. serializationObject.minSize = this.minSize;
  26654. serializationObject.maxSize = this.maxSize;
  26655. serializationObject.minEmitPower = this.minEmitPower;
  26656. serializationObject.maxEmitPower = this.maxEmitPower;
  26657. serializationObject.minLifeTime = this.minLifeTime;
  26658. serializationObject.maxLifeTime = this.maxLifeTime;
  26659. serializationObject.emitRate = this.emitRate;
  26660. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26661. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26662. serializationObject.gravity = this.gravity.asArray();
  26663. serializationObject.direction1 = this.direction1.asArray();
  26664. serializationObject.direction2 = this.direction2.asArray();
  26665. serializationObject.color1 = this.color1.asArray();
  26666. serializationObject.color2 = this.color2.asArray();
  26667. serializationObject.colorDead = this.colorDead.asArray();
  26668. serializationObject.updateSpeed = this.updateSpeed;
  26669. serializationObject.targetStopDuration = this.targetStopDuration;
  26670. serializationObject.textureMask = this.textureMask.asArray();
  26671. serializationObject.blendMode = this.blendMode;
  26672. return serializationObject;
  26673. };
  26674. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26675. var name = parsedParticleSystem.name;
  26676. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26677. if (parsedParticleSystem.id) {
  26678. particleSystem.id = parsedParticleSystem.id;
  26679. }
  26680. // Texture
  26681. if (parsedParticleSystem.textureName) {
  26682. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26683. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26684. }
  26685. // Emitter
  26686. if (parsedParticleSystem.emitterId) {
  26687. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26688. }
  26689. else {
  26690. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26691. }
  26692. // Animations
  26693. if (parsedParticleSystem.animations) {
  26694. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26695. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26696. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26697. }
  26698. }
  26699. if (parsedParticleSystem.autoAnimate) {
  26700. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26701. }
  26702. // Particle system
  26703. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26704. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26705. particleSystem.minSize = parsedParticleSystem.minSize;
  26706. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26707. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26708. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26709. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26710. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26711. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26712. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26713. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26714. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26715. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26716. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26717. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26718. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26719. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26720. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26721. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26722. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26723. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26724. if (!parsedParticleSystem.preventAutoStart) {
  26725. particleSystem.start();
  26726. }
  26727. return particleSystem;
  26728. };
  26729. // Statics
  26730. ParticleSystem.BLENDMODE_ONEONE = 0;
  26731. ParticleSystem.BLENDMODE_STANDARD = 1;
  26732. return ParticleSystem;
  26733. }());
  26734. BABYLON.ParticleSystem = ParticleSystem;
  26735. })(BABYLON || (BABYLON = {}));
  26736. var BABYLON;
  26737. (function (BABYLON) {
  26738. var AnimationRange = (function () {
  26739. function AnimationRange(name, from, to) {
  26740. this.name = name;
  26741. this.from = from;
  26742. this.to = to;
  26743. }
  26744. AnimationRange.prototype.clone = function () {
  26745. return new AnimationRange(this.name, this.from, this.to);
  26746. };
  26747. return AnimationRange;
  26748. }());
  26749. BABYLON.AnimationRange = AnimationRange;
  26750. /**
  26751. * Composed of a frame, and an action function
  26752. */
  26753. var AnimationEvent = (function () {
  26754. function AnimationEvent(frame, action, onlyOnce) {
  26755. this.frame = frame;
  26756. this.action = action;
  26757. this.onlyOnce = onlyOnce;
  26758. this.isDone = false;
  26759. }
  26760. return AnimationEvent;
  26761. }());
  26762. BABYLON.AnimationEvent = AnimationEvent;
  26763. var PathCursor = (function () {
  26764. function PathCursor(path) {
  26765. this.path = path;
  26766. this._onchange = new Array();
  26767. this.value = 0;
  26768. this.animations = new Array();
  26769. }
  26770. PathCursor.prototype.getPoint = function () {
  26771. var point = this.path.getPointAtLengthPosition(this.value);
  26772. return new BABYLON.Vector3(point.x, 0, point.y);
  26773. };
  26774. PathCursor.prototype.moveAhead = function (step) {
  26775. if (step === void 0) { step = 0.002; }
  26776. this.move(step);
  26777. return this;
  26778. };
  26779. PathCursor.prototype.moveBack = function (step) {
  26780. if (step === void 0) { step = 0.002; }
  26781. this.move(-step);
  26782. return this;
  26783. };
  26784. PathCursor.prototype.move = function (step) {
  26785. if (Math.abs(step) > 1) {
  26786. throw "step size should be less than 1.";
  26787. }
  26788. this.value += step;
  26789. this.ensureLimits();
  26790. this.raiseOnChange();
  26791. return this;
  26792. };
  26793. PathCursor.prototype.ensureLimits = function () {
  26794. while (this.value > 1) {
  26795. this.value -= 1;
  26796. }
  26797. while (this.value < 0) {
  26798. this.value += 1;
  26799. }
  26800. return this;
  26801. };
  26802. // used by animation engine
  26803. PathCursor.prototype.markAsDirty = function (propertyName) {
  26804. this.ensureLimits();
  26805. this.raiseOnChange();
  26806. return this;
  26807. };
  26808. PathCursor.prototype.raiseOnChange = function () {
  26809. var _this = this;
  26810. this._onchange.forEach(function (f) { return f(_this); });
  26811. return this;
  26812. };
  26813. PathCursor.prototype.onchange = function (f) {
  26814. this._onchange.push(f);
  26815. return this;
  26816. };
  26817. return PathCursor;
  26818. }());
  26819. BABYLON.PathCursor = PathCursor;
  26820. var Animation = (function () {
  26821. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26822. this.name = name;
  26823. this.targetProperty = targetProperty;
  26824. this.framePerSecond = framePerSecond;
  26825. this.dataType = dataType;
  26826. this.loopMode = loopMode;
  26827. this.enableBlending = enableBlending;
  26828. this._offsetsCache = {};
  26829. this._highLimitsCache = {};
  26830. this._stopped = false;
  26831. this._blendingFactor = 0;
  26832. // The set of event that will be linked to this animation
  26833. this._events = new Array();
  26834. this.allowMatricesInterpolation = false;
  26835. this.blendingSpeed = 0.01;
  26836. this._ranges = {};
  26837. this.targetPropertyPath = targetProperty.split(".");
  26838. this.dataType = dataType;
  26839. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26840. }
  26841. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26842. var dataType = undefined;
  26843. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26844. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26845. }
  26846. else if (from instanceof BABYLON.Quaternion) {
  26847. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26848. }
  26849. else if (from instanceof BABYLON.Vector3) {
  26850. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26851. }
  26852. else if (from instanceof BABYLON.Vector2) {
  26853. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26854. }
  26855. else if (from instanceof BABYLON.Color3) {
  26856. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26857. }
  26858. else if (from instanceof BABYLON.Size) {
  26859. dataType = Animation.ANIMATIONTYPE_SIZE;
  26860. }
  26861. if (dataType == undefined) {
  26862. return null;
  26863. }
  26864. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26865. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26866. animation.setKeys(keys);
  26867. if (easingFunction !== undefined) {
  26868. animation.setEasingFunction(easingFunction);
  26869. }
  26870. return animation;
  26871. };
  26872. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26873. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26874. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26875. };
  26876. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26877. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26878. node.animations.push(animation);
  26879. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26880. };
  26881. // Methods
  26882. /**
  26883. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26884. */
  26885. Animation.prototype.toString = function (fullDetails) {
  26886. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26887. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26888. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26889. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26890. if (fullDetails) {
  26891. ret += ", Ranges: {";
  26892. var first = true;
  26893. for (var name in this._ranges) {
  26894. if (first) {
  26895. ret += ", ";
  26896. first = false;
  26897. }
  26898. ret += name;
  26899. }
  26900. ret += "}";
  26901. }
  26902. return ret;
  26903. };
  26904. /**
  26905. * Add an event to this animation.
  26906. */
  26907. Animation.prototype.addEvent = function (event) {
  26908. this._events.push(event);
  26909. };
  26910. /**
  26911. * Remove all events found at the given frame
  26912. * @param frame
  26913. */
  26914. Animation.prototype.removeEvents = function (frame) {
  26915. for (var index = 0; index < this._events.length; index++) {
  26916. if (this._events[index].frame === frame) {
  26917. this._events.splice(index, 1);
  26918. index--;
  26919. }
  26920. }
  26921. };
  26922. Animation.prototype.createRange = function (name, from, to) {
  26923. // check name not already in use; could happen for bones after serialized
  26924. if (!this._ranges[name]) {
  26925. this._ranges[name] = new AnimationRange(name, from, to);
  26926. }
  26927. };
  26928. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26929. if (deleteFrames === void 0) { deleteFrames = true; }
  26930. if (this._ranges[name]) {
  26931. if (deleteFrames) {
  26932. var from = this._ranges[name].from;
  26933. var to = this._ranges[name].to;
  26934. // this loop MUST go high to low for multiple splices to work
  26935. for (var key = this._keys.length - 1; key >= 0; key--) {
  26936. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26937. this._keys.splice(key, 1);
  26938. }
  26939. }
  26940. }
  26941. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26942. }
  26943. };
  26944. Animation.prototype.getRange = function (name) {
  26945. return this._ranges[name];
  26946. };
  26947. Animation.prototype.reset = function () {
  26948. this._offsetsCache = {};
  26949. this._highLimitsCache = {};
  26950. this.currentFrame = 0;
  26951. this._blendingFactor = 0;
  26952. this._originalBlendValue = null;
  26953. };
  26954. Animation.prototype.isStopped = function () {
  26955. return this._stopped;
  26956. };
  26957. Animation.prototype.getKeys = function () {
  26958. return this._keys;
  26959. };
  26960. Animation.prototype.getHighestFrame = function () {
  26961. var ret = 0;
  26962. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26963. if (ret < this._keys[key].frame) {
  26964. ret = this._keys[key].frame;
  26965. }
  26966. }
  26967. return ret;
  26968. };
  26969. Animation.prototype.getEasingFunction = function () {
  26970. return this._easingFunction;
  26971. };
  26972. Animation.prototype.setEasingFunction = function (easingFunction) {
  26973. this._easingFunction = easingFunction;
  26974. };
  26975. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26976. return startValue + (endValue - startValue) * gradient;
  26977. };
  26978. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26979. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26980. };
  26981. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26982. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26983. };
  26984. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26985. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26986. };
  26987. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26988. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26989. };
  26990. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26991. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26992. };
  26993. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26994. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26995. };
  26996. Animation.prototype.clone = function () {
  26997. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26998. if (this._keys) {
  26999. clone.setKeys(this._keys);
  27000. }
  27001. if (this._ranges) {
  27002. clone._ranges = {};
  27003. for (var name in this._ranges) {
  27004. clone._ranges[name] = this._ranges[name].clone();
  27005. }
  27006. }
  27007. return clone;
  27008. };
  27009. Animation.prototype.setKeys = function (values) {
  27010. this._keys = values.slice(0);
  27011. this._offsetsCache = {};
  27012. this._highLimitsCache = {};
  27013. };
  27014. Animation.prototype._getKeyValue = function (value) {
  27015. if (typeof value === "function") {
  27016. return value();
  27017. }
  27018. return value;
  27019. };
  27020. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27021. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27022. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27023. }
  27024. this.currentFrame = currentFrame;
  27025. // Try to get a hash to find the right key
  27026. 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));
  27027. if (this._keys[startKey].frame >= currentFrame) {
  27028. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27029. startKey--;
  27030. }
  27031. }
  27032. for (var key = startKey; key < this._keys.length; key++) {
  27033. if (this._keys[key + 1].frame >= currentFrame) {
  27034. var startValue = this._getKeyValue(this._keys[key].value);
  27035. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27036. // gradient : percent of currentFrame between the frame inf and the frame sup
  27037. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27038. // check for easingFunction and correction of gradient
  27039. if (this._easingFunction != null) {
  27040. gradient = this._easingFunction.ease(gradient);
  27041. }
  27042. switch (this.dataType) {
  27043. // Float
  27044. case Animation.ANIMATIONTYPE_FLOAT:
  27045. switch (loopMode) {
  27046. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27047. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27048. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27049. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27050. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27051. }
  27052. break;
  27053. // Quaternion
  27054. case Animation.ANIMATIONTYPE_QUATERNION:
  27055. var quaternion = null;
  27056. switch (loopMode) {
  27057. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27058. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27059. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27060. break;
  27061. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27062. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27063. break;
  27064. }
  27065. return quaternion;
  27066. // Vector3
  27067. case Animation.ANIMATIONTYPE_VECTOR3:
  27068. switch (loopMode) {
  27069. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27070. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27071. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27072. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27073. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27074. }
  27075. // Vector2
  27076. case Animation.ANIMATIONTYPE_VECTOR2:
  27077. switch (loopMode) {
  27078. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27079. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27080. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27081. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27082. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27083. }
  27084. // Size
  27085. case Animation.ANIMATIONTYPE_SIZE:
  27086. switch (loopMode) {
  27087. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27088. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27089. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27090. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27091. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27092. }
  27093. // Color3
  27094. case Animation.ANIMATIONTYPE_COLOR3:
  27095. switch (loopMode) {
  27096. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27097. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27098. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27099. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27100. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27101. }
  27102. // Matrix
  27103. case Animation.ANIMATIONTYPE_MATRIX:
  27104. switch (loopMode) {
  27105. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27106. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27107. if (this.allowMatricesInterpolation) {
  27108. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27109. }
  27110. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27111. return startValue;
  27112. }
  27113. default:
  27114. break;
  27115. }
  27116. break;
  27117. }
  27118. }
  27119. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27120. };
  27121. Animation.prototype.setValue = function (currentValue, blend) {
  27122. if (blend === void 0) { blend = false; }
  27123. // Set value
  27124. var path;
  27125. var destination;
  27126. if (this.targetPropertyPath.length > 1) {
  27127. var property = this._target[this.targetPropertyPath[0]];
  27128. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27129. property = property[this.targetPropertyPath[index]];
  27130. }
  27131. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27132. destination = property;
  27133. }
  27134. else {
  27135. path = this.targetPropertyPath[0];
  27136. destination = this._target;
  27137. }
  27138. // Blending
  27139. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27140. if (!this._originalBlendValue) {
  27141. if (destination[path].clone) {
  27142. this._originalBlendValue = destination[path].clone();
  27143. }
  27144. else {
  27145. this._originalBlendValue = destination[path];
  27146. }
  27147. }
  27148. if (this._originalBlendValue.prototype) {
  27149. if (this._originalBlendValue.prototype.Lerp) {
  27150. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27151. }
  27152. else {
  27153. destination[path] = currentValue;
  27154. }
  27155. }
  27156. else if (this._originalBlendValue.m) {
  27157. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27158. }
  27159. else {
  27160. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27161. }
  27162. this._blendingFactor += this.blendingSpeed;
  27163. }
  27164. else {
  27165. destination[path] = currentValue;
  27166. }
  27167. if (this._target.markAsDirty) {
  27168. this._target.markAsDirty(this.targetProperty);
  27169. }
  27170. };
  27171. Animation.prototype.goToFrame = function (frame) {
  27172. if (frame < this._keys[0].frame) {
  27173. frame = this._keys[0].frame;
  27174. }
  27175. else if (frame > this._keys[this._keys.length - 1].frame) {
  27176. frame = this._keys[this._keys.length - 1].frame;
  27177. }
  27178. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27179. this.setValue(currentValue);
  27180. };
  27181. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27182. if (blend === void 0) { blend = false; }
  27183. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27184. this._stopped = true;
  27185. return false;
  27186. }
  27187. var returnValue = true;
  27188. // Adding a start key at frame 0 if missing
  27189. if (this._keys[0].frame !== 0) {
  27190. var newKey = { frame: 0, value: this._keys[0].value };
  27191. this._keys.splice(0, 0, newKey);
  27192. }
  27193. // Check limits
  27194. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27195. from = this._keys[0].frame;
  27196. }
  27197. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27198. to = this._keys[this._keys.length - 1].frame;
  27199. }
  27200. // Compute ratio
  27201. var range = to - from;
  27202. var offsetValue;
  27203. // ratio represents the frame delta between from and to
  27204. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27205. var highLimitValue = 0;
  27206. if (ratio > range && !loop) {
  27207. returnValue = false;
  27208. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27209. }
  27210. else {
  27211. // Get max value if required
  27212. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27213. var keyOffset = to.toString() + from.toString();
  27214. if (!this._offsetsCache[keyOffset]) {
  27215. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27216. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27217. switch (this.dataType) {
  27218. // Float
  27219. case Animation.ANIMATIONTYPE_FLOAT:
  27220. this._offsetsCache[keyOffset] = toValue - fromValue;
  27221. break;
  27222. // Quaternion
  27223. case Animation.ANIMATIONTYPE_QUATERNION:
  27224. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27225. break;
  27226. // Vector3
  27227. case Animation.ANIMATIONTYPE_VECTOR3:
  27228. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27229. // Vector2
  27230. case Animation.ANIMATIONTYPE_VECTOR2:
  27231. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27232. // Size
  27233. case Animation.ANIMATIONTYPE_SIZE:
  27234. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27235. // Color3
  27236. case Animation.ANIMATIONTYPE_COLOR3:
  27237. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27238. default:
  27239. break;
  27240. }
  27241. this._highLimitsCache[keyOffset] = toValue;
  27242. }
  27243. highLimitValue = this._highLimitsCache[keyOffset];
  27244. offsetValue = this._offsetsCache[keyOffset];
  27245. }
  27246. }
  27247. if (offsetValue === undefined) {
  27248. switch (this.dataType) {
  27249. // Float
  27250. case Animation.ANIMATIONTYPE_FLOAT:
  27251. offsetValue = 0;
  27252. break;
  27253. // Quaternion
  27254. case Animation.ANIMATIONTYPE_QUATERNION:
  27255. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27256. break;
  27257. // Vector3
  27258. case Animation.ANIMATIONTYPE_VECTOR3:
  27259. offsetValue = BABYLON.Vector3.Zero();
  27260. break;
  27261. // Vector2
  27262. case Animation.ANIMATIONTYPE_VECTOR2:
  27263. offsetValue = BABYLON.Vector2.Zero();
  27264. break;
  27265. // Size
  27266. case Animation.ANIMATIONTYPE_SIZE:
  27267. offsetValue = BABYLON.Size.Zero();
  27268. break;
  27269. // Color3
  27270. case Animation.ANIMATIONTYPE_COLOR3:
  27271. offsetValue = BABYLON.Color3.Black();
  27272. }
  27273. }
  27274. // Compute value
  27275. var repeatCount = (ratio / range) >> 0;
  27276. var currentFrame = returnValue ? from + ratio % range : to;
  27277. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27278. // Set value
  27279. this.setValue(currentValue);
  27280. // Check events
  27281. for (var index = 0; index < this._events.length; index++) {
  27282. if (currentFrame >= this._events[index].frame) {
  27283. var event = this._events[index];
  27284. if (!event.isDone) {
  27285. // If event should be done only once, remove it.
  27286. if (event.onlyOnce) {
  27287. this._events.splice(index, 1);
  27288. index--;
  27289. }
  27290. event.isDone = true;
  27291. event.action();
  27292. } // Don't do anything if the event has already be done.
  27293. }
  27294. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27295. // reset event, the animation is looping
  27296. this._events[index].isDone = false;
  27297. }
  27298. }
  27299. if (!returnValue) {
  27300. this._stopped = true;
  27301. }
  27302. return returnValue;
  27303. };
  27304. Animation.prototype.serialize = function () {
  27305. var serializationObject = {};
  27306. serializationObject.name = this.name;
  27307. serializationObject.property = this.targetProperty;
  27308. serializationObject.framePerSecond = this.framePerSecond;
  27309. serializationObject.dataType = this.dataType;
  27310. serializationObject.loopBehavior = this.loopMode;
  27311. var dataType = this.dataType;
  27312. serializationObject.keys = [];
  27313. var keys = this.getKeys();
  27314. for (var index = 0; index < keys.length; index++) {
  27315. var animationKey = keys[index];
  27316. var key = {};
  27317. key.frame = animationKey.frame;
  27318. switch (dataType) {
  27319. case Animation.ANIMATIONTYPE_FLOAT:
  27320. key.values = [animationKey.value];
  27321. break;
  27322. case Animation.ANIMATIONTYPE_QUATERNION:
  27323. case Animation.ANIMATIONTYPE_MATRIX:
  27324. case Animation.ANIMATIONTYPE_VECTOR3:
  27325. case Animation.ANIMATIONTYPE_COLOR3:
  27326. key.values = animationKey.value.asArray();
  27327. break;
  27328. }
  27329. serializationObject.keys.push(key);
  27330. }
  27331. serializationObject.ranges = [];
  27332. for (var name in this._ranges) {
  27333. var range = {};
  27334. range.name = name;
  27335. range.from = this._ranges[name].from;
  27336. range.to = this._ranges[name].to;
  27337. serializationObject.ranges.push(range);
  27338. }
  27339. return serializationObject;
  27340. };
  27341. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27342. get: function () {
  27343. return Animation._ANIMATIONTYPE_FLOAT;
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27349. get: function () {
  27350. return Animation._ANIMATIONTYPE_VECTOR3;
  27351. },
  27352. enumerable: true,
  27353. configurable: true
  27354. });
  27355. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27356. get: function () {
  27357. return Animation._ANIMATIONTYPE_VECTOR2;
  27358. },
  27359. enumerable: true,
  27360. configurable: true
  27361. });
  27362. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27363. get: function () {
  27364. return Animation._ANIMATIONTYPE_SIZE;
  27365. },
  27366. enumerable: true,
  27367. configurable: true
  27368. });
  27369. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27370. get: function () {
  27371. return Animation._ANIMATIONTYPE_QUATERNION;
  27372. },
  27373. enumerable: true,
  27374. configurable: true
  27375. });
  27376. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27377. get: function () {
  27378. return Animation._ANIMATIONTYPE_MATRIX;
  27379. },
  27380. enumerable: true,
  27381. configurable: true
  27382. });
  27383. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27384. get: function () {
  27385. return Animation._ANIMATIONTYPE_COLOR3;
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27391. get: function () {
  27392. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27398. get: function () {
  27399. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27400. },
  27401. enumerable: true,
  27402. configurable: true
  27403. });
  27404. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27405. get: function () {
  27406. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27407. },
  27408. enumerable: true,
  27409. configurable: true
  27410. });
  27411. Animation.Parse = function (parsedAnimation) {
  27412. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27413. var dataType = parsedAnimation.dataType;
  27414. var keys = [];
  27415. var data;
  27416. var index;
  27417. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27418. var key = parsedAnimation.keys[index];
  27419. switch (dataType) {
  27420. case Animation.ANIMATIONTYPE_FLOAT:
  27421. data = key.values[0];
  27422. break;
  27423. case Animation.ANIMATIONTYPE_QUATERNION:
  27424. data = BABYLON.Quaternion.FromArray(key.values);
  27425. break;
  27426. case Animation.ANIMATIONTYPE_MATRIX:
  27427. data = BABYLON.Matrix.FromArray(key.values);
  27428. break;
  27429. case Animation.ANIMATIONTYPE_COLOR3:
  27430. data = BABYLON.Color3.FromArray(key.values);
  27431. break;
  27432. case Animation.ANIMATIONTYPE_VECTOR3:
  27433. default:
  27434. data = BABYLON.Vector3.FromArray(key.values);
  27435. break;
  27436. }
  27437. keys.push({
  27438. frame: key.frame,
  27439. value: data
  27440. });
  27441. }
  27442. animation.setKeys(keys);
  27443. if (parsedAnimation.ranges) {
  27444. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27445. data = parsedAnimation.ranges[index];
  27446. animation.createRange(data.name, data.from, data.to);
  27447. }
  27448. }
  27449. return animation;
  27450. };
  27451. Animation.AppendSerializedAnimations = function (source, destination) {
  27452. if (source.animations) {
  27453. destination.animations = [];
  27454. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27455. var animation = source.animations[animationIndex];
  27456. destination.animations.push(animation.serialize());
  27457. }
  27458. }
  27459. };
  27460. // Statics
  27461. Animation._ANIMATIONTYPE_FLOAT = 0;
  27462. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27463. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27464. Animation._ANIMATIONTYPE_MATRIX = 3;
  27465. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27466. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27467. Animation._ANIMATIONTYPE_SIZE = 6;
  27468. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27469. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27470. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27471. return Animation;
  27472. }());
  27473. BABYLON.Animation = Animation;
  27474. })(BABYLON || (BABYLON = {}));
  27475. var BABYLON;
  27476. (function (BABYLON) {
  27477. var Animatable = (function () {
  27478. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27479. if (fromFrame === void 0) { fromFrame = 0; }
  27480. if (toFrame === void 0) { toFrame = 100; }
  27481. if (loopAnimation === void 0) { loopAnimation = false; }
  27482. if (speedRatio === void 0) { speedRatio = 1.0; }
  27483. this.target = target;
  27484. this.fromFrame = fromFrame;
  27485. this.toFrame = toFrame;
  27486. this.loopAnimation = loopAnimation;
  27487. this.speedRatio = speedRatio;
  27488. this.onAnimationEnd = onAnimationEnd;
  27489. this._animations = new Array();
  27490. this._paused = false;
  27491. this.animationStarted = false;
  27492. if (animations) {
  27493. this.appendAnimations(target, animations);
  27494. }
  27495. this._scene = scene;
  27496. scene._activeAnimatables.push(this);
  27497. }
  27498. // Methods
  27499. Animatable.prototype.getAnimations = function () {
  27500. return this._animations;
  27501. };
  27502. Animatable.prototype.appendAnimations = function (target, animations) {
  27503. for (var index = 0; index < animations.length; index++) {
  27504. var animation = animations[index];
  27505. animation._target = target;
  27506. this._animations.push(animation);
  27507. }
  27508. };
  27509. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27510. var animations = this._animations;
  27511. for (var index = 0; index < animations.length; index++) {
  27512. if (animations[index].targetProperty === property) {
  27513. return animations[index];
  27514. }
  27515. }
  27516. return null;
  27517. };
  27518. Animatable.prototype.reset = function () {
  27519. var animations = this._animations;
  27520. for (var index = 0; index < animations.length; index++) {
  27521. animations[index].reset();
  27522. }
  27523. this._localDelayOffset = null;
  27524. this._pausedDelay = null;
  27525. };
  27526. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27527. var animations = this._animations;
  27528. for (var index = 0; index < animations.length; index++) {
  27529. animations[index].enableBlending = true;
  27530. animations[index].blendingSpeed = blendingSpeed;
  27531. }
  27532. };
  27533. Animatable.prototype.disableBlending = function () {
  27534. var animations = this._animations;
  27535. for (var index = 0; index < animations.length; index++) {
  27536. animations[index].enableBlending = false;
  27537. }
  27538. };
  27539. Animatable.prototype.goToFrame = function (frame) {
  27540. var animations = this._animations;
  27541. for (var index = 0; index < animations.length; index++) {
  27542. animations[index].goToFrame(frame);
  27543. }
  27544. };
  27545. Animatable.prototype.pause = function () {
  27546. if (this._paused) {
  27547. return;
  27548. }
  27549. this._paused = true;
  27550. };
  27551. Animatable.prototype.restart = function () {
  27552. this._paused = false;
  27553. };
  27554. Animatable.prototype.stop = function () {
  27555. var index = this._scene._activeAnimatables.indexOf(this);
  27556. if (index > -1) {
  27557. this._scene._activeAnimatables.splice(index, 1);
  27558. var animations = this._animations;
  27559. for (var index = 0; index < animations.length; index++) {
  27560. animations[index].reset();
  27561. }
  27562. if (this.onAnimationEnd) {
  27563. this.onAnimationEnd();
  27564. }
  27565. }
  27566. };
  27567. Animatable.prototype._animate = function (delay) {
  27568. if (this._paused) {
  27569. this.animationStarted = false;
  27570. if (!this._pausedDelay) {
  27571. this._pausedDelay = delay;
  27572. }
  27573. return true;
  27574. }
  27575. if (!this._localDelayOffset) {
  27576. this._localDelayOffset = delay;
  27577. }
  27578. else if (this._pausedDelay) {
  27579. this._localDelayOffset += delay - this._pausedDelay;
  27580. this._pausedDelay = null;
  27581. }
  27582. // Animating
  27583. var running = false;
  27584. var animations = this._animations;
  27585. var index;
  27586. for (index = 0; index < animations.length; index++) {
  27587. var animation = animations[index];
  27588. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27589. running = running || isRunning;
  27590. }
  27591. this.animationStarted = running;
  27592. if (!running) {
  27593. // Remove from active animatables
  27594. index = this._scene._activeAnimatables.indexOf(this);
  27595. this._scene._activeAnimatables.splice(index, 1);
  27596. }
  27597. if (!running && this.onAnimationEnd) {
  27598. this.onAnimationEnd();
  27599. this.onAnimationEnd = null;
  27600. }
  27601. return running;
  27602. };
  27603. return Animatable;
  27604. }());
  27605. BABYLON.Animatable = Animatable;
  27606. })(BABYLON || (BABYLON = {}));
  27607. var BABYLON;
  27608. (function (BABYLON) {
  27609. var EasingFunction = (function () {
  27610. function EasingFunction() {
  27611. // Properties
  27612. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27613. }
  27614. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27615. get: function () {
  27616. return EasingFunction._EASINGMODE_EASEIN;
  27617. },
  27618. enumerable: true,
  27619. configurable: true
  27620. });
  27621. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27622. get: function () {
  27623. return EasingFunction._EASINGMODE_EASEOUT;
  27624. },
  27625. enumerable: true,
  27626. configurable: true
  27627. });
  27628. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27629. get: function () {
  27630. return EasingFunction._EASINGMODE_EASEINOUT;
  27631. },
  27632. enumerable: true,
  27633. configurable: true
  27634. });
  27635. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27636. var n = Math.min(Math.max(easingMode, 0), 2);
  27637. this._easingMode = n;
  27638. };
  27639. EasingFunction.prototype.getEasingMode = function () {
  27640. return this._easingMode;
  27641. };
  27642. EasingFunction.prototype.easeInCore = function (gradient) {
  27643. throw new Error('You must implement this method');
  27644. };
  27645. EasingFunction.prototype.ease = function (gradient) {
  27646. switch (this._easingMode) {
  27647. case EasingFunction.EASINGMODE_EASEIN:
  27648. return this.easeInCore(gradient);
  27649. case EasingFunction.EASINGMODE_EASEOUT:
  27650. return (1 - this.easeInCore(1 - gradient));
  27651. }
  27652. if (gradient >= 0.5) {
  27653. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27654. }
  27655. return (this.easeInCore(gradient * 2) * 0.5);
  27656. };
  27657. //Statics
  27658. EasingFunction._EASINGMODE_EASEIN = 0;
  27659. EasingFunction._EASINGMODE_EASEOUT = 1;
  27660. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27661. return EasingFunction;
  27662. }());
  27663. BABYLON.EasingFunction = EasingFunction;
  27664. var CircleEase = (function (_super) {
  27665. __extends(CircleEase, _super);
  27666. function CircleEase() {
  27667. _super.apply(this, arguments);
  27668. }
  27669. CircleEase.prototype.easeInCore = function (gradient) {
  27670. gradient = Math.max(0, Math.min(1, gradient));
  27671. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27672. };
  27673. return CircleEase;
  27674. }(EasingFunction));
  27675. BABYLON.CircleEase = CircleEase;
  27676. var BackEase = (function (_super) {
  27677. __extends(BackEase, _super);
  27678. function BackEase(amplitude) {
  27679. if (amplitude === void 0) { amplitude = 1; }
  27680. _super.call(this);
  27681. this.amplitude = amplitude;
  27682. }
  27683. BackEase.prototype.easeInCore = function (gradient) {
  27684. var num = Math.max(0, this.amplitude);
  27685. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27686. };
  27687. return BackEase;
  27688. }(EasingFunction));
  27689. BABYLON.BackEase = BackEase;
  27690. var BounceEase = (function (_super) {
  27691. __extends(BounceEase, _super);
  27692. function BounceEase(bounces, bounciness) {
  27693. if (bounces === void 0) { bounces = 3; }
  27694. if (bounciness === void 0) { bounciness = 2; }
  27695. _super.call(this);
  27696. this.bounces = bounces;
  27697. this.bounciness = bounciness;
  27698. }
  27699. BounceEase.prototype.easeInCore = function (gradient) {
  27700. var y = Math.max(0.0, this.bounces);
  27701. var bounciness = this.bounciness;
  27702. if (bounciness <= 1.0) {
  27703. bounciness = 1.001;
  27704. }
  27705. var num9 = Math.pow(bounciness, y);
  27706. var num5 = 1.0 - bounciness;
  27707. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27708. var num15 = gradient * num4;
  27709. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27710. var num3 = Math.floor(num65);
  27711. var num13 = num3 + 1.0;
  27712. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27713. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27714. var num7 = (num8 + num12) * 0.5;
  27715. var num6 = gradient - num7;
  27716. var num2 = num7 - num8;
  27717. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27718. };
  27719. return BounceEase;
  27720. }(EasingFunction));
  27721. BABYLON.BounceEase = BounceEase;
  27722. var CubicEase = (function (_super) {
  27723. __extends(CubicEase, _super);
  27724. function CubicEase() {
  27725. _super.apply(this, arguments);
  27726. }
  27727. CubicEase.prototype.easeInCore = function (gradient) {
  27728. return (gradient * gradient * gradient);
  27729. };
  27730. return CubicEase;
  27731. }(EasingFunction));
  27732. BABYLON.CubicEase = CubicEase;
  27733. var ElasticEase = (function (_super) {
  27734. __extends(ElasticEase, _super);
  27735. function ElasticEase(oscillations, springiness) {
  27736. if (oscillations === void 0) { oscillations = 3; }
  27737. if (springiness === void 0) { springiness = 3; }
  27738. _super.call(this);
  27739. this.oscillations = oscillations;
  27740. this.springiness = springiness;
  27741. }
  27742. ElasticEase.prototype.easeInCore = function (gradient) {
  27743. var num2;
  27744. var num3 = Math.max(0.0, this.oscillations);
  27745. var num = Math.max(0.0, this.springiness);
  27746. if (num == 0) {
  27747. num2 = gradient;
  27748. }
  27749. else {
  27750. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27751. }
  27752. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27753. };
  27754. return ElasticEase;
  27755. }(EasingFunction));
  27756. BABYLON.ElasticEase = ElasticEase;
  27757. var ExponentialEase = (function (_super) {
  27758. __extends(ExponentialEase, _super);
  27759. function ExponentialEase(exponent) {
  27760. if (exponent === void 0) { exponent = 2; }
  27761. _super.call(this);
  27762. this.exponent = exponent;
  27763. }
  27764. ExponentialEase.prototype.easeInCore = function (gradient) {
  27765. if (this.exponent <= 0) {
  27766. return gradient;
  27767. }
  27768. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27769. };
  27770. return ExponentialEase;
  27771. }(EasingFunction));
  27772. BABYLON.ExponentialEase = ExponentialEase;
  27773. var PowerEase = (function (_super) {
  27774. __extends(PowerEase, _super);
  27775. function PowerEase(power) {
  27776. if (power === void 0) { power = 2; }
  27777. _super.call(this);
  27778. this.power = power;
  27779. }
  27780. PowerEase.prototype.easeInCore = function (gradient) {
  27781. var y = Math.max(0.0, this.power);
  27782. return Math.pow(gradient, y);
  27783. };
  27784. return PowerEase;
  27785. }(EasingFunction));
  27786. BABYLON.PowerEase = PowerEase;
  27787. var QuadraticEase = (function (_super) {
  27788. __extends(QuadraticEase, _super);
  27789. function QuadraticEase() {
  27790. _super.apply(this, arguments);
  27791. }
  27792. QuadraticEase.prototype.easeInCore = function (gradient) {
  27793. return (gradient * gradient);
  27794. };
  27795. return QuadraticEase;
  27796. }(EasingFunction));
  27797. BABYLON.QuadraticEase = QuadraticEase;
  27798. var QuarticEase = (function (_super) {
  27799. __extends(QuarticEase, _super);
  27800. function QuarticEase() {
  27801. _super.apply(this, arguments);
  27802. }
  27803. QuarticEase.prototype.easeInCore = function (gradient) {
  27804. return (gradient * gradient * gradient * gradient);
  27805. };
  27806. return QuarticEase;
  27807. }(EasingFunction));
  27808. BABYLON.QuarticEase = QuarticEase;
  27809. var QuinticEase = (function (_super) {
  27810. __extends(QuinticEase, _super);
  27811. function QuinticEase() {
  27812. _super.apply(this, arguments);
  27813. }
  27814. QuinticEase.prototype.easeInCore = function (gradient) {
  27815. return (gradient * gradient * gradient * gradient * gradient);
  27816. };
  27817. return QuinticEase;
  27818. }(EasingFunction));
  27819. BABYLON.QuinticEase = QuinticEase;
  27820. var SineEase = (function (_super) {
  27821. __extends(SineEase, _super);
  27822. function SineEase() {
  27823. _super.apply(this, arguments);
  27824. }
  27825. SineEase.prototype.easeInCore = function (gradient) {
  27826. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27827. };
  27828. return SineEase;
  27829. }(EasingFunction));
  27830. BABYLON.SineEase = SineEase;
  27831. var BezierCurveEase = (function (_super) {
  27832. __extends(BezierCurveEase, _super);
  27833. function BezierCurveEase(x1, y1, x2, y2) {
  27834. if (x1 === void 0) { x1 = 0; }
  27835. if (y1 === void 0) { y1 = 0; }
  27836. if (x2 === void 0) { x2 = 1; }
  27837. if (y2 === void 0) { y2 = 1; }
  27838. _super.call(this);
  27839. this.x1 = x1;
  27840. this.y1 = y1;
  27841. this.x2 = x2;
  27842. this.y2 = y2;
  27843. }
  27844. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27845. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27846. };
  27847. return BezierCurveEase;
  27848. }(EasingFunction));
  27849. BABYLON.BezierCurveEase = BezierCurveEase;
  27850. })(BABYLON || (BABYLON = {}));
  27851. var BABYLON;
  27852. (function (BABYLON) {
  27853. var Bone = (function (_super) {
  27854. __extends(Bone, _super);
  27855. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27856. _super.call(this, name, skeleton.getScene());
  27857. this.name = name;
  27858. this.children = new Array();
  27859. this.animations = new Array();
  27860. this._worldTransform = new BABYLON.Matrix();
  27861. this._absoluteTransform = new BABYLON.Matrix();
  27862. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27863. this._skeleton = skeleton;
  27864. this._matrix = matrix;
  27865. this._baseMatrix = matrix;
  27866. this._restPose = restPose ? restPose : matrix.clone();
  27867. skeleton.bones.push(this);
  27868. if (parentBone) {
  27869. this._parent = parentBone;
  27870. parentBone.children.push(this);
  27871. }
  27872. else {
  27873. this._parent = null;
  27874. }
  27875. this._updateDifferenceMatrix();
  27876. }
  27877. // Members
  27878. Bone.prototype.getParent = function () {
  27879. return this._parent;
  27880. };
  27881. Bone.prototype.getLocalMatrix = function () {
  27882. return this._matrix;
  27883. };
  27884. Bone.prototype.getBaseMatrix = function () {
  27885. return this._baseMatrix;
  27886. };
  27887. Bone.prototype.getRestPose = function () {
  27888. return this._restPose;
  27889. };
  27890. Bone.prototype.returnToRest = function () {
  27891. this.updateMatrix(this._restPose.clone());
  27892. };
  27893. Bone.prototype.getWorldMatrix = function () {
  27894. return this._worldTransform;
  27895. };
  27896. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27897. return this._invertedAbsoluteTransform;
  27898. };
  27899. Bone.prototype.getAbsoluteTransform = function () {
  27900. return this._absoluteTransform;
  27901. };
  27902. // Methods
  27903. Bone.prototype.updateMatrix = function (matrix) {
  27904. this._baseMatrix = matrix.clone();
  27905. this._matrix = matrix.clone();
  27906. this._skeleton._markAsDirty();
  27907. this._updateDifferenceMatrix();
  27908. };
  27909. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27910. if (!rootMatrix) {
  27911. rootMatrix = this._baseMatrix;
  27912. }
  27913. if (this._parent) {
  27914. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27915. }
  27916. else {
  27917. this._absoluteTransform.copyFrom(rootMatrix);
  27918. }
  27919. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27920. for (var index = 0; index < this.children.length; index++) {
  27921. this.children[index]._updateDifferenceMatrix();
  27922. }
  27923. };
  27924. Bone.prototype.markAsDirty = function () {
  27925. this._currentRenderId++;
  27926. this._skeleton._markAsDirty();
  27927. };
  27928. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27929. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27930. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27931. // all animation may be coming from a library skeleton, so may need to create animation
  27932. if (this.animations.length === 0) {
  27933. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27934. this.animations[0].setKeys([]);
  27935. }
  27936. // get animation info / verify there is such a range from the source bone
  27937. var sourceRange = source.animations[0].getRange(rangeName);
  27938. if (!sourceRange) {
  27939. return false;
  27940. }
  27941. var from = sourceRange.from;
  27942. var to = sourceRange.to;
  27943. var sourceKeys = source.animations[0].getKeys();
  27944. // rescaling prep
  27945. var sourceBoneLength = source.length;
  27946. var sourceParent = source.getParent();
  27947. var parent = this.getParent();
  27948. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27949. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27950. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27951. var destKeys = this.animations[0].getKeys();
  27952. // loop vars declaration
  27953. var orig;
  27954. var origTranslation;
  27955. var mat;
  27956. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27957. orig = sourceKeys[key];
  27958. if (orig.frame >= from && orig.frame <= to) {
  27959. if (rescaleAsRequired) {
  27960. mat = orig.value.clone();
  27961. // scale based on parent ratio, when bone has parent
  27962. if (parentScalingReqd) {
  27963. origTranslation = mat.getTranslation();
  27964. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27965. }
  27966. else if (dimensionsScalingReqd) {
  27967. origTranslation = mat.getTranslation();
  27968. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27969. }
  27970. else {
  27971. mat = orig.value;
  27972. }
  27973. }
  27974. else {
  27975. mat = orig.value;
  27976. }
  27977. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27978. }
  27979. }
  27980. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27981. return true;
  27982. };
  27983. return Bone;
  27984. }(BABYLON.Node));
  27985. BABYLON.Bone = Bone;
  27986. })(BABYLON || (BABYLON = {}));
  27987. var BABYLON;
  27988. (function (BABYLON) {
  27989. var Skeleton = (function () {
  27990. function Skeleton(name, id, scene) {
  27991. this.name = name;
  27992. this.id = id;
  27993. this.bones = new Array();
  27994. this.needInitialSkinMatrix = false;
  27995. this._isDirty = true;
  27996. this._meshesWithPoseMatrix = new Array();
  27997. this._identity = BABYLON.Matrix.Identity();
  27998. this._ranges = {};
  27999. this.bones = [];
  28000. this._scene = scene;
  28001. scene.skeletons.push(this);
  28002. //make sure it will recalculate the matrix next time prepare is called.
  28003. this._isDirty = true;
  28004. }
  28005. // Members
  28006. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28007. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28008. return mesh._bonesTransformMatrices;
  28009. }
  28010. return this._transformMatrices;
  28011. };
  28012. Skeleton.prototype.getScene = function () {
  28013. return this._scene;
  28014. };
  28015. // Methods
  28016. /**
  28017. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28018. */
  28019. Skeleton.prototype.toString = function (fullDetails) {
  28020. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28021. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28022. if (fullDetails) {
  28023. ret += ", Ranges: {";
  28024. var first = true;
  28025. for (var name_1 in this._ranges) {
  28026. if (first) {
  28027. ret += ", ";
  28028. first = false;
  28029. }
  28030. ret += name_1;
  28031. }
  28032. ret += "}";
  28033. }
  28034. return ret;
  28035. };
  28036. /**
  28037. * Get bone's index searching by name
  28038. * @param {string} name is bone's name to search for
  28039. * @return {number} Indice of the bone. Returns -1 if not found
  28040. */
  28041. Skeleton.prototype.getBoneIndexByName = function (name) {
  28042. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28043. if (this.bones[boneIndex].name === name) {
  28044. return boneIndex;
  28045. }
  28046. }
  28047. return -1;
  28048. };
  28049. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28050. // check name not already in use
  28051. if (!this._ranges[name]) {
  28052. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28053. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28054. if (this.bones[i].animations[0]) {
  28055. this.bones[i].animations[0].createRange(name, from, to);
  28056. }
  28057. }
  28058. }
  28059. };
  28060. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28061. if (deleteFrames === void 0) { deleteFrames = true; }
  28062. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28063. if (this.bones[i].animations[0]) {
  28064. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28065. }
  28066. }
  28067. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28068. };
  28069. Skeleton.prototype.getAnimationRange = function (name) {
  28070. return this._ranges[name];
  28071. };
  28072. /**
  28073. * Returns as an Array, all AnimationRanges defined on this skeleton
  28074. */
  28075. Skeleton.prototype.getAnimationRanges = function () {
  28076. var animationRanges = [];
  28077. var name;
  28078. var i = 0;
  28079. for (name in this._ranges) {
  28080. animationRanges[i] = this._ranges[name];
  28081. i++;
  28082. }
  28083. return animationRanges;
  28084. };
  28085. /**
  28086. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28087. */
  28088. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28089. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28090. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28091. return false;
  28092. }
  28093. var ret = true;
  28094. var frameOffset = this._getHighestAnimationFrame() + 1;
  28095. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28096. var boneDict = {};
  28097. var sourceBones = source.bones;
  28098. var nBones;
  28099. var i;
  28100. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28101. boneDict[sourceBones[i].name] = sourceBones[i];
  28102. }
  28103. if (this.bones.length !== sourceBones.length) {
  28104. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28105. ret = false;
  28106. }
  28107. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28108. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28109. var boneName = this.bones[i].name;
  28110. var sourceBone = boneDict[boneName];
  28111. if (sourceBone) {
  28112. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28113. }
  28114. else {
  28115. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28116. ret = false;
  28117. }
  28118. }
  28119. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28120. var range = source.getAnimationRange(name);
  28121. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28122. return ret;
  28123. };
  28124. Skeleton.prototype.returnToRest = function () {
  28125. for (var index = 0; index < this.bones.length; index++) {
  28126. this.bones[index].returnToRest();
  28127. }
  28128. };
  28129. Skeleton.prototype._getHighestAnimationFrame = function () {
  28130. var ret = 0;
  28131. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28132. if (this.bones[i].animations[0]) {
  28133. var highest = this.bones[i].animations[0].getHighestFrame();
  28134. if (ret < highest) {
  28135. ret = highest;
  28136. }
  28137. }
  28138. }
  28139. return ret;
  28140. };
  28141. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28142. var range = this.getAnimationRange(name);
  28143. if (!range) {
  28144. return null;
  28145. }
  28146. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28147. };
  28148. Skeleton.prototype._markAsDirty = function () {
  28149. this._isDirty = true;
  28150. };
  28151. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28152. this._meshesWithPoseMatrix.push(mesh);
  28153. };
  28154. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28155. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28156. if (index > -1) {
  28157. this._meshesWithPoseMatrix.splice(index, 1);
  28158. }
  28159. };
  28160. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28161. for (var index = 0; index < this.bones.length; index++) {
  28162. var bone = this.bones[index];
  28163. var parentBone = bone.getParent();
  28164. if (parentBone) {
  28165. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28166. }
  28167. else {
  28168. if (initialSkinMatrix) {
  28169. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28170. }
  28171. else {
  28172. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28173. }
  28174. }
  28175. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28176. }
  28177. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28178. };
  28179. Skeleton.prototype.prepare = function () {
  28180. if (!this._isDirty) {
  28181. return;
  28182. }
  28183. if (this.needInitialSkinMatrix) {
  28184. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28185. var mesh = this._meshesWithPoseMatrix[index];
  28186. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28187. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28188. }
  28189. var poseMatrix = mesh.getPoseMatrix();
  28190. // Prepare bones
  28191. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28192. var bone = this.bones[boneIndex];
  28193. if (!bone.getParent()) {
  28194. var matrix = bone.getBaseMatrix();
  28195. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28196. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28197. }
  28198. }
  28199. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28200. }
  28201. }
  28202. else {
  28203. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28204. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28205. }
  28206. this._computeTransformMatrices(this._transformMatrices, null);
  28207. }
  28208. this._isDirty = false;
  28209. this._scene._activeBones.addCount(this.bones.length, false);
  28210. };
  28211. Skeleton.prototype.getAnimatables = function () {
  28212. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28213. this._animatables = [];
  28214. for (var index = 0; index < this.bones.length; index++) {
  28215. this._animatables.push(this.bones[index]);
  28216. }
  28217. }
  28218. return this._animatables;
  28219. };
  28220. Skeleton.prototype.clone = function (name, id) {
  28221. var result = new Skeleton(name, id || name, this._scene);
  28222. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28223. for (var index = 0; index < this.bones.length; index++) {
  28224. var source = this.bones[index];
  28225. var parentBone = null;
  28226. if (source.getParent()) {
  28227. var parentIndex = this.bones.indexOf(source.getParent());
  28228. parentBone = result.bones[parentIndex];
  28229. }
  28230. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28231. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28232. }
  28233. if (this._ranges) {
  28234. result._ranges = {};
  28235. for (var rangeName in this._ranges) {
  28236. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28237. }
  28238. }
  28239. this._isDirty = true;
  28240. return result;
  28241. };
  28242. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28243. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28244. this.bones.forEach(function (bone) {
  28245. bone.animations.forEach(function (animation) {
  28246. animation.enableBlending = true;
  28247. animation.blendingSpeed = blendingSpeed;
  28248. });
  28249. });
  28250. };
  28251. Skeleton.prototype.dispose = function () {
  28252. this._meshesWithPoseMatrix = [];
  28253. // Animations
  28254. this.getScene().stopAnimation(this);
  28255. // Remove from scene
  28256. this.getScene().removeSkeleton(this);
  28257. };
  28258. Skeleton.prototype.serialize = function () {
  28259. var serializationObject = {};
  28260. serializationObject.name = this.name;
  28261. serializationObject.id = this.id;
  28262. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28263. serializationObject.bones = [];
  28264. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28265. for (var index = 0; index < this.bones.length; index++) {
  28266. var bone = this.bones[index];
  28267. var serializedBone = {
  28268. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28269. name: bone.name,
  28270. matrix: bone.getLocalMatrix().toArray(),
  28271. rest: bone.getRestPose().toArray()
  28272. };
  28273. serializationObject.bones.push(serializedBone);
  28274. if (bone.length) {
  28275. serializedBone.length = bone.length;
  28276. }
  28277. if (bone.animations && bone.animations.length > 0) {
  28278. serializedBone.animation = bone.animations[0].serialize();
  28279. }
  28280. serializationObject.ranges = [];
  28281. for (var name in this._ranges) {
  28282. var range = {};
  28283. range.name = name;
  28284. range.from = this._ranges[name].from;
  28285. range.to = this._ranges[name].to;
  28286. serializationObject.ranges.push(range);
  28287. }
  28288. }
  28289. return serializationObject;
  28290. };
  28291. Skeleton.Parse = function (parsedSkeleton, scene) {
  28292. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28293. if (parsedSkeleton.dimensionsAtRest) {
  28294. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28295. }
  28296. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28297. var index;
  28298. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28299. var parsedBone = parsedSkeleton.bones[index];
  28300. var parentBone = null;
  28301. if (parsedBone.parentBoneIndex > -1) {
  28302. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28303. }
  28304. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28305. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28306. if (parsedBone.length) {
  28307. bone.length = parsedBone.length;
  28308. }
  28309. if (parsedBone.animation) {
  28310. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28311. }
  28312. }
  28313. // placed after bones, so createAnimationRange can cascade down
  28314. if (parsedSkeleton.ranges) {
  28315. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28316. var data = parsedSkeleton.ranges[index];
  28317. skeleton.createAnimationRange(data.name, data.from, data.to);
  28318. }
  28319. }
  28320. return skeleton;
  28321. };
  28322. return Skeleton;
  28323. }());
  28324. BABYLON.Skeleton = Skeleton;
  28325. })(BABYLON || (BABYLON = {}));
  28326. var BABYLON;
  28327. (function (BABYLON) {
  28328. var PostProcess = (function () {
  28329. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28332. this.name = name;
  28333. this.width = -1;
  28334. this.height = -1;
  28335. /*
  28336. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28337. Can only be used on a single postprocess or on the last one of a chain.
  28338. */
  28339. this.enablePixelPerfectMode = false;
  28340. this._reusable = false;
  28341. this._textures = new BABYLON.SmartArray(2);
  28342. this._currentRenderTextureInd = 0;
  28343. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28344. // Events
  28345. /**
  28346. * An event triggered when the postprocess is activated.
  28347. * @type {BABYLON.Observable}
  28348. */
  28349. this.onActivateObservable = new BABYLON.Observable();
  28350. /**
  28351. * An event triggered when the postprocess changes its size.
  28352. * @type {BABYLON.Observable}
  28353. */
  28354. this.onSizeChangedObservable = new BABYLON.Observable();
  28355. /**
  28356. * An event triggered when the postprocess applies its effect.
  28357. * @type {BABYLON.Observable}
  28358. */
  28359. this.onApplyObservable = new BABYLON.Observable();
  28360. /**
  28361. * An event triggered before rendering the postprocess
  28362. * @type {BABYLON.Observable}
  28363. */
  28364. this.onBeforeRenderObservable = new BABYLON.Observable();
  28365. /**
  28366. * An event triggered after rendering the postprocess
  28367. * @type {BABYLON.Observable}
  28368. */
  28369. this.onAfterRenderObservable = new BABYLON.Observable();
  28370. if (camera != null) {
  28371. this._camera = camera;
  28372. this._scene = camera.getScene();
  28373. camera.attachPostProcess(this);
  28374. this._engine = this._scene.getEngine();
  28375. }
  28376. else {
  28377. this._engine = engine;
  28378. }
  28379. this._options = options;
  28380. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28381. this._reusable = reusable || false;
  28382. this._textureType = textureType;
  28383. this._samplers = samplers || [];
  28384. this._samplers.push("textureSampler");
  28385. this._fragmentUrl = fragmentUrl;
  28386. this._parameters = parameters || [];
  28387. this._parameters.push("scale");
  28388. this.updateEffect(defines);
  28389. }
  28390. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28391. set: function (callback) {
  28392. if (this._onActivateObserver) {
  28393. this.onActivateObservable.remove(this._onActivateObserver);
  28394. }
  28395. this._onActivateObserver = this.onActivateObservable.add(callback);
  28396. },
  28397. enumerable: true,
  28398. configurable: true
  28399. });
  28400. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28401. set: function (callback) {
  28402. if (this._onSizeChangedObserver) {
  28403. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28404. }
  28405. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28406. },
  28407. enumerable: true,
  28408. configurable: true
  28409. });
  28410. Object.defineProperty(PostProcess.prototype, "onApply", {
  28411. set: function (callback) {
  28412. if (this._onApplyObserver) {
  28413. this.onApplyObservable.remove(this._onApplyObserver);
  28414. }
  28415. this._onApplyObserver = this.onApplyObservable.add(callback);
  28416. },
  28417. enumerable: true,
  28418. configurable: true
  28419. });
  28420. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28421. set: function (callback) {
  28422. if (this._onBeforeRenderObserver) {
  28423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28424. }
  28425. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28426. },
  28427. enumerable: true,
  28428. configurable: true
  28429. });
  28430. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28431. set: function (callback) {
  28432. if (this._onAfterRenderObserver) {
  28433. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28434. }
  28435. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28436. },
  28437. enumerable: true,
  28438. configurable: true
  28439. });
  28440. PostProcess.prototype.updateEffect = function (defines) {
  28441. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28442. };
  28443. PostProcess.prototype.isReusable = function () {
  28444. return this._reusable;
  28445. };
  28446. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28447. PostProcess.prototype.markTextureDirty = function () {
  28448. this.width = -1;
  28449. };
  28450. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28451. camera = camera || this._camera;
  28452. var scene = camera.getScene();
  28453. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28454. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28455. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28456. var desiredWidth = this._options.width || requiredWidth;
  28457. var desiredHeight = this._options.height || requiredHeight;
  28458. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28459. if (!this._options.width) {
  28460. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28461. }
  28462. if (!this._options.height) {
  28463. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28464. }
  28465. }
  28466. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28467. if (this._textures.length > 0) {
  28468. for (var i = 0; i < this._textures.length; i++) {
  28469. this._engine._releaseTexture(this._textures.data[i]);
  28470. }
  28471. this._textures.reset();
  28472. }
  28473. this.width = desiredWidth;
  28474. this.height = desiredHeight;
  28475. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28476. if (this._reusable) {
  28477. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  28478. }
  28479. this.onSizeChangedObservable.notifyObservers(this);
  28480. }
  28481. if (this.enablePixelPerfectMode) {
  28482. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28483. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28484. }
  28485. else {
  28486. this._scaleRatio.copyFromFloats(1, 1);
  28487. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28488. }
  28489. this.onActivateObservable.notifyObservers(camera);
  28490. // Clear
  28491. if (this.clearColor) {
  28492. this._engine.clear(this.clearColor, true, true);
  28493. }
  28494. else {
  28495. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28496. }
  28497. if (this._reusable) {
  28498. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28499. }
  28500. };
  28501. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28502. get: function () {
  28503. return this._effect.isSupported;
  28504. },
  28505. enumerable: true,
  28506. configurable: true
  28507. });
  28508. PostProcess.prototype.apply = function () {
  28509. // Check
  28510. if (!this._effect.isReady())
  28511. return null;
  28512. // States
  28513. this._engine.enableEffect(this._effect);
  28514. this._engine.setState(false);
  28515. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28516. this._engine.setDepthBuffer(false);
  28517. this._engine.setDepthWrite(false);
  28518. // Texture
  28519. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28520. // Parameters
  28521. this._effect.setVector2("scale", this._scaleRatio);
  28522. this.onApplyObservable.notifyObservers(this._effect);
  28523. return this._effect;
  28524. };
  28525. PostProcess.prototype.dispose = function (camera) {
  28526. camera = camera || this._camera;
  28527. if (this._textures.length > 0) {
  28528. for (var i = 0; i < this._textures.length; i++) {
  28529. this._engine._releaseTexture(this._textures.data[i]);
  28530. }
  28531. this._textures.reset();
  28532. }
  28533. if (!camera) {
  28534. return;
  28535. }
  28536. camera.detachPostProcess(this);
  28537. var index = camera._postProcesses.indexOf(this);
  28538. if (index === 0 && camera._postProcesses.length > 0) {
  28539. this._camera._postProcesses[0].markTextureDirty();
  28540. }
  28541. this.onActivateObservable.clear();
  28542. this.onAfterRenderObservable.clear();
  28543. this.onApplyObservable.clear();
  28544. this.onBeforeRenderObservable.clear();
  28545. this.onSizeChangedObservable.clear();
  28546. };
  28547. return PostProcess;
  28548. }());
  28549. BABYLON.PostProcess = PostProcess;
  28550. })(BABYLON || (BABYLON = {}));
  28551. var BABYLON;
  28552. (function (BABYLON) {
  28553. var PostProcessManager = (function () {
  28554. function PostProcessManager(scene) {
  28555. this._vertexBuffers = {};
  28556. this._scene = scene;
  28557. }
  28558. PostProcessManager.prototype._prepareBuffers = function () {
  28559. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28560. return;
  28561. }
  28562. // VBO
  28563. var vertices = [];
  28564. vertices.push(1, 1);
  28565. vertices.push(-1, 1);
  28566. vertices.push(-1, -1);
  28567. vertices.push(1, -1);
  28568. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28569. // Indices
  28570. var indices = [];
  28571. indices.push(0);
  28572. indices.push(1);
  28573. indices.push(2);
  28574. indices.push(0);
  28575. indices.push(2);
  28576. indices.push(3);
  28577. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28578. };
  28579. // Methods
  28580. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28581. var postProcesses = this._scene.activeCamera._postProcesses;
  28582. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28583. return false;
  28584. }
  28585. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28586. return true;
  28587. };
  28588. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28589. var engine = this._scene.getEngine();
  28590. for (var index = 0; index < postProcesses.length; index++) {
  28591. if (index < postProcesses.length - 1) {
  28592. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28593. }
  28594. else {
  28595. if (targetTexture) {
  28596. engine.bindFramebuffer(targetTexture);
  28597. }
  28598. else {
  28599. engine.restoreDefaultFramebuffer();
  28600. }
  28601. }
  28602. var pp = postProcesses[index];
  28603. var effect = pp.apply();
  28604. if (effect) {
  28605. pp.onBeforeRenderObservable.notifyObservers(effect);
  28606. // VBOs
  28607. this._prepareBuffers();
  28608. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28609. // Draw order
  28610. engine.draw(true, 0, 6);
  28611. pp.onAfterRenderObservable.notifyObservers(effect);
  28612. }
  28613. }
  28614. // Restore depth buffer
  28615. engine.setDepthBuffer(true);
  28616. engine.setDepthWrite(true);
  28617. };
  28618. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28619. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28620. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28621. return;
  28622. }
  28623. var engine = this._scene.getEngine();
  28624. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28625. if (index < len - 1) {
  28626. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28627. }
  28628. else {
  28629. if (targetTexture) {
  28630. engine.bindFramebuffer(targetTexture, faceIndex);
  28631. }
  28632. else {
  28633. engine.restoreDefaultFramebuffer();
  28634. }
  28635. }
  28636. if (doNotPresent) {
  28637. break;
  28638. }
  28639. var pp = postProcesses[index];
  28640. var effect = pp.apply();
  28641. if (effect) {
  28642. pp.onBeforeRenderObservable.notifyObservers(effect);
  28643. // VBOs
  28644. this._prepareBuffers();
  28645. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28646. // Draw order
  28647. engine.draw(true, 0, 6);
  28648. pp.onAfterRenderObservable.notifyObservers(effect);
  28649. }
  28650. }
  28651. // Restore depth buffer
  28652. engine.setDepthBuffer(true);
  28653. engine.setDepthWrite(true);
  28654. };
  28655. PostProcessManager.prototype.dispose = function () {
  28656. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28657. if (buffer) {
  28658. buffer.dispose();
  28659. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28660. }
  28661. if (this._indexBuffer) {
  28662. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28663. this._indexBuffer = null;
  28664. }
  28665. };
  28666. return PostProcessManager;
  28667. }());
  28668. BABYLON.PostProcessManager = PostProcessManager;
  28669. })(BABYLON || (BABYLON = {}));
  28670. var BABYLON;
  28671. (function (BABYLON) {
  28672. var PassPostProcess = (function (_super) {
  28673. __extends(PassPostProcess, _super);
  28674. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28675. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28676. }
  28677. return PassPostProcess;
  28678. }(BABYLON.PostProcess));
  28679. BABYLON.PassPostProcess = PassPostProcess;
  28680. })(BABYLON || (BABYLON = {}));
  28681. var BABYLON;
  28682. (function (BABYLON) {
  28683. /**
  28684. * This is a holder class for the physics joint created by the physics plugin.
  28685. * It holds a set of functions to control the underlying joint.
  28686. */
  28687. var PhysicsJoint = (function () {
  28688. function PhysicsJoint(type, jointData) {
  28689. this.type = type;
  28690. this.jointData = jointData;
  28691. jointData.nativeParams = jointData.nativeParams || {};
  28692. }
  28693. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28694. get: function () {
  28695. return this._physicsJoint;
  28696. },
  28697. set: function (newJoint) {
  28698. if (this._physicsJoint) {
  28699. }
  28700. this._physicsJoint = newJoint;
  28701. },
  28702. enumerable: true,
  28703. configurable: true
  28704. });
  28705. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28706. set: function (physicsPlugin) {
  28707. this._physicsPlugin = physicsPlugin;
  28708. },
  28709. enumerable: true,
  28710. configurable: true
  28711. });
  28712. /**
  28713. * Execute a function that is physics-plugin specific.
  28714. * @param {Function} func the function that will be executed.
  28715. * It accepts two parameters: the physics world and the physics joint.
  28716. */
  28717. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28718. func(this._physicsPlugin.world, this._physicsJoint);
  28719. };
  28720. //TODO check if the native joints are the same
  28721. //Joint Types
  28722. PhysicsJoint.DistanceJoint = 0;
  28723. PhysicsJoint.HingeJoint = 1;
  28724. PhysicsJoint.BallAndSocketJoint = 2;
  28725. PhysicsJoint.WheelJoint = 3;
  28726. PhysicsJoint.SliderJoint = 4;
  28727. //OIMO
  28728. PhysicsJoint.PrismaticJoint = 5;
  28729. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28730. PhysicsJoint.UniversalJoint = 6;
  28731. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28732. //Cannon
  28733. //Similar to a Ball-Joint. Different in params
  28734. PhysicsJoint.PointToPointJoint = 8;
  28735. //Cannon only at the moment
  28736. PhysicsJoint.SpringJoint = 9;
  28737. PhysicsJoint.LockJoint = 10;
  28738. return PhysicsJoint;
  28739. }());
  28740. BABYLON.PhysicsJoint = PhysicsJoint;
  28741. /**
  28742. * A class representing a physics distance joint.
  28743. */
  28744. var DistanceJoint = (function (_super) {
  28745. __extends(DistanceJoint, _super);
  28746. function DistanceJoint(jointData) {
  28747. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28748. }
  28749. /**
  28750. * Update the predefined distance.
  28751. */
  28752. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28753. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28754. };
  28755. return DistanceJoint;
  28756. }(PhysicsJoint));
  28757. BABYLON.DistanceJoint = DistanceJoint;
  28758. var MotorEnabledJoint = (function (_super) {
  28759. __extends(MotorEnabledJoint, _super);
  28760. function MotorEnabledJoint(type, jointData) {
  28761. _super.call(this, type, jointData);
  28762. }
  28763. /**
  28764. * Set the motor values.
  28765. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28766. * @param {number} force the force to apply
  28767. * @param {number} maxForce max force for this motor.
  28768. */
  28769. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28770. this._physicsPlugin.setMotor(this, force, maxForce);
  28771. };
  28772. /**
  28773. * Set the motor's limits.
  28774. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28775. */
  28776. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28777. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28778. };
  28779. return MotorEnabledJoint;
  28780. }(PhysicsJoint));
  28781. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28782. /**
  28783. * This class represents a single hinge physics joint
  28784. */
  28785. var HingeJoint = (function (_super) {
  28786. __extends(HingeJoint, _super);
  28787. function HingeJoint(jointData) {
  28788. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28789. }
  28790. /**
  28791. * Set the motor values.
  28792. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28793. * @param {number} force the force to apply
  28794. * @param {number} maxForce max force for this motor.
  28795. */
  28796. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28797. this._physicsPlugin.setMotor(this, force, maxForce);
  28798. };
  28799. /**
  28800. * Set the motor's limits.
  28801. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28802. */
  28803. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28804. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28805. };
  28806. return HingeJoint;
  28807. }(MotorEnabledJoint));
  28808. BABYLON.HingeJoint = HingeJoint;
  28809. /**
  28810. * This class represents a dual hinge physics joint (same as wheel joint)
  28811. */
  28812. var Hinge2Joint = (function (_super) {
  28813. __extends(Hinge2Joint, _super);
  28814. function Hinge2Joint(jointData) {
  28815. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28816. }
  28817. /**
  28818. * Set the motor values.
  28819. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28820. * @param {number} force the force to apply
  28821. * @param {number} maxForce max force for this motor.
  28822. * @param {motorIndex} the motor's index, 0 or 1.
  28823. */
  28824. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28825. if (motorIndex === void 0) { motorIndex = 0; }
  28826. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28827. };
  28828. /**
  28829. * Set the motor limits.
  28830. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28831. * @param {number} upperLimit the upper limit
  28832. * @param {number} lowerLimit lower limit
  28833. * @param {motorIndex} the motor's index, 0 or 1.
  28834. */
  28835. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28836. if (motorIndex === void 0) { motorIndex = 0; }
  28837. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28838. };
  28839. return Hinge2Joint;
  28840. }(MotorEnabledJoint));
  28841. BABYLON.Hinge2Joint = Hinge2Joint;
  28842. })(BABYLON || (BABYLON = {}));
  28843. var BABYLON;
  28844. (function (BABYLON) {
  28845. var PhysicsImpostor = (function () {
  28846. function PhysicsImpostor(object, type, _options, _scene) {
  28847. var _this = this;
  28848. if (_options === void 0) { _options = { mass: 0 }; }
  28849. this.object = object;
  28850. this.type = type;
  28851. this._options = _options;
  28852. this._scene = _scene;
  28853. this._bodyUpdateRequired = false;
  28854. this._onBeforePhysicsStepCallbacks = new Array();
  28855. this._onAfterPhysicsStepCallbacks = new Array();
  28856. this._onPhysicsCollideCallbacks = [];
  28857. this._deltaPosition = BABYLON.Vector3.Zero();
  28858. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28859. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28860. /**
  28861. * this function is executed by the physics engine.
  28862. */
  28863. this.beforeStep = function () {
  28864. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28865. //conjugate deltaRotation
  28866. if (_this._deltaRotationConjugated) {
  28867. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28868. }
  28869. else {
  28870. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28871. }
  28872. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28873. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28874. func(_this);
  28875. });
  28876. };
  28877. /**
  28878. * this function is executed by the physics engine.
  28879. */
  28880. this.afterStep = function () {
  28881. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28882. func(_this);
  28883. });
  28884. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28885. _this.object.position.addInPlace(_this._deltaPosition);
  28886. if (_this._deltaRotation) {
  28887. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28888. }
  28889. };
  28890. //event and body object due to cannon's event-based architecture.
  28891. this.onCollide = function (e) {
  28892. if (!_this._onPhysicsCollideCallbacks.length)
  28893. return;
  28894. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28895. if (otherImpostor) {
  28896. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28897. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28898. }).forEach(function (obj) {
  28899. obj.callback(_this, otherImpostor);
  28900. });
  28901. }
  28902. };
  28903. //sanity check!
  28904. if (!this.object) {
  28905. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28906. return;
  28907. }
  28908. //legacy support for old syntax.
  28909. if (!this._scene && object.getScene) {
  28910. this._scene = object.getScene();
  28911. }
  28912. this._physicsEngine = this._scene.getPhysicsEngine();
  28913. if (!this._physicsEngine) {
  28914. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28915. }
  28916. else {
  28917. //set the object's quaternion, if not set
  28918. if (!this.object.rotationQuaternion) {
  28919. if (this.object.rotation) {
  28920. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28921. }
  28922. else {
  28923. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28924. }
  28925. }
  28926. //default options params
  28927. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28928. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28929. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28930. this._joints = [];
  28931. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28932. if (!this.object.parent) {
  28933. this._init();
  28934. }
  28935. }
  28936. }
  28937. /**
  28938. * This function will completly initialize this impostor.
  28939. * It will create a new body - but only if this mesh has no parent.
  28940. * If it has, this impostor will not be used other than to define the impostor
  28941. * of the child mesh.
  28942. */
  28943. PhysicsImpostor.prototype._init = function () {
  28944. this._physicsEngine.removeImpostor(this);
  28945. this.physicsBody = null;
  28946. this._parent = this._parent || this._getPhysicsParent();
  28947. if (!this.parent) {
  28948. this._physicsEngine.addImpostor(this);
  28949. }
  28950. };
  28951. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28952. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28953. var parentMesh = this.object.parent;
  28954. return parentMesh.physicsImpostor;
  28955. }
  28956. return;
  28957. };
  28958. /**
  28959. * Should a new body be generated.
  28960. */
  28961. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28962. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28963. };
  28964. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28965. this.forceUpdate();
  28966. };
  28967. /**
  28968. * Force a regeneration of this or the parent's impostor's body.
  28969. * Use under cautious - This will remove all joints already implemented.
  28970. */
  28971. PhysicsImpostor.prototype.forceUpdate = function () {
  28972. this._init();
  28973. if (this.parent) {
  28974. this.parent.forceUpdate();
  28975. }
  28976. };
  28977. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28978. /*public get mesh(): AbstractMesh {
  28979. return this._mesh;
  28980. }*/
  28981. /**
  28982. * Gets the body that holds this impostor. Either its own, or its parent.
  28983. */
  28984. get: function () {
  28985. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28986. },
  28987. /**
  28988. * Set the physics body. Used mainly by the physics engine/plugin
  28989. */
  28990. set: function (physicsBody) {
  28991. if (this._physicsBody) {
  28992. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28993. }
  28994. this._physicsBody = physicsBody;
  28995. this.resetUpdateFlags();
  28996. },
  28997. enumerable: true,
  28998. configurable: true
  28999. });
  29000. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29001. get: function () {
  29002. return this._parent;
  29003. },
  29004. enumerable: true,
  29005. configurable: true
  29006. });
  29007. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29008. this._bodyUpdateRequired = false;
  29009. };
  29010. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29011. if (this.object.getBoundingInfo) {
  29012. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29013. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29014. }
  29015. else {
  29016. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29017. }
  29018. };
  29019. PhysicsImpostor.prototype.getObjectCenter = function () {
  29020. if (this.object.getBoundingInfo) {
  29021. return this.object.getBoundingInfo().boundingBox.center;
  29022. }
  29023. else {
  29024. return this.object.position;
  29025. }
  29026. };
  29027. /**
  29028. * Get a specific parametes from the options parameter.
  29029. */
  29030. PhysicsImpostor.prototype.getParam = function (paramName) {
  29031. return this._options[paramName];
  29032. };
  29033. /**
  29034. * Sets a specific parameter in the options given to the physics plugin
  29035. */
  29036. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29037. this._options[paramName] = value;
  29038. this._bodyUpdateRequired = true;
  29039. };
  29040. /**
  29041. * Specifically change the body's mass option. Won't recreate the physics body object
  29042. */
  29043. PhysicsImpostor.prototype.setMass = function (mass) {
  29044. if (this.getParam("mass") !== mass) {
  29045. this.setParam("mass", mass);
  29046. }
  29047. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29048. };
  29049. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29050. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29051. };
  29052. /**
  29053. * Set the body's linear velocity.
  29054. */
  29055. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29056. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29057. };
  29058. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29059. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29060. };
  29061. /**
  29062. * Set the body's linear velocity.
  29063. */
  29064. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29065. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29066. };
  29067. /**
  29068. * Execute a function with the physics plugin native code.
  29069. * Provide a function the will have two variables - the world object and the physics body object.
  29070. */
  29071. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29072. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29073. };
  29074. /**
  29075. * Register a function that will be executed before the physics world is stepping forward.
  29076. */
  29077. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29078. this._onBeforePhysicsStepCallbacks.push(func);
  29079. };
  29080. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29081. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29082. if (index > -1) {
  29083. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29084. }
  29085. else {
  29086. BABYLON.Tools.Warn("Function to remove was not found");
  29087. }
  29088. };
  29089. /**
  29090. * Register a function that will be executed after the physics step
  29091. */
  29092. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29093. this._onAfterPhysicsStepCallbacks.push(func);
  29094. };
  29095. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29096. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29097. if (index > -1) {
  29098. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29099. }
  29100. else {
  29101. BABYLON.Tools.Warn("Function to remove was not found");
  29102. }
  29103. };
  29104. /**
  29105. * register a function that will be executed when this impostor collides against a different body.
  29106. */
  29107. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29108. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29109. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29110. };
  29111. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29112. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29113. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29114. if (index > -1) {
  29115. this._onPhysicsCollideCallbacks.splice(index, 1);
  29116. }
  29117. else {
  29118. BABYLON.Tools.Warn("Function to remove was not found");
  29119. }
  29120. };
  29121. /**
  29122. * Apply a force
  29123. */
  29124. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29125. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29126. };
  29127. /**
  29128. * Apply an impulse
  29129. */
  29130. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29131. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29132. };
  29133. /**
  29134. * A help function to create a joint.
  29135. */
  29136. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29137. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29138. this.addJoint(otherImpostor, joint);
  29139. };
  29140. /**
  29141. * Add a joint to this impostor with a different impostor.
  29142. */
  29143. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29144. this._joints.push({
  29145. otherImpostor: otherImpostor,
  29146. joint: joint
  29147. });
  29148. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29149. };
  29150. /**
  29151. * Will keep this body still, in a sleep mode.
  29152. */
  29153. PhysicsImpostor.prototype.sleep = function () {
  29154. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29155. };
  29156. /**
  29157. * Wake the body up.
  29158. */
  29159. PhysicsImpostor.prototype.wakeUp = function () {
  29160. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29161. };
  29162. PhysicsImpostor.prototype.clone = function (newObject) {
  29163. if (!newObject)
  29164. return null;
  29165. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29166. };
  29167. PhysicsImpostor.prototype.dispose = function () {
  29168. var _this = this;
  29169. //no dispose if no physics engine is available.
  29170. if (!this._physicsEngine) {
  29171. return;
  29172. }
  29173. this._joints.forEach(function (j) {
  29174. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29175. });
  29176. //dispose the physics body
  29177. this._physicsEngine.removeImpostor(this);
  29178. if (this.parent) {
  29179. this.parent.forceUpdate();
  29180. }
  29181. else {
  29182. }
  29183. };
  29184. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29185. this._deltaPosition.copyFrom(position);
  29186. };
  29187. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29188. if (!this._deltaRotation) {
  29189. this._deltaRotation = new BABYLON.Quaternion();
  29190. }
  29191. this._deltaRotation.copyFrom(rotation);
  29192. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29193. };
  29194. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29195. //Impostor types
  29196. PhysicsImpostor.NoImpostor = 0;
  29197. PhysicsImpostor.SphereImpostor = 1;
  29198. PhysicsImpostor.BoxImpostor = 2;
  29199. PhysicsImpostor.PlaneImpostor = 3;
  29200. PhysicsImpostor.MeshImpostor = 4;
  29201. PhysicsImpostor.CylinderImpostor = 7;
  29202. PhysicsImpostor.ParticleImpostor = 8;
  29203. PhysicsImpostor.HeightmapImpostor = 9;
  29204. return PhysicsImpostor;
  29205. }());
  29206. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29207. })(BABYLON || (BABYLON = {}));
  29208. var BABYLON;
  29209. (function (BABYLON) {
  29210. var PhysicsEngine = (function () {
  29211. function PhysicsEngine(gravity, _physicsPlugin) {
  29212. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29213. this._physicsPlugin = _physicsPlugin;
  29214. //new methods and parameters
  29215. this._impostors = [];
  29216. this._joints = [];
  29217. if (!this._physicsPlugin.isSupported()) {
  29218. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29219. + "Please make sure it is included.");
  29220. }
  29221. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29222. this.setGravity(gravity);
  29223. this.setTimeStep();
  29224. }
  29225. PhysicsEngine.prototype.setGravity = function (gravity) {
  29226. this.gravity = gravity;
  29227. this._physicsPlugin.setGravity(this.gravity);
  29228. };
  29229. /**
  29230. * Set the time step of the physics engine.
  29231. * default is 1/60.
  29232. * To slow it down, enter 1/600 for example.
  29233. * To speed it up, 1/30
  29234. * @param {number} newTimeStep the new timestep to apply to this world.
  29235. */
  29236. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29237. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29238. this._physicsPlugin.setTimeStep(newTimeStep);
  29239. };
  29240. PhysicsEngine.prototype.dispose = function () {
  29241. this._impostors.forEach(function (impostor) {
  29242. impostor.dispose();
  29243. });
  29244. this._physicsPlugin.dispose();
  29245. };
  29246. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29247. return this._physicsPlugin.name;
  29248. };
  29249. /**
  29250. * Adding a new impostor for the impostor tracking.
  29251. * This will be done by the impostor itself.
  29252. * @param {PhysicsImpostor} impostor the impostor to add
  29253. */
  29254. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29255. impostor.uniqueId = this._impostors.push(impostor);
  29256. //if no parent, generate the body
  29257. if (!impostor.parent) {
  29258. this._physicsPlugin.generatePhysicsBody(impostor);
  29259. }
  29260. };
  29261. /**
  29262. * Remove an impostor from the engine.
  29263. * This impostor and its mesh will not longer be updated by the physics engine.
  29264. * @param {PhysicsImpostor} impostor the impostor to remove
  29265. */
  29266. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29267. var index = this._impostors.indexOf(impostor);
  29268. if (index > -1) {
  29269. var removed = this._impostors.splice(index, 1);
  29270. //Is it needed?
  29271. if (removed.length) {
  29272. //this will also remove it from the world.
  29273. removed[0].physicsBody = null;
  29274. }
  29275. }
  29276. };
  29277. /**
  29278. * Add a joint to the physics engine
  29279. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29280. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29281. * @param {PhysicsJoint} the joint that will connect both impostors.
  29282. */
  29283. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29284. var impostorJoint = {
  29285. mainImpostor: mainImpostor,
  29286. connectedImpostor: connectedImpostor,
  29287. joint: joint
  29288. };
  29289. joint.physicsPlugin = this._physicsPlugin;
  29290. this._joints.push(impostorJoint);
  29291. this._physicsPlugin.generateJoint(impostorJoint);
  29292. };
  29293. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29294. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29295. return (impostorJoint.connectedImpostor === connectedImpostor
  29296. && impostorJoint.joint === joint
  29297. && impostorJoint.mainImpostor === mainImpostor);
  29298. });
  29299. if (matchingJoints.length) {
  29300. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29301. }
  29302. };
  29303. /**
  29304. * Called by the scene. no need to call it.
  29305. */
  29306. PhysicsEngine.prototype._step = function (delta) {
  29307. var _this = this;
  29308. //check if any mesh has no body / requires an update
  29309. this._impostors.forEach(function (impostor) {
  29310. if (impostor.isBodyInitRequired()) {
  29311. _this._physicsPlugin.generatePhysicsBody(impostor);
  29312. }
  29313. });
  29314. if (delta > 0.1) {
  29315. delta = 0.1;
  29316. }
  29317. else if (delta <= 0) {
  29318. delta = 1.0 / 60.0;
  29319. }
  29320. this._physicsPlugin.executeStep(delta, this._impostors);
  29321. };
  29322. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29323. return this._physicsPlugin;
  29324. };
  29325. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29326. for (var i = 0; i < this._impostors.length; ++i) {
  29327. if (this._impostors[i].object === object) {
  29328. return this._impostors[i];
  29329. }
  29330. }
  29331. };
  29332. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29333. for (var i = 0; i < this._impostors.length; ++i) {
  29334. if (this._impostors[i].physicsBody === body) {
  29335. return this._impostors[i];
  29336. }
  29337. }
  29338. };
  29339. // Statics, Legacy support.
  29340. /**
  29341. * @Deprecated
  29342. *
  29343. */
  29344. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29345. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29346. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29347. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29348. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29349. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29350. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29351. PhysicsEngine.CapsuleImpostor = -1;
  29352. PhysicsEngine.ConeImpostor = -1;
  29353. PhysicsEngine.ConvexHullImpostor = -1;
  29354. PhysicsEngine.Epsilon = 0.001;
  29355. return PhysicsEngine;
  29356. }());
  29357. BABYLON.PhysicsEngine = PhysicsEngine;
  29358. })(BABYLON || (BABYLON = {}));
  29359. var BABYLON;
  29360. (function (BABYLON) {
  29361. var VertexData = (function () {
  29362. function VertexData() {
  29363. }
  29364. VertexData.prototype.set = function (data, kind) {
  29365. switch (kind) {
  29366. case BABYLON.VertexBuffer.PositionKind:
  29367. this.positions = data;
  29368. break;
  29369. case BABYLON.VertexBuffer.NormalKind:
  29370. this.normals = data;
  29371. break;
  29372. case BABYLON.VertexBuffer.UVKind:
  29373. this.uvs = data;
  29374. break;
  29375. case BABYLON.VertexBuffer.UV2Kind:
  29376. this.uvs2 = data;
  29377. break;
  29378. case BABYLON.VertexBuffer.UV3Kind:
  29379. this.uvs3 = data;
  29380. break;
  29381. case BABYLON.VertexBuffer.UV4Kind:
  29382. this.uvs4 = data;
  29383. break;
  29384. case BABYLON.VertexBuffer.UV5Kind:
  29385. this.uvs5 = data;
  29386. break;
  29387. case BABYLON.VertexBuffer.UV6Kind:
  29388. this.uvs6 = data;
  29389. break;
  29390. case BABYLON.VertexBuffer.ColorKind:
  29391. this.colors = data;
  29392. break;
  29393. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29394. this.matricesIndices = data;
  29395. break;
  29396. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29397. this.matricesWeights = data;
  29398. break;
  29399. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29400. this.matricesIndicesExtra = data;
  29401. break;
  29402. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29403. this.matricesWeightsExtra = data;
  29404. break;
  29405. }
  29406. };
  29407. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29408. this._applyTo(mesh, updatable);
  29409. };
  29410. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29411. this._applyTo(geometry, updatable);
  29412. };
  29413. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29414. this._update(mesh);
  29415. };
  29416. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29417. this._update(geometry);
  29418. };
  29419. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29420. if (this.positions) {
  29421. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29422. }
  29423. if (this.normals) {
  29424. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29425. }
  29426. if (this.uvs) {
  29427. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29428. }
  29429. if (this.uvs2) {
  29430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29431. }
  29432. if (this.uvs3) {
  29433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29434. }
  29435. if (this.uvs4) {
  29436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29437. }
  29438. if (this.uvs5) {
  29439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29440. }
  29441. if (this.uvs6) {
  29442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29443. }
  29444. if (this.colors) {
  29445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29446. }
  29447. if (this.matricesIndices) {
  29448. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29449. }
  29450. if (this.matricesWeights) {
  29451. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29452. }
  29453. if (this.matricesIndicesExtra) {
  29454. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29455. }
  29456. if (this.matricesWeightsExtra) {
  29457. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29458. }
  29459. if (this.indices) {
  29460. meshOrGeometry.setIndices(this.indices);
  29461. }
  29462. };
  29463. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29464. if (this.positions) {
  29465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29466. }
  29467. if (this.normals) {
  29468. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29469. }
  29470. if (this.uvs) {
  29471. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29472. }
  29473. if (this.uvs2) {
  29474. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29475. }
  29476. if (this.uvs3) {
  29477. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29478. }
  29479. if (this.uvs4) {
  29480. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29481. }
  29482. if (this.uvs5) {
  29483. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29484. }
  29485. if (this.uvs6) {
  29486. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29487. }
  29488. if (this.colors) {
  29489. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29490. }
  29491. if (this.matricesIndices) {
  29492. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29493. }
  29494. if (this.matricesWeights) {
  29495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29496. }
  29497. if (this.matricesIndicesExtra) {
  29498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29499. }
  29500. if (this.matricesWeightsExtra) {
  29501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29502. }
  29503. if (this.indices) {
  29504. meshOrGeometry.setIndices(this.indices);
  29505. }
  29506. };
  29507. VertexData.prototype.transform = function (matrix) {
  29508. var transformed = BABYLON.Vector3.Zero();
  29509. var index;
  29510. if (this.positions) {
  29511. var position = BABYLON.Vector3.Zero();
  29512. for (index = 0; index < this.positions.length; index += 3) {
  29513. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29514. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29515. this.positions[index] = transformed.x;
  29516. this.positions[index + 1] = transformed.y;
  29517. this.positions[index + 2] = transformed.z;
  29518. }
  29519. }
  29520. if (this.normals) {
  29521. var normal = BABYLON.Vector3.Zero();
  29522. for (index = 0; index < this.normals.length; index += 3) {
  29523. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29524. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29525. this.normals[index] = transformed.x;
  29526. this.normals[index + 1] = transformed.y;
  29527. this.normals[index + 2] = transformed.z;
  29528. }
  29529. }
  29530. };
  29531. VertexData.prototype.merge = function (other) {
  29532. if (other.indices) {
  29533. if (!this.indices) {
  29534. this.indices = [];
  29535. }
  29536. var offset = this.positions ? this.positions.length / 3 : 0;
  29537. for (var index = 0; index < other.indices.length; index++) {
  29538. //TODO check type - if Int32Array!
  29539. this.indices.push(other.indices[index] + offset);
  29540. }
  29541. }
  29542. this.positions = this._mergeElement(this.positions, other.positions);
  29543. this.normals = this._mergeElement(this.normals, other.normals);
  29544. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29545. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29546. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29547. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29548. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29549. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29550. this.colors = this._mergeElement(this.colors, other.colors);
  29551. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29552. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29553. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29554. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29555. };
  29556. VertexData.prototype._mergeElement = function (source, other) {
  29557. if (!other)
  29558. return source;
  29559. if (!source)
  29560. return other;
  29561. var len = other.length + source.length;
  29562. var isSrcTypedArray = source instanceof Float32Array;
  29563. var isOthTypedArray = other instanceof Float32Array;
  29564. // use non-loop method when the source is Float32Array
  29565. if (isSrcTypedArray) {
  29566. var ret32 = new Float32Array(len);
  29567. ret32.set(source);
  29568. ret32.set(other, source.length);
  29569. return ret32;
  29570. }
  29571. else if (!isOthTypedArray) {
  29572. return source.concat(other);
  29573. }
  29574. else {
  29575. var ret = source.slice(0); // copy source to a separate array
  29576. for (var i = 0, len = other.length; i < len; i++) {
  29577. ret.push(other[i]);
  29578. }
  29579. return ret;
  29580. }
  29581. };
  29582. VertexData.prototype.serialize = function () {
  29583. var serializationObject = this.serialize();
  29584. if (this.positions) {
  29585. serializationObject.positions = this.positions;
  29586. }
  29587. if (this.normals) {
  29588. serializationObject.normals = this.normals;
  29589. }
  29590. if (this.uvs) {
  29591. serializationObject.uvs = this.uvs;
  29592. }
  29593. if (this.uvs2) {
  29594. serializationObject.uvs2 = this.uvs2;
  29595. }
  29596. if (this.uvs3) {
  29597. serializationObject.uvs3 = this.uvs3;
  29598. }
  29599. if (this.uvs4) {
  29600. serializationObject.uvs4 = this.uvs4;
  29601. }
  29602. if (this.uvs5) {
  29603. serializationObject.uvs5 = this.uvs5;
  29604. }
  29605. if (this.uvs6) {
  29606. serializationObject.uvs6 = this.uvs6;
  29607. }
  29608. if (this.colors) {
  29609. serializationObject.colors = this.colors;
  29610. }
  29611. if (this.matricesIndices) {
  29612. serializationObject.matricesIndices = this.matricesIndices;
  29613. serializationObject.matricesIndices._isExpanded = true;
  29614. }
  29615. if (this.matricesWeights) {
  29616. serializationObject.matricesWeights = this.matricesWeights;
  29617. }
  29618. if (this.matricesIndicesExtra) {
  29619. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29620. serializationObject.matricesIndicesExtra._isExpanded = true;
  29621. }
  29622. if (this.matricesWeightsExtra) {
  29623. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29624. }
  29625. serializationObject.indices = this.indices;
  29626. return serializationObject;
  29627. };
  29628. // Statics
  29629. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29630. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29631. };
  29632. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29633. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29634. };
  29635. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29636. var result = new VertexData();
  29637. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29638. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29639. }
  29640. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29641. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29642. }
  29643. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29644. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29645. }
  29646. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29647. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29648. }
  29649. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29650. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29651. }
  29652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29653. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29654. }
  29655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29656. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29657. }
  29658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29659. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29660. }
  29661. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29662. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29663. }
  29664. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29665. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29666. }
  29667. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29668. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29669. }
  29670. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29671. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29672. }
  29673. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29674. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29675. }
  29676. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29677. return result;
  29678. };
  29679. VertexData.CreateRibbon = function (options) {
  29680. var pathArray = options.pathArray;
  29681. var closeArray = options.closeArray || false;
  29682. var closePath = options.closePath || false;
  29683. var invertUV = options.invertUV || false;
  29684. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29685. var offset = options.offset || defaultOffset;
  29686. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29687. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29688. var positions = [];
  29689. var indices = [];
  29690. var normals = [];
  29691. var uvs = [];
  29692. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29693. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29694. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29695. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29696. var minlg; // minimal length among all paths from pathArray
  29697. var lg = []; // array of path lengths : nb of vertex per path
  29698. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29699. var p; // path iterator
  29700. var i; // point iterator
  29701. var j; // point iterator
  29702. // if single path in pathArray
  29703. if (pathArray.length < 2) {
  29704. var ar1 = [];
  29705. var ar2 = [];
  29706. for (i = 0; i < pathArray[0].length - offset; i++) {
  29707. ar1.push(pathArray[0][i]);
  29708. ar2.push(pathArray[0][i + offset]);
  29709. }
  29710. pathArray = [ar1, ar2];
  29711. }
  29712. // positions and horizontal distances (u)
  29713. var idc = 0;
  29714. var closePathCorr = (closePath) ? 1 : 0;
  29715. var path;
  29716. var l;
  29717. minlg = pathArray[0].length;
  29718. var vectlg;
  29719. var dist;
  29720. for (p = 0; p < pathArray.length; p++) {
  29721. uTotalDistance[p] = 0;
  29722. us[p] = [0];
  29723. path = pathArray[p];
  29724. l = path.length;
  29725. minlg = (minlg < l) ? minlg : l;
  29726. j = 0;
  29727. while (j < l) {
  29728. positions.push(path[j].x, path[j].y, path[j].z);
  29729. if (j > 0) {
  29730. vectlg = path[j].subtract(path[j - 1]).length();
  29731. dist = vectlg + uTotalDistance[p];
  29732. us[p].push(dist);
  29733. uTotalDistance[p] = dist;
  29734. }
  29735. j++;
  29736. }
  29737. if (closePath) {
  29738. j--;
  29739. positions.push(path[0].x, path[0].y, path[0].z);
  29740. vectlg = path[j].subtract(path[0]).length();
  29741. dist = vectlg + uTotalDistance[p];
  29742. us[p].push(dist);
  29743. uTotalDistance[p] = dist;
  29744. }
  29745. lg[p] = l + closePathCorr;
  29746. idx[p] = idc;
  29747. idc += (l + closePathCorr);
  29748. }
  29749. // vertical distances (v)
  29750. var path1;
  29751. var path2;
  29752. var vertex1;
  29753. var vertex2;
  29754. for (i = 0; i < minlg + closePathCorr; i++) {
  29755. vTotalDistance[i] = 0;
  29756. vs[i] = [0];
  29757. for (p = 0; p < pathArray.length - 1; p++) {
  29758. path1 = pathArray[p];
  29759. path2 = pathArray[p + 1];
  29760. if (i === minlg) {
  29761. vertex1 = path1[0];
  29762. vertex2 = path2[0];
  29763. }
  29764. else {
  29765. vertex1 = path1[i];
  29766. vertex2 = path2[i];
  29767. }
  29768. vectlg = vertex2.subtract(vertex1).length();
  29769. dist = vectlg + vTotalDistance[i];
  29770. vs[i].push(dist);
  29771. vTotalDistance[i] = dist;
  29772. }
  29773. if (closeArray) {
  29774. path1 = pathArray[p];
  29775. path2 = pathArray[0];
  29776. if (i === minlg) {
  29777. vertex2 = path2[0];
  29778. }
  29779. vectlg = vertex2.subtract(vertex1).length();
  29780. dist = vectlg + vTotalDistance[i];
  29781. vTotalDistance[i] = dist;
  29782. }
  29783. }
  29784. // uvs
  29785. var u;
  29786. var v;
  29787. for (p = 0; p < pathArray.length; p++) {
  29788. for (i = 0; i < minlg + closePathCorr; i++) {
  29789. u = us[p][i] / uTotalDistance[p];
  29790. v = vs[i][p] / vTotalDistance[i];
  29791. if (invertUV) {
  29792. uvs.push(v, u);
  29793. }
  29794. else {
  29795. uvs.push(u, v);
  29796. }
  29797. }
  29798. }
  29799. // indices
  29800. p = 0; // path index
  29801. var pi = 0; // positions array index
  29802. var l1 = lg[p] - 1; // path1 length
  29803. var l2 = lg[p + 1] - 1; // path2 length
  29804. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29805. var shft = idx[1] - idx[0]; // shift
  29806. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29807. while (pi <= min && p < path1nb) {
  29808. // 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
  29809. indices.push(pi, pi + shft, pi + 1);
  29810. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29811. pi += 1;
  29812. if (pi === min) {
  29813. p++;
  29814. if (p === lg.length - 1) {
  29815. shft = idx[0] - idx[p];
  29816. l1 = lg[p] - 1;
  29817. l2 = lg[0] - 1;
  29818. }
  29819. else {
  29820. shft = idx[p + 1] - idx[p];
  29821. l1 = lg[p] - 1;
  29822. l2 = lg[p + 1] - 1;
  29823. }
  29824. pi = idx[p];
  29825. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29826. }
  29827. }
  29828. // normals
  29829. VertexData.ComputeNormals(positions, indices, normals);
  29830. if (closePath) {
  29831. var indexFirst = 0;
  29832. var indexLast = 0;
  29833. for (p = 0; p < pathArray.length; p++) {
  29834. indexFirst = idx[p] * 3;
  29835. if (p + 1 < pathArray.length) {
  29836. indexLast = (idx[p + 1] - 1) * 3;
  29837. }
  29838. else {
  29839. indexLast = normals.length - 3;
  29840. }
  29841. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29842. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29843. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29844. normals[indexLast] = normals[indexFirst];
  29845. normals[indexLast + 1] = normals[indexFirst + 1];
  29846. normals[indexLast + 2] = normals[indexFirst + 2];
  29847. }
  29848. }
  29849. // sides
  29850. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29851. // Result
  29852. var vertexData = new VertexData();
  29853. vertexData.indices = indices;
  29854. vertexData.positions = positions;
  29855. vertexData.normals = normals;
  29856. vertexData.uvs = uvs;
  29857. if (closePath) {
  29858. vertexData._idx = idx;
  29859. }
  29860. return vertexData;
  29861. };
  29862. VertexData.CreateBox = function (options) {
  29863. var normalsSource = [
  29864. new BABYLON.Vector3(0, 0, 1),
  29865. new BABYLON.Vector3(0, 0, -1),
  29866. new BABYLON.Vector3(1, 0, 0),
  29867. new BABYLON.Vector3(-1, 0, 0),
  29868. new BABYLON.Vector3(0, 1, 0),
  29869. new BABYLON.Vector3(0, -1, 0)
  29870. ];
  29871. var indices = [];
  29872. var positions = [];
  29873. var normals = [];
  29874. var uvs = [];
  29875. var width = options.width || options.size || 1;
  29876. var height = options.height || options.size || 1;
  29877. var depth = options.depth || options.size || 1;
  29878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29879. var faceUV = options.faceUV || new Array(6);
  29880. var faceColors = options.faceColors;
  29881. var colors = [];
  29882. // default face colors and UV if undefined
  29883. for (var f = 0; f < 6; f++) {
  29884. if (faceUV[f] === undefined) {
  29885. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29886. }
  29887. if (faceColors && faceColors[f] === undefined) {
  29888. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29889. }
  29890. }
  29891. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29892. // Create each face in turn.
  29893. for (var index = 0; index < normalsSource.length; index++) {
  29894. var normal = normalsSource[index];
  29895. // Get two vectors perpendicular to the face normal and to each other.
  29896. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29897. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29898. // Six indices (two triangles) per face.
  29899. var verticesLength = positions.length / 3;
  29900. indices.push(verticesLength);
  29901. indices.push(verticesLength + 1);
  29902. indices.push(verticesLength + 2);
  29903. indices.push(verticesLength);
  29904. indices.push(verticesLength + 2);
  29905. indices.push(verticesLength + 3);
  29906. // Four vertices per face.
  29907. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29908. positions.push(vertex.x, vertex.y, vertex.z);
  29909. normals.push(normal.x, normal.y, normal.z);
  29910. uvs.push(faceUV[index].z, faceUV[index].w);
  29911. if (faceColors) {
  29912. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29913. }
  29914. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29915. positions.push(vertex.x, vertex.y, vertex.z);
  29916. normals.push(normal.x, normal.y, normal.z);
  29917. uvs.push(faceUV[index].x, faceUV[index].w);
  29918. if (faceColors) {
  29919. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29920. }
  29921. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29922. positions.push(vertex.x, vertex.y, vertex.z);
  29923. normals.push(normal.x, normal.y, normal.z);
  29924. uvs.push(faceUV[index].x, faceUV[index].y);
  29925. if (faceColors) {
  29926. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29927. }
  29928. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29929. positions.push(vertex.x, vertex.y, vertex.z);
  29930. normals.push(normal.x, normal.y, normal.z);
  29931. uvs.push(faceUV[index].z, faceUV[index].y);
  29932. if (faceColors) {
  29933. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29934. }
  29935. }
  29936. // sides
  29937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29938. // Result
  29939. var vertexData = new VertexData();
  29940. vertexData.indices = indices;
  29941. vertexData.positions = positions;
  29942. vertexData.normals = normals;
  29943. vertexData.uvs = uvs;
  29944. if (faceColors) {
  29945. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29946. vertexData.colors = totalColors;
  29947. }
  29948. return vertexData;
  29949. };
  29950. VertexData.CreateSphere = function (options) {
  29951. var segments = options.segments || 32;
  29952. var diameterX = options.diameterX || options.diameter || 1;
  29953. var diameterY = options.diameterY || options.diameter || 1;
  29954. var diameterZ = options.diameterZ || options.diameter || 1;
  29955. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29956. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29957. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29958. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29959. var totalZRotationSteps = 2 + segments;
  29960. var totalYRotationSteps = 2 * totalZRotationSteps;
  29961. var indices = [];
  29962. var positions = [];
  29963. var normals = [];
  29964. var uvs = [];
  29965. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29966. var normalizedZ = zRotationStep / totalZRotationSteps;
  29967. var angleZ = normalizedZ * Math.PI * slice;
  29968. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29969. var normalizedY = yRotationStep / totalYRotationSteps;
  29970. var angleY = normalizedY * Math.PI * 2 * arc;
  29971. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29972. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29973. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29974. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29975. var vertex = complete.multiply(radius);
  29976. var normal = complete.divide(radius).normalize();
  29977. positions.push(vertex.x, vertex.y, vertex.z);
  29978. normals.push(normal.x, normal.y, normal.z);
  29979. uvs.push(normalizedY, normalizedZ);
  29980. }
  29981. if (zRotationStep > 0) {
  29982. var verticesCount = positions.length / 3;
  29983. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29984. indices.push((firstIndex));
  29985. indices.push((firstIndex + 1));
  29986. indices.push(firstIndex + totalYRotationSteps + 1);
  29987. indices.push((firstIndex + totalYRotationSteps + 1));
  29988. indices.push((firstIndex + 1));
  29989. indices.push((firstIndex + totalYRotationSteps + 2));
  29990. }
  29991. }
  29992. }
  29993. // Sides
  29994. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29995. // Result
  29996. var vertexData = new VertexData();
  29997. vertexData.indices = indices;
  29998. vertexData.positions = positions;
  29999. vertexData.normals = normals;
  30000. vertexData.uvs = uvs;
  30001. return vertexData;
  30002. };
  30003. // Cylinder and cone
  30004. VertexData.CreateCylinder = function (options) {
  30005. var height = options.height || 2;
  30006. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30007. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30008. var tessellation = options.tessellation || 24;
  30009. var subdivisions = options.subdivisions || 1;
  30010. var hasRings = options.hasRings;
  30011. var enclose = options.enclose;
  30012. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30013. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30014. var faceUV = options.faceUV || new Array(3);
  30015. var faceColors = options.faceColors;
  30016. // default face colors and UV if undefined
  30017. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30018. var ringNb = (hasRings) ? subdivisions : 1;
  30019. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30020. var f;
  30021. for (f = 0; f < surfaceNb; f++) {
  30022. if (faceColors && faceColors[f] === undefined) {
  30023. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30024. }
  30025. }
  30026. for (f = 0; f < surfaceNb; f++) {
  30027. if (faceUV && faceUV[f] === undefined) {
  30028. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30029. }
  30030. }
  30031. var indices = [];
  30032. var positions = [];
  30033. var normals = [];
  30034. var uvs = [];
  30035. var colors = [];
  30036. var angle_step = Math.PI * 2 * arc / tessellation;
  30037. var angle;
  30038. var h;
  30039. var radius;
  30040. var tan = (diameterBottom - diameterTop) / 2 / height;
  30041. var ringVertex = BABYLON.Vector3.Zero();
  30042. var ringNormal = BABYLON.Vector3.Zero();
  30043. var ringFirstVertex = BABYLON.Vector3.Zero();
  30044. var ringFirstNormal = BABYLON.Vector3.Zero();
  30045. var quadNormal = BABYLON.Vector3.Zero();
  30046. var Y = BABYLON.Axis.Y;
  30047. // positions, normals, uvs
  30048. var i;
  30049. var j;
  30050. var r;
  30051. var ringIdx = 1;
  30052. var s = 1; // surface index
  30053. var cs = 0;
  30054. var v = 0;
  30055. for (i = 0; i <= subdivisions; i++) {
  30056. h = i / subdivisions;
  30057. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30058. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30059. for (r = 0; r < ringIdx; r++) {
  30060. if (hasRings) {
  30061. s += r;
  30062. }
  30063. if (enclose) {
  30064. s += 2 * r;
  30065. }
  30066. for (j = 0; j <= tessellation; j++) {
  30067. angle = j * angle_step;
  30068. // position
  30069. ringVertex.x = Math.cos(-angle) * radius;
  30070. ringVertex.y = -height / 2 + h * height;
  30071. ringVertex.z = Math.sin(-angle) * radius;
  30072. // normal
  30073. if (diameterTop === 0 && i === subdivisions) {
  30074. // if no top cap, reuse former normals
  30075. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30076. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30077. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30078. }
  30079. else {
  30080. ringNormal.x = ringVertex.x;
  30081. ringNormal.z = ringVertex.z;
  30082. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30083. ringNormal.normalize();
  30084. }
  30085. // keep first ring vertex values for enclose
  30086. if (j === 0) {
  30087. ringFirstVertex.copyFrom(ringVertex);
  30088. ringFirstNormal.copyFrom(ringNormal);
  30089. }
  30090. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30091. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30092. if (hasRings) {
  30093. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30094. }
  30095. else {
  30096. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30097. }
  30098. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30099. if (faceColors) {
  30100. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30101. }
  30102. }
  30103. // if enclose, add four vertices and their dedicated normals
  30104. if (arc !== 1 && enclose) {
  30105. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30106. positions.push(0, ringVertex.y, 0);
  30107. positions.push(0, ringVertex.y, 0);
  30108. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30109. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30110. quadNormal.normalize();
  30111. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30112. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30113. quadNormal.normalize();
  30114. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30115. if (hasRings) {
  30116. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30117. }
  30118. else {
  30119. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30120. }
  30121. uvs.push(faceUV[s + 1].x, v);
  30122. uvs.push(faceUV[s + 1].z, v);
  30123. if (hasRings) {
  30124. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30125. }
  30126. else {
  30127. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30128. }
  30129. uvs.push(faceUV[s + 2].x, v);
  30130. uvs.push(faceUV[s + 2].z, v);
  30131. if (faceColors) {
  30132. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30133. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30134. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30135. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30136. }
  30137. }
  30138. if (cs !== s) {
  30139. cs = s;
  30140. }
  30141. }
  30142. }
  30143. // indices
  30144. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30145. var s;
  30146. i = 0;
  30147. for (s = 0; s < subdivisions; s++) {
  30148. for (j = 0; j < tessellation; j++) {
  30149. var i0 = i * (e + 1) + j;
  30150. var i1 = (i + 1) * (e + 1) + j;
  30151. var i2 = i * (e + 1) + (j + 1);
  30152. var i3 = (i + 1) * (e + 1) + (j + 1);
  30153. indices.push(i0, i1, i2);
  30154. indices.push(i3, i2, i1);
  30155. }
  30156. if (arc !== 1 && enclose) {
  30157. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30158. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30159. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30160. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30161. }
  30162. i = (hasRings) ? (i + 2) : (i + 1);
  30163. }
  30164. // Caps
  30165. var createCylinderCap = function (isTop) {
  30166. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30167. if (radius === 0) {
  30168. return;
  30169. }
  30170. // Cap positions, normals & uvs
  30171. var angle;
  30172. var circleVector;
  30173. var i;
  30174. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30175. var c;
  30176. if (faceColors) {
  30177. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30178. }
  30179. // cap center
  30180. var vbase = positions.length / 3;
  30181. var offset = isTop ? height / 2 : -height / 2;
  30182. var center = new BABYLON.Vector3(0, offset, 0);
  30183. positions.push(center.x, center.y, center.z);
  30184. normals.push(0, isTop ? 1 : -1, 0);
  30185. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30186. if (faceColors) {
  30187. colors.push(c.r, c.g, c.b, c.a);
  30188. }
  30189. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30190. for (i = 0; i <= tessellation; i++) {
  30191. angle = Math.PI * 2 * i * arc / tessellation;
  30192. var cos = Math.cos(-angle);
  30193. var sin = Math.sin(-angle);
  30194. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30195. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30196. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30197. normals.push(0, isTop ? 1 : -1, 0);
  30198. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30199. if (faceColors) {
  30200. colors.push(c.r, c.g, c.b, c.a);
  30201. }
  30202. }
  30203. // Cap indices
  30204. for (i = 0; i < tessellation; i++) {
  30205. if (!isTop) {
  30206. indices.push(vbase);
  30207. indices.push(vbase + (i + 1));
  30208. indices.push(vbase + (i + 2));
  30209. }
  30210. else {
  30211. indices.push(vbase);
  30212. indices.push(vbase + (i + 2));
  30213. indices.push(vbase + (i + 1));
  30214. }
  30215. }
  30216. };
  30217. // add caps to geometry
  30218. createCylinderCap(false);
  30219. createCylinderCap(true);
  30220. // Sides
  30221. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30222. var vertexData = new VertexData();
  30223. vertexData.indices = indices;
  30224. vertexData.positions = positions;
  30225. vertexData.normals = normals;
  30226. vertexData.uvs = uvs;
  30227. if (faceColors) {
  30228. vertexData.colors = colors;
  30229. }
  30230. return vertexData;
  30231. };
  30232. VertexData.CreateTorus = function (options) {
  30233. var indices = [];
  30234. var positions = [];
  30235. var normals = [];
  30236. var uvs = [];
  30237. var diameter = options.diameter || 1;
  30238. var thickness = options.thickness || 0.5;
  30239. var tessellation = options.tessellation || 16;
  30240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30241. var stride = tessellation + 1;
  30242. for (var i = 0; i <= tessellation; i++) {
  30243. var u = i / tessellation;
  30244. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30245. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30246. for (var j = 0; j <= tessellation; j++) {
  30247. var v = 1 - j / tessellation;
  30248. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30249. var dx = Math.cos(innerAngle);
  30250. var dy = Math.sin(innerAngle);
  30251. // Create a vertex.
  30252. var normal = new BABYLON.Vector3(dx, dy, 0);
  30253. var position = normal.scale(thickness / 2);
  30254. var textureCoordinate = new BABYLON.Vector2(u, v);
  30255. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30256. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30257. positions.push(position.x, position.y, position.z);
  30258. normals.push(normal.x, normal.y, normal.z);
  30259. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30260. // And create indices for two triangles.
  30261. var nextI = (i + 1) % stride;
  30262. var nextJ = (j + 1) % stride;
  30263. indices.push(i * stride + j);
  30264. indices.push(i * stride + nextJ);
  30265. indices.push(nextI * stride + j);
  30266. indices.push(i * stride + nextJ);
  30267. indices.push(nextI * stride + nextJ);
  30268. indices.push(nextI * stride + j);
  30269. }
  30270. }
  30271. // Sides
  30272. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30273. // Result
  30274. var vertexData = new VertexData();
  30275. vertexData.indices = indices;
  30276. vertexData.positions = positions;
  30277. vertexData.normals = normals;
  30278. vertexData.uvs = uvs;
  30279. return vertexData;
  30280. };
  30281. VertexData.CreateLineSystem = function (options) {
  30282. var indices = [];
  30283. var positions = [];
  30284. var lines = options.lines;
  30285. var idx = 0;
  30286. for (var l = 0; l < lines.length; l++) {
  30287. var points = lines[l];
  30288. for (var index = 0; index < points.length; index++) {
  30289. positions.push(points[index].x, points[index].y, points[index].z);
  30290. if (index > 0) {
  30291. indices.push(idx - 1);
  30292. indices.push(idx);
  30293. }
  30294. idx++;
  30295. }
  30296. }
  30297. var vertexData = new VertexData();
  30298. vertexData.indices = indices;
  30299. vertexData.positions = positions;
  30300. return vertexData;
  30301. };
  30302. VertexData.CreateDashedLines = function (options) {
  30303. var dashSize = options.dashSize || 3;
  30304. var gapSize = options.gapSize || 1;
  30305. var dashNb = options.dashNb || 200;
  30306. var points = options.points;
  30307. var positions = new Array();
  30308. var indices = new Array();
  30309. var curvect = BABYLON.Vector3.Zero();
  30310. var lg = 0;
  30311. var nb = 0;
  30312. var shft = 0;
  30313. var dashshft = 0;
  30314. var curshft = 0;
  30315. var idx = 0;
  30316. var i = 0;
  30317. for (i = 0; i < points.length - 1; i++) {
  30318. points[i + 1].subtractToRef(points[i], curvect);
  30319. lg += curvect.length();
  30320. }
  30321. shft = lg / dashNb;
  30322. dashshft = dashSize * shft / (dashSize + gapSize);
  30323. for (i = 0; i < points.length - 1; i++) {
  30324. points[i + 1].subtractToRef(points[i], curvect);
  30325. nb = Math.floor(curvect.length() / shft);
  30326. curvect.normalize();
  30327. for (var j = 0; j < nb; j++) {
  30328. curshft = shft * j;
  30329. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30330. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30331. indices.push(idx, idx + 1);
  30332. idx += 2;
  30333. }
  30334. }
  30335. // Result
  30336. var vertexData = new VertexData();
  30337. vertexData.positions = positions;
  30338. vertexData.indices = indices;
  30339. return vertexData;
  30340. };
  30341. VertexData.CreateGround = function (options) {
  30342. var indices = [];
  30343. var positions = [];
  30344. var normals = [];
  30345. var uvs = [];
  30346. var row, col;
  30347. var width = options.width || 1;
  30348. var height = options.height || 1;
  30349. var subdivisions = options.subdivisions || 1;
  30350. for (row = 0; row <= subdivisions; row++) {
  30351. for (col = 0; col <= subdivisions; col++) {
  30352. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30353. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30354. positions.push(position.x, position.y, position.z);
  30355. normals.push(normal.x, normal.y, normal.z);
  30356. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30357. }
  30358. }
  30359. for (row = 0; row < subdivisions; row++) {
  30360. for (col = 0; col < subdivisions; col++) {
  30361. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30362. indices.push(col + 1 + row * (subdivisions + 1));
  30363. indices.push(col + row * (subdivisions + 1));
  30364. indices.push(col + (row + 1) * (subdivisions + 1));
  30365. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30366. indices.push(col + row * (subdivisions + 1));
  30367. }
  30368. }
  30369. // Result
  30370. var vertexData = new VertexData();
  30371. vertexData.indices = indices;
  30372. vertexData.positions = positions;
  30373. vertexData.normals = normals;
  30374. vertexData.uvs = uvs;
  30375. return vertexData;
  30376. };
  30377. VertexData.CreateTiledGround = function (options) {
  30378. var xmin = options.xmin || -1.0;
  30379. var zmin = options.zmin || -1.0;
  30380. var xmax = options.xmax || 1.0;
  30381. var zmax = options.zmax || 1.0;
  30382. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30383. var precision = options.precision || { w: 1, h: 1 };
  30384. var indices = [];
  30385. var positions = [];
  30386. var normals = [];
  30387. var uvs = [];
  30388. var row, col, tileRow, tileCol;
  30389. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30390. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30391. precision.w = (precision.w < 1) ? 1 : precision.w;
  30392. precision.h = (precision.h < 1) ? 1 : precision.h;
  30393. var tileSize = {
  30394. 'w': (xmax - xmin) / subdivisions.w,
  30395. 'h': (zmax - zmin) / subdivisions.h
  30396. };
  30397. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30398. // Indices
  30399. var base = positions.length / 3;
  30400. var rowLength = precision.w + 1;
  30401. for (row = 0; row < precision.h; row++) {
  30402. for (col = 0; col < precision.w; col++) {
  30403. var square = [
  30404. base + col + row * rowLength,
  30405. base + (col + 1) + row * rowLength,
  30406. base + (col + 1) + (row + 1) * rowLength,
  30407. base + col + (row + 1) * rowLength
  30408. ];
  30409. indices.push(square[1]);
  30410. indices.push(square[2]);
  30411. indices.push(square[3]);
  30412. indices.push(square[0]);
  30413. indices.push(square[1]);
  30414. indices.push(square[3]);
  30415. }
  30416. }
  30417. // Position, normals and uvs
  30418. var position = BABYLON.Vector3.Zero();
  30419. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30420. for (row = 0; row <= precision.h; row++) {
  30421. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30422. for (col = 0; col <= precision.w; col++) {
  30423. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30424. position.y = 0;
  30425. positions.push(position.x, position.y, position.z);
  30426. normals.push(normal.x, normal.y, normal.z);
  30427. uvs.push(col / precision.w, row / precision.h);
  30428. }
  30429. }
  30430. }
  30431. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30432. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30433. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30434. }
  30435. }
  30436. // Result
  30437. var vertexData = new VertexData();
  30438. vertexData.indices = indices;
  30439. vertexData.positions = positions;
  30440. vertexData.normals = normals;
  30441. vertexData.uvs = uvs;
  30442. return vertexData;
  30443. };
  30444. VertexData.CreateGroundFromHeightMap = function (options) {
  30445. var indices = [];
  30446. var positions = [];
  30447. var normals = [];
  30448. var uvs = [];
  30449. var row, col;
  30450. // Vertices
  30451. for (row = 0; row <= options.subdivisions; row++) {
  30452. for (col = 0; col <= options.subdivisions; col++) {
  30453. 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));
  30454. // Compute height
  30455. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30456. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30457. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30458. var r = options.buffer[pos] / 255.0;
  30459. var g = options.buffer[pos + 1] / 255.0;
  30460. var b = options.buffer[pos + 2] / 255.0;
  30461. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30462. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30463. // Add vertex
  30464. positions.push(position.x, position.y, position.z);
  30465. normals.push(0, 0, 0);
  30466. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30467. }
  30468. }
  30469. // Indices
  30470. for (row = 0; row < options.subdivisions; row++) {
  30471. for (col = 0; col < options.subdivisions; col++) {
  30472. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30473. indices.push(col + 1 + row * (options.subdivisions + 1));
  30474. indices.push(col + row * (options.subdivisions + 1));
  30475. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30476. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30477. indices.push(col + row * (options.subdivisions + 1));
  30478. }
  30479. }
  30480. // Normals
  30481. VertexData.ComputeNormals(positions, indices, normals);
  30482. // Result
  30483. var vertexData = new VertexData();
  30484. vertexData.indices = indices;
  30485. vertexData.positions = positions;
  30486. vertexData.normals = normals;
  30487. vertexData.uvs = uvs;
  30488. return vertexData;
  30489. };
  30490. VertexData.CreatePlane = function (options) {
  30491. var indices = [];
  30492. var positions = [];
  30493. var normals = [];
  30494. var uvs = [];
  30495. var width = options.width || options.size || 1;
  30496. var height = options.height || options.size || 1;
  30497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30498. // Vertices
  30499. var halfWidth = width / 2.0;
  30500. var halfHeight = height / 2.0;
  30501. positions.push(-halfWidth, -halfHeight, 0);
  30502. normals.push(0, 0, -1.0);
  30503. uvs.push(0.0, 0.0);
  30504. positions.push(halfWidth, -halfHeight, 0);
  30505. normals.push(0, 0, -1.0);
  30506. uvs.push(1.0, 0.0);
  30507. positions.push(halfWidth, halfHeight, 0);
  30508. normals.push(0, 0, -1.0);
  30509. uvs.push(1.0, 1.0);
  30510. positions.push(-halfWidth, halfHeight, 0);
  30511. normals.push(0, 0, -1.0);
  30512. uvs.push(0.0, 1.0);
  30513. // Indices
  30514. indices.push(0);
  30515. indices.push(1);
  30516. indices.push(2);
  30517. indices.push(0);
  30518. indices.push(2);
  30519. indices.push(3);
  30520. // Sides
  30521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30522. // Result
  30523. var vertexData = new VertexData();
  30524. vertexData.indices = indices;
  30525. vertexData.positions = positions;
  30526. vertexData.normals = normals;
  30527. vertexData.uvs = uvs;
  30528. return vertexData;
  30529. };
  30530. VertexData.CreateDisc = function (options) {
  30531. var positions = [];
  30532. var indices = [];
  30533. var normals = [];
  30534. var uvs = [];
  30535. var radius = options.radius || 0.5;
  30536. var tessellation = options.tessellation || 64;
  30537. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30538. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30539. // positions and uvs
  30540. positions.push(0, 0, 0); // disc center first
  30541. uvs.push(0.5, 0.5);
  30542. var theta = Math.PI * 2 * arc;
  30543. var step = theta / tessellation;
  30544. for (var a = 0; a < theta; a += step) {
  30545. var x = Math.cos(a);
  30546. var y = Math.sin(a);
  30547. var u = (x + 1) / 2;
  30548. var v = (1 - y) / 2;
  30549. positions.push(radius * x, radius * y, 0);
  30550. uvs.push(u, v);
  30551. }
  30552. if (arc === 1) {
  30553. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30554. uvs.push(uvs[2], uvs[3]);
  30555. }
  30556. //indices
  30557. var vertexNb = positions.length / 3;
  30558. for (var i = 1; i < vertexNb - 1; i++) {
  30559. indices.push(i + 1, 0, i);
  30560. }
  30561. // result
  30562. VertexData.ComputeNormals(positions, indices, normals);
  30563. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30564. var vertexData = new VertexData();
  30565. vertexData.indices = indices;
  30566. vertexData.positions = positions;
  30567. vertexData.normals = normals;
  30568. vertexData.uvs = uvs;
  30569. return vertexData;
  30570. };
  30571. VertexData.CreateIcoSphere = function (options) {
  30572. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30573. var radius = options.radius || 1;
  30574. var flat = (options.flat === undefined) ? true : options.flat;
  30575. var subdivisions = options.subdivisions || 4;
  30576. var radiusX = options.radiusX || radius;
  30577. var radiusY = options.radiusY || radius;
  30578. var radiusZ = options.radiusZ || radius;
  30579. var t = (1 + Math.sqrt(5)) / 2;
  30580. // 12 vertex x,y,z
  30581. var ico_vertices = [
  30582. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30583. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30584. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30585. ];
  30586. // index of 3 vertex makes a face of icopshere
  30587. var ico_indices = [
  30588. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30589. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30590. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30591. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30592. ];
  30593. // vertex for uv have aliased position, not for UV
  30594. var vertices_unalias_id = [
  30595. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30596. // vertex alias
  30597. 0,
  30598. 2,
  30599. 3,
  30600. 3,
  30601. 3,
  30602. 4,
  30603. 7,
  30604. 8,
  30605. 9,
  30606. 9,
  30607. 10,
  30608. 11 // 23: B + 12
  30609. ];
  30610. // uv as integer step (not pixels !)
  30611. var ico_vertexuv = [
  30612. 5, 1, 3, 1, 6, 4, 0, 0,
  30613. 5, 3, 4, 2, 2, 2, 4, 0,
  30614. 2, 0, 1, 1, 6, 0, 6, 2,
  30615. // vertex alias (for same vertex on different faces)
  30616. 0, 4,
  30617. 3, 3,
  30618. 4, 4,
  30619. 3, 1,
  30620. 4, 2,
  30621. 4, 4,
  30622. 0, 2,
  30623. 1, 1,
  30624. 2, 2,
  30625. 3, 3,
  30626. 1, 3,
  30627. 2, 4 // 23: B + 12
  30628. ];
  30629. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30630. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30631. // First island of uv mapping
  30632. // v = 4h 3+ 2
  30633. // v = 3h 9+ 4
  30634. // v = 2h 9+ 5 B
  30635. // v = 1h 9 1 0
  30636. // v = 0h 3 8 7 A
  30637. // u = 0 1 2 3 4 5 6 *a
  30638. // Second island of uv mapping
  30639. // v = 4h 0+ B+ 4+
  30640. // v = 3h A+ 2+
  30641. // v = 2h 7+ 6 3+
  30642. // v = 1h 8+ 3+
  30643. // v = 0h
  30644. // u = 0 1 2 3 4 5 6 *a
  30645. // Face layout on texture UV mapping
  30646. // ============
  30647. // \ 4 /\ 16 / ======
  30648. // \ / \ / /\ 11 /
  30649. // \/ 7 \/ / \ /
  30650. // ======= / 10 \/
  30651. // /\ 17 /\ =======
  30652. // / \ / \ \ 15 /\
  30653. // / 8 \/ 12 \ \ / \
  30654. // ============ \/ 6 \
  30655. // \ 18 /\ ============
  30656. // \ / \ \ 5 /\ 0 /
  30657. // \/ 13 \ \ / \ /
  30658. // ======= \/ 1 \/
  30659. // =============
  30660. // /\ 19 /\ 2 /\
  30661. // / \ / \ / \
  30662. // / 14 \/ 9 \/ 3 \
  30663. // ===================
  30664. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30665. var ustep = 138 / 1024;
  30666. var vstep = 239 / 1024;
  30667. var uoffset = 60 / 1024;
  30668. var voffset = 26 / 1024;
  30669. // Second island should have margin, not to touch the first island
  30670. // avoid any borderline artefact in pixel rounding
  30671. var island_u_offset = -40 / 1024;
  30672. var island_v_offset = +20 / 1024;
  30673. // face is either island 0 or 1 :
  30674. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30675. var island = [
  30676. 0, 0, 0, 0, 1,
  30677. 0, 0, 1, 1, 0,
  30678. 0, 0, 1, 1, 0,
  30679. 0, 1, 1, 1, 0 // 15 - 19
  30680. ];
  30681. var indices = [];
  30682. var positions = [];
  30683. var normals = [];
  30684. var uvs = [];
  30685. var current_indice = 0;
  30686. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30687. var face_vertex_pos = new Array(3);
  30688. var face_vertex_uv = new Array(3);
  30689. var v012;
  30690. for (v012 = 0; v012 < 3; v012++) {
  30691. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30692. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30693. }
  30694. // create all with normals
  30695. for (var face = 0; face < 20; face++) {
  30696. // 3 vertex per face
  30697. for (v012 = 0; v012 < 3; v012++) {
  30698. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30699. var v_id = ico_indices[3 * face + v012];
  30700. // vertex have 3D position (x,y,z)
  30701. 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]);
  30702. // Normalize to get normal, then scale to radius
  30703. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30704. // uv Coordinates from vertex ID
  30705. 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);
  30706. }
  30707. // Subdivide the face (interpolate pos, norm, uv)
  30708. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30709. // - norm is linear interpolation of vertex corner normal
  30710. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30711. // - uv is linear interpolation
  30712. //
  30713. // Topology is as below for sub-divide by 2
  30714. // vertex shown as v0,v1,v2
  30715. // interp index is i1 to progress in range [v0,v1[
  30716. // interp index is i2 to progress in range [v0,v2[
  30717. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30718. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30719. //
  30720. //
  30721. // i2 v2
  30722. // ^ ^
  30723. // / / \
  30724. // / / \
  30725. // / / \
  30726. // / / (0,1) \
  30727. // / #---------\
  30728. // / / \ (0,0)'/ \
  30729. // / / \ / \
  30730. // / / \ / \
  30731. // / / (0,0) \ / (1,0) \
  30732. // / #---------#---------\
  30733. // v0 v1
  30734. //
  30735. // --------------------> i1
  30736. //
  30737. // interp of (i1,i2):
  30738. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30739. // along i1 : lerp(x0,x1, i1/(S-i2))
  30740. //
  30741. // centroid of triangle is needed to get help normal computation
  30742. // (c1,c2) are used for centroid location
  30743. var interp_vertex = function (i1, i2, c1, c2) {
  30744. // vertex is interpolated from
  30745. // - face_vertex_pos[0..2]
  30746. // - face_vertex_uv[0..2]
  30747. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30748. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30749. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30750. pos_interp.normalize();
  30751. var vertex_normal;
  30752. if (flat) {
  30753. // in flat mode, recalculate normal as face centroid normal
  30754. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30755. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30756. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30757. }
  30758. else {
  30759. // in smooth mode, recalculate normal from each single vertex position
  30760. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30761. }
  30762. // Vertex normal need correction due to X,Y,Z radius scaling
  30763. vertex_normal.x /= radiusX;
  30764. vertex_normal.y /= radiusY;
  30765. vertex_normal.z /= radiusZ;
  30766. vertex_normal.normalize();
  30767. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30768. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30769. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30770. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30771. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30772. uvs.push(uv_interp.x, uv_interp.y);
  30773. // push each vertex has member of a face
  30774. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30775. indices.push(current_indice);
  30776. current_indice++;
  30777. };
  30778. for (var i2 = 0; i2 < subdivisions; i2++) {
  30779. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30780. // face : (i1,i2) for /\ :
  30781. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30782. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30783. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30784. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30785. if (i1 + i2 + 1 < subdivisions) {
  30786. // face : (i1,i2)' for \/ :
  30787. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30788. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30789. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30790. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30791. }
  30792. }
  30793. }
  30794. }
  30795. // Sides
  30796. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30797. // Result
  30798. var vertexData = new VertexData();
  30799. vertexData.indices = indices;
  30800. vertexData.positions = positions;
  30801. vertexData.normals = normals;
  30802. vertexData.uvs = uvs;
  30803. return vertexData;
  30804. };
  30805. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30806. VertexData.CreatePolyhedron = function (options) {
  30807. // provided polyhedron types :
  30808. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30809. // 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)
  30810. var polyhedra = [];
  30811. 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]] };
  30812. 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]] };
  30813. polyhedra[2] = {
  30814. 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]],
  30815. 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]]
  30816. };
  30817. polyhedra[3] = {
  30818. 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]],
  30819. 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]]
  30820. };
  30821. polyhedra[4] = {
  30822. 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]],
  30823. 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]]
  30824. };
  30825. 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]] };
  30826. 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]] };
  30827. 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]] };
  30828. 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]] };
  30829. 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]] };
  30830. 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]] };
  30831. 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]] };
  30832. 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]] };
  30833. 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]] };
  30834. polyhedra[14] = {
  30835. 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]],
  30836. 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]]
  30837. };
  30838. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30839. var size = options.size;
  30840. var sizeX = options.sizeX || size || 1;
  30841. var sizeY = options.sizeY || size || 1;
  30842. var sizeZ = options.sizeZ || size || 1;
  30843. var data = options.custom || polyhedra[type];
  30844. var nbfaces = data.face.length;
  30845. var faceUV = options.faceUV || new Array(nbfaces);
  30846. var faceColors = options.faceColors;
  30847. var flat = (options.flat === undefined) ? true : options.flat;
  30848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30849. var positions = [];
  30850. var indices = [];
  30851. var normals = [];
  30852. var uvs = [];
  30853. var colors = [];
  30854. var index = 0;
  30855. var faceIdx = 0; // face cursor in the array "indexes"
  30856. var indexes = [];
  30857. var i = 0;
  30858. var f = 0;
  30859. var u, v, ang, x, y, tmp;
  30860. // default face colors and UV if undefined
  30861. if (flat) {
  30862. for (f = 0; f < nbfaces; f++) {
  30863. if (faceColors && faceColors[f] === undefined) {
  30864. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30865. }
  30866. if (faceUV && faceUV[f] === undefined) {
  30867. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30868. }
  30869. }
  30870. }
  30871. if (!flat) {
  30872. for (i = 0; i < data.vertex.length; i++) {
  30873. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30874. uvs.push(0, 0);
  30875. }
  30876. for (f = 0; f < nbfaces; f++) {
  30877. for (i = 0; i < data.face[f].length - 2; i++) {
  30878. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30879. }
  30880. }
  30881. }
  30882. else {
  30883. for (f = 0; f < nbfaces; f++) {
  30884. var fl = data.face[f].length; // number of vertices of the current face
  30885. ang = 2 * Math.PI / fl;
  30886. x = 0.5 * Math.tan(ang / 2);
  30887. y = 0.5;
  30888. // positions, uvs, colors
  30889. for (i = 0; i < fl; i++) {
  30890. // positions
  30891. 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);
  30892. indexes.push(index);
  30893. index++;
  30894. // uvs
  30895. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30896. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30897. uvs.push(u, v);
  30898. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30899. y = x * Math.sin(ang) + y * Math.cos(ang);
  30900. x = tmp;
  30901. // colors
  30902. if (faceColors) {
  30903. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30904. }
  30905. }
  30906. // indices from indexes
  30907. for (i = 0; i < fl - 2; i++) {
  30908. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30909. }
  30910. faceIdx += fl;
  30911. }
  30912. }
  30913. VertexData.ComputeNormals(positions, indices, normals);
  30914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30915. var vertexData = new VertexData();
  30916. vertexData.positions = positions;
  30917. vertexData.indices = indices;
  30918. vertexData.normals = normals;
  30919. vertexData.uvs = uvs;
  30920. if (faceColors && flat) {
  30921. vertexData.colors = colors;
  30922. }
  30923. return vertexData;
  30924. };
  30925. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30926. VertexData.CreateTorusKnot = function (options) {
  30927. var indices = [];
  30928. var positions = [];
  30929. var normals = [];
  30930. var uvs = [];
  30931. var radius = options.radius || 2;
  30932. var tube = options.tube || 0.5;
  30933. var radialSegments = options.radialSegments || 32;
  30934. var tubularSegments = options.tubularSegments || 32;
  30935. var p = options.p || 2;
  30936. var q = options.q || 3;
  30937. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30938. // Helper
  30939. var getPos = function (angle) {
  30940. var cu = Math.cos(angle);
  30941. var su = Math.sin(angle);
  30942. var quOverP = q / p * angle;
  30943. var cs = Math.cos(quOverP);
  30944. var tx = radius * (2 + cs) * 0.5 * cu;
  30945. var ty = radius * (2 + cs) * su * 0.5;
  30946. var tz = radius * Math.sin(quOverP) * 0.5;
  30947. return new BABYLON.Vector3(tx, ty, tz);
  30948. };
  30949. // Vertices
  30950. var i;
  30951. var j;
  30952. for (i = 0; i <= radialSegments; i++) {
  30953. var modI = i % radialSegments;
  30954. var u = modI / radialSegments * 2 * p * Math.PI;
  30955. var p1 = getPos(u);
  30956. var p2 = getPos(u + 0.01);
  30957. var tang = p2.subtract(p1);
  30958. var n = p2.add(p1);
  30959. var bitan = BABYLON.Vector3.Cross(tang, n);
  30960. n = BABYLON.Vector3.Cross(bitan, tang);
  30961. bitan.normalize();
  30962. n.normalize();
  30963. for (j = 0; j < tubularSegments; j++) {
  30964. var modJ = j % tubularSegments;
  30965. var v = modJ / tubularSegments * 2 * Math.PI;
  30966. var cx = -tube * Math.cos(v);
  30967. var cy = tube * Math.sin(v);
  30968. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30969. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30970. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30971. uvs.push(i / radialSegments);
  30972. uvs.push(j / tubularSegments);
  30973. }
  30974. }
  30975. for (i = 0; i < radialSegments; i++) {
  30976. for (j = 0; j < tubularSegments; j++) {
  30977. var jNext = (j + 1) % tubularSegments;
  30978. var a = i * tubularSegments + j;
  30979. var b = (i + 1) * tubularSegments + j;
  30980. var c = (i + 1) * tubularSegments + jNext;
  30981. var d = i * tubularSegments + jNext;
  30982. indices.push(d);
  30983. indices.push(b);
  30984. indices.push(a);
  30985. indices.push(d);
  30986. indices.push(c);
  30987. indices.push(b);
  30988. }
  30989. }
  30990. // Normals
  30991. VertexData.ComputeNormals(positions, indices, normals);
  30992. // Sides
  30993. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30994. // Result
  30995. var vertexData = new VertexData();
  30996. vertexData.indices = indices;
  30997. vertexData.positions = positions;
  30998. vertexData.normals = normals;
  30999. vertexData.uvs = uvs;
  31000. return vertexData;
  31001. };
  31002. // Tools
  31003. /**
  31004. * @param {any} - positions (number[] or Float32Array)
  31005. * @param {any} - indices (number[] or Uint16Array)
  31006. * @param {any} - normals (number[] or Float32Array)
  31007. */
  31008. VertexData.ComputeNormals = function (positions, indices, normals) {
  31009. var index = 0;
  31010. var p1p2x = 0.0;
  31011. var p1p2y = 0.0;
  31012. var p1p2z = 0.0;
  31013. var p3p2x = 0.0;
  31014. var p3p2y = 0.0;
  31015. var p3p2z = 0.0;
  31016. var faceNormalx = 0.0;
  31017. var faceNormaly = 0.0;
  31018. var faceNormalz = 0.0;
  31019. var length = 0.0;
  31020. var i1 = 0;
  31021. var i2 = 0;
  31022. var i3 = 0;
  31023. for (index = 0; index < positions.length; index++) {
  31024. normals[index] = 0.0;
  31025. }
  31026. // indice triplet = 1 face
  31027. var nbFaces = indices.length / 3;
  31028. for (index = 0; index < nbFaces; index++) {
  31029. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31030. i2 = indices[index * 3 + 1];
  31031. i3 = indices[index * 3 + 2];
  31032. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31033. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31034. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31035. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31036. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31037. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31038. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31039. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31040. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31041. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31042. length = (length === 0) ? 1.0 : length;
  31043. faceNormalx /= length; // normalize this normal
  31044. faceNormaly /= length;
  31045. faceNormalz /= length;
  31046. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31047. normals[i1 * 3 + 1] += faceNormaly;
  31048. normals[i1 * 3 + 2] += faceNormalz;
  31049. normals[i2 * 3] += faceNormalx;
  31050. normals[i2 * 3 + 1] += faceNormaly;
  31051. normals[i2 * 3 + 2] += faceNormalz;
  31052. normals[i3 * 3] += faceNormalx;
  31053. normals[i3 * 3 + 1] += faceNormaly;
  31054. normals[i3 * 3 + 2] += faceNormalz;
  31055. }
  31056. // last normalization of each normal
  31057. for (index = 0; index < normals.length / 3; index++) {
  31058. faceNormalx = normals[index * 3];
  31059. faceNormaly = normals[index * 3 + 1];
  31060. faceNormalz = normals[index * 3 + 2];
  31061. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31062. length = (length === 0) ? 1.0 : length;
  31063. faceNormalx /= length;
  31064. faceNormaly /= length;
  31065. faceNormalz /= length;
  31066. normals[index * 3] = faceNormalx;
  31067. normals[index * 3 + 1] = faceNormaly;
  31068. normals[index * 3 + 2] = faceNormalz;
  31069. }
  31070. };
  31071. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31072. var li = indices.length;
  31073. var ln = normals.length;
  31074. var i;
  31075. var n;
  31076. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31077. switch (sideOrientation) {
  31078. case BABYLON.Mesh.FRONTSIDE:
  31079. // nothing changed
  31080. break;
  31081. case BABYLON.Mesh.BACKSIDE:
  31082. var tmp;
  31083. // indices
  31084. for (i = 0; i < li; i += 3) {
  31085. tmp = indices[i];
  31086. indices[i] = indices[i + 2];
  31087. indices[i + 2] = tmp;
  31088. }
  31089. // normals
  31090. for (n = 0; n < ln; n++) {
  31091. normals[n] = -normals[n];
  31092. }
  31093. break;
  31094. case BABYLON.Mesh.DOUBLESIDE:
  31095. // positions
  31096. var lp = positions.length;
  31097. var l = lp / 3;
  31098. for (var p = 0; p < lp; p++) {
  31099. positions[lp + p] = positions[p];
  31100. }
  31101. // indices
  31102. for (i = 0; i < li; i += 3) {
  31103. indices[i + li] = indices[i + 2] + l;
  31104. indices[i + 1 + li] = indices[i + 1] + l;
  31105. indices[i + 2 + li] = indices[i] + l;
  31106. }
  31107. // normals
  31108. for (n = 0; n < ln; n++) {
  31109. normals[ln + n] = -normals[n];
  31110. }
  31111. // uvs
  31112. var lu = uvs.length;
  31113. for (var u = 0; u < lu; u++) {
  31114. uvs[u + lu] = uvs[u];
  31115. }
  31116. break;
  31117. }
  31118. };
  31119. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31120. var vertexData = new VertexData();
  31121. // positions
  31122. var positions = parsedVertexData.positions;
  31123. if (positions) {
  31124. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31125. }
  31126. // normals
  31127. var normals = parsedVertexData.normals;
  31128. if (normals) {
  31129. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31130. }
  31131. // uvs
  31132. var uvs = parsedVertexData.uvs;
  31133. if (uvs) {
  31134. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31135. }
  31136. // uv2s
  31137. var uv2s = parsedVertexData.uv2s;
  31138. if (uv2s) {
  31139. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31140. }
  31141. // uv3s
  31142. var uv3s = parsedVertexData.uv3s;
  31143. if (uv3s) {
  31144. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31145. }
  31146. // uv4s
  31147. var uv4s = parsedVertexData.uv4s;
  31148. if (uv4s) {
  31149. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31150. }
  31151. // uv5s
  31152. var uv5s = parsedVertexData.uv5s;
  31153. if (uv5s) {
  31154. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31155. }
  31156. // uv6s
  31157. var uv6s = parsedVertexData.uv6s;
  31158. if (uv6s) {
  31159. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31160. }
  31161. // colors
  31162. var colors = parsedVertexData.colors;
  31163. if (colors) {
  31164. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31165. }
  31166. // matricesIndices
  31167. var matricesIndices = parsedVertexData.matricesIndices;
  31168. if (matricesIndices) {
  31169. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31170. }
  31171. // matricesWeights
  31172. var matricesWeights = parsedVertexData.matricesWeights;
  31173. if (matricesWeights) {
  31174. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31175. }
  31176. // indices
  31177. var indices = parsedVertexData.indices;
  31178. if (indices) {
  31179. vertexData.indices = indices;
  31180. }
  31181. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31182. };
  31183. return VertexData;
  31184. }());
  31185. BABYLON.VertexData = VertexData;
  31186. })(BABYLON || (BABYLON = {}));
  31187. var BABYLON;
  31188. (function (BABYLON) {
  31189. var Tags = (function () {
  31190. function Tags() {
  31191. }
  31192. Tags.EnableFor = function (obj) {
  31193. obj._tags = obj._tags || {};
  31194. obj.hasTags = function () {
  31195. return Tags.HasTags(obj);
  31196. };
  31197. obj.addTags = function (tagsString) {
  31198. return Tags.AddTagsTo(obj, tagsString);
  31199. };
  31200. obj.removeTags = function (tagsString) {
  31201. return Tags.RemoveTagsFrom(obj, tagsString);
  31202. };
  31203. obj.matchesTagsQuery = function (tagsQuery) {
  31204. return Tags.MatchesQuery(obj, tagsQuery);
  31205. };
  31206. };
  31207. Tags.DisableFor = function (obj) {
  31208. delete obj._tags;
  31209. delete obj.hasTags;
  31210. delete obj.addTags;
  31211. delete obj.removeTags;
  31212. delete obj.matchesTagsQuery;
  31213. };
  31214. Tags.HasTags = function (obj) {
  31215. if (!obj._tags) {
  31216. return false;
  31217. }
  31218. return !BABYLON.Tools.IsEmpty(obj._tags);
  31219. };
  31220. Tags.GetTags = function (obj, asString) {
  31221. if (asString === void 0) { asString = true; }
  31222. if (!obj._tags) {
  31223. return null;
  31224. }
  31225. if (asString) {
  31226. var tagsArray = [];
  31227. for (var tag in obj._tags) {
  31228. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31229. tagsArray.push(tag);
  31230. }
  31231. }
  31232. return tagsArray.join(" ");
  31233. }
  31234. else {
  31235. return obj._tags;
  31236. }
  31237. };
  31238. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31239. // a tag cannot start with '||', '&&', and '!'
  31240. // it cannot contain whitespaces
  31241. Tags.AddTagsTo = function (obj, tagsString) {
  31242. if (!tagsString) {
  31243. return;
  31244. }
  31245. if (typeof tagsString !== "string") {
  31246. return;
  31247. }
  31248. var tags = tagsString.split(" ");
  31249. for (var t in tags) {
  31250. Tags._AddTagTo(obj, tags[t]);
  31251. }
  31252. };
  31253. Tags._AddTagTo = function (obj, tag) {
  31254. tag = tag.trim();
  31255. if (tag === "" || tag === "true" || tag === "false") {
  31256. return;
  31257. }
  31258. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31259. return;
  31260. }
  31261. Tags.EnableFor(obj);
  31262. obj._tags[tag] = true;
  31263. };
  31264. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31265. if (!Tags.HasTags(obj)) {
  31266. return;
  31267. }
  31268. var tags = tagsString.split(" ");
  31269. for (var t in tags) {
  31270. Tags._RemoveTagFrom(obj, tags[t]);
  31271. }
  31272. };
  31273. Tags._RemoveTagFrom = function (obj, tag) {
  31274. delete obj._tags[tag];
  31275. };
  31276. Tags.MatchesQuery = function (obj, tagsQuery) {
  31277. if (tagsQuery === undefined) {
  31278. return true;
  31279. }
  31280. if (tagsQuery === "") {
  31281. return Tags.HasTags(obj);
  31282. }
  31283. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31284. };
  31285. return Tags;
  31286. }());
  31287. BABYLON.Tags = Tags;
  31288. })(BABYLON || (BABYLON = {}));
  31289. var BABYLON;
  31290. (function (BABYLON) {
  31291. var Internals;
  31292. (function (Internals) {
  31293. var AndOrNotEvaluator = (function () {
  31294. function AndOrNotEvaluator() {
  31295. }
  31296. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31297. if (!query.match(/\([^\(\)]*\)/g)) {
  31298. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31299. }
  31300. else {
  31301. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31302. // remove parenthesis
  31303. r = r.slice(1, r.length - 1);
  31304. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31305. });
  31306. }
  31307. if (query === "true") {
  31308. return true;
  31309. }
  31310. if (query === "false") {
  31311. return false;
  31312. }
  31313. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31314. };
  31315. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31316. evaluateCallback = evaluateCallback || (function (r) {
  31317. return r === "true" ? true : false;
  31318. });
  31319. var result;
  31320. var or = parenthesisContent.split("||");
  31321. for (var i in or) {
  31322. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31323. var and = ori.split("&&");
  31324. if (and.length > 1) {
  31325. for (var j = 0; j < and.length; ++j) {
  31326. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31327. if (andj !== "true" && andj !== "false") {
  31328. if (andj[0] === "!") {
  31329. result = !evaluateCallback(andj.substring(1));
  31330. }
  31331. else {
  31332. result = evaluateCallback(andj);
  31333. }
  31334. }
  31335. else {
  31336. result = andj === "true" ? true : false;
  31337. }
  31338. if (!result) {
  31339. ori = "false";
  31340. break;
  31341. }
  31342. }
  31343. }
  31344. if (result || ori === "true") {
  31345. result = true;
  31346. break;
  31347. }
  31348. // result equals false (or undefined)
  31349. if (ori !== "true" && ori !== "false") {
  31350. if (ori[0] === "!") {
  31351. result = !evaluateCallback(ori.substring(1));
  31352. }
  31353. else {
  31354. result = evaluateCallback(ori);
  31355. }
  31356. }
  31357. else {
  31358. result = ori === "true" ? true : false;
  31359. }
  31360. }
  31361. // the whole parenthesis scope is replaced by 'true' or 'false'
  31362. return result ? "true" : "false";
  31363. };
  31364. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31365. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31366. // remove whitespaces
  31367. r = r.replace(/[\s]/g, function () { return ""; });
  31368. return r.length % 2 ? "!" : "";
  31369. });
  31370. booleanString = booleanString.trim();
  31371. if (booleanString === "!true") {
  31372. booleanString = "false";
  31373. }
  31374. else if (booleanString === "!false") {
  31375. booleanString = "true";
  31376. }
  31377. return booleanString;
  31378. };
  31379. return AndOrNotEvaluator;
  31380. }());
  31381. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31382. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31383. })(BABYLON || (BABYLON = {}));
  31384. var BABYLON;
  31385. (function (BABYLON) {
  31386. var PostProcessRenderPass = (function () {
  31387. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31388. this._enabled = true;
  31389. this._refCount = 0;
  31390. this._name = name;
  31391. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31392. this.setRenderList(renderList);
  31393. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31394. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31395. this._scene = scene;
  31396. this._renderList = renderList;
  31397. }
  31398. // private
  31399. PostProcessRenderPass.prototype._incRefCount = function () {
  31400. if (this._refCount === 0) {
  31401. this._scene.customRenderTargets.push(this._renderTexture);
  31402. }
  31403. return ++this._refCount;
  31404. };
  31405. PostProcessRenderPass.prototype._decRefCount = function () {
  31406. this._refCount--;
  31407. if (this._refCount <= 0) {
  31408. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31409. }
  31410. return this._refCount;
  31411. };
  31412. PostProcessRenderPass.prototype._update = function () {
  31413. this.setRenderList(this._renderList);
  31414. };
  31415. // public
  31416. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31417. this._renderTexture.renderList = renderList;
  31418. };
  31419. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31420. return this._renderTexture;
  31421. };
  31422. return PostProcessRenderPass;
  31423. }());
  31424. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31425. })(BABYLON || (BABYLON = {}));
  31426. var BABYLON;
  31427. (function (BABYLON) {
  31428. var PostProcessRenderEffect = (function () {
  31429. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31430. this._engine = engine;
  31431. this._name = name;
  31432. this._singleInstance = singleInstance || true;
  31433. this._getPostProcess = getPostProcess;
  31434. this._cameras = [];
  31435. this._indicesForCamera = [];
  31436. this._postProcesses = {};
  31437. this._renderPasses = {};
  31438. this._renderEffectAsPasses = {};
  31439. }
  31440. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31441. get: function () {
  31442. for (var index in this._postProcesses) {
  31443. if (!this._postProcesses[index].isSupported) {
  31444. return false;
  31445. }
  31446. }
  31447. return true;
  31448. },
  31449. enumerable: true,
  31450. configurable: true
  31451. });
  31452. PostProcessRenderEffect.prototype._update = function () {
  31453. for (var renderPassName in this._renderPasses) {
  31454. this._renderPasses[renderPassName]._update();
  31455. }
  31456. };
  31457. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31458. this._renderPasses[renderPass._name] = renderPass;
  31459. this._linkParameters();
  31460. };
  31461. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31462. delete this._renderPasses[renderPass._name];
  31463. this._linkParameters();
  31464. };
  31465. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31466. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31467. this._linkParameters();
  31468. };
  31469. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31470. for (var renderPassName in this._renderPasses) {
  31471. if (renderPassName === passName) {
  31472. return this._renderPasses[passName];
  31473. }
  31474. }
  31475. };
  31476. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31477. this._renderPasses = {};
  31478. this._linkParameters();
  31479. };
  31480. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31481. var cameraKey;
  31482. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31483. for (var i = 0; i < _cam.length; i++) {
  31484. var camera = _cam[i];
  31485. var cameraName = camera.name;
  31486. if (this._singleInstance) {
  31487. cameraKey = 0;
  31488. }
  31489. else {
  31490. cameraKey = cameraName;
  31491. }
  31492. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31493. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31494. if (!this._indicesForCamera[cameraName]) {
  31495. this._indicesForCamera[cameraName] = [];
  31496. }
  31497. this._indicesForCamera[cameraName].push(index);
  31498. if (this._cameras.indexOf(camera) === -1) {
  31499. this._cameras[cameraName] = camera;
  31500. }
  31501. for (var passName in this._renderPasses) {
  31502. this._renderPasses[passName]._incRefCount();
  31503. }
  31504. }
  31505. this._linkParameters();
  31506. };
  31507. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31508. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31509. for (var i = 0; i < _cam.length; i++) {
  31510. var camera = _cam[i];
  31511. var cameraName = camera.name;
  31512. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31513. var index = this._cameras.indexOf(cameraName);
  31514. this._indicesForCamera.splice(index, 1);
  31515. this._cameras.splice(index, 1);
  31516. for (var passName in this._renderPasses) {
  31517. this._renderPasses[passName]._decRefCount();
  31518. }
  31519. }
  31520. };
  31521. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31522. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31523. for (var i = 0; i < _cam.length; i++) {
  31524. var camera = _cam[i];
  31525. var cameraName = camera.name;
  31526. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31527. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31528. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31529. }
  31530. }
  31531. for (var passName in this._renderPasses) {
  31532. this._renderPasses[passName]._incRefCount();
  31533. }
  31534. }
  31535. };
  31536. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31537. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31538. for (var i = 0; i < _cam.length; i++) {
  31539. var camera = _cam[i];
  31540. var cameraName = camera.Name;
  31541. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31542. for (var passName in this._renderPasses) {
  31543. this._renderPasses[passName]._decRefCount();
  31544. }
  31545. }
  31546. };
  31547. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31548. if (this._singleInstance) {
  31549. return this._postProcesses[0];
  31550. }
  31551. else {
  31552. return this._postProcesses[camera.name];
  31553. }
  31554. };
  31555. PostProcessRenderEffect.prototype._linkParameters = function () {
  31556. var _this = this;
  31557. for (var index in this._postProcesses) {
  31558. if (this.applyParameters) {
  31559. this.applyParameters(this._postProcesses[index]);
  31560. }
  31561. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31562. _this._linkTextures(effect);
  31563. });
  31564. }
  31565. };
  31566. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31567. for (var renderPassName in this._renderPasses) {
  31568. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31569. }
  31570. for (var renderEffectName in this._renderEffectAsPasses) {
  31571. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31572. }
  31573. };
  31574. return PostProcessRenderEffect;
  31575. }());
  31576. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31577. })(BABYLON || (BABYLON = {}));
  31578. var BABYLON;
  31579. (function (BABYLON) {
  31580. var PostProcessRenderPipeline = (function () {
  31581. function PostProcessRenderPipeline(engine, name) {
  31582. this._engine = engine;
  31583. this._name = name;
  31584. this._renderEffects = {};
  31585. this._renderEffectsForIsolatedPass = {};
  31586. this._cameras = [];
  31587. }
  31588. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31589. get: function () {
  31590. for (var renderEffectName in this._renderEffects) {
  31591. if (!this._renderEffects[renderEffectName].isSupported) {
  31592. return false;
  31593. }
  31594. }
  31595. return true;
  31596. },
  31597. enumerable: true,
  31598. configurable: true
  31599. });
  31600. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31601. this._renderEffects[renderEffect._name] = renderEffect;
  31602. };
  31603. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31604. var renderEffects = this._renderEffects[renderEffectName];
  31605. if (!renderEffects) {
  31606. return;
  31607. }
  31608. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31609. };
  31610. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31611. var renderEffects = this._renderEffects[renderEffectName];
  31612. if (!renderEffects) {
  31613. return;
  31614. }
  31615. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31616. };
  31617. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31618. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31619. var indicesToDelete = [];
  31620. var i;
  31621. for (i = 0; i < _cam.length; i++) {
  31622. var camera = _cam[i];
  31623. var cameraName = camera.name;
  31624. if (this._cameras.indexOf(camera) === -1) {
  31625. this._cameras[cameraName] = camera;
  31626. }
  31627. else if (unique) {
  31628. indicesToDelete.push(i);
  31629. }
  31630. }
  31631. for (i = 0; i < indicesToDelete.length; i++) {
  31632. cameras.splice(indicesToDelete[i], 1);
  31633. }
  31634. for (var renderEffectName in this._renderEffects) {
  31635. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31636. }
  31637. };
  31638. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31639. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31640. for (var renderEffectName in this._renderEffects) {
  31641. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31642. }
  31643. for (var i = 0; i < _cam.length; i++) {
  31644. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31645. }
  31646. };
  31647. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31648. var _this = this;
  31649. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31650. var pass = null;
  31651. var renderEffectName;
  31652. for (renderEffectName in this._renderEffects) {
  31653. pass = this._renderEffects[renderEffectName].getPass(passName);
  31654. if (pass != null) {
  31655. break;
  31656. }
  31657. }
  31658. if (pass === null) {
  31659. return;
  31660. }
  31661. for (renderEffectName in this._renderEffects) {
  31662. this._renderEffects[renderEffectName]._disable(_cam);
  31663. }
  31664. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31665. for (var i = 0; i < _cam.length; i++) {
  31666. var camera = _cam[i];
  31667. var cameraName = camera.name;
  31668. 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); });
  31669. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31670. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31671. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31672. }
  31673. };
  31674. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31675. var _this = this;
  31676. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31677. for (var i = 0; i < _cam.length; i++) {
  31678. var camera = _cam[i];
  31679. var cameraName = camera.name;
  31680. 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); });
  31681. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31682. }
  31683. for (var renderEffectName in this._renderEffects) {
  31684. this._renderEffects[renderEffectName]._enable(_cam);
  31685. }
  31686. };
  31687. PostProcessRenderPipeline.prototype._update = function () {
  31688. for (var renderEffectName in this._renderEffects) {
  31689. this._renderEffects[renderEffectName]._update();
  31690. }
  31691. for (var i = 0; i < this._cameras.length; i++) {
  31692. var cameraName = this._cameras[i].name;
  31693. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31694. this._renderEffectsForIsolatedPass[cameraName]._update();
  31695. }
  31696. }
  31697. };
  31698. PostProcessRenderPipeline.prototype.dispose = function () {
  31699. // Must be implemented by children
  31700. };
  31701. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31702. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31703. return PostProcessRenderPipeline;
  31704. }());
  31705. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31706. })(BABYLON || (BABYLON = {}));
  31707. var BABYLON;
  31708. (function (BABYLON) {
  31709. var PostProcessRenderPipelineManager = (function () {
  31710. function PostProcessRenderPipelineManager() {
  31711. this._renderPipelines = {};
  31712. }
  31713. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31714. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31715. };
  31716. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31717. var renderPipeline = this._renderPipelines[renderPipelineName];
  31718. if (!renderPipeline) {
  31719. return;
  31720. }
  31721. renderPipeline._attachCameras(cameras, unique);
  31722. };
  31723. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31724. var renderPipeline = this._renderPipelines[renderPipelineName];
  31725. if (!renderPipeline) {
  31726. return;
  31727. }
  31728. renderPipeline._detachCameras(cameras);
  31729. };
  31730. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31731. var renderPipeline = this._renderPipelines[renderPipelineName];
  31732. if (!renderPipeline) {
  31733. return;
  31734. }
  31735. renderPipeline._enableEffect(renderEffectName, cameras);
  31736. };
  31737. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31738. var renderPipeline = this._renderPipelines[renderPipelineName];
  31739. if (!renderPipeline) {
  31740. return;
  31741. }
  31742. renderPipeline._disableEffect(renderEffectName, cameras);
  31743. };
  31744. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31745. var renderPipeline = this._renderPipelines[renderPipelineName];
  31746. if (!renderPipeline) {
  31747. return;
  31748. }
  31749. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31750. };
  31751. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31752. var renderPipeline = this._renderPipelines[renderPipelineName];
  31753. if (!renderPipeline) {
  31754. return;
  31755. }
  31756. renderPipeline._disableDisplayOnlyPass(cameras);
  31757. };
  31758. PostProcessRenderPipelineManager.prototype.update = function () {
  31759. for (var renderPipelineName in this._renderPipelines) {
  31760. var pipeline = this._renderPipelines[renderPipelineName];
  31761. if (!pipeline.isSupported) {
  31762. pipeline.dispose();
  31763. delete this._renderPipelines[renderPipelineName];
  31764. }
  31765. else {
  31766. pipeline._update();
  31767. }
  31768. }
  31769. };
  31770. return PostProcessRenderPipelineManager;
  31771. }());
  31772. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31773. })(BABYLON || (BABYLON = {}));
  31774. var BABYLON;
  31775. (function (BABYLON) {
  31776. var BoundingBoxRenderer = (function () {
  31777. function BoundingBoxRenderer(scene) {
  31778. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31779. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31780. this.showBackLines = true;
  31781. this.renderList = new BABYLON.SmartArray(32);
  31782. this._vertexBuffers = {};
  31783. this._scene = scene;
  31784. }
  31785. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31786. if (this._colorShader) {
  31787. return;
  31788. }
  31789. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31790. attributes: [BABYLON.VertexBuffer.PositionKind],
  31791. uniforms: ["worldViewProjection", "color"]
  31792. });
  31793. var engine = this._scene.getEngine();
  31794. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31796. 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]);
  31797. };
  31798. BoundingBoxRenderer.prototype.reset = function () {
  31799. this.renderList.reset();
  31800. };
  31801. BoundingBoxRenderer.prototype.render = function () {
  31802. if (this.renderList.length === 0) {
  31803. return;
  31804. }
  31805. this._prepareRessources();
  31806. if (!this._colorShader.isReady()) {
  31807. return;
  31808. }
  31809. var engine = this._scene.getEngine();
  31810. engine.setDepthWrite(false);
  31811. this._colorShader._preBind();
  31812. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31813. var boundingBox = this.renderList.data[boundingBoxIndex];
  31814. var min = boundingBox.minimum;
  31815. var max = boundingBox.maximum;
  31816. var diff = max.subtract(min);
  31817. var median = min.add(diff.scale(0.5));
  31818. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31819. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31820. .multiply(boundingBox.getWorldMatrix());
  31821. // VBOs
  31822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31823. if (this.showBackLines) {
  31824. // Back
  31825. engine.setDepthFunctionToGreaterOrEqual();
  31826. this._scene.resetCachedMaterial();
  31827. this._colorShader.setColor4("color", this.backColor.toColor4());
  31828. this._colorShader.bind(worldMatrix);
  31829. // Draw order
  31830. engine.draw(false, 0, 24);
  31831. }
  31832. // Front
  31833. engine.setDepthFunctionToLess();
  31834. this._scene.resetCachedMaterial();
  31835. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31836. this._colorShader.bind(worldMatrix);
  31837. // Draw order
  31838. engine.draw(false, 0, 24);
  31839. }
  31840. this._colorShader.unbind();
  31841. engine.setDepthFunctionToLessOrEqual();
  31842. engine.setDepthWrite(true);
  31843. };
  31844. BoundingBoxRenderer.prototype.dispose = function () {
  31845. if (!this._colorShader) {
  31846. return;
  31847. }
  31848. this._colorShader.dispose();
  31849. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31850. if (buffer) {
  31851. buffer.dispose();
  31852. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31853. }
  31854. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31855. };
  31856. return BoundingBoxRenderer;
  31857. }());
  31858. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31859. })(BABYLON || (BABYLON = {}));
  31860. var BABYLON;
  31861. (function (BABYLON) {
  31862. var Condition = (function () {
  31863. function Condition(actionManager) {
  31864. this._actionManager = actionManager;
  31865. }
  31866. Condition.prototype.isValid = function () {
  31867. return true;
  31868. };
  31869. Condition.prototype._getProperty = function (propertyPath) {
  31870. return this._actionManager._getProperty(propertyPath);
  31871. };
  31872. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31873. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31874. };
  31875. Condition.prototype.serialize = function () {
  31876. };
  31877. Condition.prototype._serialize = function (serializedCondition) {
  31878. return {
  31879. type: 2,
  31880. children: [],
  31881. name: serializedCondition.name,
  31882. properties: serializedCondition.properties
  31883. };
  31884. };
  31885. return Condition;
  31886. }());
  31887. BABYLON.Condition = Condition;
  31888. var ValueCondition = (function (_super) {
  31889. __extends(ValueCondition, _super);
  31890. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31891. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31892. _super.call(this, actionManager);
  31893. this.propertyPath = propertyPath;
  31894. this.value = value;
  31895. this.operator = operator;
  31896. this._target = target;
  31897. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31898. this._property = this._getProperty(this.propertyPath);
  31899. }
  31900. Object.defineProperty(ValueCondition, "IsEqual", {
  31901. get: function () {
  31902. return ValueCondition._IsEqual;
  31903. },
  31904. enumerable: true,
  31905. configurable: true
  31906. });
  31907. Object.defineProperty(ValueCondition, "IsDifferent", {
  31908. get: function () {
  31909. return ValueCondition._IsDifferent;
  31910. },
  31911. enumerable: true,
  31912. configurable: true
  31913. });
  31914. Object.defineProperty(ValueCondition, "IsGreater", {
  31915. get: function () {
  31916. return ValueCondition._IsGreater;
  31917. },
  31918. enumerable: true,
  31919. configurable: true
  31920. });
  31921. Object.defineProperty(ValueCondition, "IsLesser", {
  31922. get: function () {
  31923. return ValueCondition._IsLesser;
  31924. },
  31925. enumerable: true,
  31926. configurable: true
  31927. });
  31928. // Methods
  31929. ValueCondition.prototype.isValid = function () {
  31930. switch (this.operator) {
  31931. case ValueCondition.IsGreater:
  31932. return this._effectiveTarget[this._property] > this.value;
  31933. case ValueCondition.IsLesser:
  31934. return this._effectiveTarget[this._property] < this.value;
  31935. case ValueCondition.IsEqual:
  31936. case ValueCondition.IsDifferent:
  31937. var check;
  31938. if (this.value.equals) {
  31939. check = this.value.equals(this._effectiveTarget[this._property]);
  31940. }
  31941. else {
  31942. check = this.value === this._effectiveTarget[this._property];
  31943. }
  31944. return this.operator === ValueCondition.IsEqual ? check : !check;
  31945. }
  31946. return false;
  31947. };
  31948. ValueCondition.prototype.serialize = function () {
  31949. return this._serialize({
  31950. name: "ValueCondition",
  31951. properties: [
  31952. BABYLON.Action._GetTargetProperty(this._target),
  31953. { name: "propertyPath", value: this.propertyPath },
  31954. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31955. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31956. ]
  31957. });
  31958. };
  31959. ValueCondition.GetOperatorName = function (operator) {
  31960. switch (operator) {
  31961. case ValueCondition._IsEqual: return "IsEqual";
  31962. case ValueCondition._IsDifferent: return "IsDifferent";
  31963. case ValueCondition._IsGreater: return "IsGreater";
  31964. case ValueCondition._IsLesser: return "IsLesser";
  31965. default: return "";
  31966. }
  31967. };
  31968. // Statics
  31969. ValueCondition._IsEqual = 0;
  31970. ValueCondition._IsDifferent = 1;
  31971. ValueCondition._IsGreater = 2;
  31972. ValueCondition._IsLesser = 3;
  31973. return ValueCondition;
  31974. }(Condition));
  31975. BABYLON.ValueCondition = ValueCondition;
  31976. var PredicateCondition = (function (_super) {
  31977. __extends(PredicateCondition, _super);
  31978. function PredicateCondition(actionManager, predicate) {
  31979. _super.call(this, actionManager);
  31980. this.predicate = predicate;
  31981. }
  31982. PredicateCondition.prototype.isValid = function () {
  31983. return this.predicate();
  31984. };
  31985. return PredicateCondition;
  31986. }(Condition));
  31987. BABYLON.PredicateCondition = PredicateCondition;
  31988. var StateCondition = (function (_super) {
  31989. __extends(StateCondition, _super);
  31990. function StateCondition(actionManager, target, value) {
  31991. _super.call(this, actionManager);
  31992. this.value = value;
  31993. this._target = target;
  31994. }
  31995. // Methods
  31996. StateCondition.prototype.isValid = function () {
  31997. return this._target.state === this.value;
  31998. };
  31999. StateCondition.prototype.serialize = function () {
  32000. return this._serialize({
  32001. name: "StateCondition",
  32002. properties: [
  32003. BABYLON.Action._GetTargetProperty(this._target),
  32004. { name: "value", value: this.value }
  32005. ]
  32006. });
  32007. };
  32008. return StateCondition;
  32009. }(Condition));
  32010. BABYLON.StateCondition = StateCondition;
  32011. })(BABYLON || (BABYLON = {}));
  32012. var BABYLON;
  32013. (function (BABYLON) {
  32014. var Action = (function () {
  32015. function Action(triggerOptions, condition) {
  32016. this.triggerOptions = triggerOptions;
  32017. if (triggerOptions.parameter) {
  32018. this.trigger = triggerOptions.trigger;
  32019. this._triggerParameter = triggerOptions.parameter;
  32020. }
  32021. else {
  32022. this.trigger = triggerOptions;
  32023. }
  32024. this._nextActiveAction = this;
  32025. this._condition = condition;
  32026. }
  32027. // Methods
  32028. Action.prototype._prepare = function () {
  32029. };
  32030. Action.prototype.getTriggerParameter = function () {
  32031. return this._triggerParameter;
  32032. };
  32033. Action.prototype._executeCurrent = function (evt) {
  32034. if (this._nextActiveAction._condition) {
  32035. var condition = this._nextActiveAction._condition;
  32036. var currentRenderId = this._actionManager.getScene().getRenderId();
  32037. // We cache the current evaluation for the current frame
  32038. if (condition._evaluationId === currentRenderId) {
  32039. if (!condition._currentResult) {
  32040. return;
  32041. }
  32042. }
  32043. else {
  32044. condition._evaluationId = currentRenderId;
  32045. if (!condition.isValid()) {
  32046. condition._currentResult = false;
  32047. return;
  32048. }
  32049. condition._currentResult = true;
  32050. }
  32051. }
  32052. this._nextActiveAction.execute(evt);
  32053. this.skipToNextActiveAction();
  32054. };
  32055. Action.prototype.execute = function (evt) {
  32056. };
  32057. Action.prototype.skipToNextActiveAction = function () {
  32058. if (this._nextActiveAction._child) {
  32059. if (!this._nextActiveAction._child._actionManager) {
  32060. this._nextActiveAction._child._actionManager = this._actionManager;
  32061. }
  32062. this._nextActiveAction = this._nextActiveAction._child;
  32063. }
  32064. else {
  32065. this._nextActiveAction = this;
  32066. }
  32067. };
  32068. Action.prototype.then = function (action) {
  32069. this._child = action;
  32070. action._actionManager = this._actionManager;
  32071. action._prepare();
  32072. return action;
  32073. };
  32074. Action.prototype._getProperty = function (propertyPath) {
  32075. return this._actionManager._getProperty(propertyPath);
  32076. };
  32077. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32078. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32079. };
  32080. Action.prototype.serialize = function (parent) {
  32081. };
  32082. // Called by BABYLON.Action objects in serialize(...). Internal use
  32083. Action.prototype._serialize = function (serializedAction, parent) {
  32084. var serializationObject = {
  32085. type: 1,
  32086. children: [],
  32087. name: serializedAction.name,
  32088. properties: serializedAction.properties || []
  32089. };
  32090. // Serialize child
  32091. if (this._child) {
  32092. this._child.serialize(serializationObject);
  32093. }
  32094. // Check if "this" has a condition
  32095. if (this._condition) {
  32096. var serializedCondition = this._condition.serialize();
  32097. serializedCondition.children.push(serializationObject);
  32098. if (parent) {
  32099. parent.children.push(serializedCondition);
  32100. }
  32101. return serializedCondition;
  32102. }
  32103. if (parent) {
  32104. parent.children.push(serializationObject);
  32105. }
  32106. return serializationObject;
  32107. };
  32108. Action._SerializeValueAsString = function (value) {
  32109. if (typeof value === "number") {
  32110. return value.toString();
  32111. }
  32112. if (typeof value === "boolean") {
  32113. return value ? "true" : "false";
  32114. }
  32115. if (value instanceof BABYLON.Vector2) {
  32116. return value.x + ", " + value.y;
  32117. }
  32118. if (value instanceof BABYLON.Vector3) {
  32119. return value.x + ", " + value.y + ", " + value.z;
  32120. }
  32121. if (value instanceof BABYLON.Color3) {
  32122. return value.r + ", " + value.g + ", " + value.b;
  32123. }
  32124. if (value instanceof BABYLON.Color4) {
  32125. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32126. }
  32127. return value; // string
  32128. };
  32129. Action._GetTargetProperty = function (target) {
  32130. return {
  32131. name: "target",
  32132. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32133. : target instanceof BABYLON.Light ? "LightProperties"
  32134. : target instanceof BABYLON.Camera ? "CameraProperties"
  32135. : "SceneProperties",
  32136. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32137. };
  32138. };
  32139. return Action;
  32140. }());
  32141. BABYLON.Action = Action;
  32142. })(BABYLON || (BABYLON = {}));
  32143. var BABYLON;
  32144. (function (BABYLON) {
  32145. /**
  32146. * ActionEvent is the event beint sent when an action is triggered.
  32147. */
  32148. var ActionEvent = (function () {
  32149. /**
  32150. * @constructor
  32151. * @param source The mesh or sprite that triggered the action.
  32152. * @param pointerX The X mouse cursor position at the time of the event
  32153. * @param pointerY The Y mouse cursor position at the time of the event
  32154. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32155. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32156. */
  32157. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32158. this.source = source;
  32159. this.pointerX = pointerX;
  32160. this.pointerY = pointerY;
  32161. this.meshUnderPointer = meshUnderPointer;
  32162. this.sourceEvent = sourceEvent;
  32163. this.additionalData = additionalData;
  32164. }
  32165. /**
  32166. * Helper function to auto-create an ActionEvent from a source mesh.
  32167. * @param source The source mesh that triggered the event
  32168. * @param evt {Event} The original (browser) event
  32169. */
  32170. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32171. var scene = source.getScene();
  32172. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32173. };
  32174. /**
  32175. * Helper function to auto-create an ActionEvent from a source mesh.
  32176. * @param source The source sprite that triggered the event
  32177. * @param scene Scene associated with the sprite
  32178. * @param evt {Event} The original (browser) event
  32179. */
  32180. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32181. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32182. };
  32183. /**
  32184. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32185. * @param scene the scene where the event occurred
  32186. * @param evt {Event} The original (browser) event
  32187. */
  32188. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32189. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32190. };
  32191. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32192. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32193. };
  32194. return ActionEvent;
  32195. }());
  32196. BABYLON.ActionEvent = ActionEvent;
  32197. /**
  32198. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32199. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32200. */
  32201. var ActionManager = (function () {
  32202. function ActionManager(scene) {
  32203. // Members
  32204. this.actions = new Array();
  32205. this._scene = scene;
  32206. scene._actionManagers.push(this);
  32207. }
  32208. Object.defineProperty(ActionManager, "NothingTrigger", {
  32209. get: function () {
  32210. return ActionManager._NothingTrigger;
  32211. },
  32212. enumerable: true,
  32213. configurable: true
  32214. });
  32215. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32216. get: function () {
  32217. return ActionManager._OnPickTrigger;
  32218. },
  32219. enumerable: true,
  32220. configurable: true
  32221. });
  32222. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32223. get: function () {
  32224. return ActionManager._OnLeftPickTrigger;
  32225. },
  32226. enumerable: true,
  32227. configurable: true
  32228. });
  32229. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32230. get: function () {
  32231. return ActionManager._OnRightPickTrigger;
  32232. },
  32233. enumerable: true,
  32234. configurable: true
  32235. });
  32236. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32237. get: function () {
  32238. return ActionManager._OnCenterPickTrigger;
  32239. },
  32240. enumerable: true,
  32241. configurable: true
  32242. });
  32243. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32244. get: function () {
  32245. return ActionManager._OnPickDownTrigger;
  32246. },
  32247. enumerable: true,
  32248. configurable: true
  32249. });
  32250. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32251. get: function () {
  32252. return ActionManager._OnPickUpTrigger;
  32253. },
  32254. enumerable: true,
  32255. configurable: true
  32256. });
  32257. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32258. /// This trigger will only be raised if you also declared a OnPickDown
  32259. get: function () {
  32260. return ActionManager._OnPickOutTrigger;
  32261. },
  32262. enumerable: true,
  32263. configurable: true
  32264. });
  32265. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32266. get: function () {
  32267. return ActionManager._OnLongPressTrigger;
  32268. },
  32269. enumerable: true,
  32270. configurable: true
  32271. });
  32272. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32273. get: function () {
  32274. return ActionManager._OnPointerOverTrigger;
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32280. get: function () {
  32281. return ActionManager._OnPointerOutTrigger;
  32282. },
  32283. enumerable: true,
  32284. configurable: true
  32285. });
  32286. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32287. get: function () {
  32288. return ActionManager._OnEveryFrameTrigger;
  32289. },
  32290. enumerable: true,
  32291. configurable: true
  32292. });
  32293. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32294. get: function () {
  32295. return ActionManager._OnIntersectionEnterTrigger;
  32296. },
  32297. enumerable: true,
  32298. configurable: true
  32299. });
  32300. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32301. get: function () {
  32302. return ActionManager._OnIntersectionExitTrigger;
  32303. },
  32304. enumerable: true,
  32305. configurable: true
  32306. });
  32307. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32308. get: function () {
  32309. return ActionManager._OnKeyDownTrigger;
  32310. },
  32311. enumerable: true,
  32312. configurable: true
  32313. });
  32314. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32315. get: function () {
  32316. return ActionManager._OnKeyUpTrigger;
  32317. },
  32318. enumerable: true,
  32319. configurable: true
  32320. });
  32321. // Methods
  32322. ActionManager.prototype.dispose = function () {
  32323. var index = this._scene._actionManagers.indexOf(this);
  32324. if (index > -1) {
  32325. this._scene._actionManagers.splice(index, 1);
  32326. }
  32327. };
  32328. ActionManager.prototype.getScene = function () {
  32329. return this._scene;
  32330. };
  32331. /**
  32332. * Does this action manager handles actions of any of the given triggers
  32333. * @param {number[]} triggers - the triggers to be tested
  32334. * @return {boolean} whether one (or more) of the triggers is handeled
  32335. */
  32336. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32337. for (var index = 0; index < this.actions.length; index++) {
  32338. var action = this.actions[index];
  32339. if (triggers.indexOf(action.trigger) > -1) {
  32340. return true;
  32341. }
  32342. }
  32343. return false;
  32344. };
  32345. /**
  32346. * Does this action manager handles actions of a given trigger
  32347. * @param {number} trigger - the trigger to be tested
  32348. * @return {boolean} whether the trigger is handeled
  32349. */
  32350. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32351. for (var index = 0; index < this.actions.length; index++) {
  32352. var action = this.actions[index];
  32353. if (action.trigger === trigger) {
  32354. return true;
  32355. }
  32356. }
  32357. return false;
  32358. };
  32359. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32360. /**
  32361. * Does this action manager has pointer triggers
  32362. * @return {boolean} whether or not it has pointer triggers
  32363. */
  32364. get: function () {
  32365. for (var index = 0; index < this.actions.length; index++) {
  32366. var action = this.actions[index];
  32367. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32368. return true;
  32369. }
  32370. }
  32371. return false;
  32372. },
  32373. enumerable: true,
  32374. configurable: true
  32375. });
  32376. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32377. /**
  32378. * Does this action manager has pick triggers
  32379. * @return {boolean} whether or not it has pick triggers
  32380. */
  32381. get: function () {
  32382. for (var index = 0; index < this.actions.length; index++) {
  32383. var action = this.actions[index];
  32384. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32385. return true;
  32386. }
  32387. }
  32388. return false;
  32389. },
  32390. enumerable: true,
  32391. configurable: true
  32392. });
  32393. /**
  32394. * Registers an action to this action manager
  32395. * @param {BABYLON.Action} action - the action to be registered
  32396. * @return {BABYLON.Action} the action amended (prepared) after registration
  32397. */
  32398. ActionManager.prototype.registerAction = function (action) {
  32399. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32400. if (this.getScene().actionManager !== this) {
  32401. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32402. return null;
  32403. }
  32404. }
  32405. this.actions.push(action);
  32406. action._actionManager = this;
  32407. action._prepare();
  32408. return action;
  32409. };
  32410. /**
  32411. * Process a specific trigger
  32412. * @param {number} trigger - the trigger to process
  32413. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32414. */
  32415. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32416. for (var index = 0; index < this.actions.length; index++) {
  32417. var action = this.actions[index];
  32418. if (action.trigger === trigger) {
  32419. if (trigger === ActionManager.OnKeyUpTrigger
  32420. || trigger === ActionManager.OnKeyDownTrigger) {
  32421. var parameter = action.getTriggerParameter();
  32422. if (parameter) {
  32423. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32424. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32425. if (actualkey !== parameter.toLowerCase()) {
  32426. continue;
  32427. }
  32428. }
  32429. }
  32430. action._executeCurrent(evt);
  32431. }
  32432. }
  32433. };
  32434. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32435. var properties = propertyPath.split(".");
  32436. for (var index = 0; index < properties.length - 1; index++) {
  32437. target = target[properties[index]];
  32438. }
  32439. return target;
  32440. };
  32441. ActionManager.prototype._getProperty = function (propertyPath) {
  32442. var properties = propertyPath.split(".");
  32443. return properties[properties.length - 1];
  32444. };
  32445. ActionManager.prototype.serialize = function (name) {
  32446. var root = {
  32447. children: [],
  32448. name: name,
  32449. type: 3,
  32450. properties: [] // Empty for root but required
  32451. };
  32452. for (var i = 0; i < this.actions.length; i++) {
  32453. var triggerObject = {
  32454. type: 0,
  32455. children: [],
  32456. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32457. properties: []
  32458. };
  32459. var triggerOptions = this.actions[i].triggerOptions;
  32460. if (triggerOptions && typeof triggerOptions !== "number") {
  32461. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32462. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32463. }
  32464. else {
  32465. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32466. }
  32467. }
  32468. // Serialize child action, recursively
  32469. this.actions[i].serialize(triggerObject);
  32470. // Add serialized trigger
  32471. root.children.push(triggerObject);
  32472. }
  32473. return root;
  32474. };
  32475. ActionManager.Parse = function (parsedActions, object, scene) {
  32476. var actionManager = new BABYLON.ActionManager(scene);
  32477. if (object === null)
  32478. scene.actionManager = actionManager;
  32479. else
  32480. object.actionManager = actionManager;
  32481. // instanciate a new object
  32482. var instanciate = function (name, params) {
  32483. var newInstance = Object.create(BABYLON[name].prototype);
  32484. newInstance.constructor.apply(newInstance, params);
  32485. return newInstance;
  32486. };
  32487. var parseParameter = function (name, value, target, propertyPath) {
  32488. if (propertyPath === null) {
  32489. // String, boolean or float
  32490. var floatValue = parseFloat(value);
  32491. if (value === "true" || value === "false")
  32492. return value === "true";
  32493. else
  32494. return isNaN(floatValue) ? value : floatValue;
  32495. }
  32496. var effectiveTarget = propertyPath.split(".");
  32497. var values = value.split(",");
  32498. // Get effective Target
  32499. for (var i = 0; i < effectiveTarget.length; i++) {
  32500. target = target[effectiveTarget[i]];
  32501. }
  32502. // Return appropriate value with its type
  32503. if (typeof (target) === "boolean")
  32504. return values[0] === "true";
  32505. if (typeof (target) === "string")
  32506. return values[0];
  32507. // Parameters with multiple values such as Vector3 etc.
  32508. var split = new Array();
  32509. for (var i = 0; i < values.length; i++)
  32510. split.push(parseFloat(values[i]));
  32511. if (target instanceof BABYLON.Vector3)
  32512. return BABYLON.Vector3.FromArray(split);
  32513. if (target instanceof BABYLON.Vector4)
  32514. return BABYLON.Vector4.FromArray(split);
  32515. if (target instanceof BABYLON.Color3)
  32516. return BABYLON.Color3.FromArray(split);
  32517. if (target instanceof BABYLON.Color4)
  32518. return BABYLON.Color4.FromArray(split);
  32519. return parseFloat(values[0]);
  32520. };
  32521. // traverse graph per trigger
  32522. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32523. if (combineArray === void 0) { combineArray = null; }
  32524. if (parsedAction.detached)
  32525. return;
  32526. var parameters = new Array();
  32527. var target = null;
  32528. var propertyPath = null;
  32529. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32530. // Parameters
  32531. if (parsedAction.type === 2)
  32532. parameters.push(actionManager);
  32533. else
  32534. parameters.push(trigger);
  32535. if (combine) {
  32536. var actions = new Array();
  32537. for (var j = 0; j < parsedAction.combine.length; j++) {
  32538. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32539. }
  32540. parameters.push(actions);
  32541. }
  32542. else {
  32543. for (var i = 0; i < parsedAction.properties.length; i++) {
  32544. var value = parsedAction.properties[i].value;
  32545. var name = parsedAction.properties[i].name;
  32546. var targetType = parsedAction.properties[i].targetType;
  32547. if (name === "target")
  32548. if (targetType !== null && targetType === "SceneProperties")
  32549. value = target = scene;
  32550. else
  32551. value = target = scene.getNodeByName(value);
  32552. else if (name === "parent")
  32553. value = scene.getNodeByName(value);
  32554. else if (name === "sound")
  32555. value = scene.getSoundByName(value);
  32556. else if (name !== "propertyPath") {
  32557. if (parsedAction.type === 2 && name === "operator")
  32558. value = BABYLON.ValueCondition[value];
  32559. else
  32560. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32561. }
  32562. else {
  32563. propertyPath = value;
  32564. }
  32565. parameters.push(value);
  32566. }
  32567. }
  32568. if (combineArray === null) {
  32569. parameters.push(condition);
  32570. }
  32571. else {
  32572. parameters.push(null);
  32573. }
  32574. // If interpolate value action
  32575. if (parsedAction.name === "InterpolateValueAction") {
  32576. var param = parameters[parameters.length - 2];
  32577. parameters[parameters.length - 1] = param;
  32578. parameters[parameters.length - 2] = condition;
  32579. }
  32580. // Action or condition(s) and not CombineAction
  32581. var newAction = instanciate(parsedAction.name, parameters);
  32582. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32583. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32584. if (action)
  32585. action.then(nothing);
  32586. else
  32587. actionManager.registerAction(nothing);
  32588. action = nothing;
  32589. }
  32590. if (combineArray === null) {
  32591. if (newAction instanceof BABYLON.Condition) {
  32592. condition = newAction;
  32593. newAction = action;
  32594. }
  32595. else {
  32596. condition = null;
  32597. if (action)
  32598. action.then(newAction);
  32599. else
  32600. actionManager.registerAction(newAction);
  32601. }
  32602. }
  32603. else {
  32604. combineArray.push(newAction);
  32605. }
  32606. for (var i = 0; i < parsedAction.children.length; i++)
  32607. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32608. };
  32609. // triggers
  32610. for (var i = 0; i < parsedActions.children.length; i++) {
  32611. var triggerParams;
  32612. var trigger = parsedActions.children[i];
  32613. if (trigger.properties.length > 0) {
  32614. var param = trigger.properties[0].value;
  32615. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32616. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32617. }
  32618. else
  32619. triggerParams = BABYLON.ActionManager[trigger.name];
  32620. for (var j = 0; j < trigger.children.length; j++) {
  32621. if (!trigger.detached)
  32622. traverse(trigger.children[j], triggerParams, null, null);
  32623. }
  32624. }
  32625. };
  32626. ActionManager.GetTriggerName = function (trigger) {
  32627. switch (trigger) {
  32628. case 0: return "NothingTrigger";
  32629. case 1: return "OnPickTrigger";
  32630. case 2: return "OnLeftPickTrigger";
  32631. case 3: return "OnRightPickTrigger";
  32632. case 4: return "OnCenterPickTrigger";
  32633. case 5: return "OnPickDownTrigger";
  32634. case 6: return "OnPickUpTrigger";
  32635. case 7: return "OnLongPressTrigger";
  32636. case 8: return "OnPointerOverTrigger";
  32637. case 9: return "OnPointerOutTrigger";
  32638. case 10: return "OnEveryFrameTrigger";
  32639. case 11: return "OnIntersectionEnterTrigger";
  32640. case 12: return "OnIntersectionExitTrigger";
  32641. case 13: return "OnKeyDownTrigger";
  32642. case 14: return "OnKeyUpTrigger";
  32643. case 15: return "OnPickOutTrigger";
  32644. default: return "";
  32645. }
  32646. };
  32647. // Statics
  32648. ActionManager._NothingTrigger = 0;
  32649. ActionManager._OnPickTrigger = 1;
  32650. ActionManager._OnLeftPickTrigger = 2;
  32651. ActionManager._OnRightPickTrigger = 3;
  32652. ActionManager._OnCenterPickTrigger = 4;
  32653. ActionManager._OnPickDownTrigger = 5;
  32654. ActionManager._OnPickUpTrigger = 6;
  32655. ActionManager._OnLongPressTrigger = 7;
  32656. ActionManager._OnPointerOverTrigger = 8;
  32657. ActionManager._OnPointerOutTrigger = 9;
  32658. ActionManager._OnEveryFrameTrigger = 10;
  32659. ActionManager._OnIntersectionEnterTrigger = 11;
  32660. ActionManager._OnIntersectionExitTrigger = 12;
  32661. ActionManager._OnKeyDownTrigger = 13;
  32662. ActionManager._OnKeyUpTrigger = 14;
  32663. ActionManager._OnPickOutTrigger = 15;
  32664. ActionManager.DragMovementThreshold = 10; // in pixels
  32665. ActionManager.LongPressDelay = 500; // in milliseconds
  32666. return ActionManager;
  32667. }());
  32668. BABYLON.ActionManager = ActionManager;
  32669. })(BABYLON || (BABYLON = {}));
  32670. var BABYLON;
  32671. (function (BABYLON) {
  32672. var InterpolateValueAction = (function (_super) {
  32673. __extends(InterpolateValueAction, _super);
  32674. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32675. if (duration === void 0) { duration = 1000; }
  32676. _super.call(this, triggerOptions, condition);
  32677. this.propertyPath = propertyPath;
  32678. this.value = value;
  32679. this.duration = duration;
  32680. this.stopOtherAnimations = stopOtherAnimations;
  32681. this.onInterpolationDone = onInterpolationDone;
  32682. this._target = this._effectiveTarget = target;
  32683. }
  32684. InterpolateValueAction.prototype._prepare = function () {
  32685. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32686. this._property = this._getProperty(this.propertyPath);
  32687. };
  32688. InterpolateValueAction.prototype.execute = function () {
  32689. var scene = this._actionManager.getScene();
  32690. var keys = [
  32691. {
  32692. frame: 0,
  32693. value: this._effectiveTarget[this._property]
  32694. }, {
  32695. frame: 100,
  32696. value: this.value
  32697. }
  32698. ];
  32699. var dataType;
  32700. if (typeof this.value === "number") {
  32701. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32702. }
  32703. else if (this.value instanceof BABYLON.Color3) {
  32704. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32705. }
  32706. else if (this.value instanceof BABYLON.Vector3) {
  32707. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32708. }
  32709. else if (this.value instanceof BABYLON.Matrix) {
  32710. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32711. }
  32712. else if (this.value instanceof BABYLON.Quaternion) {
  32713. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32714. }
  32715. else {
  32716. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32717. return;
  32718. }
  32719. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32720. animation.setKeys(keys);
  32721. if (this.stopOtherAnimations) {
  32722. scene.stopAnimation(this._effectiveTarget);
  32723. }
  32724. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32725. };
  32726. InterpolateValueAction.prototype.serialize = function (parent) {
  32727. return _super.prototype._serialize.call(this, {
  32728. name: "InterpolateValueAction",
  32729. properties: [
  32730. BABYLON.Action._GetTargetProperty(this._target),
  32731. { name: "propertyPath", value: this.propertyPath },
  32732. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32733. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32734. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32735. ]
  32736. }, parent);
  32737. };
  32738. return InterpolateValueAction;
  32739. }(BABYLON.Action));
  32740. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32741. })(BABYLON || (BABYLON = {}));
  32742. var BABYLON;
  32743. (function (BABYLON) {
  32744. var SwitchBooleanAction = (function (_super) {
  32745. __extends(SwitchBooleanAction, _super);
  32746. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32747. _super.call(this, triggerOptions, condition);
  32748. this.propertyPath = propertyPath;
  32749. this._target = this._effectiveTarget = target;
  32750. }
  32751. SwitchBooleanAction.prototype._prepare = function () {
  32752. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32753. this._property = this._getProperty(this.propertyPath);
  32754. };
  32755. SwitchBooleanAction.prototype.execute = function () {
  32756. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32757. };
  32758. SwitchBooleanAction.prototype.serialize = function (parent) {
  32759. return _super.prototype._serialize.call(this, {
  32760. name: "SwitchBooleanAction",
  32761. properties: [
  32762. BABYLON.Action._GetTargetProperty(this._target),
  32763. { name: "propertyPath", value: this.propertyPath }
  32764. ]
  32765. }, parent);
  32766. };
  32767. return SwitchBooleanAction;
  32768. }(BABYLON.Action));
  32769. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32770. var SetStateAction = (function (_super) {
  32771. __extends(SetStateAction, _super);
  32772. function SetStateAction(triggerOptions, target, value, condition) {
  32773. _super.call(this, triggerOptions, condition);
  32774. this.value = value;
  32775. this._target = target;
  32776. }
  32777. SetStateAction.prototype.execute = function () {
  32778. this._target.state = this.value;
  32779. };
  32780. SetStateAction.prototype.serialize = function (parent) {
  32781. return _super.prototype._serialize.call(this, {
  32782. name: "SetStateAction",
  32783. properties: [
  32784. BABYLON.Action._GetTargetProperty(this._target),
  32785. { name: "value", value: this.value }
  32786. ]
  32787. }, parent);
  32788. };
  32789. return SetStateAction;
  32790. }(BABYLON.Action));
  32791. BABYLON.SetStateAction = SetStateAction;
  32792. var SetValueAction = (function (_super) {
  32793. __extends(SetValueAction, _super);
  32794. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32795. _super.call(this, triggerOptions, condition);
  32796. this.propertyPath = propertyPath;
  32797. this.value = value;
  32798. this._target = this._effectiveTarget = target;
  32799. }
  32800. SetValueAction.prototype._prepare = function () {
  32801. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32802. this._property = this._getProperty(this.propertyPath);
  32803. };
  32804. SetValueAction.prototype.execute = function () {
  32805. this._effectiveTarget[this._property] = this.value;
  32806. if (this._target.markAsDirty) {
  32807. this._target.markAsDirty(this._property);
  32808. }
  32809. };
  32810. SetValueAction.prototype.serialize = function (parent) {
  32811. return _super.prototype._serialize.call(this, {
  32812. name: "SetValueAction",
  32813. properties: [
  32814. BABYLON.Action._GetTargetProperty(this._target),
  32815. { name: "propertyPath", value: this.propertyPath },
  32816. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32817. ]
  32818. }, parent);
  32819. };
  32820. return SetValueAction;
  32821. }(BABYLON.Action));
  32822. BABYLON.SetValueAction = SetValueAction;
  32823. var IncrementValueAction = (function (_super) {
  32824. __extends(IncrementValueAction, _super);
  32825. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32826. _super.call(this, triggerOptions, condition);
  32827. this.propertyPath = propertyPath;
  32828. this.value = value;
  32829. this._target = this._effectiveTarget = target;
  32830. }
  32831. IncrementValueAction.prototype._prepare = function () {
  32832. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32833. this._property = this._getProperty(this.propertyPath);
  32834. if (typeof this._effectiveTarget[this._property] !== "number") {
  32835. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32836. }
  32837. };
  32838. IncrementValueAction.prototype.execute = function () {
  32839. this._effectiveTarget[this._property] += this.value;
  32840. if (this._target.markAsDirty) {
  32841. this._target.markAsDirty(this._property);
  32842. }
  32843. };
  32844. IncrementValueAction.prototype.serialize = function (parent) {
  32845. return _super.prototype._serialize.call(this, {
  32846. name: "IncrementValueAction",
  32847. properties: [
  32848. BABYLON.Action._GetTargetProperty(this._target),
  32849. { name: "propertyPath", value: this.propertyPath },
  32850. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32851. ]
  32852. }, parent);
  32853. };
  32854. return IncrementValueAction;
  32855. }(BABYLON.Action));
  32856. BABYLON.IncrementValueAction = IncrementValueAction;
  32857. var PlayAnimationAction = (function (_super) {
  32858. __extends(PlayAnimationAction, _super);
  32859. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32860. _super.call(this, triggerOptions, condition);
  32861. this.from = from;
  32862. this.to = to;
  32863. this.loop = loop;
  32864. this._target = target;
  32865. }
  32866. PlayAnimationAction.prototype._prepare = function () {
  32867. };
  32868. PlayAnimationAction.prototype.execute = function () {
  32869. var scene = this._actionManager.getScene();
  32870. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32871. };
  32872. PlayAnimationAction.prototype.serialize = function (parent) {
  32873. return _super.prototype._serialize.call(this, {
  32874. name: "PlayAnimationAction",
  32875. properties: [
  32876. BABYLON.Action._GetTargetProperty(this._target),
  32877. { name: "from", value: String(this.from) },
  32878. { name: "to", value: String(this.to) },
  32879. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32880. ]
  32881. }, parent);
  32882. };
  32883. return PlayAnimationAction;
  32884. }(BABYLON.Action));
  32885. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32886. var StopAnimationAction = (function (_super) {
  32887. __extends(StopAnimationAction, _super);
  32888. function StopAnimationAction(triggerOptions, target, condition) {
  32889. _super.call(this, triggerOptions, condition);
  32890. this._target = target;
  32891. }
  32892. StopAnimationAction.prototype._prepare = function () {
  32893. };
  32894. StopAnimationAction.prototype.execute = function () {
  32895. var scene = this._actionManager.getScene();
  32896. scene.stopAnimation(this._target);
  32897. };
  32898. StopAnimationAction.prototype.serialize = function (parent) {
  32899. return _super.prototype._serialize.call(this, {
  32900. name: "StopAnimationAction",
  32901. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32902. }, parent);
  32903. };
  32904. return StopAnimationAction;
  32905. }(BABYLON.Action));
  32906. BABYLON.StopAnimationAction = StopAnimationAction;
  32907. var DoNothingAction = (function (_super) {
  32908. __extends(DoNothingAction, _super);
  32909. function DoNothingAction(triggerOptions, condition) {
  32910. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32911. _super.call(this, triggerOptions, condition);
  32912. }
  32913. DoNothingAction.prototype.execute = function () {
  32914. };
  32915. DoNothingAction.prototype.serialize = function (parent) {
  32916. return _super.prototype._serialize.call(this, {
  32917. name: "DoNothingAction",
  32918. properties: []
  32919. }, parent);
  32920. };
  32921. return DoNothingAction;
  32922. }(BABYLON.Action));
  32923. BABYLON.DoNothingAction = DoNothingAction;
  32924. var CombineAction = (function (_super) {
  32925. __extends(CombineAction, _super);
  32926. function CombineAction(triggerOptions, children, condition) {
  32927. _super.call(this, triggerOptions, condition);
  32928. this.children = children;
  32929. }
  32930. CombineAction.prototype._prepare = function () {
  32931. for (var index = 0; index < this.children.length; index++) {
  32932. this.children[index]._actionManager = this._actionManager;
  32933. this.children[index]._prepare();
  32934. }
  32935. };
  32936. CombineAction.prototype.execute = function (evt) {
  32937. for (var index = 0; index < this.children.length; index++) {
  32938. this.children[index].execute(evt);
  32939. }
  32940. };
  32941. CombineAction.prototype.serialize = function (parent) {
  32942. var serializationObject = _super.prototype._serialize.call(this, {
  32943. name: "CombineAction",
  32944. properties: [],
  32945. combine: []
  32946. }, parent);
  32947. for (var i = 0; i < this.children.length; i++) {
  32948. serializationObject.combine.push(this.children[i].serialize(null));
  32949. }
  32950. return serializationObject;
  32951. };
  32952. return CombineAction;
  32953. }(BABYLON.Action));
  32954. BABYLON.CombineAction = CombineAction;
  32955. var ExecuteCodeAction = (function (_super) {
  32956. __extends(ExecuteCodeAction, _super);
  32957. function ExecuteCodeAction(triggerOptions, func, condition) {
  32958. _super.call(this, triggerOptions, condition);
  32959. this.func = func;
  32960. }
  32961. ExecuteCodeAction.prototype.execute = function (evt) {
  32962. this.func(evt);
  32963. };
  32964. return ExecuteCodeAction;
  32965. }(BABYLON.Action));
  32966. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32967. var SetParentAction = (function (_super) {
  32968. __extends(SetParentAction, _super);
  32969. function SetParentAction(triggerOptions, target, parent, condition) {
  32970. _super.call(this, triggerOptions, condition);
  32971. this._target = target;
  32972. this._parent = parent;
  32973. }
  32974. SetParentAction.prototype._prepare = function () {
  32975. };
  32976. SetParentAction.prototype.execute = function () {
  32977. if (this._target.parent === this._parent) {
  32978. return;
  32979. }
  32980. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32981. invertParentWorldMatrix.invert();
  32982. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32983. this._target.parent = this._parent;
  32984. };
  32985. SetParentAction.prototype.serialize = function (parent) {
  32986. return _super.prototype._serialize.call(this, {
  32987. name: "SetParentAction",
  32988. properties: [
  32989. BABYLON.Action._GetTargetProperty(this._target),
  32990. BABYLON.Action._GetTargetProperty(this._parent),
  32991. ]
  32992. }, parent);
  32993. };
  32994. return SetParentAction;
  32995. }(BABYLON.Action));
  32996. BABYLON.SetParentAction = SetParentAction;
  32997. var PlaySoundAction = (function (_super) {
  32998. __extends(PlaySoundAction, _super);
  32999. function PlaySoundAction(triggerOptions, sound, condition) {
  33000. _super.call(this, triggerOptions, condition);
  33001. this._sound = sound;
  33002. }
  33003. PlaySoundAction.prototype._prepare = function () {
  33004. };
  33005. PlaySoundAction.prototype.execute = function () {
  33006. if (this._sound !== undefined)
  33007. this._sound.play();
  33008. };
  33009. PlaySoundAction.prototype.serialize = function (parent) {
  33010. return _super.prototype._serialize.call(this, {
  33011. name: "PlaySoundAction",
  33012. properties: [{ name: "sound", value: this._sound.name }]
  33013. }, parent);
  33014. };
  33015. return PlaySoundAction;
  33016. }(BABYLON.Action));
  33017. BABYLON.PlaySoundAction = PlaySoundAction;
  33018. var StopSoundAction = (function (_super) {
  33019. __extends(StopSoundAction, _super);
  33020. function StopSoundAction(triggerOptions, sound, condition) {
  33021. _super.call(this, triggerOptions, condition);
  33022. this._sound = sound;
  33023. }
  33024. StopSoundAction.prototype._prepare = function () {
  33025. };
  33026. StopSoundAction.prototype.execute = function () {
  33027. if (this._sound !== undefined)
  33028. this._sound.stop();
  33029. };
  33030. StopSoundAction.prototype.serialize = function (parent) {
  33031. return _super.prototype._serialize.call(this, {
  33032. name: "StopSoundAction",
  33033. properties: [{ name: "sound", value: this._sound.name }]
  33034. }, parent);
  33035. };
  33036. return StopSoundAction;
  33037. }(BABYLON.Action));
  33038. BABYLON.StopSoundAction = StopSoundAction;
  33039. })(BABYLON || (BABYLON = {}));
  33040. var BABYLON;
  33041. (function (BABYLON) {
  33042. var Geometry = (function () {
  33043. function Geometry(id, scene, vertexData, updatable, mesh) {
  33044. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33045. this._totalVertices = 0;
  33046. this._isDisposed = false;
  33047. this.id = id;
  33048. this._engine = scene.getEngine();
  33049. this._meshes = [];
  33050. this._scene = scene;
  33051. //Init vertex buffer cache
  33052. this._vertexBuffers = {};
  33053. this._indices = [];
  33054. // vertexData
  33055. if (vertexData) {
  33056. this.setAllVerticesData(vertexData, updatable);
  33057. }
  33058. else {
  33059. this._totalVertices = 0;
  33060. this._indices = [];
  33061. }
  33062. // applyToMesh
  33063. if (mesh) {
  33064. if (mesh instanceof BABYLON.LinesMesh) {
  33065. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33066. this.updateExtend();
  33067. }
  33068. this.applyToMesh(mesh);
  33069. mesh.computeWorldMatrix(true);
  33070. }
  33071. }
  33072. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33073. /**
  33074. * 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
  33075. * @returns The Bias Vector
  33076. */
  33077. get: function () {
  33078. return this._boundingBias;
  33079. },
  33080. set: function (value) {
  33081. if (this._boundingBias && this._boundingBias.equals(value)) {
  33082. return;
  33083. }
  33084. this._boundingBias = value.clone();
  33085. this.updateBoundingInfo(true, null);
  33086. },
  33087. enumerable: true,
  33088. configurable: true
  33089. });
  33090. Object.defineProperty(Geometry.prototype, "extend", {
  33091. get: function () {
  33092. return this._extend;
  33093. },
  33094. enumerable: true,
  33095. configurable: true
  33096. });
  33097. Geometry.prototype.getScene = function () {
  33098. return this._scene;
  33099. };
  33100. Geometry.prototype.getEngine = function () {
  33101. return this._engine;
  33102. };
  33103. Geometry.prototype.isReady = function () {
  33104. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33105. };
  33106. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33107. vertexData.applyToGeometry(this, updatable);
  33108. this.notifyUpdate();
  33109. };
  33110. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33111. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33112. this.setVerticesBuffer(buffer);
  33113. };
  33114. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33115. var kind = buffer.getKind();
  33116. if (this._vertexBuffers[kind]) {
  33117. this._vertexBuffers[kind].dispose();
  33118. }
  33119. this._vertexBuffers[kind] = buffer;
  33120. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33121. var data = buffer.getData();
  33122. var stride = buffer.getStrideSize();
  33123. this._totalVertices = data.length / stride;
  33124. this.updateExtend(data, stride);
  33125. var meshes = this._meshes;
  33126. var numOfMeshes = meshes.length;
  33127. for (var index = 0; index < numOfMeshes; index++) {
  33128. var mesh = meshes[index];
  33129. mesh._resetPointsArrayCache();
  33130. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33131. mesh._createGlobalSubMesh();
  33132. mesh.computeWorldMatrix(true);
  33133. }
  33134. }
  33135. this.notifyUpdate(kind);
  33136. };
  33137. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33138. var vertexBuffer = this.getVertexBuffer(kind);
  33139. if (!vertexBuffer) {
  33140. return;
  33141. }
  33142. vertexBuffer.updateDirectly(data, offset);
  33143. this.notifyUpdate(kind);
  33144. };
  33145. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33146. var vertexBuffer = this.getVertexBuffer(kind);
  33147. if (!vertexBuffer) {
  33148. return;
  33149. }
  33150. vertexBuffer.update(data);
  33151. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33152. var stride = vertexBuffer.getStrideSize();
  33153. this._totalVertices = data.length / stride;
  33154. this.updateBoundingInfo(updateExtends, data);
  33155. }
  33156. this.notifyUpdate(kind);
  33157. };
  33158. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33159. if (updateExtends) {
  33160. this.updateExtend(data);
  33161. }
  33162. var meshes = this._meshes;
  33163. var numOfMeshes = meshes.length;
  33164. for (var index = 0; index < numOfMeshes; index++) {
  33165. var mesh = meshes[index];
  33166. mesh._resetPointsArrayCache();
  33167. if (updateExtends) {
  33168. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33169. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33170. var subMesh = mesh.subMeshes[subIndex];
  33171. subMesh.refreshBoundingInfo();
  33172. }
  33173. }
  33174. }
  33175. };
  33176. Geometry.prototype.getTotalVertices = function () {
  33177. if (!this.isReady()) {
  33178. return 0;
  33179. }
  33180. return this._totalVertices;
  33181. };
  33182. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33183. var vertexBuffer = this.getVertexBuffer(kind);
  33184. if (!vertexBuffer) {
  33185. return null;
  33186. }
  33187. var orig = vertexBuffer.getData();
  33188. if (!copyWhenShared || this._meshes.length === 1) {
  33189. return orig;
  33190. }
  33191. else {
  33192. var len = orig.length;
  33193. var copy = [];
  33194. for (var i = 0; i < len; i++) {
  33195. copy.push(orig[i]);
  33196. }
  33197. return copy;
  33198. }
  33199. };
  33200. Geometry.prototype.getVertexBuffer = function (kind) {
  33201. if (!this.isReady()) {
  33202. return null;
  33203. }
  33204. return this._vertexBuffers[kind];
  33205. };
  33206. Geometry.prototype.getVertexBuffers = function () {
  33207. if (!this.isReady()) {
  33208. return null;
  33209. }
  33210. return this._vertexBuffers;
  33211. };
  33212. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33213. if (!this._vertexBuffers) {
  33214. if (this._delayInfo) {
  33215. return this._delayInfo.indexOf(kind) !== -1;
  33216. }
  33217. return false;
  33218. }
  33219. return this._vertexBuffers[kind] !== undefined;
  33220. };
  33221. Geometry.prototype.getVerticesDataKinds = function () {
  33222. var result = [];
  33223. var kind;
  33224. if (!this._vertexBuffers && this._delayInfo) {
  33225. for (kind in this._delayInfo) {
  33226. result.push(kind);
  33227. }
  33228. }
  33229. else {
  33230. for (kind in this._vertexBuffers) {
  33231. result.push(kind);
  33232. }
  33233. }
  33234. return result;
  33235. };
  33236. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33237. if (this._indexBuffer) {
  33238. this._engine._releaseBuffer(this._indexBuffer);
  33239. }
  33240. this._indices = indices;
  33241. if (this._meshes.length !== 0 && this._indices) {
  33242. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33243. }
  33244. if (totalVertices !== undefined) {
  33245. this._totalVertices = totalVertices;
  33246. }
  33247. var meshes = this._meshes;
  33248. var numOfMeshes = meshes.length;
  33249. for (var index = 0; index < numOfMeshes; index++) {
  33250. meshes[index]._createGlobalSubMesh();
  33251. }
  33252. this.notifyUpdate();
  33253. };
  33254. Geometry.prototype.getTotalIndices = function () {
  33255. if (!this.isReady()) {
  33256. return 0;
  33257. }
  33258. return this._indices.length;
  33259. };
  33260. Geometry.prototype.getIndices = function (copyWhenShared) {
  33261. if (!this.isReady()) {
  33262. return null;
  33263. }
  33264. var orig = this._indices;
  33265. if (!copyWhenShared || this._meshes.length === 1) {
  33266. return orig;
  33267. }
  33268. else {
  33269. var len = orig.length;
  33270. var copy = [];
  33271. for (var i = 0; i < len; i++) {
  33272. copy.push(orig[i]);
  33273. }
  33274. return copy;
  33275. }
  33276. };
  33277. Geometry.prototype.getIndexBuffer = function () {
  33278. if (!this.isReady()) {
  33279. return null;
  33280. }
  33281. return this._indexBuffer;
  33282. };
  33283. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33284. var meshes = this._meshes;
  33285. var index = meshes.indexOf(mesh);
  33286. if (index === -1) {
  33287. return;
  33288. }
  33289. for (var kind in this._vertexBuffers) {
  33290. this._vertexBuffers[kind].dispose();
  33291. }
  33292. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33293. this._indexBuffer = null;
  33294. }
  33295. meshes.splice(index, 1);
  33296. mesh._geometry = null;
  33297. if (meshes.length === 0 && shouldDispose) {
  33298. this.dispose();
  33299. }
  33300. };
  33301. Geometry.prototype.applyToMesh = function (mesh) {
  33302. if (mesh._geometry === this) {
  33303. return;
  33304. }
  33305. var previousGeometry = mesh._geometry;
  33306. if (previousGeometry) {
  33307. previousGeometry.releaseForMesh(mesh);
  33308. }
  33309. var meshes = this._meshes;
  33310. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33311. mesh._geometry = this;
  33312. this._scene.pushGeometry(this);
  33313. meshes.push(mesh);
  33314. if (this.isReady()) {
  33315. this._applyToMesh(mesh);
  33316. }
  33317. else {
  33318. mesh._boundingInfo = this._boundingInfo;
  33319. }
  33320. };
  33321. Geometry.prototype.updateExtend = function (data, stride) {
  33322. if (data === void 0) { data = null; }
  33323. if (!data) {
  33324. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33325. }
  33326. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33327. };
  33328. Geometry.prototype._applyToMesh = function (mesh) {
  33329. var numOfMeshes = this._meshes.length;
  33330. // vertexBuffers
  33331. for (var kind in this._vertexBuffers) {
  33332. if (numOfMeshes === 1) {
  33333. this._vertexBuffers[kind].create();
  33334. }
  33335. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33336. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33337. mesh._resetPointsArrayCache();
  33338. if (!this._extend) {
  33339. this.updateExtend(this._vertexBuffers[kind].getData());
  33340. }
  33341. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33342. mesh._createGlobalSubMesh();
  33343. //bounding info was just created again, world matrix should be applied again.
  33344. mesh._updateBoundingInfo();
  33345. }
  33346. }
  33347. // indexBuffer
  33348. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33349. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33350. }
  33351. if (this._indexBuffer) {
  33352. this._indexBuffer.references = numOfMeshes;
  33353. }
  33354. };
  33355. Geometry.prototype.notifyUpdate = function (kind) {
  33356. if (this.onGeometryUpdated) {
  33357. this.onGeometryUpdated(this, kind);
  33358. }
  33359. };
  33360. Geometry.prototype.load = function (scene, onLoaded) {
  33361. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33362. return;
  33363. }
  33364. if (this.isReady()) {
  33365. if (onLoaded) {
  33366. onLoaded();
  33367. }
  33368. return;
  33369. }
  33370. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33371. this._queueLoad(scene, onLoaded);
  33372. };
  33373. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33374. var _this = this;
  33375. scene._addPendingData(this);
  33376. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33377. _this._delayLoadingFunction(JSON.parse(data), _this);
  33378. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33379. _this._delayInfo = [];
  33380. scene._removePendingData(_this);
  33381. var meshes = _this._meshes;
  33382. var numOfMeshes = meshes.length;
  33383. for (var index = 0; index < numOfMeshes; index++) {
  33384. _this._applyToMesh(meshes[index]);
  33385. }
  33386. if (onLoaded) {
  33387. onLoaded();
  33388. }
  33389. }, function () { }, scene.database);
  33390. };
  33391. /**
  33392. * Invert the geometry to move from a right handed system to a left handed one.
  33393. */
  33394. Geometry.prototype.toLeftHanded = function () {
  33395. // Flip faces
  33396. var tIndices = this.getIndices(false);
  33397. if (tIndices != null && tIndices.length > 0) {
  33398. for (var i = 0; i < tIndices.length; i += 3) {
  33399. var tTemp = tIndices[i + 0];
  33400. tIndices[i + 0] = tIndices[i + 2];
  33401. tIndices[i + 2] = tTemp;
  33402. }
  33403. this.setIndices(tIndices);
  33404. }
  33405. // Negate position.z
  33406. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33407. if (tPositions != null && tPositions.length > 0) {
  33408. for (var i = 0; i < tPositions.length; i += 3) {
  33409. tPositions[i + 2] = -tPositions[i + 2];
  33410. }
  33411. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33412. }
  33413. // Negate normal.z
  33414. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33415. if (tNormals != null && tNormals.length > 0) {
  33416. for (var i = 0; i < tNormals.length; i += 3) {
  33417. tNormals[i + 2] = -tNormals[i + 2];
  33418. }
  33419. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33420. }
  33421. };
  33422. Geometry.prototype.isDisposed = function () {
  33423. return this._isDisposed;
  33424. };
  33425. Geometry.prototype.dispose = function () {
  33426. var meshes = this._meshes;
  33427. var numOfMeshes = meshes.length;
  33428. var index;
  33429. for (index = 0; index < numOfMeshes; index++) {
  33430. this.releaseForMesh(meshes[index]);
  33431. }
  33432. this._meshes = [];
  33433. for (var kind in this._vertexBuffers) {
  33434. this._vertexBuffers[kind].dispose();
  33435. }
  33436. this._vertexBuffers = {};
  33437. this._totalVertices = 0;
  33438. if (this._indexBuffer) {
  33439. this._engine._releaseBuffer(this._indexBuffer);
  33440. }
  33441. this._indexBuffer = null;
  33442. this._indices = [];
  33443. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33444. this.delayLoadingFile = null;
  33445. this._delayLoadingFunction = null;
  33446. this._delayInfo = [];
  33447. this._boundingInfo = null;
  33448. this._scene.removeGeometry(this);
  33449. this._isDisposed = true;
  33450. };
  33451. Geometry.prototype.copy = function (id) {
  33452. var vertexData = new BABYLON.VertexData();
  33453. vertexData.indices = [];
  33454. var indices = this.getIndices();
  33455. for (var index = 0; index < indices.length; index++) {
  33456. vertexData.indices.push(indices[index]);
  33457. }
  33458. var updatable = false;
  33459. var stopChecking = false;
  33460. var kind;
  33461. for (kind in this._vertexBuffers) {
  33462. // using slice() to make a copy of the array and not just reference it
  33463. var data = this.getVerticesData(kind);
  33464. if (data instanceof Float32Array) {
  33465. vertexData.set(new Float32Array(data), kind);
  33466. }
  33467. else {
  33468. vertexData.set(data.slice(0), kind);
  33469. }
  33470. if (!stopChecking) {
  33471. updatable = this.getVertexBuffer(kind).isUpdatable();
  33472. stopChecking = !updatable;
  33473. }
  33474. }
  33475. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33476. geometry.delayLoadState = this.delayLoadState;
  33477. geometry.delayLoadingFile = this.delayLoadingFile;
  33478. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33479. for (kind in this._delayInfo) {
  33480. geometry._delayInfo = geometry._delayInfo || [];
  33481. geometry._delayInfo.push(kind);
  33482. }
  33483. // Bounding info
  33484. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33485. return geometry;
  33486. };
  33487. Geometry.prototype.serialize = function () {
  33488. var serializationObject = {};
  33489. serializationObject.id = this.id;
  33490. if (BABYLON.Tags.HasTags(this)) {
  33491. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33492. }
  33493. return serializationObject;
  33494. };
  33495. Geometry.prototype.serializeVerticeData = function () {
  33496. var serializationObject = this.serialize();
  33497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33498. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33499. }
  33500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33501. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33502. }
  33503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33504. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33505. }
  33506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33507. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33508. }
  33509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33510. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33511. }
  33512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33513. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33514. }
  33515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33516. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33517. }
  33518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33519. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33520. }
  33521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33522. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33523. }
  33524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33525. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33526. serializationObject.matricesIndices._isExpanded = true;
  33527. }
  33528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33529. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33530. }
  33531. serializationObject.indices = this.getIndices();
  33532. return serializationObject;
  33533. };
  33534. // Statics
  33535. Geometry.ExtractFromMesh = function (mesh, id) {
  33536. var geometry = mesh._geometry;
  33537. if (!geometry) {
  33538. return null;
  33539. }
  33540. return geometry.copy(id);
  33541. };
  33542. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33543. // be aware Math.random() could cause collisions
  33544. Geometry.RandomId = function () {
  33545. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33546. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33547. return v.toString(16);
  33548. });
  33549. };
  33550. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33551. var scene = mesh.getScene();
  33552. // Geometry
  33553. var geometryId = parsedGeometry.geometryId;
  33554. if (geometryId) {
  33555. var geometry = scene.getGeometryByID(geometryId);
  33556. if (geometry) {
  33557. geometry.applyToMesh(mesh);
  33558. }
  33559. }
  33560. else if (parsedGeometry instanceof ArrayBuffer) {
  33561. var binaryInfo = mesh._binaryInfo;
  33562. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33563. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33564. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33565. }
  33566. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33567. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33568. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33569. }
  33570. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33571. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33572. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33573. }
  33574. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33575. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33576. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33577. }
  33578. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33579. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33580. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33581. }
  33582. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33583. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33584. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33585. }
  33586. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33587. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33588. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33589. }
  33590. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33591. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33592. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33593. }
  33594. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33595. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33596. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33597. }
  33598. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33599. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33601. }
  33602. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33603. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33605. }
  33606. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33607. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33608. mesh.setIndices(indicesData);
  33609. }
  33610. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33611. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33612. mesh.subMeshes = [];
  33613. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33614. var materialIndex = subMeshesData[(i * 5) + 0];
  33615. var verticesStart = subMeshesData[(i * 5) + 1];
  33616. var verticesCount = subMeshesData[(i * 5) + 2];
  33617. var indexStart = subMeshesData[(i * 5) + 3];
  33618. var indexCount = subMeshesData[(i * 5) + 4];
  33619. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33620. }
  33621. }
  33622. }
  33623. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33625. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33626. if (parsedGeometry.uvs) {
  33627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33628. }
  33629. if (parsedGeometry.uvs2) {
  33630. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33631. }
  33632. if (parsedGeometry.uvs3) {
  33633. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33634. }
  33635. if (parsedGeometry.uvs4) {
  33636. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33637. }
  33638. if (parsedGeometry.uvs5) {
  33639. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33640. }
  33641. if (parsedGeometry.uvs6) {
  33642. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33643. }
  33644. if (parsedGeometry.colors) {
  33645. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33646. }
  33647. if (parsedGeometry.matricesIndices) {
  33648. if (!parsedGeometry.matricesIndices._isExpanded) {
  33649. var floatIndices = [];
  33650. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33651. var matricesIndex = parsedGeometry.matricesIndices[i];
  33652. floatIndices.push(matricesIndex & 0x000000FF);
  33653. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33654. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33655. floatIndices.push(matricesIndex >> 24);
  33656. }
  33657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33658. }
  33659. else {
  33660. delete parsedGeometry.matricesIndices._isExpanded;
  33661. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33662. }
  33663. }
  33664. if (parsedGeometry.matricesIndicesExtra) {
  33665. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33666. var floatIndices = [];
  33667. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33668. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33669. floatIndices.push(matricesIndex & 0x000000FF);
  33670. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33671. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33672. floatIndices.push(matricesIndex >> 24);
  33673. }
  33674. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33675. }
  33676. else {
  33677. delete parsedGeometry.matricesIndices._isExpanded;
  33678. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33679. }
  33680. }
  33681. if (parsedGeometry.matricesWeights) {
  33682. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33683. }
  33684. if (parsedGeometry.matricesWeightsExtra) {
  33685. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33686. }
  33687. mesh.setIndices(parsedGeometry.indices);
  33688. }
  33689. // SubMeshes
  33690. if (parsedGeometry.subMeshes) {
  33691. mesh.subMeshes = [];
  33692. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33693. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33694. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33695. }
  33696. }
  33697. // Flat shading
  33698. if (mesh._shouldGenerateFlatShading) {
  33699. mesh.convertToFlatShadedMesh();
  33700. delete mesh._shouldGenerateFlatShading;
  33701. }
  33702. // Update
  33703. mesh.computeWorldMatrix(true);
  33704. // Octree
  33705. if (scene['_selectionOctree']) {
  33706. scene['_selectionOctree'].addMesh(mesh);
  33707. }
  33708. };
  33709. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33710. if (scene.getGeometryByID(parsedVertexData.id)) {
  33711. return null; // null since geometry could be something else than a box...
  33712. }
  33713. var geometry = new Geometry(parsedVertexData.id, scene);
  33714. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33715. if (parsedVertexData.delayLoadingFile) {
  33716. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33717. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33718. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33719. geometry._delayInfo = [];
  33720. if (parsedVertexData.hasUVs) {
  33721. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33722. }
  33723. if (parsedVertexData.hasUVs2) {
  33724. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33725. }
  33726. if (parsedVertexData.hasUVs3) {
  33727. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33728. }
  33729. if (parsedVertexData.hasUVs4) {
  33730. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33731. }
  33732. if (parsedVertexData.hasUVs5) {
  33733. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33734. }
  33735. if (parsedVertexData.hasUVs6) {
  33736. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33737. }
  33738. if (parsedVertexData.hasColors) {
  33739. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33740. }
  33741. if (parsedVertexData.hasMatricesIndices) {
  33742. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33743. }
  33744. if (parsedVertexData.hasMatricesWeights) {
  33745. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33746. }
  33747. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33748. }
  33749. else {
  33750. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33751. }
  33752. scene.pushGeometry(geometry, true);
  33753. return geometry;
  33754. };
  33755. return Geometry;
  33756. }());
  33757. BABYLON.Geometry = Geometry;
  33758. /////// Primitives //////////////////////////////////////////////
  33759. var Geometry;
  33760. (function (Geometry) {
  33761. var Primitives;
  33762. (function (Primitives) {
  33763. /// Abstract class
  33764. var _Primitive = (function (_super) {
  33765. __extends(_Primitive, _super);
  33766. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33767. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33768. this._canBeRegenerated = _canBeRegenerated;
  33769. this._beingRegenerated = true;
  33770. this.regenerate();
  33771. this._beingRegenerated = false;
  33772. }
  33773. _Primitive.prototype.canBeRegenerated = function () {
  33774. return this._canBeRegenerated;
  33775. };
  33776. _Primitive.prototype.regenerate = function () {
  33777. if (!this._canBeRegenerated) {
  33778. return;
  33779. }
  33780. this._beingRegenerated = true;
  33781. this.setAllVerticesData(this._regenerateVertexData(), false);
  33782. this._beingRegenerated = false;
  33783. };
  33784. _Primitive.prototype.asNewGeometry = function (id) {
  33785. return _super.prototype.copy.call(this, id);
  33786. };
  33787. // overrides
  33788. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33789. if (!this._beingRegenerated) {
  33790. return;
  33791. }
  33792. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33793. };
  33794. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33795. if (!this._beingRegenerated) {
  33796. return;
  33797. }
  33798. _super.prototype.setVerticesData.call(this, kind, data, false);
  33799. };
  33800. // to override
  33801. // protected
  33802. _Primitive.prototype._regenerateVertexData = function () {
  33803. throw new Error("Abstract method");
  33804. };
  33805. _Primitive.prototype.copy = function (id) {
  33806. throw new Error("Must be overriden in sub-classes.");
  33807. };
  33808. _Primitive.prototype.serialize = function () {
  33809. var serializationObject = _super.prototype.serialize.call(this);
  33810. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33811. return serializationObject;
  33812. };
  33813. return _Primitive;
  33814. }(Geometry));
  33815. Primitives._Primitive = _Primitive;
  33816. var Ribbon = (function (_super) {
  33817. __extends(Ribbon, _super);
  33818. // Members
  33819. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33821. _super.call(this, id, scene, canBeRegenerated, mesh);
  33822. this.pathArray = pathArray;
  33823. this.closeArray = closeArray;
  33824. this.closePath = closePath;
  33825. this.offset = offset;
  33826. this.side = side;
  33827. }
  33828. Ribbon.prototype._regenerateVertexData = function () {
  33829. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33830. };
  33831. Ribbon.prototype.copy = function (id) {
  33832. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33833. };
  33834. return Ribbon;
  33835. }(_Primitive));
  33836. Primitives.Ribbon = Ribbon;
  33837. var Box = (function (_super) {
  33838. __extends(Box, _super);
  33839. // Members
  33840. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33841. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33842. _super.call(this, id, scene, canBeRegenerated, mesh);
  33843. this.size = size;
  33844. this.side = side;
  33845. }
  33846. Box.prototype._regenerateVertexData = function () {
  33847. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33848. };
  33849. Box.prototype.copy = function (id) {
  33850. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33851. };
  33852. Box.prototype.serialize = function () {
  33853. var serializationObject = _super.prototype.serialize.call(this);
  33854. serializationObject.size = this.size;
  33855. return serializationObject;
  33856. };
  33857. Box.Parse = function (parsedBox, scene) {
  33858. if (scene.getGeometryByID(parsedBox.id)) {
  33859. return null; // null since geometry could be something else than a box...
  33860. }
  33861. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33862. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33863. scene.pushGeometry(box, true);
  33864. return box;
  33865. };
  33866. return Box;
  33867. }(_Primitive));
  33868. Primitives.Box = Box;
  33869. var Sphere = (function (_super) {
  33870. __extends(Sphere, _super);
  33871. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33872. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33873. _super.call(this, id, scene, canBeRegenerated, mesh);
  33874. this.segments = segments;
  33875. this.diameter = diameter;
  33876. this.side = side;
  33877. }
  33878. Sphere.prototype._regenerateVertexData = function () {
  33879. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33880. };
  33881. Sphere.prototype.copy = function (id) {
  33882. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33883. };
  33884. Sphere.prototype.serialize = function () {
  33885. var serializationObject = _super.prototype.serialize.call(this);
  33886. serializationObject.segments = this.segments;
  33887. serializationObject.diameter = this.diameter;
  33888. return serializationObject;
  33889. };
  33890. Sphere.Parse = function (parsedSphere, scene) {
  33891. if (scene.getGeometryByID(parsedSphere.id)) {
  33892. return null; // null since geometry could be something else than a sphere...
  33893. }
  33894. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33895. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33896. scene.pushGeometry(sphere, true);
  33897. return sphere;
  33898. };
  33899. return Sphere;
  33900. }(_Primitive));
  33901. Primitives.Sphere = Sphere;
  33902. var Disc = (function (_super) {
  33903. __extends(Disc, _super);
  33904. // Members
  33905. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33906. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33907. _super.call(this, id, scene, canBeRegenerated, mesh);
  33908. this.radius = radius;
  33909. this.tessellation = tessellation;
  33910. this.side = side;
  33911. }
  33912. Disc.prototype._regenerateVertexData = function () {
  33913. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33914. };
  33915. Disc.prototype.copy = function (id) {
  33916. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33917. };
  33918. return Disc;
  33919. }(_Primitive));
  33920. Primitives.Disc = Disc;
  33921. var Cylinder = (function (_super) {
  33922. __extends(Cylinder, _super);
  33923. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33924. if (subdivisions === void 0) { subdivisions = 1; }
  33925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33926. _super.call(this, id, scene, canBeRegenerated, mesh);
  33927. this.height = height;
  33928. this.diameterTop = diameterTop;
  33929. this.diameterBottom = diameterBottom;
  33930. this.tessellation = tessellation;
  33931. this.subdivisions = subdivisions;
  33932. this.side = side;
  33933. }
  33934. Cylinder.prototype._regenerateVertexData = function () {
  33935. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33936. };
  33937. Cylinder.prototype.copy = function (id) {
  33938. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33939. };
  33940. Cylinder.prototype.serialize = function () {
  33941. var serializationObject = _super.prototype.serialize.call(this);
  33942. serializationObject.height = this.height;
  33943. serializationObject.diameterTop = this.diameterTop;
  33944. serializationObject.diameterBottom = this.diameterBottom;
  33945. serializationObject.tessellation = this.tessellation;
  33946. return serializationObject;
  33947. };
  33948. Cylinder.Parse = function (parsedCylinder, scene) {
  33949. if (scene.getGeometryByID(parsedCylinder.id)) {
  33950. return null; // null since geometry could be something else than a cylinder...
  33951. }
  33952. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33953. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33954. scene.pushGeometry(cylinder, true);
  33955. return cylinder;
  33956. };
  33957. return Cylinder;
  33958. }(_Primitive));
  33959. Primitives.Cylinder = Cylinder;
  33960. var Torus = (function (_super) {
  33961. __extends(Torus, _super);
  33962. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33963. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33964. _super.call(this, id, scene, canBeRegenerated, mesh);
  33965. this.diameter = diameter;
  33966. this.thickness = thickness;
  33967. this.tessellation = tessellation;
  33968. this.side = side;
  33969. }
  33970. Torus.prototype._regenerateVertexData = function () {
  33971. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33972. };
  33973. Torus.prototype.copy = function (id) {
  33974. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33975. };
  33976. Torus.prototype.serialize = function () {
  33977. var serializationObject = _super.prototype.serialize.call(this);
  33978. serializationObject.diameter = this.diameter;
  33979. serializationObject.thickness = this.thickness;
  33980. serializationObject.tessellation = this.tessellation;
  33981. return serializationObject;
  33982. };
  33983. Torus.Parse = function (parsedTorus, scene) {
  33984. if (scene.getGeometryByID(parsedTorus.id)) {
  33985. return null; // null since geometry could be something else than a torus...
  33986. }
  33987. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33988. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33989. scene.pushGeometry(torus, true);
  33990. return torus;
  33991. };
  33992. return Torus;
  33993. }(_Primitive));
  33994. Primitives.Torus = Torus;
  33995. var Ground = (function (_super) {
  33996. __extends(Ground, _super);
  33997. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33998. _super.call(this, id, scene, canBeRegenerated, mesh);
  33999. this.width = width;
  34000. this.height = height;
  34001. this.subdivisions = subdivisions;
  34002. }
  34003. Ground.prototype._regenerateVertexData = function () {
  34004. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34005. };
  34006. Ground.prototype.copy = function (id) {
  34007. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34008. };
  34009. Ground.prototype.serialize = function () {
  34010. var serializationObject = _super.prototype.serialize.call(this);
  34011. serializationObject.width = this.width;
  34012. serializationObject.height = this.height;
  34013. serializationObject.subdivisions = this.subdivisions;
  34014. return serializationObject;
  34015. };
  34016. Ground.Parse = function (parsedGround, scene) {
  34017. if (scene.getGeometryByID(parsedGround.id)) {
  34018. return null; // null since geometry could be something else than a ground...
  34019. }
  34020. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34021. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34022. scene.pushGeometry(ground, true);
  34023. return ground;
  34024. };
  34025. return Ground;
  34026. }(_Primitive));
  34027. Primitives.Ground = Ground;
  34028. var TiledGround = (function (_super) {
  34029. __extends(TiledGround, _super);
  34030. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34031. _super.call(this, id, scene, canBeRegenerated, mesh);
  34032. this.xmin = xmin;
  34033. this.zmin = zmin;
  34034. this.xmax = xmax;
  34035. this.zmax = zmax;
  34036. this.subdivisions = subdivisions;
  34037. this.precision = precision;
  34038. }
  34039. TiledGround.prototype._regenerateVertexData = function () {
  34040. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34041. };
  34042. TiledGround.prototype.copy = function (id) {
  34043. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34044. };
  34045. return TiledGround;
  34046. }(_Primitive));
  34047. Primitives.TiledGround = TiledGround;
  34048. var Plane = (function (_super) {
  34049. __extends(Plane, _super);
  34050. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34051. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34052. _super.call(this, id, scene, canBeRegenerated, mesh);
  34053. this.size = size;
  34054. this.side = side;
  34055. }
  34056. Plane.prototype._regenerateVertexData = function () {
  34057. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34058. };
  34059. Plane.prototype.copy = function (id) {
  34060. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34061. };
  34062. Plane.prototype.serialize = function () {
  34063. var serializationObject = _super.prototype.serialize.call(this);
  34064. serializationObject.size = this.size;
  34065. return serializationObject;
  34066. };
  34067. Plane.Parse = function (parsedPlane, scene) {
  34068. if (scene.getGeometryByID(parsedPlane.id)) {
  34069. return null; // null since geometry could be something else than a ground...
  34070. }
  34071. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34072. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34073. scene.pushGeometry(plane, true);
  34074. return plane;
  34075. };
  34076. return Plane;
  34077. }(_Primitive));
  34078. Primitives.Plane = Plane;
  34079. var TorusKnot = (function (_super) {
  34080. __extends(TorusKnot, _super);
  34081. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34083. _super.call(this, id, scene, canBeRegenerated, mesh);
  34084. this.radius = radius;
  34085. this.tube = tube;
  34086. this.radialSegments = radialSegments;
  34087. this.tubularSegments = tubularSegments;
  34088. this.p = p;
  34089. this.q = q;
  34090. this.side = side;
  34091. }
  34092. TorusKnot.prototype._regenerateVertexData = function () {
  34093. 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 });
  34094. };
  34095. TorusKnot.prototype.copy = function (id) {
  34096. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34097. };
  34098. TorusKnot.prototype.serialize = function () {
  34099. var serializationObject = _super.prototype.serialize.call(this);
  34100. serializationObject.radius = this.radius;
  34101. serializationObject.tube = this.tube;
  34102. serializationObject.radialSegments = this.radialSegments;
  34103. serializationObject.tubularSegments = this.tubularSegments;
  34104. serializationObject.p = this.p;
  34105. serializationObject.q = this.q;
  34106. return serializationObject;
  34107. };
  34108. ;
  34109. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34110. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34111. return null; // null since geometry could be something else than a ground...
  34112. }
  34113. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34114. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34115. scene.pushGeometry(torusKnot, true);
  34116. return torusKnot;
  34117. };
  34118. return TorusKnot;
  34119. }(_Primitive));
  34120. Primitives.TorusKnot = TorusKnot;
  34121. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34122. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34123. })(BABYLON || (BABYLON = {}));
  34124. var BABYLON;
  34125. (function (BABYLON) {
  34126. var GroundMesh = (function (_super) {
  34127. __extends(GroundMesh, _super);
  34128. function GroundMesh(name, scene) {
  34129. _super.call(this, name, scene);
  34130. this.generateOctree = false;
  34131. this._worldInverse = new BABYLON.Matrix();
  34132. }
  34133. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34134. get: function () {
  34135. return this._subdivisions;
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34141. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34142. this._subdivisions = chunksCount;
  34143. this.subdivide(this._subdivisions);
  34144. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34145. };
  34146. /**
  34147. * Returns a height (y) value in the Worl system :
  34148. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34149. * Returns the ground y position if (x, z) are outside the ground surface.
  34150. * Not pertinent if the ground is rotated.
  34151. */
  34152. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34153. // express x and y in the ground local system
  34154. x -= this.position.x;
  34155. z -= this.position.z;
  34156. x /= this.scaling.x;
  34157. z /= this.scaling.z;
  34158. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34159. return this.position.y;
  34160. }
  34161. if (!this._heightQuads || this._heightQuads.length == 0) {
  34162. this._initHeightQuads();
  34163. this._computeHeightQuads();
  34164. }
  34165. var facet = this._getFacetAt(x, z);
  34166. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34167. // return y in the World system
  34168. return y * this.scaling.y + this.position.y;
  34169. };
  34170. /**
  34171. * Returns a normalized vector (Vector3) orthogonal to the ground
  34172. * at the ground coordinates (x, z) expressed in the World system.
  34173. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34174. * Not pertinent if the ground is rotated.
  34175. */
  34176. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34177. var normal = new BABYLON.Vector3(0, 1, 0);
  34178. this.getNormalAtCoordinatesToRef(x, z, normal);
  34179. return normal;
  34180. };
  34181. /**
  34182. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34183. * at the ground coordinates (x, z) expressed in the World system.
  34184. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34185. * Not pertinent if the ground is rotated.
  34186. */
  34187. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34188. // express x and y in the ground local system
  34189. x -= this.position.x;
  34190. z -= this.position.z;
  34191. x /= this.scaling.x;
  34192. z /= this.scaling.z;
  34193. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34194. return;
  34195. }
  34196. if (!this._heightQuads || this._heightQuads.length == 0) {
  34197. this._initHeightQuads();
  34198. this._computeHeightQuads();
  34199. }
  34200. var facet = this._getFacetAt(x, z);
  34201. ref.x = facet.x;
  34202. ref.y = facet.y;
  34203. ref.z = facet.z;
  34204. };
  34205. /**
  34206. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34207. * if the ground has been updated.
  34208. * This can be used in the render loop
  34209. */
  34210. GroundMesh.prototype.updateCoordinateHeights = function () {
  34211. if (!this._heightQuads || this._heightQuads.length == 0) {
  34212. this._initHeightQuads();
  34213. }
  34214. this._computeHeightQuads();
  34215. };
  34216. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34217. GroundMesh.prototype._getFacetAt = function (x, z) {
  34218. // retrieve col and row from x, z coordinates in the ground local system
  34219. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34220. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34221. var quad = this._heightQuads[row * this._subdivisions + col];
  34222. var facet;
  34223. if (z < quad.slope.x * x + quad.slope.y) {
  34224. facet = quad.facet1;
  34225. }
  34226. else {
  34227. facet = quad.facet2;
  34228. }
  34229. return facet;
  34230. };
  34231. // Creates and populates the heightMap array with "facet" elements :
  34232. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34233. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34234. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34235. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34236. GroundMesh.prototype._initHeightQuads = function () {
  34237. this._heightQuads = new Array();
  34238. for (var row = 0; row < this._subdivisions; row++) {
  34239. for (var col = 0; col < this._subdivisions; col++) {
  34240. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34241. this._heightQuads[row * this._subdivisions + col] = quad;
  34242. }
  34243. }
  34244. };
  34245. // Compute each quad element values and update the the heightMap array :
  34246. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34247. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34248. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34249. GroundMesh.prototype._computeHeightQuads = function () {
  34250. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34251. var v1 = BABYLON.Tmp.Vector3[3];
  34252. var v2 = BABYLON.Tmp.Vector3[2];
  34253. var v3 = BABYLON.Tmp.Vector3[1];
  34254. var v4 = BABYLON.Tmp.Vector3[0];
  34255. var v1v2 = BABYLON.Tmp.Vector3[4];
  34256. var v1v3 = BABYLON.Tmp.Vector3[5];
  34257. var v1v4 = BABYLON.Tmp.Vector3[6];
  34258. var norm1 = BABYLON.Tmp.Vector3[7];
  34259. var norm2 = BABYLON.Tmp.Vector3[8];
  34260. var i = 0;
  34261. var j = 0;
  34262. var k = 0;
  34263. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34264. var h = 0;
  34265. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34266. var d2 = 0;
  34267. for (var row = 0; row < this._subdivisions; row++) {
  34268. for (var col = 0; col < this._subdivisions; col++) {
  34269. i = col * 3;
  34270. j = row * (this._subdivisions + 1) * 3;
  34271. k = (row + 1) * (this._subdivisions + 1) * 3;
  34272. v1.x = positions[j + i];
  34273. v1.y = positions[j + i + 1];
  34274. v1.z = positions[j + i + 2];
  34275. v2.x = positions[j + i + 3];
  34276. v2.y = positions[j + i + 4];
  34277. v2.z = positions[j + i + 5];
  34278. v3.x = positions[k + i];
  34279. v3.y = positions[k + i + 1];
  34280. v3.z = positions[k + i + 2];
  34281. v4.x = positions[k + i + 3];
  34282. v4.y = positions[k + i + 4];
  34283. v4.z = positions[k + i + 5];
  34284. // 2D slope V1V4
  34285. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34286. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34287. // facet equations :
  34288. // we compute each facet normal vector
  34289. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34290. // we compute the value d by applying the equation to v1 which belongs to the plane
  34291. // then we store the facet equation in a Vector4
  34292. v2.subtractToRef(v1, v1v2);
  34293. v3.subtractToRef(v1, v1v3);
  34294. v4.subtractToRef(v1, v1v4);
  34295. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34296. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34297. norm1.normalize();
  34298. norm2.normalize();
  34299. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34300. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34301. var quad = this._heightQuads[row * this._subdivisions + col];
  34302. quad.slope.copyFromFloats(cd, h);
  34303. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34304. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34305. }
  34306. }
  34307. };
  34308. return GroundMesh;
  34309. }(BABYLON.Mesh));
  34310. BABYLON.GroundMesh = GroundMesh;
  34311. })(BABYLON || (BABYLON = {}));
  34312. var BABYLON;
  34313. (function (BABYLON) {
  34314. var LinesMesh = (function (_super) {
  34315. __extends(LinesMesh, _super);
  34316. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34317. if (parent === void 0) { parent = null; }
  34318. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34319. this.color = new BABYLON.Color3(1, 1, 1);
  34320. this.alpha = 1;
  34321. this._positionBuffer = {};
  34322. if (source) {
  34323. this.color = source.color.clone();
  34324. this.alpha = source.alpha;
  34325. }
  34326. this._intersectionThreshold = 0.1;
  34327. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34328. attributes: [BABYLON.VertexBuffer.PositionKind],
  34329. uniforms: ["worldViewProjection", "color"],
  34330. needAlphaBlending: true
  34331. });
  34332. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34333. }
  34334. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34335. /**
  34336. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34337. * This margin is expressed in world space coordinates, so its value may vary.
  34338. * Default value is 0.1
  34339. * @returns the intersection Threshold value.
  34340. */
  34341. get: function () {
  34342. return this._intersectionThreshold;
  34343. },
  34344. /**
  34345. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34346. * This margin is expressed in world space coordinates, so its value may vary.
  34347. * @param value the new threshold to apply
  34348. */
  34349. set: function (value) {
  34350. if (this._intersectionThreshold === value) {
  34351. return;
  34352. }
  34353. this._intersectionThreshold = value;
  34354. if (this.geometry) {
  34355. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34356. }
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. Object.defineProperty(LinesMesh.prototype, "material", {
  34362. get: function () {
  34363. return this._colorShader;
  34364. },
  34365. enumerable: true,
  34366. configurable: true
  34367. });
  34368. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34369. get: function () {
  34370. return false;
  34371. },
  34372. enumerable: true,
  34373. configurable: true
  34374. });
  34375. LinesMesh.prototype.createInstance = function (name) {
  34376. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34377. return null;
  34378. };
  34379. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34380. var engine = this.getScene().getEngine();
  34381. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34382. // VBOs
  34383. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34384. // Color
  34385. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34386. };
  34387. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34388. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34389. return;
  34390. }
  34391. var engine = this.getScene().getEngine();
  34392. // Draw order
  34393. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34394. };
  34395. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34396. this._colorShader.dispose();
  34397. _super.prototype.dispose.call(this, doNotRecurse);
  34398. };
  34399. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34400. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34401. };
  34402. return LinesMesh;
  34403. }(BABYLON.Mesh));
  34404. BABYLON.LinesMesh = LinesMesh;
  34405. })(BABYLON || (BABYLON = {}));
  34406. var BABYLON;
  34407. (function (BABYLON) {
  34408. var DefaultLoadingScreen = (function () {
  34409. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34410. var _this = this;
  34411. if (_loadingText === void 0) { _loadingText = ""; }
  34412. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34413. this._renderingCanvas = _renderingCanvas;
  34414. this._loadingText = _loadingText;
  34415. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34416. // Resize
  34417. this._resizeLoadingUI = function () {
  34418. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34419. _this._loadingDiv.style.position = "absolute";
  34420. _this._loadingDiv.style.left = canvasRect.left + "px";
  34421. _this._loadingDiv.style.top = canvasRect.top + "px";
  34422. _this._loadingDiv.style.width = canvasRect.width + "px";
  34423. _this._loadingDiv.style.height = canvasRect.height + "px";
  34424. };
  34425. }
  34426. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34427. var _this = this;
  34428. if (this._loadingDiv) {
  34429. // Do not add a loading screen if there is already one
  34430. return;
  34431. }
  34432. this._loadingDiv = document.createElement("div");
  34433. this._loadingDiv.id = "babylonjsLoadingDiv";
  34434. this._loadingDiv.style.opacity = "0";
  34435. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34436. // Loading text
  34437. this._loadingTextDiv = document.createElement("div");
  34438. this._loadingTextDiv.style.position = "absolute";
  34439. this._loadingTextDiv.style.left = "0";
  34440. this._loadingTextDiv.style.top = "50%";
  34441. this._loadingTextDiv.style.marginTop = "80px";
  34442. this._loadingTextDiv.style.width = "100%";
  34443. this._loadingTextDiv.style.height = "20px";
  34444. this._loadingTextDiv.style.fontFamily = "Arial";
  34445. this._loadingTextDiv.style.fontSize = "14px";
  34446. this._loadingTextDiv.style.color = "white";
  34447. this._loadingTextDiv.style.textAlign = "center";
  34448. this._loadingTextDiv.innerHTML = "Loading";
  34449. this._loadingDiv.appendChild(this._loadingTextDiv);
  34450. //set the predefined text
  34451. this._loadingTextDiv.innerHTML = this._loadingText;
  34452. // Loading img
  34453. var imgBack = new Image();
  34454. 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==";
  34455. imgBack.style.position = "absolute";
  34456. imgBack.style.left = "50%";
  34457. imgBack.style.top = "50%";
  34458. imgBack.style.marginLeft = "-50px";
  34459. imgBack.style.marginTop = "-50px";
  34460. imgBack.style.transition = "transform 1.0s ease";
  34461. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34462. var deg = 360;
  34463. var onTransitionEnd = function () {
  34464. deg += 360;
  34465. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34466. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34467. };
  34468. imgBack.addEventListener("transitionend", onTransitionEnd);
  34469. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34470. this._loadingDiv.appendChild(imgBack);
  34471. // front image
  34472. var imgFront = new Image();
  34473. 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=";
  34474. imgFront.style.position = "absolute";
  34475. imgFront.style.left = "50%";
  34476. imgFront.style.top = "50%";
  34477. imgFront.style.marginLeft = "-50px";
  34478. imgFront.style.marginTop = "-50px";
  34479. this._loadingDiv.appendChild(imgFront);
  34480. this._resizeLoadingUI();
  34481. window.addEventListener("resize", this._resizeLoadingUI);
  34482. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34483. document.body.appendChild(this._loadingDiv);
  34484. setTimeout(function () {
  34485. _this._loadingDiv.style.opacity = "1";
  34486. imgBack.style.transform = "rotateZ(360deg)";
  34487. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34488. }, 0);
  34489. };
  34490. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34491. var _this = this;
  34492. if (!this._loadingDiv) {
  34493. return;
  34494. }
  34495. var onTransitionEnd = function () {
  34496. if (!_this._loadingDiv) {
  34497. return;
  34498. }
  34499. document.body.removeChild(_this._loadingDiv);
  34500. window.removeEventListener("resize", _this._resizeLoadingUI);
  34501. _this._loadingDiv = null;
  34502. };
  34503. this._loadingDiv.style.opacity = "0";
  34504. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34505. };
  34506. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34507. set: function (text) {
  34508. this._loadingText = text;
  34509. if (this._loadingTextDiv) {
  34510. this._loadingTextDiv.innerHTML = this._loadingText;
  34511. }
  34512. },
  34513. enumerable: true,
  34514. configurable: true
  34515. });
  34516. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34517. get: function () {
  34518. return this._loadingDivBackgroundColor;
  34519. },
  34520. set: function (color) {
  34521. this._loadingDivBackgroundColor = color;
  34522. if (!this._loadingDiv) {
  34523. return;
  34524. }
  34525. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34526. },
  34527. enumerable: true,
  34528. configurable: true
  34529. });
  34530. return DefaultLoadingScreen;
  34531. }());
  34532. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34533. })(BABYLON || (BABYLON = {}));
  34534. var BABYLON;
  34535. (function (BABYLON) {
  34536. var AudioEngine = (function () {
  34537. function AudioEngine() {
  34538. this._audioContext = null;
  34539. this._audioContextInitialized = false;
  34540. this.canUseWebAudio = false;
  34541. this.WarnedWebAudioUnsupported = false;
  34542. this.unlocked = false;
  34543. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34544. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34545. this.canUseWebAudio = true;
  34546. }
  34547. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34548. this._unlockiOSaudio();
  34549. }
  34550. else {
  34551. this.unlocked = true;
  34552. }
  34553. }
  34554. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34555. get: function () {
  34556. if (!this._audioContextInitialized) {
  34557. this._initializeAudioContext();
  34558. }
  34559. return this._audioContext;
  34560. },
  34561. enumerable: true,
  34562. configurable: true
  34563. });
  34564. AudioEngine.prototype._unlockiOSaudio = function () {
  34565. var _this = this;
  34566. var unlockaudio = function () {
  34567. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34568. var source = _this.audioContext.createBufferSource();
  34569. source.buffer = buffer;
  34570. source.connect(_this.audioContext.destination);
  34571. source.start(0);
  34572. setTimeout(function () {
  34573. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34574. _this.unlocked = true;
  34575. window.removeEventListener('touchend', unlockaudio, false);
  34576. if (_this.onAudioUnlocked) {
  34577. _this.onAudioUnlocked();
  34578. }
  34579. }
  34580. }, 0);
  34581. };
  34582. window.addEventListener('touchend', unlockaudio, false);
  34583. };
  34584. AudioEngine.prototype._initializeAudioContext = function () {
  34585. try {
  34586. if (this.canUseWebAudio) {
  34587. this._audioContext = new AudioContext();
  34588. // create a global volume gain node
  34589. this.masterGain = this._audioContext.createGain();
  34590. this.masterGain.gain.value = 1;
  34591. this.masterGain.connect(this._audioContext.destination);
  34592. this._audioContextInitialized = true;
  34593. }
  34594. }
  34595. catch (e) {
  34596. this.canUseWebAudio = false;
  34597. BABYLON.Tools.Error("Web Audio: " + e.message);
  34598. }
  34599. };
  34600. AudioEngine.prototype.dispose = function () {
  34601. if (this.canUseWebAudio && this._audioContextInitialized) {
  34602. if (this._connectedAnalyser) {
  34603. this._connectedAnalyser.stopDebugCanvas();
  34604. this._connectedAnalyser.dispose();
  34605. this.masterGain.disconnect();
  34606. this.masterGain.connect(this._audioContext.destination);
  34607. this._connectedAnalyser = null;
  34608. }
  34609. this.masterGain.gain.value = 1;
  34610. }
  34611. this.WarnedWebAudioUnsupported = false;
  34612. };
  34613. AudioEngine.prototype.getGlobalVolume = function () {
  34614. if (this.canUseWebAudio && this._audioContextInitialized) {
  34615. return this.masterGain.gain.value;
  34616. }
  34617. else {
  34618. return -1;
  34619. }
  34620. };
  34621. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34622. if (this.canUseWebAudio && this._audioContextInitialized) {
  34623. this.masterGain.gain.value = newVolume;
  34624. }
  34625. };
  34626. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34627. if (this._connectedAnalyser) {
  34628. this._connectedAnalyser.stopDebugCanvas();
  34629. }
  34630. if (this.canUseWebAudio && this._audioContextInitialized) {
  34631. this._connectedAnalyser = analyser;
  34632. this.masterGain.disconnect();
  34633. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34634. }
  34635. };
  34636. return AudioEngine;
  34637. }());
  34638. BABYLON.AudioEngine = AudioEngine;
  34639. })(BABYLON || (BABYLON = {}));
  34640. var BABYLON;
  34641. (function (BABYLON) {
  34642. var Sound = (function () {
  34643. /**
  34644. * Create a sound and attach it to a scene
  34645. * @param name Name of your sound
  34646. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34647. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34648. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34649. */
  34650. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34651. var _this = this;
  34652. this.autoplay = false;
  34653. this.loop = false;
  34654. this.useCustomAttenuation = false;
  34655. this.spatialSound = false;
  34656. this.refDistance = 1;
  34657. this.rolloffFactor = 1;
  34658. this.maxDistance = 100;
  34659. this.distanceModel = "linear";
  34660. this._panningModel = "equalpower";
  34661. this._playbackRate = 1;
  34662. this._streaming = false;
  34663. this._startTime = 0;
  34664. this._startOffset = 0;
  34665. this._position = BABYLON.Vector3.Zero();
  34666. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34667. this._volume = 1;
  34668. this._isLoaded = false;
  34669. this._isReadyToPlay = false;
  34670. this.isPlaying = false;
  34671. this.isPaused = false;
  34672. this._isDirectional = false;
  34673. // Used if you'd like to create a directional sound.
  34674. // If not set, the sound will be omnidirectional
  34675. this._coneInnerAngle = 360;
  34676. this._coneOuterAngle = 360;
  34677. this._coneOuterGain = 0;
  34678. this._isOutputConnected = false;
  34679. this.name = name;
  34680. this._scene = scene;
  34681. this._readyToPlayCallback = readyToPlayCallback;
  34682. // Default custom attenuation function is a linear attenuation
  34683. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34684. if (currentDistance < maxDistance) {
  34685. return currentVolume * (1 - currentDistance / maxDistance);
  34686. }
  34687. else {
  34688. return 0;
  34689. }
  34690. };
  34691. if (options) {
  34692. this.autoplay = options.autoplay || false;
  34693. this.loop = options.loop || false;
  34694. // if volume === 0, we need another way to check this option
  34695. if (options.volume !== undefined) {
  34696. this._volume = options.volume;
  34697. }
  34698. this.spatialSound = options.spatialSound || false;
  34699. this.maxDistance = options.maxDistance || 100;
  34700. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34701. this.rolloffFactor = options.rolloffFactor || 1;
  34702. this.refDistance = options.refDistance || 1;
  34703. this.distanceModel = options.distanceModel || "linear";
  34704. this._playbackRate = options.playbackRate || 1;
  34705. this._streaming = options.streaming || false;
  34706. }
  34707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34708. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34709. this._soundGain.gain.value = this._volume;
  34710. this._inputAudioNode = this._soundGain;
  34711. this._ouputAudioNode = this._soundGain;
  34712. if (this.spatialSound) {
  34713. this._createSpatialParameters();
  34714. }
  34715. this._scene.mainSoundTrack.AddSound(this);
  34716. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34717. if (urlOrArrayBuffer) {
  34718. // If it's an URL
  34719. if (typeof (urlOrArrayBuffer) === "string") {
  34720. // Loading sound using XHR2
  34721. if (!this._streaming) {
  34722. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34723. }
  34724. else {
  34725. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34726. this._htmlAudioElement.controls = false;
  34727. this._htmlAudioElement.loop = this.loop;
  34728. this._htmlAudioElement.crossOrigin = "anonymous";
  34729. this._htmlAudioElement.preload = "auto";
  34730. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34731. _this._isReadyToPlay = true;
  34732. if (_this.autoplay) {
  34733. _this.play();
  34734. }
  34735. if (_this._readyToPlayCallback) {
  34736. _this._readyToPlayCallback();
  34737. }
  34738. });
  34739. document.body.appendChild(this._htmlAudioElement);
  34740. }
  34741. }
  34742. else {
  34743. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34744. if (urlOrArrayBuffer.byteLength > 0) {
  34745. this._soundLoaded(urlOrArrayBuffer);
  34746. }
  34747. }
  34748. else {
  34749. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34750. }
  34751. }
  34752. }
  34753. }
  34754. else {
  34755. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34756. this._scene.mainSoundTrack.AddSound(this);
  34757. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34758. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34759. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34760. }
  34761. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34762. if (this._readyToPlayCallback) {
  34763. window.setTimeout(function () {
  34764. _this._readyToPlayCallback();
  34765. }, 1000);
  34766. }
  34767. }
  34768. }
  34769. Sound.prototype.dispose = function () {
  34770. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34771. if (this.isPlaying) {
  34772. this.stop();
  34773. }
  34774. this._isReadyToPlay = false;
  34775. if (this.soundTrackId === -1) {
  34776. this._scene.mainSoundTrack.RemoveSound(this);
  34777. }
  34778. else {
  34779. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34780. }
  34781. if (this._soundGain) {
  34782. this._soundGain.disconnect();
  34783. this._soundGain = null;
  34784. }
  34785. if (this._soundPanner) {
  34786. this._soundPanner.disconnect();
  34787. this._soundPanner = null;
  34788. }
  34789. if (this._soundSource) {
  34790. this._soundSource.disconnect();
  34791. this._soundSource = null;
  34792. }
  34793. this._audioBuffer = null;
  34794. if (this._htmlAudioElement) {
  34795. this._htmlAudioElement.pause();
  34796. this._htmlAudioElement.src = "";
  34797. document.body.removeChild(this._htmlAudioElement);
  34798. }
  34799. if (this._connectedMesh) {
  34800. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34801. this._connectedMesh = null;
  34802. }
  34803. }
  34804. };
  34805. Sound.prototype._soundLoaded = function (audioData) {
  34806. var _this = this;
  34807. this._isLoaded = true;
  34808. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34809. _this._audioBuffer = buffer;
  34810. _this._isReadyToPlay = true;
  34811. if (_this.autoplay) {
  34812. _this.play();
  34813. }
  34814. if (_this._readyToPlayCallback) {
  34815. _this._readyToPlayCallback();
  34816. }
  34817. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34818. };
  34819. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34820. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34821. this._audioBuffer = audioBuffer;
  34822. this._isReadyToPlay = true;
  34823. }
  34824. };
  34825. Sound.prototype.updateOptions = function (options) {
  34826. if (options) {
  34827. this.loop = options.loop || this.loop;
  34828. this.maxDistance = options.maxDistance || this.maxDistance;
  34829. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34830. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34831. this.refDistance = options.refDistance || this.refDistance;
  34832. this.distanceModel = options.distanceModel || this.distanceModel;
  34833. this._playbackRate = options.playbackRate || this._playbackRate;
  34834. this._updateSpatialParameters();
  34835. if (this.isPlaying) {
  34836. if (this._streaming) {
  34837. this._htmlAudioElement.playbackRate = this._playbackRate;
  34838. }
  34839. else {
  34840. this._soundSource.playbackRate.value = this._playbackRate;
  34841. }
  34842. }
  34843. }
  34844. };
  34845. Sound.prototype._createSpatialParameters = function () {
  34846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34847. if (this._scene.headphone) {
  34848. this._panningModel = "HRTF";
  34849. }
  34850. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34851. this._updateSpatialParameters();
  34852. this._soundPanner.connect(this._ouputAudioNode);
  34853. this._inputAudioNode = this._soundPanner;
  34854. }
  34855. };
  34856. Sound.prototype._updateSpatialParameters = function () {
  34857. if (this.spatialSound) {
  34858. if (this.useCustomAttenuation) {
  34859. // Tricks to disable in a way embedded Web Audio attenuation
  34860. this._soundPanner.distanceModel = "linear";
  34861. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34862. this._soundPanner.refDistance = 1;
  34863. this._soundPanner.rolloffFactor = 1;
  34864. this._soundPanner.panningModel = this._panningModel;
  34865. }
  34866. else {
  34867. this._soundPanner.distanceModel = this.distanceModel;
  34868. this._soundPanner.maxDistance = this.maxDistance;
  34869. this._soundPanner.refDistance = this.refDistance;
  34870. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34871. this._soundPanner.panningModel = this._panningModel;
  34872. }
  34873. }
  34874. };
  34875. Sound.prototype.switchPanningModelToHRTF = function () {
  34876. this._panningModel = "HRTF";
  34877. this._switchPanningModel();
  34878. };
  34879. Sound.prototype.switchPanningModelToEqualPower = function () {
  34880. this._panningModel = "equalpower";
  34881. this._switchPanningModel();
  34882. };
  34883. Sound.prototype._switchPanningModel = function () {
  34884. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34885. this._soundPanner.panningModel = this._panningModel;
  34886. }
  34887. };
  34888. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34890. if (this._isOutputConnected) {
  34891. this._ouputAudioNode.disconnect();
  34892. }
  34893. this._ouputAudioNode.connect(soundTrackAudioNode);
  34894. this._isOutputConnected = true;
  34895. }
  34896. };
  34897. /**
  34898. * Transform this sound into a directional source
  34899. * @param coneInnerAngle Size of the inner cone in degree
  34900. * @param coneOuterAngle Size of the outer cone in degree
  34901. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34902. */
  34903. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34904. if (coneOuterAngle < coneInnerAngle) {
  34905. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34906. return;
  34907. }
  34908. this._coneInnerAngle = coneInnerAngle;
  34909. this._coneOuterAngle = coneOuterAngle;
  34910. this._coneOuterGain = coneOuterGain;
  34911. this._isDirectional = true;
  34912. if (this.isPlaying && this.loop) {
  34913. this.stop();
  34914. this.play();
  34915. }
  34916. };
  34917. Sound.prototype.setPosition = function (newPosition) {
  34918. this._position = newPosition;
  34919. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34920. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34921. }
  34922. };
  34923. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34924. this._localDirection = newLocalDirection;
  34925. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34926. this._updateDirection();
  34927. }
  34928. };
  34929. Sound.prototype._updateDirection = function () {
  34930. var mat = this._connectedMesh.getWorldMatrix();
  34931. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34932. direction.normalize();
  34933. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34934. };
  34935. Sound.prototype.updateDistanceFromListener = function () {
  34936. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34937. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34938. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34939. }
  34940. };
  34941. Sound.prototype.setAttenuationFunction = function (callback) {
  34942. this._customAttenuationFunction = callback;
  34943. };
  34944. /**
  34945. * Play the sound
  34946. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34947. * @param offset (optional) Start the sound setting it at a specific time
  34948. */
  34949. Sound.prototype.play = function (time, offset) {
  34950. var _this = this;
  34951. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34952. try {
  34953. if (this._startOffset < 0) {
  34954. time = -this._startOffset;
  34955. this._startOffset = 0;
  34956. }
  34957. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34958. if (!this._soundSource || !this._streamingSource) {
  34959. if (this.spatialSound) {
  34960. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34961. if (this._isDirectional) {
  34962. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34963. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34964. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34965. if (this._connectedMesh) {
  34966. this._updateDirection();
  34967. }
  34968. else {
  34969. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34970. }
  34971. }
  34972. }
  34973. }
  34974. if (this._streaming) {
  34975. if (!this._streamingSource) {
  34976. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34977. this._htmlAudioElement.onended = function () { _this._onended(); };
  34978. this._htmlAudioElement.playbackRate = this._playbackRate;
  34979. }
  34980. this._streamingSource.disconnect();
  34981. this._streamingSource.connect(this._inputAudioNode);
  34982. this._htmlAudioElement.play();
  34983. }
  34984. else {
  34985. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34986. this._soundSource.buffer = this._audioBuffer;
  34987. this._soundSource.connect(this._inputAudioNode);
  34988. this._soundSource.loop = this.loop;
  34989. this._soundSource.playbackRate.value = this._playbackRate;
  34990. this._soundSource.onended = function () { _this._onended(); };
  34991. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  34992. }
  34993. this._startTime = startTime;
  34994. this.isPlaying = true;
  34995. this.isPaused = false;
  34996. }
  34997. catch (ex) {
  34998. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34999. }
  35000. }
  35001. };
  35002. Sound.prototype._onended = function () {
  35003. this.isPlaying = false;
  35004. if (this.onended) {
  35005. this.onended();
  35006. }
  35007. };
  35008. /**
  35009. * Stop the sound
  35010. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35011. */
  35012. Sound.prototype.stop = function (time) {
  35013. if (this.isPlaying) {
  35014. if (this._streaming) {
  35015. this._htmlAudioElement.pause();
  35016. // Test needed for Firefox or it will generate an Invalid State Error
  35017. if (this._htmlAudioElement.currentTime > 0) {
  35018. this._htmlAudioElement.currentTime = 0;
  35019. }
  35020. }
  35021. else {
  35022. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35023. this._soundSource.stop(stopTime);
  35024. this._soundSource.onended = null;
  35025. if (!this.isPaused) {
  35026. this._startOffset = 0;
  35027. }
  35028. }
  35029. this.isPlaying = false;
  35030. }
  35031. };
  35032. Sound.prototype.pause = function () {
  35033. if (this.isPlaying) {
  35034. this.isPaused = true;
  35035. if (this._streaming) {
  35036. this._htmlAudioElement.pause();
  35037. }
  35038. else {
  35039. this.stop(0);
  35040. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35041. }
  35042. }
  35043. };
  35044. Sound.prototype.setVolume = function (newVolume, time) {
  35045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35046. if (time) {
  35047. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35048. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35049. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35050. }
  35051. else {
  35052. this._soundGain.gain.value = newVolume;
  35053. }
  35054. }
  35055. this._volume = newVolume;
  35056. };
  35057. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35058. this._playbackRate = newPlaybackRate;
  35059. if (this.isPlaying) {
  35060. if (this._streaming) {
  35061. this._htmlAudioElement.playbackRate = this._playbackRate;
  35062. }
  35063. else {
  35064. this._soundSource.playbackRate.value = this._playbackRate;
  35065. }
  35066. }
  35067. };
  35068. Sound.prototype.getVolume = function () {
  35069. return this._volume;
  35070. };
  35071. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35072. var _this = this;
  35073. if (this._connectedMesh) {
  35074. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35075. this._registerFunc = null;
  35076. }
  35077. this._connectedMesh = meshToConnectTo;
  35078. if (!this.spatialSound) {
  35079. this.spatialSound = true;
  35080. this._createSpatialParameters();
  35081. if (this.isPlaying && this.loop) {
  35082. this.stop();
  35083. this.play();
  35084. }
  35085. }
  35086. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35087. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35088. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35089. };
  35090. Sound.prototype.detachFromMesh = function () {
  35091. if (this._connectedMesh) {
  35092. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35093. this._registerFunc = null;
  35094. this._connectedMesh = null;
  35095. }
  35096. };
  35097. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35098. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35099. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35100. this._updateDirection();
  35101. }
  35102. };
  35103. Sound.prototype.clone = function () {
  35104. var _this = this;
  35105. if (!this._streaming) {
  35106. var setBufferAndRun = function () {
  35107. if (_this._isReadyToPlay) {
  35108. clonedSound._audioBuffer = _this.getAudioBuffer();
  35109. clonedSound._isReadyToPlay = true;
  35110. if (clonedSound.autoplay) {
  35111. clonedSound.play();
  35112. }
  35113. }
  35114. else {
  35115. window.setTimeout(setBufferAndRun, 300);
  35116. }
  35117. };
  35118. var currentOptions = {
  35119. autoplay: this.autoplay, loop: this.loop,
  35120. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35121. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35122. refDistance: this.refDistance, distanceModel: this.distanceModel
  35123. };
  35124. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35125. if (this.useCustomAttenuation) {
  35126. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35127. }
  35128. clonedSound.setPosition(this._position);
  35129. clonedSound.setPlaybackRate(this._playbackRate);
  35130. setBufferAndRun();
  35131. return clonedSound;
  35132. }
  35133. else {
  35134. return null;
  35135. }
  35136. };
  35137. Sound.prototype.getAudioBuffer = function () {
  35138. return this._audioBuffer;
  35139. };
  35140. Sound.prototype.serialize = function () {
  35141. var serializationObject = {
  35142. name: this.name,
  35143. url: this.name,
  35144. autoplay: this.autoplay,
  35145. loop: this.loop,
  35146. volume: this._volume,
  35147. spatialSound: this.spatialSound,
  35148. maxDistance: this.maxDistance,
  35149. rolloffFactor: this.rolloffFactor,
  35150. refDistance: this.refDistance,
  35151. distanceModel: this.distanceModel,
  35152. playbackRate: this._playbackRate,
  35153. panningModel: this._panningModel,
  35154. soundTrackId: this.soundTrackId
  35155. };
  35156. if (this.spatialSound) {
  35157. if (this._connectedMesh)
  35158. serializationObject.connectedMeshId = this._connectedMesh.id;
  35159. serializationObject.position = this._position.asArray();
  35160. serializationObject.refDistance = this.refDistance;
  35161. serializationObject.distanceModel = this.distanceModel;
  35162. serializationObject.isDirectional = this._isDirectional;
  35163. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35164. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35165. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35166. serializationObject.coneOuterGain = this._coneOuterGain;
  35167. }
  35168. return serializationObject;
  35169. };
  35170. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35171. var soundName = parsedSound.name;
  35172. var soundUrl;
  35173. if (parsedSound.url) {
  35174. soundUrl = rootUrl + parsedSound.url;
  35175. }
  35176. else {
  35177. soundUrl = rootUrl + soundName;
  35178. }
  35179. var options = {
  35180. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35181. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35182. rolloffFactor: parsedSound.rolloffFactor,
  35183. refDistance: parsedSound.refDistance,
  35184. distanceModel: parsedSound.distanceModel,
  35185. playbackRate: parsedSound.playbackRate
  35186. };
  35187. var newSound;
  35188. if (!sourceSound) {
  35189. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35190. scene._addPendingData(newSound);
  35191. }
  35192. else {
  35193. var setBufferAndRun = function () {
  35194. if (sourceSound._isReadyToPlay) {
  35195. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35196. newSound._isReadyToPlay = true;
  35197. if (newSound.autoplay) {
  35198. newSound.play();
  35199. }
  35200. }
  35201. else {
  35202. window.setTimeout(setBufferAndRun, 300);
  35203. }
  35204. };
  35205. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35206. setBufferAndRun();
  35207. }
  35208. if (parsedSound.position) {
  35209. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35210. newSound.setPosition(soundPosition);
  35211. }
  35212. if (parsedSound.isDirectional) {
  35213. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35214. if (parsedSound.localDirectionToMesh) {
  35215. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35216. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35217. }
  35218. }
  35219. if (parsedSound.connectedMeshId) {
  35220. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35221. if (connectedMesh) {
  35222. newSound.attachToMesh(connectedMesh);
  35223. }
  35224. }
  35225. return newSound;
  35226. };
  35227. return Sound;
  35228. }());
  35229. BABYLON.Sound = Sound;
  35230. })(BABYLON || (BABYLON = {}));
  35231. var BABYLON;
  35232. (function (BABYLON) {
  35233. var SoundTrack = (function () {
  35234. function SoundTrack(scene, options) {
  35235. this.id = -1;
  35236. this._isMainTrack = false;
  35237. this._isInitialized = false;
  35238. this._scene = scene;
  35239. this.soundCollection = new Array();
  35240. this._options = options;
  35241. if (!this._isMainTrack) {
  35242. this._scene.soundTracks.push(this);
  35243. this.id = this._scene.soundTracks.length - 1;
  35244. }
  35245. }
  35246. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35247. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35248. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35249. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35250. if (this._options) {
  35251. if (this._options.volume) {
  35252. this._outputAudioNode.gain.value = this._options.volume;
  35253. }
  35254. if (this._options.mainTrack) {
  35255. this._isMainTrack = this._options.mainTrack;
  35256. }
  35257. }
  35258. this._isInitialized = true;
  35259. }
  35260. };
  35261. SoundTrack.prototype.dispose = function () {
  35262. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35263. if (this._connectedAnalyser) {
  35264. this._connectedAnalyser.stopDebugCanvas();
  35265. }
  35266. while (this.soundCollection.length) {
  35267. this.soundCollection[0].dispose();
  35268. }
  35269. if (this._outputAudioNode) {
  35270. this._outputAudioNode.disconnect();
  35271. }
  35272. this._outputAudioNode = null;
  35273. }
  35274. };
  35275. SoundTrack.prototype.AddSound = function (sound) {
  35276. if (!this._isInitialized) {
  35277. this._initializeSoundTrackAudioGraph();
  35278. }
  35279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35280. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35281. }
  35282. if (sound.soundTrackId) {
  35283. if (sound.soundTrackId === -1) {
  35284. this._scene.mainSoundTrack.RemoveSound(sound);
  35285. }
  35286. else {
  35287. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35288. }
  35289. }
  35290. this.soundCollection.push(sound);
  35291. sound.soundTrackId = this.id;
  35292. };
  35293. SoundTrack.prototype.RemoveSound = function (sound) {
  35294. var index = this.soundCollection.indexOf(sound);
  35295. if (index !== -1) {
  35296. this.soundCollection.splice(index, 1);
  35297. }
  35298. };
  35299. SoundTrack.prototype.setVolume = function (newVolume) {
  35300. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35301. this._outputAudioNode.gain.value = newVolume;
  35302. }
  35303. };
  35304. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35306. for (var i = 0; i < this.soundCollection.length; i++) {
  35307. this.soundCollection[i].switchPanningModelToHRTF();
  35308. }
  35309. }
  35310. };
  35311. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35312. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35313. for (var i = 0; i < this.soundCollection.length; i++) {
  35314. this.soundCollection[i].switchPanningModelToEqualPower();
  35315. }
  35316. }
  35317. };
  35318. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35319. if (this._connectedAnalyser) {
  35320. this._connectedAnalyser.stopDebugCanvas();
  35321. }
  35322. this._connectedAnalyser = analyser;
  35323. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35324. this._outputAudioNode.disconnect();
  35325. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35326. }
  35327. };
  35328. return SoundTrack;
  35329. }());
  35330. BABYLON.SoundTrack = SoundTrack;
  35331. })(BABYLON || (BABYLON = {}));
  35332. var BABYLON;
  35333. (function (BABYLON) {
  35334. var SIMDVector3 = (function () {
  35335. function SIMDVector3() {
  35336. }
  35337. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  35338. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  35339. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35340. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35341. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35342. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35343. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  35344. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35345. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35346. };
  35347. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  35348. var v0 = SIMD.float32x4.splat(x);
  35349. var v1 = SIMD.float32x4.splat(y);
  35350. var v2 = SIMD.float32x4.splat(z);
  35351. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35352. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35353. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35354. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35355. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  35356. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35357. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35358. };
  35359. return SIMDVector3;
  35360. }());
  35361. BABYLON.SIMDVector3 = SIMDVector3;
  35362. var SIMDMatrix = (function () {
  35363. function SIMDMatrix() {
  35364. }
  35365. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  35366. if (offset === void 0) { offset = 0; }
  35367. var tm = this.m;
  35368. var om = other.m;
  35369. var om0 = SIMD.float32x4.load(om, 0);
  35370. var om1 = SIMD.float32x4.load(om, 4);
  35371. var om2 = SIMD.float32x4.load(om, 8);
  35372. var om3 = SIMD.float32x4.load(om, 12);
  35373. var tm0 = SIMD.float32x4.load(tm, 0);
  35374. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  35375. var tm1 = SIMD.float32x4.load(tm, 4);
  35376. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  35377. var tm2 = SIMD.float32x4.load(tm, 8);
  35378. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  35379. var tm3 = SIMD.float32x4.load(tm, 12);
  35380. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  35381. };
  35382. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  35383. var src = this.m;
  35384. var dest = other.m;
  35385. var row0, row1, row2, row3;
  35386. var tmp1;
  35387. var minor0, minor1, minor2, minor3;
  35388. var det;
  35389. // Load the 4 rows
  35390. var src0 = SIMD.float32x4.load(src, 0);
  35391. var src1 = SIMD.float32x4.load(src, 4);
  35392. var src2 = SIMD.float32x4.load(src, 8);
  35393. var src3 = SIMD.float32x4.load(src, 12);
  35394. // Transpose the source matrix. Sort of. Not a true transpose operation
  35395. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35396. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35397. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  35398. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  35399. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35400. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35401. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  35402. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  35403. // This is a true transposition, but it will lead to an incorrect result
  35404. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35405. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35406. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35407. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35408. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35409. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35410. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35411. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35412. // ----
  35413. tmp1 = SIMD.float32x4.mul(row2, row3);
  35414. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35415. minor0 = SIMD.float32x4.mul(row1, tmp1);
  35416. minor1 = SIMD.float32x4.mul(row0, tmp1);
  35417. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35418. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  35419. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  35420. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  35421. // ----
  35422. tmp1 = SIMD.float32x4.mul(row1, row2);
  35423. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35424. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  35425. minor3 = SIMD.float32x4.mul(row0, tmp1);
  35426. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35427. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  35428. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  35429. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  35430. // ----
  35431. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  35432. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35433. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  35434. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  35435. minor2 = SIMD.float32x4.mul(row0, tmp1);
  35436. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35437. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  35438. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  35439. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  35440. // ----
  35441. tmp1 = SIMD.float32x4.mul(row0, row1);
  35442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35443. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  35444. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  35445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35446. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  35447. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  35448. // ----
  35449. tmp1 = SIMD.float32x4.mul(row0, row3);
  35450. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35451. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  35452. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  35453. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35454. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  35455. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  35456. // ----
  35457. tmp1 = SIMD.float32x4.mul(row0, row2);
  35458. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35459. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  35460. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  35461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35462. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  35463. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  35464. // Compute determinant
  35465. det = SIMD.float32x4.mul(row0, minor0);
  35466. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  35467. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  35468. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  35469. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  35470. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  35471. // These shuffles aren't necessary if the faulty transposition is done
  35472. // up at the top of this function.
  35473. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  35474. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  35475. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  35476. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  35477. // Compute final values by multiplying with 1/det
  35478. minor0 = SIMD.float32x4.mul(det, minor0);
  35479. minor1 = SIMD.float32x4.mul(det, minor1);
  35480. minor2 = SIMD.float32x4.mul(det, minor2);
  35481. minor3 = SIMD.float32x4.mul(det, minor3);
  35482. SIMD.float32x4.store(dest, 0, minor0);
  35483. SIMD.float32x4.store(dest, 4, minor1);
  35484. SIMD.float32x4.store(dest, 8, minor2);
  35485. SIMD.float32x4.store(dest, 12, minor3);
  35486. return this;
  35487. };
  35488. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  35489. var out = result.m;
  35490. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  35491. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  35492. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  35493. // cc.kmVec3Subtract(f, pCenter, pEye);
  35494. var f = SIMD.float32x4.sub(center, eye);
  35495. // cc.kmVec3Normalize(f, f);
  35496. var tmp = SIMD.float32x4.mul(f, f);
  35497. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35498. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35499. // cc.kmVec3Assign(up, pUp);
  35500. // cc.kmVec3Normalize(up, up);
  35501. tmp = SIMD.float32x4.mul(up, up);
  35502. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35503. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35504. // cc.kmVec3Cross(s, f, up);
  35505. 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)));
  35506. // cc.kmVec3Normalize(s, s);
  35507. tmp = SIMD.float32x4.mul(s, s);
  35508. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35509. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35510. // cc.kmVec3Cross(u, s, f);
  35511. 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)));
  35512. // cc.kmVec3Normalize(s, s);
  35513. tmp = SIMD.float32x4.mul(s, s);
  35514. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35515. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35516. var zero = SIMD.float32x4.splat(0.0);
  35517. s = SIMD.float32x4.neg(s);
  35518. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  35519. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  35520. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35521. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  35522. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  35523. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  35524. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35525. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  35526. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  35527. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  35528. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  35529. var b3 = SIMD.float32x4.neg(eye);
  35530. b3 = SIMD.float32x4.withW(b3, 1.0);
  35531. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  35532. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  35533. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  35534. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  35535. };
  35536. return SIMDMatrix;
  35537. }());
  35538. BABYLON.SIMDMatrix = SIMDMatrix;
  35539. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  35540. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  35541. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  35542. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  35543. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  35544. var SIMDHelper = (function () {
  35545. function SIMDHelper() {
  35546. }
  35547. Object.defineProperty(SIMDHelper, "IsEnabled", {
  35548. get: function () {
  35549. return SIMDHelper._isEnabled;
  35550. },
  35551. enumerable: true,
  35552. configurable: true
  35553. });
  35554. SIMDHelper.DisableSIMD = function () {
  35555. // Replace functions
  35556. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  35557. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  35558. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  35559. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  35560. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  35561. SIMDHelper._isEnabled = false;
  35562. };
  35563. SIMDHelper.EnableSIMD = function () {
  35564. if (window.SIMD === undefined) {
  35565. return;
  35566. }
  35567. // Replace functions
  35568. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  35569. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  35570. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  35571. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  35572. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  35573. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  35574. get: function () { return this._data[0]; },
  35575. set: function (value) {
  35576. if (!this._data) {
  35577. this._data = new Float32Array(3);
  35578. }
  35579. this._data[0] = value;
  35580. }
  35581. });
  35582. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  35583. get: function () { return this._data[1]; },
  35584. set: function (value) {
  35585. this._data[1] = value;
  35586. }
  35587. });
  35588. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  35589. get: function () { return this._data[2]; },
  35590. set: function (value) {
  35591. this._data[2] = value;
  35592. }
  35593. });
  35594. SIMDHelper._isEnabled = true;
  35595. };
  35596. SIMDHelper._isEnabled = false;
  35597. return SIMDHelper;
  35598. }());
  35599. BABYLON.SIMDHelper = SIMDHelper;
  35600. })(BABYLON || (BABYLON = {}));
  35601. var BABYLON;
  35602. (function (BABYLON) {
  35603. /**
  35604. * This class describe a rectangle that were added to the map.
  35605. * You have access to its coordinates either in pixel or normalized (UV)
  35606. */
  35607. var PackedRect = (function () {
  35608. function PackedRect(root, parent, pos, size) {
  35609. this._pos = pos;
  35610. this._size = size;
  35611. this._root = root;
  35612. this._parent = parent;
  35613. }
  35614. Object.defineProperty(PackedRect.prototype, "pos", {
  35615. /**
  35616. * @returns the position of this node into the map
  35617. */
  35618. get: function () {
  35619. return this._pos;
  35620. },
  35621. enumerable: true,
  35622. configurable: true
  35623. });
  35624. Object.defineProperty(PackedRect.prototype, "contentSize", {
  35625. /**
  35626. * @returns the size of the rectangle this node handles
  35627. */
  35628. get: function () {
  35629. return this._contentSize;
  35630. },
  35631. enumerable: true,
  35632. configurable: true
  35633. });
  35634. Object.defineProperty(PackedRect.prototype, "UVs", {
  35635. /**
  35636. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  35637. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  35638. */
  35639. get: function () {
  35640. return this.getUVsForCustomSize(this._root._size);
  35641. },
  35642. enumerable: true,
  35643. configurable: true
  35644. });
  35645. /**
  35646. * 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.
  35647. * This method will return the UVs for this part by given the custom size of what you really use
  35648. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  35649. */
  35650. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  35651. var mainWidth = this._root._size.width;
  35652. var mainHeight = this._root._size.height;
  35653. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  35654. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  35655. var uvs = new Array();
  35656. uvs.push(topLeft);
  35657. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  35658. uvs.push(rightBottom);
  35659. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  35660. return uvs;
  35661. };
  35662. /**
  35663. * Free this rectangle from the map.
  35664. * Call this method when you no longer need the rectangle to be in the map.
  35665. */
  35666. PackedRect.prototype.freeContent = function () {
  35667. if (!this.contentSize) {
  35668. return;
  35669. }
  35670. this._contentSize = null;
  35671. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  35672. this.attemptDefrag();
  35673. };
  35674. Object.defineProperty(PackedRect.prototype, "isUsed", {
  35675. get: function () {
  35676. return this._contentSize != null || this._leftNode != null;
  35677. },
  35678. enumerable: true,
  35679. configurable: true
  35680. });
  35681. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  35682. var node = this.findNode(contentSize);
  35683. // Not enough space...
  35684. if (!node) {
  35685. return null;
  35686. }
  35687. node.splitNode(contentSize);
  35688. return node;
  35689. };
  35690. PackedRect.prototype.findNode = function (size) {
  35691. var resNode = null;
  35692. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35693. if (this.isUsed) {
  35694. if (this._leftNode) {
  35695. resNode = this._leftNode.findNode(size);
  35696. }
  35697. if (!resNode && this._rightNode) {
  35698. resNode = this._rightNode.findNode(size);
  35699. }
  35700. if (!resNode && this._bottomNode) {
  35701. resNode = this._bottomNode.findNode(size);
  35702. }
  35703. }
  35704. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35705. resNode = this;
  35706. }
  35707. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35708. resNode = this;
  35709. }
  35710. return resNode;
  35711. };
  35712. PackedRect.prototype.splitNode = function (contentSize) {
  35713. // 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)
  35714. if (!this._contentSize && this._initialSize) {
  35715. 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));
  35716. return this._leftNode.splitNode(contentSize);
  35717. }
  35718. else {
  35719. this._contentSize = contentSize.clone();
  35720. this._initialSize = contentSize.clone();
  35721. if (contentSize.width !== this._size.width) {
  35722. 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));
  35723. }
  35724. if (contentSize.height !== this._size.height) {
  35725. 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));
  35726. }
  35727. return this;
  35728. }
  35729. };
  35730. PackedRect.prototype.attemptDefrag = function () {
  35731. if (!this.isUsed && this.isRecursiveFree) {
  35732. this.clearNode();
  35733. if (this._parent) {
  35734. this._parent.attemptDefrag();
  35735. }
  35736. }
  35737. };
  35738. PackedRect.prototype.clearNode = function () {
  35739. this._initialSize = null;
  35740. this._rightNode = null;
  35741. this._bottomNode = null;
  35742. };
  35743. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35744. get: function () {
  35745. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35746. },
  35747. enumerable: true,
  35748. configurable: true
  35749. });
  35750. PackedRect.prototype.evalFreeSize = function (size) {
  35751. var levelSize = 0;
  35752. if (!this.isUsed) {
  35753. if (this._initialSize) {
  35754. levelSize = this._initialSize.surface;
  35755. }
  35756. else {
  35757. levelSize = this._size.surface;
  35758. }
  35759. }
  35760. if (this._rightNode) {
  35761. levelSize += this._rightNode.evalFreeSize(0);
  35762. }
  35763. if (this._bottomNode) {
  35764. levelSize += this._bottomNode.evalFreeSize(0);
  35765. }
  35766. return levelSize + size;
  35767. };
  35768. return PackedRect;
  35769. }());
  35770. BABYLON.PackedRect = PackedRect;
  35771. /**
  35772. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35773. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35774. * 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.
  35775. */
  35776. var RectPackingMap = (function (_super) {
  35777. __extends(RectPackingMap, _super);
  35778. /**
  35779. * Create an instance of the object with a dimension using the given size
  35780. * @param size The dimension of the rectangle that will contain all the sub ones.
  35781. */
  35782. function RectPackingMap(size) {
  35783. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35784. this._root = this;
  35785. }
  35786. /**
  35787. * Add a rectangle, finding the best location to store it into the map
  35788. * @param size the dimension of the rectangle to store
  35789. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35790. */
  35791. RectPackingMap.prototype.addRect = function (size) {
  35792. var node = this.findAndSplitNode(size);
  35793. return node;
  35794. };
  35795. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35796. /**
  35797. * Return the current space free normalized between [0;1]
  35798. * @returns {}
  35799. */
  35800. get: function () {
  35801. var freeSize = 0;
  35802. freeSize = this.evalFreeSize(freeSize);
  35803. return freeSize / (this._size.width * this._size.height);
  35804. },
  35805. enumerable: true,
  35806. configurable: true
  35807. });
  35808. return RectPackingMap;
  35809. }(PackedRect));
  35810. BABYLON.RectPackingMap = RectPackingMap;
  35811. })(BABYLON || (BABYLON = {}));
  35812. var BABYLON;
  35813. (function (BABYLON) {
  35814. var DynamicFloatArrayElementInfo = (function () {
  35815. function DynamicFloatArrayElementInfo() {
  35816. }
  35817. return DynamicFloatArrayElementInfo;
  35818. }());
  35819. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35820. /**
  35821. * 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.
  35822. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35823. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35824. * 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.
  35825. * 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.
  35826. * 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".
  35827. */
  35828. var DynamicFloatArray = (function () {
  35829. /**
  35830. * Construct an instance of the dynamic float array
  35831. * @param stride size of one element in float (i.e. not bytes!)
  35832. * @param initialElementCount the number of available entries at construction
  35833. */
  35834. function DynamicFloatArray(stride, initialElementCount) {
  35835. this.compareValueOffset = null;
  35836. this.sortingAscending = true;
  35837. this._stride = stride;
  35838. this.buffer = new Float32Array(stride * initialElementCount);
  35839. this._lastUsed = 0;
  35840. this._firstFree = 0;
  35841. this._allEntries = new Array(initialElementCount);
  35842. this._freeEntries = new Array(initialElementCount);
  35843. for (var i = 0; i < initialElementCount; i++) {
  35844. var element = new DynamicFloatArrayElementInfo();
  35845. element.offset = i * stride;
  35846. this._allEntries[i] = element;
  35847. this._freeEntries[initialElementCount - i - 1] = element;
  35848. }
  35849. }
  35850. /**
  35851. * Allocate an element in the array.
  35852. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35853. * Beware, this offset may change when you call pack()
  35854. */
  35855. DynamicFloatArray.prototype.allocElement = function () {
  35856. if (this._freeEntries.length === 0) {
  35857. this._growBuffer();
  35858. }
  35859. var el = this._freeEntries.pop();
  35860. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35861. if (el.offset === this._firstFree) {
  35862. if (this._freeEntries.length > 0) {
  35863. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35864. }
  35865. else {
  35866. this._firstFree += this._stride;
  35867. }
  35868. }
  35869. return el;
  35870. };
  35871. /**
  35872. * Free the element corresponding to the given element info
  35873. * @param elInfo the element that describe the allocated element
  35874. */
  35875. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35876. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35877. this._freeEntries.push(elInfo);
  35878. };
  35879. /**
  35880. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35881. * 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().
  35882. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35883. */
  35884. DynamicFloatArray.prototype.pack = function () {
  35885. // no free slot? no need to pack
  35886. if (this._freeEntries.length === 0) {
  35887. return this.buffer;
  35888. }
  35889. // If the buffer is already packed the last used will always be lower than the first free
  35890. // 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.
  35891. if (this._lastUsed < this._firstFree) {
  35892. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35893. return elementsBuffer_1;
  35894. }
  35895. var s = this._stride;
  35896. // 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
  35897. var lastFree = new DynamicFloatArrayElementInfo();
  35898. lastFree.offset = this.totalElementCount * s;
  35899. this._freeEntries.push(lastFree);
  35900. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35901. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35902. var firstFreeSlotOffset = sortedFree[0].offset;
  35903. var freeZoneSize = 1;
  35904. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35905. var prevOffset = sortedFree[0].offset;
  35906. for (var i = 1; i < sortedFree.length; i++) {
  35907. // 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
  35908. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35909. break;
  35910. }
  35911. var curFree = sortedFree[i];
  35912. var curOffset = curFree.offset;
  35913. // Compute the distance between this offset and the previous
  35914. var distance = curOffset - prevOffset;
  35915. // If the distance is the stride size, they are adjacent, it good, move to the next
  35916. if (distance === s) {
  35917. // Free zone is one element bigger
  35918. ++freeZoneSize;
  35919. // as we're about to iterate to the next, the cur becomes the previous...
  35920. prevOffset = curOffset;
  35921. continue;
  35922. }
  35923. // Distance is bigger, which means there's x element between the previous free and this one
  35924. var usedRange = (distance / s) - 1;
  35925. // Two cases the free zone is smaller than the data to move or bigger
  35926. // Copy what can fit in the free zone
  35927. var curMoveOffset = curOffset - s;
  35928. var copyCount = Math.min(freeZoneSize, usedRange);
  35929. for (var j = 0; j < copyCount; j++) {
  35930. var freeI = firstFreeSlotOffset / s;
  35931. var curI = curMoveOffset / s;
  35932. var moveEl = sortedAll[curI];
  35933. this._moveElement(moveEl, firstFreeSlotOffset);
  35934. var replacedEl = sortedAll[freeI];
  35935. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35936. replacedEl.offset = curMoveOffset;
  35937. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35938. sortedAll[freeI] = moveEl;
  35939. sortedAll[curI] = replacedEl;
  35940. curMoveOffset -= s;
  35941. firstFreeSlotOffset += s;
  35942. }
  35943. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35944. if (freeZoneSize <= usedRange) {
  35945. firstFreeSlotOffset = curMoveOffset + s;
  35946. freeZoneSize = 1 + copyCount;
  35947. }
  35948. else {
  35949. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35950. }
  35951. // as we're about to iterate to the next, the cur becomes the previous...
  35952. prevOffset = curOffset;
  35953. }
  35954. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35955. this._lastUsed = firstFreeSlotOffset - s;
  35956. this._firstFree = firstFreeSlotOffset;
  35957. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35958. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35959. this._allEntries = sortedAll;
  35960. return elementsBuffer;
  35961. };
  35962. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35963. for (var i = 0; i < this._stride; i++) {
  35964. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35965. }
  35966. element.offset = destOffset;
  35967. };
  35968. DynamicFloatArray.prototype._growBuffer = function () {
  35969. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35970. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35971. var newBuffer = new Float32Array(newElCount * this._stride);
  35972. newBuffer.set(this.buffer);
  35973. var curCount = this.totalElementCount;
  35974. var addedCount = newElCount - this.totalElementCount;
  35975. for (var i = 0; i < addedCount; i++) {
  35976. var element = new DynamicFloatArrayElementInfo();
  35977. element.offset = (curCount + i) * this.stride;
  35978. this._allEntries.push(element);
  35979. this._freeEntries[addedCount - i - 1] = element;
  35980. }
  35981. this._firstFree = curCount * this.stride;
  35982. this.buffer = newBuffer;
  35983. };
  35984. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35985. /**
  35986. * Get the total count of entries that can fit in the current buffer
  35987. * @returns the elements count
  35988. */
  35989. get: function () {
  35990. return this._allEntries.length;
  35991. },
  35992. enumerable: true,
  35993. configurable: true
  35994. });
  35995. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35996. /**
  35997. * Get the count of free entries that can still be allocated without resizing the buffer
  35998. * @returns the free elements count
  35999. */
  36000. get: function () {
  36001. return this._freeEntries.length;
  36002. },
  36003. enumerable: true,
  36004. configurable: true
  36005. });
  36006. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36007. /**
  36008. * Get the count of allocated elements
  36009. * @returns the allocated elements count
  36010. */
  36011. get: function () {
  36012. return this._allEntries.length - this._freeEntries.length;
  36013. },
  36014. enumerable: true,
  36015. configurable: true
  36016. });
  36017. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36018. /**
  36019. * Return the size of one element in float
  36020. * @returns the size in float
  36021. */
  36022. get: function () {
  36023. return this._stride;
  36024. },
  36025. enumerable: true,
  36026. configurable: true
  36027. });
  36028. DynamicFloatArray.prototype.sort = function () {
  36029. var _this = this;
  36030. if (!this.compareValueOffset) {
  36031. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36032. }
  36033. var count = this.usedElementCount;
  36034. // Do we have to (re)create the sort table?
  36035. if (!this._sortTable || this._sortTable.length < count) {
  36036. // 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...
  36037. var newCount = Math.min(this.totalElementCount, count * 2);
  36038. this._sortTable = new Array(newCount);
  36039. }
  36040. if (!this._sortTable || this._sortTable.length !== count) {
  36041. this._sortedTable = new Array(count);
  36042. }
  36043. // Because, you know...
  36044. this.pack();
  36045. //let stride = this.stride;
  36046. //for (let i = 0; i < count; i++) {
  36047. // let si = this._sortTable[i];
  36048. // if (!si) {
  36049. // si = new SortInfo();
  36050. // this._sortTable[i] = si;
  36051. // }
  36052. // si.entry = this._allEntries[i];
  36053. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36054. // si.swapedOffset = null;
  36055. // this._sortedTable[i] = si;
  36056. //}
  36057. var curOffset = 0;
  36058. var stride = this.stride;
  36059. for (var i = 0; i < count; i++, curOffset += stride) {
  36060. var si = this._sortTable[i];
  36061. if (!si) {
  36062. si = new SortInfo();
  36063. this._sortTable[i] = si;
  36064. }
  36065. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36066. si.offset = curOffset;
  36067. si.swapedOffset = null;
  36068. this._sortedTable[i] = si;
  36069. }
  36070. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36071. if (this.sortingAscending) {
  36072. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36073. }
  36074. else {
  36075. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36076. }
  36077. var swapElements = function (src, dst) {
  36078. for (var i = 0; i < stride; i++) {
  36079. var tps = _this.buffer[dst + i];
  36080. _this.buffer[dst + i] = _this.buffer[src + i];
  36081. _this.buffer[src + i] = tps;
  36082. }
  36083. };
  36084. // 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:
  36085. // 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),
  36086. // and I still want something with a good algorithm complexity.
  36087. // 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,
  36088. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36089. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36090. // 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
  36091. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36092. // 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
  36093. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36094. for (var i = 0; i < count; i++) {
  36095. // Get the element to move
  36096. var sourceSI = this._sortedTable[i];
  36097. var destSI = this._sortTable[i];
  36098. var sourceOff = sourceSI.offset;
  36099. // If the source changed location, find the new one
  36100. if (sourceSI.swapedOffset) {
  36101. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36102. var curSI = sourceSI;
  36103. while (curSI.swapedOffset) {
  36104. curSI = this._sortTable[curSI.swapedOffset / stride];
  36105. }
  36106. // Finally get the right location
  36107. sourceOff = curSI.offset;
  36108. }
  36109. // Tag the element being replaced with its new location
  36110. destSI.swapedOffset = sourceOff;
  36111. // Swap elements (only if needed)
  36112. if (sourceOff !== destSI.offset) {
  36113. swapElements(sourceOff, destSI.offset);
  36114. }
  36115. // Update the offset in the corresponding DFAE
  36116. //sourceSI.entry.offset = destSI.entry.offset;
  36117. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36118. }
  36119. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36120. return true;
  36121. };
  36122. return DynamicFloatArray;
  36123. }());
  36124. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36125. var SortInfo = (function () {
  36126. function SortInfo() {
  36127. this.compareData = this.offset = this.swapedOffset = null;
  36128. }
  36129. return SortInfo;
  36130. }());
  36131. })(BABYLON || (BABYLON = {}));
  36132. var BABYLON;
  36133. (function (BABYLON) {
  36134. /**
  36135. * This class given information about a given character.
  36136. */
  36137. var CharInfo = (function () {
  36138. function CharInfo() {
  36139. }
  36140. return CharInfo;
  36141. }());
  36142. BABYLON.CharInfo = CharInfo;
  36143. var FontTexture = (function (_super) {
  36144. __extends(FontTexture, _super);
  36145. /**
  36146. * Create a new instance of the FontTexture class
  36147. * @param name the name of the texture
  36148. * @param font the font to use, use the W3C CSS notation
  36149. * @param scene the scene that owns the texture
  36150. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  36151. * @param samplingMode the texture sampling mode
  36152. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  36153. */
  36154. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  36155. if (maxCharCount === void 0) { maxCharCount = 200; }
  36156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36157. if (superSample === void 0) { superSample = false; }
  36158. _super.call(this, null, scene, true, false, samplingMode);
  36159. this._charInfos = {};
  36160. this._curCharCount = 0;
  36161. this._lastUpdateCharCount = -1;
  36162. this._usedCounter = 1;
  36163. this.name = name;
  36164. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36165. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36166. this._superSample = false;
  36167. if (superSample) {
  36168. var sfont = this.getSuperSampleFont(font);
  36169. if (sfont) {
  36170. this._superSample = true;
  36171. font = sfont;
  36172. }
  36173. }
  36174. // First canvas creation to determine the size of the texture to create
  36175. this._canvas = document.createElement("canvas");
  36176. this._context = this._canvas.getContext("2d");
  36177. this._context.font = font;
  36178. this._context.fillStyle = "white";
  36179. var res = this.getFontHeight(font);
  36180. this._lineHeightSuper = res.height;
  36181. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  36182. this._offset = res.offset - 1;
  36183. var maxCharWidth = this._context.measureText("W").width;
  36184. this._spaceWidthSuper = this._context.measureText(" ").width;
  36185. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  36186. // This is an approximate size, but should always be able to fit at least the maxCharCount
  36187. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  36188. var edge = Math.sqrt(totalEstSurface);
  36189. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  36190. // Create the texture that will store the font characters
  36191. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  36192. var textureSize = this.getSize();
  36193. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  36194. this._canvas = document.createElement("canvas");
  36195. this._canvas.width = textureSize.width;
  36196. this._canvas.height = textureSize.height;
  36197. this._context = this._canvas.getContext("2d");
  36198. this._context.textBaseline = "top";
  36199. this._context.font = font;
  36200. this._context.fillStyle = "white";
  36201. this._context.imageSmoothingEnabled = false;
  36202. this._currentFreePosition = BABYLON.Vector2.Zero();
  36203. // Add the basic ASCII based characters
  36204. for (var i = 0x20; i < 0x7F; i++) {
  36205. var c = String.fromCharCode(i);
  36206. this.getChar(c);
  36207. }
  36208. this.update();
  36209. }
  36210. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  36211. get: function () {
  36212. return this._superSample;
  36213. },
  36214. enumerable: true,
  36215. configurable: true
  36216. });
  36217. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  36218. get: function () {
  36219. return this._spaceWidth;
  36220. },
  36221. enumerable: true,
  36222. configurable: true
  36223. });
  36224. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36225. get: function () {
  36226. return this._lineHeight;
  36227. },
  36228. enumerable: true,
  36229. configurable: true
  36230. });
  36231. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36232. if (supersample === void 0) { supersample = false; }
  36233. var s = scene;
  36234. if (!s.__fontTextureCache__) {
  36235. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36236. }
  36237. var dic = s.__fontTextureCache__;
  36238. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36239. var ft = dic.get(lfn);
  36240. if (ft) {
  36241. ++ft._usedCounter;
  36242. return ft;
  36243. }
  36244. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36245. dic.add(lfn, ft);
  36246. return ft;
  36247. };
  36248. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36249. if (supersample === void 0) { supersample = false; }
  36250. var s = scene;
  36251. var dic = s.__fontTextureCache__;
  36252. if (!dic) {
  36253. return;
  36254. }
  36255. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36256. var font = dic.get(lfn);
  36257. if (--font._usedCounter === 0) {
  36258. dic.remove(lfn);
  36259. font.dispose();
  36260. }
  36261. };
  36262. /**
  36263. * Make sure the given char is present in the font map.
  36264. * @param char the character to get or add
  36265. * @return the CharInfo instance corresponding to the given character
  36266. */
  36267. FontTexture.prototype.getChar = function (char) {
  36268. if (char.length !== 1) {
  36269. return null;
  36270. }
  36271. var info = this._charInfos[char];
  36272. if (info) {
  36273. return info;
  36274. }
  36275. info = new CharInfo();
  36276. var measure = this._context.measureText(char);
  36277. var textureSize = this.getSize();
  36278. // we reached the end of the current line?
  36279. var width = Math.round(measure.width);
  36280. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  36281. var yMargin = xMargin;
  36282. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  36283. this._currentFreePosition.x = 0;
  36284. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  36285. // No more room?
  36286. if (this._currentFreePosition.y > textureSize.height) {
  36287. return this.getChar("!");
  36288. }
  36289. }
  36290. // Draw the character in the texture
  36291. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  36292. // Fill the CharInfo object
  36293. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  36294. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  36295. info.charWidth = this._superSample ? (width / 2) : width;
  36296. // Add the info structure
  36297. this._charInfos[char] = info;
  36298. this._curCharCount++;
  36299. // Set the next position
  36300. this._currentFreePosition.x += width + xMargin;
  36301. return info;
  36302. };
  36303. FontTexture.prototype.measureText = function (text, tabulationSize) {
  36304. if (tabulationSize === void 0) { tabulationSize = 4; }
  36305. var maxWidth = 0;
  36306. var curWidth = 0;
  36307. var lineCount = 1;
  36308. var charxpos = 0;
  36309. // Parse each char of the string
  36310. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  36311. var char = text_1[_i];
  36312. // Next line feed?
  36313. if (char === "\n") {
  36314. maxWidth = Math.max(maxWidth, curWidth);
  36315. charxpos = 0;
  36316. curWidth = 0;
  36317. ++lineCount;
  36318. continue;
  36319. }
  36320. // Tabulation ?
  36321. if (char === "\t") {
  36322. var nextPos = charxpos + tabulationSize;
  36323. nextPos = nextPos - (nextPos % tabulationSize);
  36324. curWidth += (nextPos - charxpos) * this.spaceWidth;
  36325. charxpos = nextPos;
  36326. continue;
  36327. }
  36328. if (char < " ") {
  36329. continue;
  36330. }
  36331. curWidth += this.getChar(char).charWidth;
  36332. ++charxpos;
  36333. }
  36334. maxWidth = Math.max(maxWidth, curWidth);
  36335. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  36336. };
  36337. FontTexture.prototype.getSuperSampleFont = function (font) {
  36338. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  36339. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  36340. var res = font.toLocaleLowerCase().match(regex);
  36341. if (res == null) {
  36342. return null;
  36343. }
  36344. var size = parseInt(res[4]);
  36345. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  36346. var newFont = "";
  36347. for (var j = 1; j < res.length; j++) {
  36348. if (res[j] != null) {
  36349. newFont += res[j] + " ";
  36350. }
  36351. }
  36352. return newFont;
  36353. };
  36354. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  36355. FontTexture.prototype.getFontHeight = function (font) {
  36356. var fontDraw = document.createElement("canvas");
  36357. var ctx = fontDraw.getContext('2d');
  36358. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  36359. ctx.textBaseline = 'top';
  36360. ctx.fillStyle = 'white';
  36361. ctx.font = font;
  36362. ctx.fillText('jH|', 0, 0);
  36363. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  36364. var start = -1;
  36365. var end = -1;
  36366. for (var row = 0; row < fontDraw.height; row++) {
  36367. for (var column = 0; column < fontDraw.width; column++) {
  36368. var index = (row * fontDraw.width + column) * 4;
  36369. if (pixels[index] === 0) {
  36370. if (column === fontDraw.width - 1 && start !== -1) {
  36371. end = row;
  36372. row = fontDraw.height;
  36373. break;
  36374. }
  36375. continue;
  36376. }
  36377. else {
  36378. if (start === -1) {
  36379. start = row;
  36380. }
  36381. break;
  36382. }
  36383. }
  36384. }
  36385. return { height: (end - start) + 1, offset: start - 1 };
  36386. };
  36387. Object.defineProperty(FontTexture.prototype, "canRescale", {
  36388. get: function () {
  36389. return false;
  36390. },
  36391. enumerable: true,
  36392. configurable: true
  36393. });
  36394. FontTexture.prototype.getContext = function () {
  36395. return this._context;
  36396. };
  36397. /**
  36398. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  36399. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  36400. */
  36401. FontTexture.prototype.update = function () {
  36402. // Update only if there's new char added since the previous update
  36403. if (this._lastUpdateCharCount < this._curCharCount) {
  36404. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  36405. this._lastUpdateCharCount = this._curCharCount;
  36406. }
  36407. };
  36408. // cloning should be prohibited, there's no point to duplicate this texture at all
  36409. FontTexture.prototype.clone = function () {
  36410. return null;
  36411. };
  36412. return FontTexture;
  36413. }(BABYLON.Texture));
  36414. BABYLON.FontTexture = FontTexture;
  36415. })(BABYLON || (BABYLON = {}));
  36416. var BABYLON;
  36417. (function (BABYLON) {
  36418. var MapTexture = (function (_super) {
  36419. __extends(MapTexture, _super);
  36420. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  36421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36422. if (useMipMap === void 0) { useMipMap = false; }
  36423. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  36424. this.name = name;
  36425. this._size = size;
  36426. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36427. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36428. // Create the rectPackMap that will allocate portion of the texture
  36429. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  36430. // Create the texture that will store the content
  36431. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  36432. }
  36433. /**
  36434. * Allocate a rectangle of a given size in the texture map
  36435. * @param size the size of the rectangle to allocation
  36436. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  36437. */
  36438. MapTexture.prototype.allocateRect = function (size) {
  36439. return this._rectPackingMap.addRect(size);
  36440. };
  36441. /**
  36442. * Free a given rectangle from the texture map
  36443. * @param rectInfo the instance corresponding to the rect to free.
  36444. */
  36445. MapTexture.prototype.freeRect = function (rectInfo) {
  36446. if (rectInfo) {
  36447. rectInfo.freeContent();
  36448. }
  36449. };
  36450. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  36451. /**
  36452. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  36453. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  36454. * @returns {}
  36455. */
  36456. get: function () {
  36457. return this._rectPackingMap.freeSpace;
  36458. },
  36459. enumerable: true,
  36460. configurable: true
  36461. });
  36462. /**
  36463. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  36464. * 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.
  36465. * Don't forget to call unbindTexture when you're done rendering
  36466. * @param rect the zone to render to
  36467. * @param clear true to clear the portion's color/depth data
  36468. */
  36469. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  36470. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  36471. };
  36472. /**
  36473. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  36474. * 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.
  36475. * Don't forget to call unbindTexture when you're done rendering
  36476. * @param pos the position into the texture
  36477. * @param size the portion to fit the clip space to
  36478. * @param clear true to clear the portion's color/depth data
  36479. */
  36480. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  36481. var engine = this.getScene().getEngine();
  36482. engine.bindFramebuffer(this._texture);
  36483. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  36484. if (clear) {
  36485. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  36486. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  36487. }
  36488. };
  36489. /**
  36490. * Unbind the texture map from the rendering engine.
  36491. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  36492. * @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.
  36493. */
  36494. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  36495. // Dump ?
  36496. if (dumpForDebug) {
  36497. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  36498. }
  36499. var engine = this.getScene().getEngine();
  36500. if (this._replacedViewport) {
  36501. engine.setViewport(this._replacedViewport);
  36502. this._replacedViewport = null;
  36503. }
  36504. engine.unBindFramebuffer(this._texture);
  36505. };
  36506. Object.defineProperty(MapTexture.prototype, "canRescale", {
  36507. get: function () {
  36508. return false;
  36509. },
  36510. enumerable: true,
  36511. configurable: true
  36512. });
  36513. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  36514. // Anyway, there's not much point to use this method for this kind of texture I guess
  36515. MapTexture.prototype.clone = function () {
  36516. return null;
  36517. };
  36518. return MapTexture;
  36519. }(BABYLON.Texture));
  36520. BABYLON.MapTexture = MapTexture;
  36521. })(BABYLON || (BABYLON = {}));
  36522. var BABYLON;
  36523. (function (BABYLON) {
  36524. /**
  36525. * Stores 2D Bounding Information.
  36526. * This class handles a circle area and a bounding rectangle one.
  36527. */
  36528. var BoundingInfo2D = (function () {
  36529. function BoundingInfo2D() {
  36530. this.radius = 0;
  36531. this.center = BABYLON.Vector2.Zero();
  36532. this.extent = BABYLON.Vector2.Zero();
  36533. }
  36534. /**
  36535. * Create a BoundingInfo2D object from a given size
  36536. * @param size the size that will be used to set the extend, radius will be computed from it.
  36537. */
  36538. BoundingInfo2D.CreateFromSize = function (size) {
  36539. var r = new BoundingInfo2D();
  36540. BoundingInfo2D.CreateFromSizeToRef(size, r);
  36541. return r;
  36542. };
  36543. /**
  36544. * Create a BoundingInfo2D object from a given radius
  36545. * @param radius the radius to use, the extent will be computed from it.
  36546. */
  36547. BoundingInfo2D.CreateFromRadius = function (radius) {
  36548. var r = new BoundingInfo2D();
  36549. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  36550. return r;
  36551. };
  36552. /**
  36553. * Create a BoundingInfo2D object from a list of points.
  36554. * The resulted object will be the smallest bounding area that includes all the given points.
  36555. * @param points an array of points to compute the bounding object from.
  36556. */
  36557. BoundingInfo2D.CreateFromPoints = function (points) {
  36558. var r = new BoundingInfo2D();
  36559. BoundingInfo2D.CreateFromPointsToRef(points, r);
  36560. return r;
  36561. };
  36562. /**
  36563. * Update a BoundingInfo2D object using the given Size as input
  36564. * @param size the bounding data will be computed from this size.
  36565. * @param b must be a valid/allocated object, it will contain the result of the operation
  36566. */
  36567. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  36568. if (!size) {
  36569. size = BABYLON.Size.Zero();
  36570. }
  36571. b.center.x = +size.width / 2;
  36572. b.center.y = +size.height / 2;
  36573. b.extent.x = b.center.x;
  36574. b.extent.y = b.center.y;
  36575. b.radius = b.extent.length();
  36576. };
  36577. /**
  36578. * Update a BoundingInfo2D object using the given radius as input
  36579. * @param radius the bounding data will be computed from this radius
  36580. * @param b must be a valid/allocated object, it will contain the result of the operation
  36581. */
  36582. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  36583. b.center.x = b.center.y = 0;
  36584. var r = +radius;
  36585. b.extent.x = r;
  36586. b.extent.y = r;
  36587. b.radius = r;
  36588. };
  36589. /**
  36590. * Update a BoundingInfo2D object using the given points array as input
  36591. * @param points the point array to use to update the bounding data
  36592. * @param b must be a valid/allocated object, it will contain the result of the operation
  36593. */
  36594. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  36595. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  36596. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  36597. var p = points_1[_i];
  36598. xmin = Math.min(p.x, xmin);
  36599. xmax = Math.max(p.x, xmax);
  36600. ymin = Math.min(p.y, ymin);
  36601. ymax = Math.max(p.y, ymax);
  36602. }
  36603. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  36604. };
  36605. /**
  36606. * Update a BoundingInfo2D object using the given min/max values as input
  36607. * @param xmin the smallest x coordinate
  36608. * @param xmax the biggest x coordinate
  36609. * @param ymin the smallest y coordinate
  36610. * @param ymax the buggest y coordinate
  36611. * @param b must be a valid/allocated object, it will contain the result of the operation
  36612. */
  36613. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  36614. var w = xmax - xmin;
  36615. var h = ymax - ymin;
  36616. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  36617. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  36618. b.radius = b.extent.length();
  36619. };
  36620. /**
  36621. * Duplicate this instance and return a new one
  36622. * @return the duplicated instance
  36623. */
  36624. BoundingInfo2D.prototype.clone = function () {
  36625. var r = new BoundingInfo2D();
  36626. r.center = this.center.clone();
  36627. r.radius = this.radius;
  36628. r.extent = this.extent.clone();
  36629. return r;
  36630. };
  36631. BoundingInfo2D.prototype.clear = function () {
  36632. this.center.copyFromFloats(0, 0);
  36633. this.radius = 0;
  36634. this.extent.copyFromFloats(0, 0);
  36635. };
  36636. BoundingInfo2D.prototype.copyFrom = function (src) {
  36637. this.center.copyFrom(src.center);
  36638. this.radius = src.radius;
  36639. this.extent.copyFrom(src.extent);
  36640. };
  36641. /**
  36642. * return the max extend of the bounding info
  36643. */
  36644. BoundingInfo2D.prototype.max = function () {
  36645. var r = BABYLON.Vector2.Zero();
  36646. this.maxToRef(r);
  36647. return r;
  36648. };
  36649. /**
  36650. * Update a vector2 with the max extend of the bounding info
  36651. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  36652. */
  36653. BoundingInfo2D.prototype.maxToRef = function (result) {
  36654. result.x = this.center.x + this.extent.x;
  36655. result.y = this.center.y + this.extent.y;
  36656. };
  36657. /**
  36658. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  36659. * @param matrix the transformation matrix to apply
  36660. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  36661. */
  36662. BoundingInfo2D.prototype.transform = function (matrix) {
  36663. var r = new BoundingInfo2D();
  36664. this.transformToRef(matrix, r);
  36665. return r;
  36666. };
  36667. /**
  36668. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  36669. * @param other the second BoundingInfo2D to compute the union with this one
  36670. * @return a new instance containing the result of the union
  36671. */
  36672. BoundingInfo2D.prototype.union = function (other) {
  36673. var r = new BoundingInfo2D();
  36674. this.unionToRef(other, r);
  36675. return r;
  36676. };
  36677. /**
  36678. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  36679. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  36680. * @param matrix The matrix to use to compute the transformation
  36681. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  36682. */
  36683. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  36684. // Construct a bounding box based on the extent values
  36685. var p = BoundingInfo2D._transform;
  36686. p[0].x = this.center.x + this.extent.x;
  36687. p[0].y = this.center.y + this.extent.y;
  36688. p[1].x = this.center.x + this.extent.x;
  36689. p[1].y = this.center.y - this.extent.y;
  36690. p[2].x = this.center.x - this.extent.x;
  36691. p[2].y = this.center.y - this.extent.y;
  36692. p[3].x = this.center.x - this.extent.x;
  36693. p[3].y = this.center.y + this.extent.y;
  36694. // Transform the four points of the bounding box with the matrix
  36695. for (var i = 0; i < 4; i++) {
  36696. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  36697. }
  36698. BoundingInfo2D.CreateFromPointsToRef(p, result);
  36699. };
  36700. /**
  36701. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  36702. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  36703. * @param other the second object used to compute the union
  36704. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  36705. */
  36706. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  36707. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  36708. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  36709. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  36710. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  36711. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  36712. };
  36713. /**
  36714. * Check if the given point is inside the BoundingInfo.
  36715. * The test is first made on the radius, then inside the rectangle described by the extent
  36716. * @param pickPosition the position to test
  36717. * @return true if the point is inside, false otherwise
  36718. */
  36719. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  36720. // is it inside the radius?
  36721. var pickLocal = pickPosition.subtract(this.center);
  36722. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  36723. // is it inside the rectangle?
  36724. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  36725. }
  36726. return false;
  36727. };
  36728. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  36729. return BoundingInfo2D;
  36730. }());
  36731. BABYLON.BoundingInfo2D = BoundingInfo2D;
  36732. })(BABYLON || (BABYLON = {}));
  36733. var BABYLON;
  36734. (function (BABYLON) {
  36735. var LayoutEngineBase = (function () {
  36736. function LayoutEngineBase() {
  36737. this.layoutDirtyOnPropertyChangedMask = 0;
  36738. }
  36739. LayoutEngineBase.prototype.updateLayout = function (prim) {
  36740. };
  36741. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  36742. get: function () {
  36743. return false;
  36744. },
  36745. enumerable: true,
  36746. configurable: true
  36747. });
  36748. LayoutEngineBase.prototype.isLocked = function () {
  36749. return this._isLocked;
  36750. };
  36751. LayoutEngineBase.prototype.lock = function () {
  36752. if (this._isLocked) {
  36753. return false;
  36754. }
  36755. this._isLocked = true;
  36756. return true;
  36757. };
  36758. LayoutEngineBase = __decorate([
  36759. BABYLON.className("LayoutEngineBase")
  36760. ], LayoutEngineBase);
  36761. return LayoutEngineBase;
  36762. }());
  36763. BABYLON.LayoutEngineBase = LayoutEngineBase;
  36764. var CanvasLayoutEngine = (function (_super) {
  36765. __extends(CanvasLayoutEngine, _super);
  36766. function CanvasLayoutEngine() {
  36767. _super.apply(this, arguments);
  36768. }
  36769. // A very simple (no) layout computing...
  36770. // The Canvas and its direct children gets the Canvas' size as Layout Area
  36771. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  36772. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  36773. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  36774. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  36775. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  36776. var child = _a[_i];
  36777. this._doUpdate(child);
  36778. }
  36779. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  36780. }
  36781. };
  36782. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  36783. // Canvas ?
  36784. if (prim instanceof BABYLON.Canvas2D) {
  36785. prim.layoutArea = prim.actualSize;
  36786. }
  36787. else if (prim.parent instanceof BABYLON.Canvas2D) {
  36788. prim.layoutArea = prim.owner.actualSize;
  36789. }
  36790. else {
  36791. prim.layoutArea = prim.parent.contentArea;
  36792. }
  36793. };
  36794. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  36795. get: function () {
  36796. return true;
  36797. },
  36798. enumerable: true,
  36799. configurable: true
  36800. });
  36801. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  36802. CanvasLayoutEngine = __decorate([
  36803. BABYLON.className("CanvasLayoutEngine")
  36804. ], CanvasLayoutEngine);
  36805. return CanvasLayoutEngine;
  36806. }(LayoutEngineBase));
  36807. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  36808. var StackPanelLayoutEngine = (function (_super) {
  36809. __extends(StackPanelLayoutEngine, _super);
  36810. function StackPanelLayoutEngine() {
  36811. _super.call(this);
  36812. this._isHorizontal = true;
  36813. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  36814. }
  36815. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  36816. get: function () {
  36817. if (!StackPanelLayoutEngine._horizontal) {
  36818. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  36819. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  36820. StackPanelLayoutEngine._horizontal.lock();
  36821. }
  36822. return StackPanelLayoutEngine._horizontal;
  36823. },
  36824. enumerable: true,
  36825. configurable: true
  36826. });
  36827. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  36828. get: function () {
  36829. if (!StackPanelLayoutEngine._vertical) {
  36830. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  36831. StackPanelLayoutEngine._vertical.isHorizontal = false;
  36832. StackPanelLayoutEngine._vertical.lock();
  36833. }
  36834. return StackPanelLayoutEngine._vertical;
  36835. },
  36836. enumerable: true,
  36837. configurable: true
  36838. });
  36839. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  36840. get: function () {
  36841. return this._isHorizontal;
  36842. },
  36843. set: function (val) {
  36844. if (this.isLocked()) {
  36845. return;
  36846. }
  36847. this._isHorizontal = val;
  36848. },
  36849. enumerable: true,
  36850. configurable: true
  36851. });
  36852. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  36853. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  36854. var x = 0;
  36855. var y = 0;
  36856. var h = this.isHorizontal;
  36857. var max = 0;
  36858. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  36859. var child = _a[_i];
  36860. var layoutArea = child.layoutArea;
  36861. child.margin.computeArea(child.actualSize, layoutArea);
  36862. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  36863. }
  36864. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  36865. var child = _c[_b];
  36866. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  36867. var layoutArea = child.layoutArea;
  36868. if (h) {
  36869. x += layoutArea.width;
  36870. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  36871. }
  36872. else {
  36873. y += layoutArea.height;
  36874. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  36875. }
  36876. }
  36877. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  36878. }
  36879. };
  36880. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  36881. get: function () {
  36882. return false;
  36883. },
  36884. enumerable: true,
  36885. configurable: true
  36886. });
  36887. StackPanelLayoutEngine._horizontal = null;
  36888. StackPanelLayoutEngine._vertical = null;
  36889. StackPanelLayoutEngine = __decorate([
  36890. BABYLON.className("StackPanelLayoutEngine")
  36891. ], StackPanelLayoutEngine);
  36892. return StackPanelLayoutEngine;
  36893. }(LayoutEngineBase));
  36894. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  36895. })(BABYLON || (BABYLON = {}));
  36896. var BABYLON;
  36897. (function (BABYLON) {
  36898. /**
  36899. * Base class implementing the ILocable interface.
  36900. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36901. */
  36902. var LockableBase = (function () {
  36903. function LockableBase() {
  36904. }
  36905. LockableBase.prototype.isLocked = function () {
  36906. return this._isLocked;
  36907. };
  36908. LockableBase.prototype.lock = function () {
  36909. if (this._isLocked) {
  36910. return true;
  36911. }
  36912. this.onLock();
  36913. this._isLocked = true;
  36914. return false;
  36915. };
  36916. /**
  36917. * Protected handler that will be called when the instance is about to be locked.
  36918. */
  36919. LockableBase.prototype.onLock = function () {
  36920. };
  36921. return LockableBase;
  36922. }());
  36923. BABYLON.LockableBase = LockableBase;
  36924. var SolidColorBrush2D = (function (_super) {
  36925. __extends(SolidColorBrush2D, _super);
  36926. function SolidColorBrush2D(color, lock) {
  36927. if (lock === void 0) { lock = false; }
  36928. _super.call(this);
  36929. this._color = color;
  36930. if (lock) {
  36931. {
  36932. this.lock();
  36933. }
  36934. }
  36935. }
  36936. /**
  36937. * Return true if the brush is transparent, false if it's totally opaque
  36938. */
  36939. SolidColorBrush2D.prototype.isTransparent = function () {
  36940. return this._color && this._color.a < 1.0;
  36941. };
  36942. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36943. /**
  36944. * The color used by this instance to render
  36945. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  36946. */
  36947. get: function () {
  36948. return this._color;
  36949. },
  36950. set: function (value) {
  36951. if (this.isLocked()) {
  36952. return;
  36953. }
  36954. this._color = value;
  36955. },
  36956. enumerable: true,
  36957. configurable: true
  36958. });
  36959. /**
  36960. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36961. */
  36962. SolidColorBrush2D.prototype.toString = function () {
  36963. return this._color.toHexString();
  36964. };
  36965. SolidColorBrush2D = __decorate([
  36966. BABYLON.className("SolidColorBrush2D")
  36967. ], SolidColorBrush2D);
  36968. return SolidColorBrush2D;
  36969. }(LockableBase));
  36970. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36971. var GradientColorBrush2D = (function (_super) {
  36972. __extends(GradientColorBrush2D, _super);
  36973. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36974. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36975. if (rotation === void 0) { rotation = 0; }
  36976. if (scale === void 0) { scale = 1; }
  36977. if (lock === void 0) { lock = false; }
  36978. _super.call(this);
  36979. this._color1 = color1;
  36980. this._color2 = color2;
  36981. this._translation = translation;
  36982. this._rotation = rotation;
  36983. this._scale = scale;
  36984. if (lock) {
  36985. this.lock();
  36986. }
  36987. }
  36988. /**
  36989. * Return true if the brush is transparent, false if it's totally opaque
  36990. */
  36991. GradientColorBrush2D.prototype.isTransparent = function () {
  36992. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36993. };
  36994. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36995. /**
  36996. * First color, the blend will start from this color
  36997. */
  36998. get: function () {
  36999. return this._color1;
  37000. },
  37001. set: function (value) {
  37002. if (this.isLocked()) {
  37003. return;
  37004. }
  37005. this._color1 = value;
  37006. },
  37007. enumerable: true,
  37008. configurable: true
  37009. });
  37010. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  37011. /**
  37012. * Second color, the blend will end to this color
  37013. */
  37014. get: function () {
  37015. return this._color2;
  37016. },
  37017. set: function (value) {
  37018. if (this.isLocked()) {
  37019. return;
  37020. }
  37021. this._color2 = value;
  37022. },
  37023. enumerable: true,
  37024. configurable: true
  37025. });
  37026. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  37027. /**
  37028. * Translation vector to apply on the blend
  37029. * Default is [0;0]
  37030. */
  37031. get: function () {
  37032. return this._translation;
  37033. },
  37034. set: function (value) {
  37035. if (this.isLocked()) {
  37036. return;
  37037. }
  37038. this._translation = value;
  37039. },
  37040. enumerable: true,
  37041. configurable: true
  37042. });
  37043. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  37044. /**
  37045. * Rotation in radian to apply to the brush
  37046. * Default direction of the brush is vertical, you can change this using this property.
  37047. * Default is 0.
  37048. */
  37049. get: function () {
  37050. return this._rotation;
  37051. },
  37052. set: function (value) {
  37053. if (this.isLocked()) {
  37054. return;
  37055. }
  37056. this._rotation = value;
  37057. },
  37058. enumerable: true,
  37059. configurable: true
  37060. });
  37061. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  37062. /**
  37063. * Scale factor to apply to the gradient.
  37064. * Default is 1: no scale.
  37065. */
  37066. get: function () {
  37067. return this._scale;
  37068. },
  37069. set: function (value) {
  37070. if (this.isLocked()) {
  37071. return;
  37072. }
  37073. this._scale = value;
  37074. },
  37075. enumerable: true,
  37076. configurable: true
  37077. });
  37078. /**
  37079. * Return a string describing the brush
  37080. */
  37081. GradientColorBrush2D.prototype.toString = function () {
  37082. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  37083. };
  37084. /**
  37085. * Build a unique key string for the given parameters
  37086. */
  37087. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  37088. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  37089. };
  37090. GradientColorBrush2D = __decorate([
  37091. BABYLON.className("GradientColorBrush2D")
  37092. ], GradientColorBrush2D);
  37093. return GradientColorBrush2D;
  37094. }(LockableBase));
  37095. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  37096. })(BABYLON || (BABYLON = {}));
  37097. var BABYLON;
  37098. (function (BABYLON) {
  37099. var Prim2DClassInfo = (function () {
  37100. function Prim2DClassInfo() {
  37101. }
  37102. return Prim2DClassInfo;
  37103. }());
  37104. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  37105. var Prim2DPropInfo = (function () {
  37106. function Prim2DPropInfo() {
  37107. }
  37108. Prim2DPropInfo.PROPKIND_MODEL = 1;
  37109. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  37110. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  37111. return Prim2DPropInfo;
  37112. }());
  37113. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  37114. /**
  37115. * Custom type of the propertyChanged observable
  37116. */
  37117. var PropertyChangedInfo = (function () {
  37118. function PropertyChangedInfo() {
  37119. }
  37120. return PropertyChangedInfo;
  37121. }());
  37122. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  37123. var ClassTreeInfo = (function () {
  37124. function ClassTreeInfo(baseClass, type, classContentFactory) {
  37125. this._baseClass = baseClass;
  37126. this._type = type;
  37127. this._subClasses = new Array();
  37128. this._levelContent = new BABYLON.StringDictionary();
  37129. this._classContentFactory = classContentFactory;
  37130. }
  37131. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  37132. get: function () {
  37133. if (!this._classContent) {
  37134. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  37135. }
  37136. return this._classContent;
  37137. },
  37138. enumerable: true,
  37139. configurable: true
  37140. });
  37141. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  37142. get: function () {
  37143. return this._type;
  37144. },
  37145. enumerable: true,
  37146. configurable: true
  37147. });
  37148. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  37149. get: function () {
  37150. return this._levelContent;
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  37156. get: function () {
  37157. if (!this._fullContent) {
  37158. var dic_1 = new BABYLON.StringDictionary();
  37159. var curLevel = this;
  37160. while (curLevel) {
  37161. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  37162. curLevel = curLevel._baseClass;
  37163. }
  37164. this._fullContent = dic_1;
  37165. }
  37166. return this._fullContent;
  37167. },
  37168. enumerable: true,
  37169. configurable: true
  37170. });
  37171. ClassTreeInfo.prototype.getLevelOf = function (type) {
  37172. // Are we already there?
  37173. if (type === this._type) {
  37174. return this;
  37175. }
  37176. var baseProto = Object.getPrototypeOf(type);
  37177. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  37178. if (!curProtoContent) {
  37179. this.getLevelOf(baseProto);
  37180. }
  37181. return this.getOrAddType(baseProto, type);
  37182. };
  37183. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  37184. // Are we at the level corresponding to the baseType?
  37185. // If so, get or add the level we're looking for
  37186. if (baseType === this._type) {
  37187. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  37188. var subType = _a[_i];
  37189. if (subType.type === type) {
  37190. return subType.node;
  37191. }
  37192. }
  37193. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  37194. var info = { type: type, node: node };
  37195. this._subClasses.push(info);
  37196. return info.node;
  37197. }
  37198. // Recurse down to keep looking for the node corresponding to the baseTypeName
  37199. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  37200. var subType = _c[_b];
  37201. var info = subType.node.getOrAddType(baseType, type);
  37202. if (info) {
  37203. return info;
  37204. }
  37205. }
  37206. return null;
  37207. };
  37208. ClassTreeInfo.get = function (type) {
  37209. var dic = type["__classTreeInfo"];
  37210. if (!dic) {
  37211. return null;
  37212. }
  37213. return dic.getLevelOf(type);
  37214. };
  37215. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  37216. var dic = type["__classTreeInfo"];
  37217. if (!dic) {
  37218. dic = new ClassTreeInfo(null, type, classContentFactory);
  37219. type["__classTreeInfo"] = dic;
  37220. }
  37221. return dic;
  37222. };
  37223. return ClassTreeInfo;
  37224. }());
  37225. BABYLON.ClassTreeInfo = ClassTreeInfo;
  37226. var SmartPropertyPrim = (function () {
  37227. function SmartPropertyPrim() {
  37228. this._flags = 0;
  37229. this._modelKey = null;
  37230. this._instanceDirtyFlags = 0;
  37231. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  37232. this.animations = new Array();
  37233. }
  37234. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  37235. /**
  37236. * Check if the object is disposed or not.
  37237. * @returns true if the object is dispose, false otherwise.
  37238. */
  37239. get: function () {
  37240. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  37241. },
  37242. enumerable: true,
  37243. configurable: true
  37244. });
  37245. /**
  37246. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  37247. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  37248. */
  37249. SmartPropertyPrim.prototype.dispose = function () {
  37250. if (this.isDisposed) {
  37251. return false;
  37252. }
  37253. // Don't set to null, it may upset somebody...
  37254. this.animations.splice(0);
  37255. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  37256. return true;
  37257. };
  37258. /**
  37259. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  37260. * Look at Sprite2D for more information
  37261. */
  37262. SmartPropertyPrim.prototype.getAnimatables = function () {
  37263. return new Array();
  37264. };
  37265. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  37266. /**
  37267. * Property giving the Model Key associated to the property.
  37268. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  37269. * @returns the model key string.
  37270. */
  37271. get: function () {
  37272. var _this = this;
  37273. // No need to compute it?
  37274. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  37275. return this._modelKey;
  37276. }
  37277. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  37278. var propDic = this.propDic;
  37279. propDic.forEach(function (k, v) {
  37280. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  37281. var propVal = _this[v.name];
  37282. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  37283. if (propVal && propVal.constructor === Array) {
  37284. var firstVal = propVal[0];
  37285. if (!firstVal) {
  37286. propVal = 0;
  37287. }
  37288. else {
  37289. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  37290. }
  37291. }
  37292. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  37293. }
  37294. });
  37295. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  37296. this._modelKey = modelKey;
  37297. return modelKey;
  37298. },
  37299. enumerable: true,
  37300. configurable: true
  37301. });
  37302. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  37303. /**
  37304. * States if the Primitive is dirty and should be rendered again next time.
  37305. * @returns true is dirty, false otherwise
  37306. */
  37307. get: function () {
  37308. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  37314. /**
  37315. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  37316. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  37317. */
  37318. get: function () {
  37319. if (!this._propInfo) {
  37320. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  37321. if (!cti) {
  37322. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  37323. }
  37324. this._propInfo = cti.fullContent;
  37325. }
  37326. return this._propInfo;
  37327. },
  37328. enumerable: true,
  37329. configurable: true
  37330. });
  37331. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  37332. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  37333. var node = dic.getLevelOf(target);
  37334. var propInfo = node.levelContent.get(propId.toString());
  37335. if (propInfo) {
  37336. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  37337. }
  37338. // Create, setup and add the PropInfo object to our prop dictionary
  37339. propInfo = new Prim2DPropInfo();
  37340. propInfo.id = propId;
  37341. propInfo.flagId = Math.pow(2, propId);
  37342. propInfo.kind = kind;
  37343. propInfo.name = propName;
  37344. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  37345. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  37346. propInfo.typeLevelCompare = typeLevelCompare;
  37347. node.levelContent.add(propName, propInfo);
  37348. return propInfo;
  37349. };
  37350. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  37351. // Nothing to nothing: nothing to do!
  37352. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  37353. return true;
  37354. }
  37355. // Check value unchanged
  37356. if ((curValue != null) && (newValue != null)) {
  37357. if (typeof (curValue.equals) == "function") {
  37358. if (curValue.equals(newValue)) {
  37359. return true;
  37360. }
  37361. }
  37362. else {
  37363. if (curValue === newValue) {
  37364. return true;
  37365. }
  37366. }
  37367. }
  37368. return false;
  37369. };
  37370. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  37371. if (this.isDisposed) {
  37372. return;
  37373. }
  37374. var i = propertyName.indexOf(".");
  37375. if (i !== -1) {
  37376. propertyName = propertyName.substr(0, i);
  37377. }
  37378. var propInfo = this.propDic.get(propertyName);
  37379. if (!propInfo) {
  37380. return;
  37381. }
  37382. var newValue = this[propertyName];
  37383. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  37384. };
  37385. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  37386. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37387. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  37388. if (this instanceof BABYLON.Prim2DBase) {
  37389. var curprim = this;
  37390. while (curprim) {
  37391. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  37392. if (curprim.isSizeAuto) {
  37393. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  37394. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  37395. }
  37396. if (curprim instanceof BABYLON.Group2D) {
  37397. if (curprim.isRenderableGroup) {
  37398. break;
  37399. }
  37400. }
  37401. curprim = curprim.parent;
  37402. }
  37403. }
  37404. };
  37405. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37406. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37407. if (propInfo.dirtyBoundingInfo) {
  37408. this._boundingBoxDirty();
  37409. }
  37410. else if (propInfo.dirtyParentBoundingInfo) {
  37411. var p = this._parent;
  37412. if (p != null) {
  37413. p._boundingBoxDirty();
  37414. }
  37415. }
  37416. // Trigger property changed
  37417. var info = SmartPropertyPrim.propChangedInfo;
  37418. info.oldValue = curValue;
  37419. info.newValue = newValue;
  37420. info.propertyName = propName;
  37421. var propMask = propInfo.flagId;
  37422. this.propertyChanged.notifyObservers(info, propMask);
  37423. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37424. if (this instanceof BABYLON.Group2D) {
  37425. this.handleGroupChanged(propInfo);
  37426. }
  37427. // Check for parent layout dirty
  37428. if (this instanceof BABYLON.Prim2DBase) {
  37429. var p = this._parent;
  37430. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  37431. p._setLayoutDirty();
  37432. }
  37433. }
  37434. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  37435. var instanceDirty = false;
  37436. if (typeLevelCompare && curValue != null && newValue != null) {
  37437. var cvProto = curValue.__proto__;
  37438. var nvProto = newValue.__proto__;
  37439. instanceDirty = (cvProto === nvProto);
  37440. }
  37441. // Set the dirty flags
  37442. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  37443. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  37444. }
  37445. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  37446. this.onPrimitivePropertyDirty(propMask);
  37447. }
  37448. };
  37449. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  37450. if (!this.isDirty) {
  37451. this.onPrimBecomesDirty();
  37452. }
  37453. this._instanceDirtyFlags |= propFlagId;
  37454. };
  37455. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  37456. };
  37457. /**
  37458. * Check if a given set of properties are dirty or not.
  37459. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37460. * @return true if at least one property is dirty, false if none of them are.
  37461. */
  37462. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  37463. return (this._instanceDirtyFlags & flags) !== 0;
  37464. };
  37465. /**
  37466. * Clear a given set of properties.
  37467. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37468. * @return the new set of property still marked as dirty
  37469. */
  37470. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  37471. this._instanceDirtyFlags &= ~flags;
  37472. return this._instanceDirtyFlags;
  37473. };
  37474. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  37475. this._instanceDirtyFlags = 0;
  37476. };
  37477. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  37478. /**
  37479. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  37480. */
  37481. get: function () {
  37482. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  37483. this.updateLevelBoundingInfo();
  37484. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37485. }
  37486. return this._levelBoundingInfo;
  37487. },
  37488. enumerable: true,
  37489. configurable: true
  37490. });
  37491. /**
  37492. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  37493. */
  37494. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  37495. };
  37496. /**
  37497. * Property method called when the Primitive becomes dirty
  37498. */
  37499. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  37500. };
  37501. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  37502. return function (target, propName, descriptor) {
  37503. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  37504. if (piStore) {
  37505. piStore(propInfo);
  37506. }
  37507. var getter = descriptor.get, setter = descriptor.set;
  37508. // Overload the property setter implementation to add our own logic
  37509. descriptor.set = function (val) {
  37510. // check for disposed first, do nothing
  37511. if (this.isDisposed) {
  37512. return;
  37513. }
  37514. var curVal = getter.call(this);
  37515. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  37516. return;
  37517. }
  37518. // Cast the object we're working one
  37519. var prim = this;
  37520. // Change the value
  37521. setter.call(this, val);
  37522. // Notify change, dirty flags update
  37523. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  37524. };
  37525. };
  37526. };
  37527. /**
  37528. * Add an externally attached data from its key.
  37529. * This method call will fail and return false, if such key already exists.
  37530. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  37531. * @param key the unique key that identifies the data
  37532. * @param data the data object to associate to the key for this Engine instance
  37533. * @return true if no such key were already present and the data was added successfully, false otherwise
  37534. */
  37535. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  37536. if (!this._externalData) {
  37537. this._externalData = new BABYLON.StringDictionary();
  37538. }
  37539. return this._externalData.add(key, data);
  37540. };
  37541. /**
  37542. * Get an externally attached data from its key
  37543. * @param key the unique key that identifies the data
  37544. * @return the associated data, if present (can be null), or undefined if not present
  37545. */
  37546. SmartPropertyPrim.prototype.getExternalData = function (key) {
  37547. if (!this._externalData) {
  37548. return null;
  37549. }
  37550. return this._externalData.get(key);
  37551. };
  37552. /**
  37553. * Get an externally attached data from its key, create it using a factory if it's not already present
  37554. * @param key the unique key that identifies the data
  37555. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  37556. * @return the associated data, can be null if the factory returned null.
  37557. */
  37558. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  37559. if (!this._externalData) {
  37560. this._externalData = new BABYLON.StringDictionary();
  37561. }
  37562. return this._externalData.getOrAddWithFactory(key, factory);
  37563. };
  37564. /**
  37565. * Remove an externally attached data from the Engine instance
  37566. * @param key the unique key that identifies the data
  37567. * @return true if the data was successfully removed, false if it doesn't exist
  37568. */
  37569. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  37570. if (!this._externalData) {
  37571. return false;
  37572. }
  37573. return this._externalData.remove(key);
  37574. };
  37575. /**
  37576. * Check if a given flag is set
  37577. * @param flag the flag value
  37578. * @return true if set, false otherwise
  37579. */
  37580. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  37581. return (this._flags & flag) !== 0;
  37582. };
  37583. /**
  37584. * Check if all given flags are set
  37585. * @param flags the flags ORed
  37586. * @return true if all the flags are set, false otherwise
  37587. */
  37588. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  37589. return (this._flags & flags) === flags;
  37590. };
  37591. /**
  37592. * Check if at least one flag of the given flags is set
  37593. * @param flags the flags ORed
  37594. * @return true if at least one flag is set, false otherwise
  37595. */
  37596. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  37597. return (this._flags & flags) !== 0;
  37598. };
  37599. /**
  37600. * Clear the given flags
  37601. * @param flags the flags to clear
  37602. */
  37603. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  37604. this._flags &= ~flags;
  37605. };
  37606. /**
  37607. * Set the given flags to true state
  37608. * @param flags the flags ORed to set
  37609. * @return the flags state before this call
  37610. */
  37611. SmartPropertyPrim.prototype._setFlags = function (flags) {
  37612. var cur = this._flags;
  37613. this._flags |= flags;
  37614. return cur;
  37615. };
  37616. /**
  37617. * Change the state of the given flags
  37618. * @param flags the flags ORed to change
  37619. * @param state true to set them, false to clear them
  37620. */
  37621. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  37622. if (state) {
  37623. this._flags |= flags;
  37624. }
  37625. else {
  37626. this._flags &= ~flags;
  37627. }
  37628. };
  37629. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  37630. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  37631. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  37632. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  37633. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  37634. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  37635. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  37636. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  37637. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  37638. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  37639. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  37640. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  37641. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  37642. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  37643. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  37644. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  37645. SmartPropertyPrim = __decorate([
  37646. BABYLON.className("SmartPropertyPrim")
  37647. ], SmartPropertyPrim);
  37648. return SmartPropertyPrim;
  37649. }());
  37650. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  37651. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37652. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37653. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37654. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37655. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  37656. }
  37657. BABYLON.modelLevelProperty = modelLevelProperty;
  37658. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37659. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37660. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37661. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37662. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  37663. }
  37664. BABYLON.instanceLevelProperty = instanceLevelProperty;
  37665. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37666. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37667. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37668. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37669. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  37670. }
  37671. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  37672. })(BABYLON || (BABYLON = {}));
  37673. var BABYLON;
  37674. (function (BABYLON) {
  37675. var PrepareRender2DContext = (function () {
  37676. function PrepareRender2DContext() {
  37677. this.forceRefreshPrimitive = false;
  37678. }
  37679. return PrepareRender2DContext;
  37680. }());
  37681. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  37682. var Render2DContext = (function () {
  37683. function Render2DContext(renderMode) {
  37684. this._renderMode = renderMode;
  37685. this.useInstancing = false;
  37686. this.groupInfoPartData = null;
  37687. this.partDataStartIndex = this.partDataEndIndex = null;
  37688. this.instancedBuffers = null;
  37689. }
  37690. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  37691. /**
  37692. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  37693. */
  37694. get: function () {
  37695. return this._renderMode;
  37696. },
  37697. enumerable: true,
  37698. configurable: true
  37699. });
  37700. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  37701. /**
  37702. * The set of primitives to render is opaque.
  37703. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  37704. */
  37705. get: function () {
  37706. return Render2DContext._renderModeOpaque;
  37707. },
  37708. enumerable: true,
  37709. configurable: true
  37710. });
  37711. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  37712. /**
  37713. * The set of primitives to render is using Alpha Test (aka masking).
  37714. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  37715. */
  37716. get: function () {
  37717. return Render2DContext._renderModeAlphaTest;
  37718. },
  37719. enumerable: true,
  37720. configurable: true
  37721. });
  37722. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  37723. /**
  37724. * The set of primitives to render is transparent.
  37725. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  37726. */
  37727. get: function () {
  37728. return Render2DContext._renderModeTransparent;
  37729. },
  37730. enumerable: true,
  37731. configurable: true
  37732. });
  37733. Render2DContext._renderModeOpaque = 1;
  37734. Render2DContext._renderModeAlphaTest = 2;
  37735. Render2DContext._renderModeTransparent = 3;
  37736. return Render2DContext;
  37737. }());
  37738. BABYLON.Render2DContext = Render2DContext;
  37739. /**
  37740. * This class store information for the pointerEventObservable Observable.
  37741. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  37742. */
  37743. var PrimitivePointerInfo = (function () {
  37744. function PrimitivePointerInfo() {
  37745. this.primitivePointerPos = BABYLON.Vector2.Zero();
  37746. this.tilt = BABYLON.Vector2.Zero();
  37747. this.cancelBubble = false;
  37748. }
  37749. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  37750. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  37751. /**
  37752. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  37753. * Bubbles: yes
  37754. */
  37755. get: function () {
  37756. return PrimitivePointerInfo._pointerOver;
  37757. },
  37758. enumerable: true,
  37759. configurable: true
  37760. });
  37761. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  37762. /**
  37763. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  37764. * Bubbles: no
  37765. */
  37766. get: function () {
  37767. return PrimitivePointerInfo._pointerEnter;
  37768. },
  37769. enumerable: true,
  37770. configurable: true
  37771. });
  37772. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  37773. /**
  37774. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  37775. * Bubbles: yes
  37776. */
  37777. get: function () {
  37778. return PrimitivePointerInfo._pointerDown;
  37779. },
  37780. enumerable: true,
  37781. configurable: true
  37782. });
  37783. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  37784. /**
  37785. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  37786. * Bubbles: yes
  37787. */
  37788. get: function () {
  37789. return PrimitivePointerInfo._pointerMouseWheel;
  37790. },
  37791. enumerable: true,
  37792. configurable: true
  37793. });
  37794. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  37795. /**
  37796. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  37797. * Bubbles: yes
  37798. */
  37799. get: function () {
  37800. return PrimitivePointerInfo._pointerMove;
  37801. },
  37802. enumerable: true,
  37803. configurable: true
  37804. });
  37805. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  37806. /**
  37807. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  37808. * Bubbles: yes
  37809. */
  37810. get: function () {
  37811. return PrimitivePointerInfo._pointerUp;
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  37817. /**
  37818. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  37819. * Bubbles: yes
  37820. */
  37821. get: function () {
  37822. return PrimitivePointerInfo._pointerOut;
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  37828. /**
  37829. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  37830. * Bubbles: no
  37831. */
  37832. get: function () {
  37833. return PrimitivePointerInfo._pointerLeave;
  37834. },
  37835. enumerable: true,
  37836. configurable: true
  37837. });
  37838. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  37839. /**
  37840. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  37841. * Bubbles: yes
  37842. */
  37843. get: function () {
  37844. return PrimitivePointerInfo._pointerGotCapture;
  37845. },
  37846. enumerable: true,
  37847. configurable: true
  37848. });
  37849. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  37850. /**
  37851. * This event type is raised after pointer capture is released for a pointer.
  37852. * Bubbles: yes
  37853. */
  37854. get: function () {
  37855. return PrimitivePointerInfo._pointerLostCapture;
  37856. },
  37857. enumerable: true,
  37858. configurable: true
  37859. });
  37860. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  37861. get: function () {
  37862. return PrimitivePointerInfo._mouseWheelPrecision;
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  37868. this.relatedTarget = prim;
  37869. this.relatedTargetPointerPos = primPointerPos;
  37870. };
  37871. PrimitivePointerInfo.getEventTypeName = function (mask) {
  37872. switch (mask) {
  37873. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  37874. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  37875. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  37876. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  37877. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  37878. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  37879. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  37880. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  37881. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  37882. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  37883. }
  37884. };
  37885. PrimitivePointerInfo._pointerOver = 0x0001;
  37886. PrimitivePointerInfo._pointerEnter = 0x0002;
  37887. PrimitivePointerInfo._pointerDown = 0x0004;
  37888. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  37889. PrimitivePointerInfo._pointerMove = 0x0010;
  37890. PrimitivePointerInfo._pointerUp = 0x0020;
  37891. PrimitivePointerInfo._pointerOut = 0x0040;
  37892. PrimitivePointerInfo._pointerLeave = 0x0080;
  37893. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  37894. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  37895. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  37896. return PrimitivePointerInfo;
  37897. }());
  37898. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  37899. /**
  37900. * Defines the horizontal and vertical alignment information for a Primitive.
  37901. */
  37902. var PrimitiveAlignment = (function () {
  37903. function PrimitiveAlignment(changeCallback) {
  37904. this._changedCallback = changeCallback;
  37905. this._horizontal = PrimitiveAlignment.AlignLeft;
  37906. this._vertical = PrimitiveAlignment.AlignBottom;
  37907. }
  37908. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  37909. /**
  37910. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  37911. */
  37912. get: function () { return PrimitiveAlignment._AlignLeft; },
  37913. enumerable: true,
  37914. configurable: true
  37915. });
  37916. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37917. /**
  37918. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37919. */
  37920. get: function () { return PrimitiveAlignment._AlignTop; },
  37921. enumerable: true,
  37922. configurable: true
  37923. });
  37924. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37925. /**
  37926. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37927. */
  37928. get: function () { return PrimitiveAlignment._AlignRight; },
  37929. enumerable: true,
  37930. configurable: true
  37931. });
  37932. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37933. /**
  37934. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37935. */
  37936. get: function () { return PrimitiveAlignment._AlignBottom; },
  37937. enumerable: true,
  37938. configurable: true
  37939. });
  37940. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37941. /**
  37942. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37943. */
  37944. get: function () { return PrimitiveAlignment._AlignCenter; },
  37945. enumerable: true,
  37946. configurable: true
  37947. });
  37948. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37949. /**
  37950. * The content is stretched toward the opposite edges of the Primitive
  37951. */
  37952. get: function () { return PrimitiveAlignment._AlignStretch; },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37957. /**
  37958. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37959. */
  37960. get: function () {
  37961. return this._horizontal;
  37962. },
  37963. set: function (value) {
  37964. if (this._horizontal === value) {
  37965. return;
  37966. }
  37967. this._horizontal = value;
  37968. this._changedCallback();
  37969. },
  37970. enumerable: true,
  37971. configurable: true
  37972. });
  37973. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37974. /**
  37975. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37976. */
  37977. get: function () {
  37978. return this._vertical;
  37979. },
  37980. set: function (value) {
  37981. if (this._vertical === value) {
  37982. return;
  37983. }
  37984. this._vertical = value;
  37985. this._changedCallback();
  37986. },
  37987. enumerable: true,
  37988. configurable: true
  37989. });
  37990. /**
  37991. * Set the horizontal alignment from a string value.
  37992. * @param text can be either: 'left','right','center','stretch'
  37993. */
  37994. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37995. var v = text.trim().toLocaleLowerCase();
  37996. switch (v) {
  37997. case "left":
  37998. this.horizontal = PrimitiveAlignment.AlignLeft;
  37999. return;
  38000. case "right":
  38001. this.horizontal = PrimitiveAlignment.AlignRight;
  38002. return;
  38003. case "center":
  38004. this.horizontal = PrimitiveAlignment.AlignCenter;
  38005. return;
  38006. case "stretch":
  38007. this.horizontal = PrimitiveAlignment.AlignStretch;
  38008. return;
  38009. }
  38010. };
  38011. /**
  38012. * Set the vertical alignment from a string value.
  38013. * @param text can be either: 'top','bottom','center','stretch'
  38014. */
  38015. PrimitiveAlignment.prototype.setVertical = function (text) {
  38016. var v = text.trim().toLocaleLowerCase();
  38017. switch (v) {
  38018. case "top":
  38019. this.vertical = PrimitiveAlignment.AlignTop;
  38020. return;
  38021. case "bottom":
  38022. this.vertical = PrimitiveAlignment.AlignBottom;
  38023. return;
  38024. case "center":
  38025. this.vertical = PrimitiveAlignment.AlignCenter;
  38026. return;
  38027. case "stretch":
  38028. this.vertical = PrimitiveAlignment.AlignStretch;
  38029. return;
  38030. }
  38031. };
  38032. /**
  38033. * Set the horizontal and or vertical alignments from a string value.
  38034. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  38035. */
  38036. PrimitiveAlignment.prototype.fromString = function (value) {
  38037. var m = value.trim().split(",");
  38038. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  38039. var v = m_1[_i];
  38040. v = v.toLocaleLowerCase().trim();
  38041. // Horizontal
  38042. var i = v.indexOf("h:");
  38043. if (i === -1) {
  38044. i = v.indexOf("horizontal:");
  38045. }
  38046. if (i !== -1) {
  38047. v = v.substr(v.indexOf(":") + 1);
  38048. this.setHorizontal(v);
  38049. continue;
  38050. }
  38051. // Vertical
  38052. i = v.indexOf("v:");
  38053. if (i === -1) {
  38054. i = v.indexOf("vertical:");
  38055. }
  38056. if (i !== -1) {
  38057. v = v.substr(v.indexOf(":") + 1);
  38058. this.setVertical(v);
  38059. continue;
  38060. }
  38061. }
  38062. };
  38063. PrimitiveAlignment._AlignLeft = 1;
  38064. PrimitiveAlignment._AlignTop = 1; // Same as left
  38065. PrimitiveAlignment._AlignRight = 2;
  38066. PrimitiveAlignment._AlignBottom = 2; // Same as right
  38067. PrimitiveAlignment._AlignCenter = 3;
  38068. PrimitiveAlignment._AlignStretch = 4;
  38069. return PrimitiveAlignment;
  38070. }());
  38071. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  38072. /**
  38073. * Stores information about a Primitive that was intersected
  38074. */
  38075. var PrimitiveIntersectedInfo = (function () {
  38076. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  38077. this.prim = prim;
  38078. this.intersectionLocation = intersectionLocation;
  38079. }
  38080. return PrimitiveIntersectedInfo;
  38081. }());
  38082. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  38083. /**
  38084. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  38085. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  38086. */
  38087. var PrimitiveThickness = (function () {
  38088. function PrimitiveThickness(parentAccess, changedCallback) {
  38089. this._parentAccess = parentAccess;
  38090. this._changedCallback = changedCallback;
  38091. this._pixels = new Array(4);
  38092. this._percentages = new Array(4);
  38093. this._setType(0, PrimitiveThickness.Auto);
  38094. this._setType(1, PrimitiveThickness.Auto);
  38095. this._setType(2, PrimitiveThickness.Auto);
  38096. this._setType(3, PrimitiveThickness.Auto);
  38097. this._pixels[0] = 0;
  38098. this._pixels[1] = 0;
  38099. this._pixels[2] = 0;
  38100. this._pixels[3] = 0;
  38101. }
  38102. /**
  38103. * Set the thickness from a string value
  38104. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  38105. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38106. */
  38107. PrimitiveThickness.prototype.fromString = function (thickness) {
  38108. this._clear();
  38109. var m = thickness.trim().split(",");
  38110. // Special case, one value to apply to all edges
  38111. if (m.length === 1 && thickness.indexOf(":") === -1) {
  38112. this._setStringValue(m[0], 0, false);
  38113. this._setStringValue(m[0], 1, false);
  38114. this._setStringValue(m[0], 2, false);
  38115. this._setStringValue(m[0], 3, false);
  38116. this._changedCallback();
  38117. return;
  38118. }
  38119. var res = false;
  38120. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  38121. var cm = m_2[_i];
  38122. res = this._extractString(cm, false) || res;
  38123. }
  38124. if (!res) {
  38125. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  38126. }
  38127. // Check the margin that weren't set and set them in auto
  38128. if ((this._flags & 0x000F) === 0)
  38129. this._flags |= PrimitiveThickness.Pixel << 0;
  38130. if ((this._flags & 0x00F0) === 0)
  38131. this._flags |= PrimitiveThickness.Pixel << 4;
  38132. if ((this._flags & 0x0F00) === 0)
  38133. this._flags |= PrimitiveThickness.Pixel << 8;
  38134. if ((this._flags & 0xF000) === 0)
  38135. this._flags |= PrimitiveThickness.Pixel << 12;
  38136. this._changedCallback();
  38137. };
  38138. /**
  38139. * Set the thickness from multiple string
  38140. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38141. * @param top the top thickness to set
  38142. * @param left the left thickness to set
  38143. * @param right the right thickness to set
  38144. * @param bottom the bottom thickness to set
  38145. */
  38146. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  38147. this._clear();
  38148. this._setStringValue(top, 0, false);
  38149. this._setStringValue(left, 1, false);
  38150. this._setStringValue(right, 2, false);
  38151. this._setStringValue(bottom, 3, false);
  38152. this._changedCallback();
  38153. return this;
  38154. };
  38155. /**
  38156. * Set the thickness from pixel values
  38157. * @param top the top thickness in pixels to set
  38158. * @param left the left thickness in pixels to set
  38159. * @param right the right thickness in pixels to set
  38160. * @param bottom the bottom thickness in pixels to set
  38161. */
  38162. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  38163. this._clear();
  38164. this._pixels[0] = top;
  38165. this._pixels[1] = left;
  38166. this._pixels[2] = right;
  38167. this._pixels[3] = bottom;
  38168. this._changedCallback();
  38169. return this;
  38170. };
  38171. /**
  38172. * Apply the same pixel value to all edges
  38173. * @param margin the value to set, in pixels.
  38174. */
  38175. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  38176. this._clear();
  38177. this._pixels[0] = margin;
  38178. this._pixels[1] = margin;
  38179. this._pixels[2] = margin;
  38180. this._pixels[3] = margin;
  38181. this._changedCallback();
  38182. return this;
  38183. };
  38184. /**
  38185. * Set all edges in auto
  38186. */
  38187. PrimitiveThickness.prototype.auto = function () {
  38188. this._clear();
  38189. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  38190. this._pixels[0] = 0;
  38191. this._pixels[1] = 0;
  38192. this._pixels[2] = 0;
  38193. this._pixels[3] = 0;
  38194. this._changedCallback();
  38195. return this;
  38196. };
  38197. PrimitiveThickness.prototype._clear = function () {
  38198. this._flags = 0;
  38199. this._pixels[0] = 0;
  38200. this._pixels[1] = 0;
  38201. this._pixels[2] = 0;
  38202. this._pixels[3] = 0;
  38203. this._percentages[0] = null;
  38204. this._percentages[1] = null;
  38205. this._percentages[2] = null;
  38206. this._percentages[3] = null;
  38207. };
  38208. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  38209. var v = value.trim().toLocaleLowerCase();
  38210. if (v.indexOf("top:") === 0) {
  38211. v = v.substr(4).trim();
  38212. return this._setStringValue(v, 0, emitChanged);
  38213. }
  38214. if (v.indexOf("left:") === 0) {
  38215. v = v.substr(5).trim();
  38216. return this._setStringValue(v, 1, emitChanged);
  38217. }
  38218. if (v.indexOf("right:") === 0) {
  38219. v = v.substr(6).trim();
  38220. return this._setStringValue(v, 2, emitChanged);
  38221. }
  38222. if (v.indexOf("bottom:") === 0) {
  38223. v = v.substr(7).trim();
  38224. return this._setStringValue(v, 3, emitChanged);
  38225. }
  38226. return false;
  38227. };
  38228. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  38229. // Check for auto
  38230. var v = value.trim().toLocaleLowerCase();
  38231. if (v === "auto") {
  38232. if (this._isType(index, PrimitiveThickness.Auto)) {
  38233. return true;
  38234. }
  38235. this._setType(index, PrimitiveThickness.Auto);
  38236. this._pixels[index] = 0;
  38237. if (emitChanged) {
  38238. this._changedCallback();
  38239. }
  38240. }
  38241. else if (v === "inherit") {
  38242. if (this._isType(index, PrimitiveThickness.Inherit)) {
  38243. return true;
  38244. }
  38245. this._setType(index, PrimitiveThickness.Inherit);
  38246. this._pixels[index] = null;
  38247. if (emitChanged) {
  38248. this._changedCallback();
  38249. }
  38250. }
  38251. else {
  38252. var pI = v.indexOf("%");
  38253. // Check for percentage
  38254. if (pI !== -1) {
  38255. var n_1 = v.substr(0, pI);
  38256. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  38257. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  38258. return true;
  38259. }
  38260. this._setType(index, PrimitiveThickness.Percentage);
  38261. if (isNaN(number_1)) {
  38262. return false;
  38263. }
  38264. this._percentages[index] = number_1;
  38265. if (emitChanged) {
  38266. this._changedCallback();
  38267. }
  38268. return true;
  38269. }
  38270. // Check for pixel
  38271. var n = void 0;
  38272. pI = v.indexOf("px");
  38273. if (pI !== -1) {
  38274. n = v.substr(0, pI).trim();
  38275. }
  38276. else {
  38277. n = v;
  38278. }
  38279. var number = Number(n);
  38280. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  38281. return true;
  38282. }
  38283. if (isNaN(number)) {
  38284. return false;
  38285. }
  38286. this._pixels[index] = number;
  38287. this._setType(index, PrimitiveThickness.Pixel);
  38288. if (emitChanged) {
  38289. this._changedCallback();
  38290. }
  38291. return true;
  38292. }
  38293. };
  38294. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  38295. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  38296. value = Math.round(value);
  38297. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  38298. return;
  38299. }
  38300. this._setType(index, PrimitiveThickness.Pixel);
  38301. this._pixels[index] = value;
  38302. if (emitChanged) {
  38303. this._changedCallback();
  38304. }
  38305. };
  38306. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  38307. // Clip Value to bounds
  38308. value = Math.min(1, value);
  38309. value = Math.max(0, value);
  38310. value = Math.round(value * 100) / 100; // 0.01 precision
  38311. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  38312. return;
  38313. }
  38314. this._setType(index, PrimitiveThickness.Percentage);
  38315. this._percentages[index] = value;
  38316. if (emitChanged) {
  38317. this._changedCallback();
  38318. }
  38319. };
  38320. PrimitiveThickness.prototype._getStringValue = function (index) {
  38321. var f = (this._flags >> (index * 4)) & 0xF;
  38322. switch (f) {
  38323. case PrimitiveThickness.Auto:
  38324. return "auto";
  38325. case PrimitiveThickness.Pixel:
  38326. return this._pixels[index] + "px";
  38327. case PrimitiveThickness.Percentage:
  38328. return this._percentages[index] * 100 + "%";
  38329. case PrimitiveThickness.Inherit:
  38330. return "inherit";
  38331. }
  38332. return "";
  38333. };
  38334. PrimitiveThickness.prototype._isType = function (index, type) {
  38335. var f = (this._flags >> (index * 4)) & 0xF;
  38336. return f === type;
  38337. };
  38338. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  38339. var t = (this._flags >> (index * 4)) & 0xF;
  38340. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  38341. var p = this._parentAccess();
  38342. if (p) {
  38343. return p._getType(index, true);
  38344. }
  38345. return PrimitiveThickness.Auto;
  38346. }
  38347. return t;
  38348. };
  38349. PrimitiveThickness.prototype._setType = function (index, type) {
  38350. this._flags &= ~(0xF << (index * 4));
  38351. this._flags |= type << (index * 4);
  38352. };
  38353. PrimitiveThickness.prototype.setTop = function (value) {
  38354. if (typeof value === "string") {
  38355. this._setStringValue(value, 0, true);
  38356. }
  38357. else {
  38358. this.topPixels = value;
  38359. }
  38360. };
  38361. PrimitiveThickness.prototype.setLeft = function (value) {
  38362. if (typeof value === "string") {
  38363. this._setStringValue(value, 1, true);
  38364. }
  38365. else {
  38366. this.leftPixels = value;
  38367. }
  38368. };
  38369. PrimitiveThickness.prototype.setRight = function (value) {
  38370. if (typeof value === "string") {
  38371. this._setStringValue(value, 2, true);
  38372. }
  38373. else {
  38374. this.rightPixels = value;
  38375. }
  38376. };
  38377. PrimitiveThickness.prototype.setBottom = function (value) {
  38378. if (typeof value === "string") {
  38379. this._setStringValue(value, 3, true);
  38380. }
  38381. else {
  38382. this.bottomPixels = value;
  38383. }
  38384. };
  38385. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  38386. /**
  38387. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38388. */
  38389. get: function () {
  38390. return this._getStringValue(0);
  38391. },
  38392. set: function (value) {
  38393. this._setStringValue(value, 0, true);
  38394. },
  38395. enumerable: true,
  38396. configurable: true
  38397. });
  38398. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  38399. /**
  38400. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38401. */
  38402. get: function () {
  38403. return this._getStringValue(1);
  38404. },
  38405. set: function (value) {
  38406. this._setStringValue(value, 1, true);
  38407. },
  38408. enumerable: true,
  38409. configurable: true
  38410. });
  38411. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  38412. /**
  38413. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38414. */
  38415. get: function () {
  38416. return this._getStringValue(2);
  38417. },
  38418. set: function (value) {
  38419. this._setStringValue(value, 2, true);
  38420. },
  38421. enumerable: true,
  38422. configurable: true
  38423. });
  38424. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38425. /**
  38426. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38427. */
  38428. get: function () {
  38429. return this._getStringValue(3);
  38430. },
  38431. set: function (value) {
  38432. this._setStringValue(value, 3, true);
  38433. },
  38434. enumerable: true,
  38435. configurable: true
  38436. });
  38437. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  38438. /**
  38439. * Get/set the top thickness in pixel.
  38440. */
  38441. get: function () {
  38442. return this._pixels[0];
  38443. },
  38444. set: function (value) {
  38445. this._setPixels(value, 0, true);
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  38451. /**
  38452. * Get/set the left thickness in pixel.
  38453. */
  38454. get: function () {
  38455. return this._pixels[1];
  38456. },
  38457. set: function (value) {
  38458. this._setPixels(value, 1, true);
  38459. },
  38460. enumerable: true,
  38461. configurable: true
  38462. });
  38463. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  38464. /**
  38465. * Get/set the right thickness in pixel.
  38466. */
  38467. get: function () {
  38468. return this._pixels[2];
  38469. },
  38470. set: function (value) {
  38471. this._setPixels(value, 2, true);
  38472. },
  38473. enumerable: true,
  38474. configurable: true
  38475. });
  38476. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  38477. /**
  38478. * Get/set the bottom thickness in pixel.
  38479. */
  38480. get: function () {
  38481. return this._pixels[3];
  38482. },
  38483. set: function (value) {
  38484. this._setPixels(value, 3, true);
  38485. },
  38486. enumerable: true,
  38487. configurable: true
  38488. });
  38489. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  38490. /**
  38491. * Get/set the top thickness in percentage.
  38492. * The get will return a valid value only if the edge type is percentage.
  38493. * The Set will change the edge mode if needed
  38494. */
  38495. get: function () {
  38496. return this._percentages[0];
  38497. },
  38498. set: function (value) {
  38499. this._setPercentage(value, 0, true);
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  38505. /**
  38506. * Get/set the left thickness in percentage.
  38507. * The get will return a valid value only if the edge mode is percentage.
  38508. * The Set will change the edge mode if needed
  38509. */
  38510. get: function () {
  38511. return this._percentages[1];
  38512. },
  38513. set: function (value) {
  38514. this._setPercentage(value, 1, true);
  38515. },
  38516. enumerable: true,
  38517. configurable: true
  38518. });
  38519. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  38520. /**
  38521. * Get/set the right thickness in percentage.
  38522. * The get will return a valid value only if the edge mode is percentage.
  38523. * The Set will change the edge mode if needed
  38524. */
  38525. get: function () {
  38526. return this._percentages[2];
  38527. },
  38528. set: function (value) {
  38529. this._setPercentage(value, 2, true);
  38530. },
  38531. enumerable: true,
  38532. configurable: true
  38533. });
  38534. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  38535. /**
  38536. * Get/set the bottom thickness in percentage.
  38537. * The get will return a valid value only if the edge mode is percentage.
  38538. * The Set will change the edge mode if needed
  38539. */
  38540. get: function () {
  38541. return this._percentages[3];
  38542. },
  38543. set: function (value) {
  38544. this._setPercentage(value, 3, true);
  38545. },
  38546. enumerable: true,
  38547. configurable: true
  38548. });
  38549. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  38550. /**
  38551. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  38552. */
  38553. get: function () {
  38554. return this._getType(0, false);
  38555. },
  38556. set: function (mode) {
  38557. this._setType(0, mode);
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  38563. /**
  38564. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  38565. */
  38566. get: function () {
  38567. return this._getType(1, false);
  38568. },
  38569. set: function (mode) {
  38570. this._setType(1, mode);
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  38576. /**
  38577. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  38578. */
  38579. get: function () {
  38580. return this._getType(2, false);
  38581. },
  38582. set: function (mode) {
  38583. this._setType(2, mode);
  38584. },
  38585. enumerable: true,
  38586. configurable: true
  38587. });
  38588. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  38589. /**
  38590. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  38591. */
  38592. get: function () {
  38593. return this._getType(3, false);
  38594. },
  38595. set: function (mode) {
  38596. this._setType(3, mode);
  38597. },
  38598. enumerable: true,
  38599. configurable: true
  38600. });
  38601. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  38602. var type = this._getType(index, false);
  38603. if (type === PrimitiveThickness.Inherit) {
  38604. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  38605. return;
  38606. }
  38607. if (type !== PrimitiveThickness.Percentage) {
  38608. return;
  38609. }
  38610. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  38611. this._pixels[index] = pixels;
  38612. if (emitChanged) {
  38613. this._changedCallback();
  38614. }
  38615. };
  38616. /**
  38617. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  38618. * @param sourceArea the source area
  38619. * @param contentSize the content size to position/resize
  38620. * @param alignment the alignment setting
  38621. * @param dstOffset the position of the content
  38622. * @param dstArea the new size of the content
  38623. */
  38624. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  38625. // Fetch some data
  38626. var topType = this._getType(0, true);
  38627. var leftType = this._getType(1, true);
  38628. var rightType = this._getType(2, true);
  38629. var bottomType = this._getType(3, true);
  38630. var hasWidth = contentSize && (contentSize.width != null);
  38631. var hasHeight = contentSize && (contentSize.height != null);
  38632. var width = hasWidth ? contentSize.width : 0;
  38633. var height = hasHeight ? contentSize.height : 0;
  38634. var isTopAuto = topType === PrimitiveThickness.Auto;
  38635. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  38636. var isRightAuto = rightType === PrimitiveThickness.Auto;
  38637. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  38638. switch (alignment.horizontal) {
  38639. case PrimitiveAlignment.AlignLeft:
  38640. {
  38641. if (isLeftAuto) {
  38642. dstOffset.x = 0;
  38643. }
  38644. else {
  38645. this._computePixels(1, sourceArea, true);
  38646. dstOffset.x = this.leftPixels;
  38647. }
  38648. dstArea.width = width;
  38649. break;
  38650. }
  38651. case PrimitiveAlignment.AlignRight:
  38652. {
  38653. if (isRightAuto) {
  38654. dstOffset.x = Math.round(sourceArea.width - width);
  38655. }
  38656. else {
  38657. this._computePixels(2, sourceArea, true);
  38658. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  38659. }
  38660. dstArea.width = width;
  38661. break;
  38662. }
  38663. case PrimitiveAlignment.AlignStretch:
  38664. {
  38665. if (isLeftAuto) {
  38666. dstOffset.x = 0;
  38667. }
  38668. else {
  38669. this._computePixels(1, sourceArea, true);
  38670. dstOffset.x = this.leftPixels;
  38671. }
  38672. var right = 0;
  38673. if (!isRightAuto) {
  38674. this._computePixels(2, sourceArea, true);
  38675. right = this.rightPixels;
  38676. }
  38677. dstArea.width = sourceArea.width - (dstOffset.x + right);
  38678. break;
  38679. }
  38680. case PrimitiveAlignment.AlignCenter:
  38681. {
  38682. if (!isLeftAuto) {
  38683. this._computePixels(1, sourceArea, true);
  38684. }
  38685. if (!isRightAuto) {
  38686. this._computePixels(2, sourceArea, true);
  38687. }
  38688. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  38689. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  38690. dstArea.width = width;
  38691. break;
  38692. }
  38693. }
  38694. switch (alignment.vertical) {
  38695. case PrimitiveAlignment.AlignTop:
  38696. {
  38697. if (isTopAuto) {
  38698. dstOffset.y = sourceArea.height - height;
  38699. }
  38700. else {
  38701. this._computePixels(0, sourceArea, true);
  38702. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  38703. }
  38704. dstArea.height = height;
  38705. break;
  38706. }
  38707. case PrimitiveAlignment.AlignBottom:
  38708. {
  38709. if (isBottomAuto) {
  38710. dstOffset.y = 0;
  38711. }
  38712. else {
  38713. this._computePixels(3, sourceArea, true);
  38714. dstOffset.y = this.bottomPixels;
  38715. }
  38716. dstArea.height = height;
  38717. break;
  38718. }
  38719. case PrimitiveAlignment.AlignStretch:
  38720. {
  38721. if (isBottomAuto) {
  38722. dstOffset.y = 0;
  38723. }
  38724. else {
  38725. this._computePixels(3, sourceArea, true);
  38726. dstOffset.y = this.bottomPixels;
  38727. }
  38728. var top_1 = 0;
  38729. if (!isTopAuto) {
  38730. this._computePixels(0, sourceArea, true);
  38731. top_1 = this.topPixels;
  38732. }
  38733. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  38734. break;
  38735. }
  38736. case PrimitiveAlignment.AlignCenter:
  38737. {
  38738. if (!isTopAuto) {
  38739. this._computePixels(0, sourceArea, true);
  38740. }
  38741. if (!isBottomAuto) {
  38742. this._computePixels(3, sourceArea, true);
  38743. }
  38744. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  38745. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  38746. dstArea.height = height;
  38747. break;
  38748. }
  38749. }
  38750. };
  38751. /**
  38752. * Compute an area and its position considering this thickness properties based on a given source area
  38753. * @param sourceArea the source area
  38754. * @param dstOffset the position of the resulting area
  38755. * @param dstArea the size of the resulting area
  38756. */
  38757. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  38758. this._computePixels(0, sourceArea, true);
  38759. this._computePixels(1, sourceArea, true);
  38760. this._computePixels(2, sourceArea, true);
  38761. this._computePixels(3, sourceArea, true);
  38762. dstOffset.x = this.leftPixels;
  38763. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  38764. dstOffset.y = this.bottomPixels;
  38765. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  38766. };
  38767. /**
  38768. * Compute an area considering this thickness properties based on a given source area
  38769. * @param sourceArea the source area
  38770. * @param result the resulting area
  38771. */
  38772. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  38773. this._computePixels(0, sourceArea, true);
  38774. this._computePixels(1, sourceArea, true);
  38775. this._computePixels(2, sourceArea, true);
  38776. this._computePixels(3, sourceArea, true);
  38777. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  38778. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  38779. };
  38780. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  38781. this._computePixels(0, sourceArea, true);
  38782. this._computePixels(1, sourceArea, true);
  38783. this._computePixels(2, sourceArea, true);
  38784. this._computePixels(3, sourceArea, true);
  38785. dstOffset.x = this.leftPixels;
  38786. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  38787. dstOffset.y = this.bottomPixels;
  38788. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  38789. };
  38790. PrimitiveThickness.Auto = 0x1;
  38791. PrimitiveThickness.Inherit = 0x2;
  38792. PrimitiveThickness.Percentage = 0x4;
  38793. PrimitiveThickness.Pixel = 0x8;
  38794. return PrimitiveThickness;
  38795. }());
  38796. BABYLON.PrimitiveThickness = PrimitiveThickness;
  38797. /**
  38798. * Main class used for the Primitive Intersection API
  38799. */
  38800. var IntersectInfo2D = (function () {
  38801. function IntersectInfo2D() {
  38802. this.findFirstOnly = false;
  38803. this.intersectHidden = false;
  38804. this.pickPosition = BABYLON.Vector2.Zero();
  38805. }
  38806. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  38807. /**
  38808. * true if at least one primitive intersected during the test
  38809. */
  38810. get: function () {
  38811. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  38812. },
  38813. enumerable: true,
  38814. configurable: true
  38815. });
  38816. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  38817. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  38818. var cur = _a[_i];
  38819. if (cur.prim === prim) {
  38820. return cur.intersectionLocation;
  38821. }
  38822. }
  38823. return null;
  38824. };
  38825. // Internals, don't use
  38826. IntersectInfo2D.prototype._exit = function (firstLevel) {
  38827. if (firstLevel) {
  38828. this._globalPickPosition = null;
  38829. }
  38830. };
  38831. return IntersectInfo2D;
  38832. }());
  38833. BABYLON.IntersectInfo2D = IntersectInfo2D;
  38834. var Prim2DBase = (function (_super) {
  38835. __extends(Prim2DBase, _super);
  38836. function Prim2DBase(settings) {
  38837. // Avoid checking every time if the object exists
  38838. if (settings == null) {
  38839. settings = {};
  38840. }
  38841. // BASE CLASS CALL
  38842. _super.call(this);
  38843. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  38844. var owner;
  38845. var parent;
  38846. if (Prim2DBase._isCanvasInit) {
  38847. owner = this;
  38848. parent = null;
  38849. this._canvasPreInit(settings);
  38850. }
  38851. else {
  38852. if (settings.parent != null) {
  38853. parent = settings.parent;
  38854. owner = settings.parent.owner;
  38855. if (!owner) {
  38856. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  38857. }
  38858. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  38859. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  38860. }
  38861. }
  38862. }
  38863. // Fields initialization
  38864. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38865. this._size = null; //Size.Zero();
  38866. this._actualSize = null;
  38867. this._boundingSize = BABYLON.Size.Zero();
  38868. this._layoutArea = BABYLON.Size.Zero();
  38869. this._layoutAreaPos = BABYLON.Vector2.Zero();
  38870. this._marginOffset = BABYLON.Vector2.Zero();
  38871. this._paddingOffset = BABYLON.Vector2.Zero();
  38872. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  38873. this._parentContentArea = BABYLON.Size.Zero();
  38874. this._lastAutoSizeArea = BABYLON.Size.Zero();
  38875. this._contentArea = new BABYLON.Size(null, null);
  38876. this._pointerEventObservable = new BABYLON.Observable();
  38877. this._boundingInfo = new BABYLON.BoundingInfo2D();
  38878. this._owner = owner;
  38879. this._parent = null;
  38880. this._margin = null;
  38881. this._padding = null;
  38882. this._marginAlignment = null;
  38883. this._id = settings.id;
  38884. this.propertyChanged = new BABYLON.Observable();
  38885. this._children = new Array();
  38886. this._localTransform = new BABYLON.Matrix();
  38887. this._globalTransform = null;
  38888. this._invGlobalTransform = null;
  38889. this._globalTransformProcessStep = 0;
  38890. this._globalTransformStep = 0;
  38891. this._renderGroup = null;
  38892. this._primLinearPosition = 0;
  38893. this._manualZOrder = null;
  38894. this._zOrder = 0;
  38895. this._zMax = 0;
  38896. this._firstZDirtyIndex = Prim2DBase._bigInt;
  38897. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  38898. if (settings.opacity != null) {
  38899. this._opacity = settings.opacity;
  38900. }
  38901. else {
  38902. this._opacity = 1;
  38903. }
  38904. if (settings.childrenFlatZOrder) {
  38905. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  38906. }
  38907. // If the parent is given, initialize the hierarchy/owner related data
  38908. if (parent != null) {
  38909. parent.addChild(this);
  38910. this._patchHierarchy(parent.owner);
  38911. }
  38912. // If it's a group, detect its own states
  38913. if (this.owner && this instanceof BABYLON.Group2D) {
  38914. var group = this;
  38915. group.detectGroupStates();
  38916. }
  38917. // Time to insert children if some are specified
  38918. if (settings.children != null) {
  38919. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  38920. var child = _a[_i];
  38921. this.addChild(child);
  38922. // Good time to patch the hierarchy, it won't go very far if there's no need to
  38923. child._patchHierarchy(this.owner);
  38924. }
  38925. }
  38926. // Set the model related properties
  38927. if (settings.position != null) {
  38928. this.position = settings.position;
  38929. }
  38930. else if (settings.x != null || settings.y != null) {
  38931. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  38932. }
  38933. else {
  38934. this._position = null;
  38935. }
  38936. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  38937. this.scale = (settings.scale == null) ? 1 : settings.scale;
  38938. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  38939. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  38940. // Layout Engine
  38941. if (settings.layoutEngine != null) {
  38942. if (typeof settings.layoutEngine === "string") {
  38943. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  38944. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  38945. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38946. }
  38947. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  38948. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38949. }
  38950. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38951. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38952. }
  38953. }
  38954. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38955. this.layoutEngine = settings.layoutEngine;
  38956. }
  38957. }
  38958. // Set the layout/margin stuffs
  38959. if (settings.marginTop) {
  38960. this.margin.setTop(settings.marginTop);
  38961. }
  38962. if (settings.marginLeft) {
  38963. this.margin.setLeft(settings.marginLeft);
  38964. }
  38965. if (settings.marginRight) {
  38966. this.margin.setRight(settings.marginRight);
  38967. }
  38968. if (settings.marginBottom) {
  38969. this.margin.setBottom(settings.marginBottom);
  38970. }
  38971. if (settings.margin) {
  38972. if (typeof settings.margin === "string") {
  38973. this.margin.fromString(settings.margin);
  38974. }
  38975. else {
  38976. this.margin.fromUniformPixels(settings.margin);
  38977. }
  38978. }
  38979. if (settings.marginHAlignment) {
  38980. this.marginAlignment.horizontal = settings.marginHAlignment;
  38981. }
  38982. if (settings.marginVAlignment) {
  38983. this.marginAlignment.vertical = settings.marginVAlignment;
  38984. }
  38985. if (settings.marginAlignment) {
  38986. this.marginAlignment.fromString(settings.marginAlignment);
  38987. }
  38988. if (settings.paddingTop) {
  38989. this.padding.setTop(settings.paddingTop);
  38990. }
  38991. if (settings.paddingLeft) {
  38992. this.padding.setLeft(settings.paddingLeft);
  38993. }
  38994. if (settings.paddingRight) {
  38995. this.padding.setRight(settings.paddingRight);
  38996. }
  38997. if (settings.paddingBottom) {
  38998. this.padding.setBottom(settings.paddingBottom);
  38999. }
  39000. if (settings.padding) {
  39001. this.padding.fromString(settings.padding);
  39002. }
  39003. // Dirty layout and positioning
  39004. this._parentLayoutDirty();
  39005. this._positioningDirty();
  39006. }
  39007. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  39008. get: function () {
  39009. if (!this._actionManager) {
  39010. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  39011. }
  39012. return this._actionManager;
  39013. },
  39014. enumerable: true,
  39015. configurable: true
  39016. });
  39017. /**
  39018. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  39019. * @param predicate the predicate to test on each parent
  39020. * @return the first primitive where the predicate was successful
  39021. */
  39022. Prim2DBase.prototype.traverseUp = function (predicate) {
  39023. var p = this;
  39024. while (p != null) {
  39025. if (predicate(p)) {
  39026. return p;
  39027. }
  39028. p = p._parent;
  39029. }
  39030. return null;
  39031. };
  39032. Object.defineProperty(Prim2DBase.prototype, "owner", {
  39033. /**
  39034. * Retrieve the owner Canvas2D
  39035. */
  39036. get: function () {
  39037. return this._owner;
  39038. },
  39039. enumerable: true,
  39040. configurable: true
  39041. });
  39042. Object.defineProperty(Prim2DBase.prototype, "parent", {
  39043. /**
  39044. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  39045. */
  39046. get: function () {
  39047. return this._parent;
  39048. },
  39049. enumerable: true,
  39050. configurable: true
  39051. });
  39052. Object.defineProperty(Prim2DBase.prototype, "children", {
  39053. /**
  39054. * The array of direct children primitives
  39055. */
  39056. get: function () {
  39057. return this._children;
  39058. },
  39059. enumerable: true,
  39060. configurable: true
  39061. });
  39062. Object.defineProperty(Prim2DBase.prototype, "id", {
  39063. /**
  39064. * The identifier of this primitive, may not be unique, it's for information purpose only
  39065. */
  39066. get: function () {
  39067. return this._id;
  39068. },
  39069. enumerable: true,
  39070. configurable: true
  39071. });
  39072. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  39073. get: function () {
  39074. if (this._actualPosition != null) {
  39075. return this._actualPosition;
  39076. }
  39077. if (this._position != null) {
  39078. return this._position;
  39079. }
  39080. // At least return 0,0, we can't return null on actualPosition
  39081. return Prim2DBase._nullPosition;
  39082. },
  39083. /**
  39084. * DO NOT INVOKE for internal purpose only
  39085. */
  39086. set: function (val) {
  39087. this._actualPosition = val;
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  39093. /**
  39094. * Shortcut to actualPosition.x
  39095. */
  39096. get: function () {
  39097. return this.actualPosition.x;
  39098. },
  39099. enumerable: true,
  39100. configurable: true
  39101. });
  39102. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  39103. /**
  39104. * Shortcut to actualPosition.y
  39105. */
  39106. get: function () {
  39107. return this.actualPosition.y;
  39108. },
  39109. enumerable: true,
  39110. configurable: true
  39111. });
  39112. Object.defineProperty(Prim2DBase.prototype, "position", {
  39113. /**
  39114. * Position of the primitive, relative to its parent.
  39115. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  39116. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  39117. * Setting this property may have no effect is specific alignment are in effect.
  39118. */
  39119. get: function () {
  39120. return this._position || Prim2DBase._nullPosition;
  39121. },
  39122. set: function (value) {
  39123. if (!this._checkPositionChange()) {
  39124. return;
  39125. }
  39126. this._position = value;
  39127. this.markAsDirty("actualPosition");
  39128. },
  39129. enumerable: true,
  39130. configurable: true
  39131. });
  39132. Object.defineProperty(Prim2DBase.prototype, "x", {
  39133. /**
  39134. * Direct access to the position.x value of the primitive
  39135. * Use this property when you only want to change one component of the position property
  39136. */
  39137. get: function () {
  39138. if (!this._position) {
  39139. return null;
  39140. }
  39141. return this._position.x;
  39142. },
  39143. set: function (value) {
  39144. if (!this._checkPositionChange()) {
  39145. return;
  39146. }
  39147. if (!this._position) {
  39148. this._position = BABYLON.Vector2.Zero();
  39149. }
  39150. if (this._position.x === value) {
  39151. return;
  39152. }
  39153. this._position.x = value;
  39154. this.markAsDirty("position");
  39155. this.markAsDirty("actualPosition");
  39156. },
  39157. enumerable: true,
  39158. configurable: true
  39159. });
  39160. Object.defineProperty(Prim2DBase.prototype, "y", {
  39161. /**
  39162. * Direct access to the position.y value of the primitive
  39163. * Use this property when you only want to change one component of the position property
  39164. */
  39165. get: function () {
  39166. if (!this._position) {
  39167. return null;
  39168. }
  39169. return this._position.y;
  39170. },
  39171. set: function (value) {
  39172. if (!this._checkPositionChange()) {
  39173. return;
  39174. }
  39175. if (!this._position) {
  39176. this._position = BABYLON.Vector2.Zero();
  39177. }
  39178. if (this._position.y === value) {
  39179. return;
  39180. }
  39181. this._position.y = value;
  39182. this.markAsDirty("position");
  39183. this.markAsDirty("actualPosition");
  39184. },
  39185. enumerable: true,
  39186. configurable: true
  39187. });
  39188. Object.defineProperty(Prim2DBase.prototype, "size", {
  39189. /**
  39190. * Size of the primitive or its bounding area
  39191. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  39192. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  39193. */
  39194. get: function () {
  39195. if (!this._size || this._size.width == null || this._size.height == null) {
  39196. if (Prim2DBase.boundinbBoxReentrency) {
  39197. return Prim2DBase.nullSize;
  39198. }
  39199. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39200. return this._boundingSize;
  39201. }
  39202. Prim2DBase.boundinbBoxReentrency = true;
  39203. var b = this.boundingInfo;
  39204. Prim2DBase.boundinbBoxReentrency = false;
  39205. return this._boundingSize;
  39206. }
  39207. return this._size;
  39208. },
  39209. set: function (value) {
  39210. this._size = value;
  39211. },
  39212. enumerable: true,
  39213. configurable: true
  39214. });
  39215. Object.defineProperty(Prim2DBase.prototype, "width", {
  39216. /**
  39217. * Direct access to the size.width value of the primitive
  39218. * Use this property when you only want to change one component of the size property
  39219. */
  39220. get: function () {
  39221. if (!this.size) {
  39222. return null;
  39223. }
  39224. return this.size.width;
  39225. },
  39226. set: function (value) {
  39227. if (!this.size) {
  39228. this.size = new BABYLON.Size(value, 0);
  39229. return;
  39230. }
  39231. if (this.size.width === value) {
  39232. return;
  39233. }
  39234. this.size.width = value;
  39235. this.markAsDirty("size");
  39236. this._positioningDirty();
  39237. },
  39238. enumerable: true,
  39239. configurable: true
  39240. });
  39241. Object.defineProperty(Prim2DBase.prototype, "height", {
  39242. /**
  39243. * Direct access to the size.height value of the primitive
  39244. * Use this property when you only want to change one component of the size property
  39245. */
  39246. get: function () {
  39247. if (!this.size) {
  39248. return null;
  39249. }
  39250. return this.size.height;
  39251. },
  39252. set: function (value) {
  39253. if (!this.size) {
  39254. this.size = new BABYLON.Size(0, value);
  39255. return;
  39256. }
  39257. if (this.size.height === value) {
  39258. return;
  39259. }
  39260. this.size.height = value;
  39261. this.markAsDirty("size");
  39262. this._positioningDirty();
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  39268. get: function () {
  39269. return this._rotation;
  39270. },
  39271. set: function (value) {
  39272. this._rotation = value;
  39273. },
  39274. enumerable: true,
  39275. configurable: true
  39276. });
  39277. Object.defineProperty(Prim2DBase.prototype, "scale", {
  39278. get: function () {
  39279. return this._scale;
  39280. },
  39281. set: function (value) {
  39282. this._scale = value;
  39283. },
  39284. enumerable: true,
  39285. configurable: true
  39286. });
  39287. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  39288. /**
  39289. * Return the size of the primitive as it's being rendered into the target.
  39290. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  39291. * BEWARE: don't use the setter, it's for internal purpose only
  39292. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  39293. */
  39294. get: function () {
  39295. if (this._actualSize) {
  39296. return this._actualSize;
  39297. }
  39298. return this._size;
  39299. },
  39300. set: function (value) {
  39301. if (this._actualSize.equals(value)) {
  39302. return;
  39303. }
  39304. this._actualSize = value;
  39305. },
  39306. enumerable: true,
  39307. configurable: true
  39308. });
  39309. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  39310. get: function () {
  39311. if (this._manualZOrder != null) {
  39312. return this._manualZOrder;
  39313. }
  39314. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39315. this._updateZOrder();
  39316. }
  39317. return (1 - this._zOrder);
  39318. },
  39319. enumerable: true,
  39320. configurable: true
  39321. });
  39322. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  39323. /**
  39324. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  39325. * The Primitive's size won't be less than specified.
  39326. * The default value depends of the Primitive type
  39327. */
  39328. get: function () {
  39329. return this._minSize;
  39330. },
  39331. set: function (value) {
  39332. if (this._minSize && value && this._minSize.equals(value)) {
  39333. return;
  39334. }
  39335. this._minSize = value;
  39336. this._parentLayoutDirty();
  39337. },
  39338. enumerable: true,
  39339. configurable: true
  39340. });
  39341. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  39342. /**
  39343. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  39344. * The Primitive's size won't be more than specified.
  39345. * The default value depends of the Primitive type
  39346. */
  39347. get: function () {
  39348. return this._maxSize;
  39349. },
  39350. set: function (value) {
  39351. if (this._maxSize && value && this._maxSize.equals(value)) {
  39352. return;
  39353. }
  39354. this._maxSize = value;
  39355. this._parentLayoutDirty();
  39356. },
  39357. enumerable: true,
  39358. configurable: true
  39359. });
  39360. Object.defineProperty(Prim2DBase.prototype, "origin", {
  39361. /**
  39362. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  39363. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  39364. * For instance:
  39365. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  39366. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  39367. * 0,1 means the center is top/left
  39368. * @returns The normalized center.
  39369. */
  39370. get: function () {
  39371. return this._origin;
  39372. },
  39373. set: function (value) {
  39374. this._origin = value;
  39375. },
  39376. enumerable: true,
  39377. configurable: true
  39378. });
  39379. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  39380. get: function () {
  39381. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  39382. },
  39383. set: function (value) {
  39384. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  39385. },
  39386. enumerable: true,
  39387. configurable: true
  39388. });
  39389. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  39390. get: function () {
  39391. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  39392. },
  39393. set: function (value) {
  39394. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  39400. get: function () {
  39401. return this._manualZOrder;
  39402. },
  39403. set: function (value) {
  39404. if (this._manualZOrder === value) {
  39405. return;
  39406. }
  39407. this._manualZOrder = value;
  39408. this.onZOrderChanged();
  39409. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  39410. this._actualZOrderChangedObservable.notifyObservers(value);
  39411. }
  39412. },
  39413. enumerable: true,
  39414. configurable: true
  39415. });
  39416. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  39417. get: function () {
  39418. return this._manualZOrder != null;
  39419. },
  39420. enumerable: true,
  39421. configurable: true
  39422. });
  39423. Object.defineProperty(Prim2DBase.prototype, "margin", {
  39424. get: function () {
  39425. var _this = this;
  39426. if (!this._margin) {
  39427. this._margin = new PrimitiveThickness(function () {
  39428. if (!_this.parent) {
  39429. return null;
  39430. }
  39431. return _this.parent.margin;
  39432. }, function () { return _this._positioningDirty(); });
  39433. }
  39434. return this._margin;
  39435. },
  39436. enumerable: true,
  39437. configurable: true
  39438. });
  39439. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  39440. get: function () {
  39441. return (this._margin !== null) || (this._marginAlignment !== null);
  39442. },
  39443. enumerable: true,
  39444. configurable: true
  39445. });
  39446. Object.defineProperty(Prim2DBase.prototype, "padding", {
  39447. get: function () {
  39448. var _this = this;
  39449. if (!this._padding) {
  39450. this._padding = new PrimitiveThickness(function () {
  39451. if (!_this.parent) {
  39452. return null;
  39453. }
  39454. return _this.parent.padding;
  39455. }, function () { return _this._positioningDirty(); });
  39456. }
  39457. return this._padding;
  39458. },
  39459. enumerable: true,
  39460. configurable: true
  39461. });
  39462. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  39463. get: function () {
  39464. return this._padding !== null;
  39465. },
  39466. enumerable: true,
  39467. configurable: true
  39468. });
  39469. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  39470. get: function () {
  39471. var _this = this;
  39472. if (!this._marginAlignment) {
  39473. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  39474. }
  39475. return this._marginAlignment;
  39476. },
  39477. enumerable: true,
  39478. configurable: true
  39479. });
  39480. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  39481. get: function () {
  39482. return this._opacity;
  39483. },
  39484. set: function (value) {
  39485. if (value < 0) {
  39486. value = 0;
  39487. }
  39488. else if (value > 1) {
  39489. value = 1;
  39490. }
  39491. if (this._opacity === value) {
  39492. return;
  39493. }
  39494. this._opacity = value;
  39495. this._updateRenderMode();
  39496. this._spreadActualOpacityChanged();
  39497. },
  39498. enumerable: true,
  39499. configurable: true
  39500. });
  39501. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  39502. get: function () {
  39503. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  39504. var cur = this.parent;
  39505. var op = this.opacity;
  39506. while (cur) {
  39507. op *= cur.opacity;
  39508. cur = cur.parent;
  39509. }
  39510. this._actualOpacity = op;
  39511. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39512. }
  39513. return this._actualOpacity;
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  39519. /**
  39520. * Get/set the layout engine to use for this primitive.
  39521. * The default layout engine is the CanvasLayoutEngine.
  39522. */
  39523. get: function () {
  39524. if (!this._layoutEngine) {
  39525. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39526. }
  39527. return this._layoutEngine;
  39528. },
  39529. set: function (value) {
  39530. if (this._layoutEngine === value) {
  39531. return;
  39532. }
  39533. this._changeLayoutEngine(value);
  39534. },
  39535. enumerable: true,
  39536. configurable: true
  39537. });
  39538. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  39539. /**
  39540. * Get/set the layout are of this primitive.
  39541. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  39542. * The setter should only be called by a Layout Engine class.
  39543. */
  39544. get: function () {
  39545. return this._layoutArea;
  39546. },
  39547. set: function (val) {
  39548. if (this._layoutArea.equals(val)) {
  39549. return;
  39550. }
  39551. this._positioningDirty();
  39552. this._layoutArea = val;
  39553. },
  39554. enumerable: true,
  39555. configurable: true
  39556. });
  39557. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  39558. /**
  39559. * Get/set the layout area position (relative to the parent primitive).
  39560. * The setter should only be called by a Layout Engine class.
  39561. */
  39562. get: function () {
  39563. return this._layoutAreaPos;
  39564. },
  39565. set: function (val) {
  39566. if (this._layoutAreaPos.equals(val)) {
  39567. return;
  39568. }
  39569. this._positioningDirty();
  39570. this._layoutAreaPos = val;
  39571. },
  39572. enumerable: true,
  39573. configurable: true
  39574. });
  39575. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  39576. /**
  39577. * Define if the Primitive can be subject to intersection test or not (default is true)
  39578. */
  39579. get: function () {
  39580. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  39581. },
  39582. set: function (value) {
  39583. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  39584. },
  39585. enumerable: true,
  39586. configurable: true
  39587. });
  39588. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  39589. /**
  39590. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  39591. */
  39592. get: function () {
  39593. return this._hierarchyDepth;
  39594. },
  39595. enumerable: true,
  39596. configurable: true
  39597. });
  39598. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  39599. /**
  39600. * Retrieve the Group that is responsible to render this primitive
  39601. */
  39602. get: function () {
  39603. return this._renderGroup;
  39604. },
  39605. enumerable: true,
  39606. configurable: true
  39607. });
  39608. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  39609. /**
  39610. * Get the global transformation matrix of the primitive
  39611. */
  39612. get: function () {
  39613. return this._globalTransform;
  39614. },
  39615. enumerable: true,
  39616. configurable: true
  39617. });
  39618. /**
  39619. * return the global position of the primitive, relative to its canvas
  39620. */
  39621. Prim2DBase.prototype.getGlobalPosition = function () {
  39622. var v = new BABYLON.Vector2(0, 0);
  39623. this.getGlobalPositionByRef(v);
  39624. return v;
  39625. };
  39626. /**
  39627. * return the global position of the primitive, relative to its canvas
  39628. * @param v the valid Vector2 object where the global position will be stored
  39629. */
  39630. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  39631. v.x = this.globalTransform.m[12];
  39632. v.y = this.globalTransform.m[13];
  39633. };
  39634. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  39635. /**
  39636. * Get invert of the global transformation matrix of the primitive
  39637. */
  39638. get: function () {
  39639. return this._invGlobalTransform;
  39640. },
  39641. enumerable: true,
  39642. configurable: true
  39643. });
  39644. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  39645. /**
  39646. * Get the local transformation of the primitive
  39647. */
  39648. get: function () {
  39649. this._updateLocalTransform();
  39650. return this._localTransform;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  39656. /**
  39657. * Get the boundingInfo associated to the primitive and its children.
  39658. * The value is supposed to be always up to date
  39659. */
  39660. get: function () {
  39661. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39662. if (this.owner) {
  39663. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  39664. }
  39665. if (this.isSizedByContent) {
  39666. this._boundingInfo.clear();
  39667. }
  39668. else {
  39669. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  39670. }
  39671. var bi = this._boundingInfo;
  39672. var tps = new BABYLON.BoundingInfo2D();
  39673. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39674. var curChild = _a[_i];
  39675. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  39676. bi.unionToRef(tps, bi);
  39677. }
  39678. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  39679. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  39680. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  39681. }
  39682. return this._boundingInfo;
  39683. },
  39684. enumerable: true,
  39685. configurable: true
  39686. });
  39687. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  39688. /**
  39689. * Determine if the size is automatically computed or fixed because manually specified.
  39690. * Use the actualSize property to get the final/real size of the primitive
  39691. * @returns true if the size is automatically computed, false if it were manually specified.
  39692. */
  39693. get: function () {
  39694. return this._size == null;
  39695. },
  39696. enumerable: true,
  39697. configurable: true
  39698. });
  39699. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  39700. /**
  39701. * Return true if this prim has an auto size which is set by the children's global bounding box
  39702. */
  39703. get: function () {
  39704. return (this._size == null) && (this._children.length > 0);
  39705. },
  39706. enumerable: true,
  39707. configurable: true
  39708. });
  39709. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  39710. /**
  39711. * Determine if the position is automatically computed or fixed because manually specified.
  39712. * Use the actualPosition property to get the final/real position of the primitive
  39713. * @returns true if the position is automatically computed, false if it were manually specified.
  39714. */
  39715. get: function () {
  39716. return this._position == null;
  39717. },
  39718. enumerable: true,
  39719. configurable: true
  39720. });
  39721. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  39722. /**
  39723. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  39724. */
  39725. get: function () {
  39726. return this._pointerEventObservable;
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  39732. get: function () {
  39733. if (!this._actualZOrderChangedObservable) {
  39734. this._actualZOrderChangedObservable = new BABYLON.Observable();
  39735. }
  39736. return this._actualZOrderChangedObservable;
  39737. },
  39738. enumerable: true,
  39739. configurable: true
  39740. });
  39741. Prim2DBase.prototype.findById = function (id) {
  39742. if (this._id === id) {
  39743. return this;
  39744. }
  39745. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39746. var child = _a[_i];
  39747. var r = child.findById(id);
  39748. if (r != null) {
  39749. return r;
  39750. }
  39751. }
  39752. };
  39753. Prim2DBase.prototype.onZOrderChanged = function () {
  39754. };
  39755. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  39756. return false;
  39757. };
  39758. /**
  39759. * Capture all the Events of the given PointerId for this primitive.
  39760. * Don't forget to call releasePointerEventsCapture when done.
  39761. * @param pointerId the Id of the pointer to capture the events from.
  39762. */
  39763. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  39764. return this.owner._setPointerCapture(pointerId, this);
  39765. };
  39766. /**
  39767. * Release a captured pointer made with setPointerEventCapture.
  39768. * @param pointerId the Id of the pointer to release the capture from.
  39769. */
  39770. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  39771. return this.owner._releasePointerCapture(pointerId, this);
  39772. };
  39773. /**
  39774. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  39775. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  39776. */
  39777. Prim2DBase.prototype.intersect = function (intersectInfo) {
  39778. if (!intersectInfo) {
  39779. return false;
  39780. }
  39781. // If this is null it means this method is call for the first level, initialize stuffs
  39782. var firstLevel = !intersectInfo._globalPickPosition;
  39783. if (firstLevel) {
  39784. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  39785. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  39786. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  39787. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  39788. intersectInfo.intersectedPrimitives = new Array();
  39789. intersectInfo.topMostIntersectedPrimitive = null;
  39790. }
  39791. if (!intersectInfo.intersectHidden && !this.isVisible) {
  39792. return false;
  39793. }
  39794. // Fast rejection test with boundingInfo
  39795. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  39796. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  39797. intersectInfo._exit(firstLevel);
  39798. return false;
  39799. }
  39800. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  39801. var levelIntersectRes = false;
  39802. if (this.isPickable) {
  39803. levelIntersectRes = this.levelIntersect(intersectInfo);
  39804. if (levelIntersectRes) {
  39805. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  39806. intersectInfo.intersectedPrimitives.push(pii);
  39807. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  39808. intersectInfo.topMostIntersectedPrimitive = pii;
  39809. }
  39810. // If we must stop at the first intersection, we're done, quit!
  39811. if (intersectInfo.findFirstOnly) {
  39812. intersectInfo._exit(firstLevel);
  39813. return true;
  39814. }
  39815. }
  39816. }
  39817. // Recurse to children if needed
  39818. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  39819. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39820. var curChild = _a[_i];
  39821. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  39822. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  39823. continue;
  39824. }
  39825. // Must compute the localPickLocation for the children level
  39826. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  39827. // If we got an intersection with the child and we only need to find the first one, quit!
  39828. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  39829. intersectInfo._exit(firstLevel);
  39830. return true;
  39831. }
  39832. }
  39833. }
  39834. intersectInfo._exit(firstLevel);
  39835. return intersectInfo.isIntersected;
  39836. };
  39837. Prim2DBase.prototype.moveChild = function (child, previous) {
  39838. if (child.parent !== this) {
  39839. return false;
  39840. }
  39841. var childIndex = this._children.indexOf(child);
  39842. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  39843. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  39844. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39845. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  39846. }
  39847. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  39848. };
  39849. Prim2DBase.prototype.addChild = function (child) {
  39850. child._parent = this;
  39851. this._boundingBoxDirty();
  39852. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39853. if (flat) {
  39854. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39855. child._setZOrder(this._zOrder, true);
  39856. child._zMax = this._zOrder;
  39857. }
  39858. else {
  39859. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39860. }
  39861. var length = this._children.push(child);
  39862. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  39863. };
  39864. /**
  39865. * Dispose the primitive, remove it from its parent.
  39866. */
  39867. Prim2DBase.prototype.dispose = function () {
  39868. if (!_super.prototype.dispose.call(this)) {
  39869. return false;
  39870. }
  39871. if (this._actionManager) {
  39872. this._actionManager.dispose();
  39873. this._actionManager = null;
  39874. }
  39875. // If there's a parent, remove this object from its parent list
  39876. if (this._parent) {
  39877. var i = this._parent._children.indexOf(this);
  39878. if (i !== undefined) {
  39879. this._parent._children.splice(i, 1);
  39880. }
  39881. this._parent = null;
  39882. }
  39883. // Recurse dispose to children
  39884. if (this._children) {
  39885. while (this._children.length > 0) {
  39886. this._children[this._children.length - 1].dispose();
  39887. }
  39888. }
  39889. return true;
  39890. };
  39891. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  39892. if (this._renderGroup) {
  39893. this._renderGroup._addPrimToDirtyList(this);
  39894. }
  39895. };
  39896. Prim2DBase.prototype._needPrepare = function () {
  39897. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  39898. };
  39899. Prim2DBase.prototype._prepareRender = function (context) {
  39900. this._prepareRenderPre(context);
  39901. this._prepareRenderPost(context);
  39902. };
  39903. Prim2DBase.prototype._prepareRenderPre = function (context) {
  39904. };
  39905. Prim2DBase.prototype._prepareRenderPost = function (context) {
  39906. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  39907. if (this instanceof BABYLON.Group2D) {
  39908. var self = this;
  39909. if (self.isRenderableGroup) {
  39910. return;
  39911. }
  39912. }
  39913. // Check if we need to recurse the prepare to children primitives
  39914. // - must have children
  39915. // - the global transform of this level have changed, or
  39916. // - the visible state of primitive has changed
  39917. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  39918. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  39919. this._children.forEach(function (c) {
  39920. // As usual stop the recursion if we meet a renderable group
  39921. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  39922. c._prepareRender(context);
  39923. }
  39924. });
  39925. }
  39926. // Finally reset the dirty flags as we've processed everything
  39927. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39928. this._instanceDirtyFlags = 0;
  39929. };
  39930. Prim2DBase.prototype._canvasPreInit = function (settings) {
  39931. };
  39932. Prim2DBase.CheckParent = function (parent) {
  39933. //if (!Prim2DBase._isCanvasInit && !parent) {
  39934. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  39935. //}
  39936. };
  39937. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  39938. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  39939. var cur = list_1[_i];
  39940. cur.updateCachedStates(recurse);
  39941. }
  39942. };
  39943. Prim2DBase.prototype._parentLayoutDirty = function () {
  39944. if (!this._parent || this._parent.isDisposed) {
  39945. return;
  39946. }
  39947. this._parent._setLayoutDirty();
  39948. };
  39949. Prim2DBase.prototype._setLayoutDirty = function () {
  39950. if (!this.isDirty) {
  39951. this.onPrimBecomesDirty();
  39952. }
  39953. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39954. };
  39955. Prim2DBase.prototype._checkPositionChange = function () {
  39956. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  39957. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  39958. return false;
  39959. }
  39960. return true;
  39961. };
  39962. Prim2DBase.prototype._positioningDirty = function () {
  39963. if (!this.isDirty) {
  39964. this.onPrimBecomesDirty();
  39965. }
  39966. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39967. };
  39968. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  39969. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39970. var child = _a[_i];
  39971. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39972. child._spreadActualOpacityChanged();
  39973. }
  39974. };
  39975. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  39976. this._layoutEngine = engine;
  39977. };
  39978. Prim2DBase.prototype._updateLocalTransform = function () {
  39979. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  39980. if (this.checkPropertiesDirty(tflags)) {
  39981. if (this.owner) {
  39982. this.owner.addupdateLocalTransformCounter(1);
  39983. }
  39984. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  39985. var local;
  39986. var pos = this.position;
  39987. if (this._origin.x === 0 && this._origin.y === 0) {
  39988. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  39989. this._localTransform = local;
  39990. }
  39991. else {
  39992. // -Origin offset
  39993. var as = this.actualSize;
  39994. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  39995. // -Origin * rotation
  39996. rot.toRotationMatrix(Prim2DBase._t1);
  39997. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  39998. // -Origin * rotation * scale
  39999. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  40000. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  40001. // -Origin * rotation * scale * (Origin + Position)
  40002. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  40003. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  40004. }
  40005. this.clearPropertiesDirty(tflags);
  40006. return true;
  40007. }
  40008. return false;
  40009. };
  40010. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  40011. if (this.isDisposed) {
  40012. return;
  40013. }
  40014. this.owner.addCachedGroupRenderCounter(1);
  40015. // Check if the parent is synced
  40016. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  40017. this._parent.updateCachedStates(false);
  40018. }
  40019. // Update Z-Order if needed
  40020. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40021. this._updateZOrder();
  40022. }
  40023. // Update actualSize only if there' not positioning to recompute and the size changed
  40024. // Otherwise positioning will take care of it.
  40025. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40026. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  40027. var size = this.size;
  40028. if (size) {
  40029. if (this.size.width != null) {
  40030. this.actualSize.width = this.size.width;
  40031. }
  40032. if (this.size.height != null) {
  40033. this.actualSize.height = this.size.height;
  40034. }
  40035. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40036. }
  40037. }
  40038. // Check for layout update
  40039. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40040. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  40041. this.owner.addUpdateLayoutCounter(1);
  40042. this._layoutEngine.updateLayout(this);
  40043. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  40044. }
  40045. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40046. var autoContentChanged = false;
  40047. if (this.isSizeAuto) {
  40048. if (!this._lastAutoSizeArea) {
  40049. autoContentChanged = this.size !== null;
  40050. }
  40051. else {
  40052. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  40053. }
  40054. }
  40055. // Check for positioning update
  40056. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  40057. this._updatePositioning();
  40058. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40059. if (sizeDirty) {
  40060. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40061. }
  40062. positioningComputed = true;
  40063. }
  40064. if (positioningComputed && this._parent) {
  40065. this._parentContentArea.copyFrom(this._parent.contentArea);
  40066. }
  40067. // Check if we must update this prim
  40068. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  40069. this.owner.addUpdateGlobalTransformCounter(1);
  40070. var curVisibleState = this.isVisible;
  40071. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  40072. // Detect a change of visibility
  40073. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  40074. // Get/compute the localTransform
  40075. var localDirty = this._updateLocalTransform();
  40076. var parentPaddingChanged = false;
  40077. var parentPaddingOffset = Prim2DBase._v0;
  40078. if (this._parent) {
  40079. parentPaddingOffset = this._parent._paddingOffset;
  40080. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  40081. }
  40082. // Check if there are changes in the parent that will force us to update the global matrix
  40083. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  40084. // Check if we have to update the globalTransform
  40085. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  40086. var globalTransform = this._parent ? this._parent._globalTransform : null;
  40087. var localTransform = void 0;
  40088. Prim2DBase._transMtx.copyFrom(this._localTransform);
  40089. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  40090. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  40091. localTransform = Prim2DBase._transMtx;
  40092. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  40093. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  40094. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  40095. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  40096. }
  40097. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  40098. }
  40099. if (recurse) {
  40100. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40101. var child = _a[_i];
  40102. // Stop the recursion if we meet a renderable group
  40103. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  40104. }
  40105. }
  40106. };
  40107. Prim2DBase.prototype._updatePositioning = function () {
  40108. if (this.owner) {
  40109. this.owner.addUpdatePositioningCounter(1);
  40110. }
  40111. // From this point we assume that the primitive layoutArea is computed and up to date.
  40112. // We know have to :
  40113. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  40114. // 2. Determine the contentArea based on the padding property.
  40115. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  40116. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  40117. if (this.actualSize.width == null) {
  40118. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  40119. }
  40120. if (this.actualSize.height == null) {
  40121. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  40122. }
  40123. }
  40124. // Apply margin
  40125. if (this._hasMargin) {
  40126. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40127. this.actualSize = Prim2DBase._size.clone();
  40128. }
  40129. var isSizeAuto = this.isSizeAuto;
  40130. if (this._hasPadding) {
  40131. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  40132. if (isSizeAuto) {
  40133. var content = this.size.clone();
  40134. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  40135. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40136. this._contentArea.copyFrom(content);
  40137. this.actualSize = Prim2DBase._size.clone();
  40138. // Changing the padding has resize the prim, which forces us to recompute margin again
  40139. if (this._hasMargin) {
  40140. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40141. }
  40142. }
  40143. else {
  40144. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40145. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40146. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40147. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40148. this._paddingOffset.x += Prim2DBase._icPos.x;
  40149. this._paddingOffset.y += Prim2DBase._icPos.y;
  40150. this._contentArea.copyFrom(Prim2DBase._size);
  40151. }
  40152. }
  40153. else {
  40154. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40155. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40156. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40157. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  40158. this._contentArea.copyFrom(Prim2DBase._icArea);
  40159. }
  40160. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  40161. this.actualPosition = aPos;
  40162. if (isSizeAuto) {
  40163. this._lastAutoSizeArea = this.size;
  40164. }
  40165. };
  40166. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  40167. /**
  40168. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  40169. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  40170. */
  40171. get: function () {
  40172. // Check for positioning update
  40173. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  40174. this._updatePositioning();
  40175. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40176. }
  40177. return this._contentArea;
  40178. },
  40179. enumerable: true,
  40180. configurable: true
  40181. });
  40182. Prim2DBase.prototype._patchHierarchy = function (owner) {
  40183. this._owner = owner;
  40184. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  40185. if (this._renderGroup != null) {
  40186. return;
  40187. }
  40188. if (this instanceof BABYLON.Group2D) {
  40189. var group = this;
  40190. group.detectGroupStates();
  40191. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40192. group.owner._registerTrackedNode(this);
  40193. }
  40194. }
  40195. if (this._parent) {
  40196. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  40197. this._parentLayoutDirty();
  40198. }
  40199. // Make sure the prim is in the dirtyList if it should be
  40200. if (this._renderGroup && this.isDirty) {
  40201. var list = this._renderGroup._renderableData._primDirtyList;
  40202. var i = list.indexOf(this);
  40203. if (i === -1) {
  40204. list.push(this);
  40205. }
  40206. }
  40207. // Recurse
  40208. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40209. var child = _a[_i];
  40210. child._hierarchyDepth = this._hierarchyDepth + 1;
  40211. child._patchHierarchy(owner);
  40212. }
  40213. };
  40214. Prim2DBase.prototype._updateZOrder = function () {
  40215. var prevLinPos = this._primLinearPosition;
  40216. var startI = 0;
  40217. var startZ = this._zOrder;
  40218. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  40219. var childrenCount = this._children.length;
  40220. if (this._firstZDirtyIndex > 0) {
  40221. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  40222. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  40223. prevLinPos = prevPrim._primLinearPosition;
  40224. startI = this._firstZDirtyIndex - 1;
  40225. startZ = prevPrim._zOrder;
  40226. }
  40227. }
  40228. var startPos = prevLinPos;
  40229. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  40230. Prim2DBase._totalCount = 0;
  40231. for (var i = startI; i < childrenCount; i++) {
  40232. var child = this._children[i];
  40233. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40234. }
  40235. // Compute the new Z-Order for all the primitives
  40236. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  40237. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  40238. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  40239. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  40240. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  40241. if (Prim2DBase._zRebuildReentrency) {
  40242. var p = this._parent;
  40243. if (p == null) {
  40244. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  40245. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  40246. Prim2DBase._zRebuildReentrency = false;
  40247. return;
  40248. }
  40249. p._firstZDirtyIndex = 0;
  40250. return p._updateZOrder();
  40251. }
  40252. Prim2DBase._zRebuildReentrency = true;
  40253. this._firstZDirtyIndex = 0;
  40254. this._updateZOrder();
  40255. Prim2DBase._zRebuildReentrency = false;
  40256. }
  40257. for (var i = startI; i < childrenCount; i++) {
  40258. var child = this._children[i];
  40259. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  40260. }
  40261. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  40262. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  40263. var p = _a[_i];
  40264. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  40265. }
  40266. Prim2DBase._zOrderChangedNotifList.splice(0);
  40267. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40268. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40269. };
  40270. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  40271. if (this.isManualZOrder) {
  40272. return prevLinPos;
  40273. }
  40274. this._primLinearPosition = ++prevLinPos;
  40275. Prim2DBase._totalCount++;
  40276. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40277. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  40278. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40279. var child = _a[_i];
  40280. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40281. }
  40282. }
  40283. return prevLinPos;
  40284. };
  40285. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  40286. if (this.isManualZOrder) {
  40287. return null;
  40288. }
  40289. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  40290. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40291. this._setZOrder(newZ, false);
  40292. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40293. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40294. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40295. }
  40296. var curZ = newZ;
  40297. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40298. if (isFlat) {
  40299. if (this._children.length > 0) {
  40300. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  40301. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40302. var child = _a[_i];
  40303. child._updatePrimitiveFlatZOrder(this._zOrder);
  40304. }
  40305. }
  40306. }
  40307. else {
  40308. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  40309. var child = _c[_b];
  40310. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  40311. if (r != null) {
  40312. curZ = r;
  40313. }
  40314. }
  40315. }
  40316. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  40317. return curZ;
  40318. };
  40319. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  40320. if (this.isManualZOrder) {
  40321. return;
  40322. }
  40323. this._setZOrder(newZ, false);
  40324. this._zMax = newZ;
  40325. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40326. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40327. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40328. }
  40329. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40330. var child = _a[_i];
  40331. child._updatePrimitiveFlatZOrder(newZ);
  40332. }
  40333. };
  40334. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  40335. if (newZ !== this._zOrder) {
  40336. this._zOrder = newZ;
  40337. if (!this.isDirty) {
  40338. this.onPrimBecomesDirty();
  40339. }
  40340. this.onZOrderChanged();
  40341. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40342. if (directEmit) {
  40343. this._actualZOrderChangedObservable.notifyObservers(newZ);
  40344. }
  40345. else {
  40346. Prim2DBase._zOrderChangedNotifList.push(this);
  40347. }
  40348. }
  40349. }
  40350. };
  40351. Prim2DBase.prototype._updateRenderMode = function () {
  40352. };
  40353. /**
  40354. * This method is used to alter the contentArea of the Primitive before margin is applied.
  40355. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  40356. * @param primSize the current size of the primitive
  40357. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  40358. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  40359. */
  40360. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  40361. initialContentArea.copyFrom(primSize);
  40362. initialContentPosition.x = initialContentPosition.y = 0;
  40363. };
  40364. /**
  40365. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  40366. * Check the Rectangle2D implementation for a concrete application.
  40367. * @param primSize the current size of the primitive
  40368. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  40369. */
  40370. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  40371. newPrimSize.copyFrom(primSize);
  40372. };
  40373. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  40374. Prim2DBase._bigInt = Math.pow(2, 30);
  40375. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  40376. Prim2DBase.boundinbBoxReentrency = false;
  40377. Prim2DBase.nullSize = BABYLON.Size.Zero();
  40378. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  40379. Prim2DBase._isCanvasInit = false;
  40380. Prim2DBase._t0 = new BABYLON.Matrix();
  40381. Prim2DBase._t1 = new BABYLON.Matrix();
  40382. Prim2DBase._t2 = new BABYLON.Matrix();
  40383. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  40384. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  40385. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  40386. Prim2DBase._icArea = BABYLON.Size.Zero();
  40387. Prim2DBase._size = BABYLON.Size.Zero();
  40388. Prim2DBase._zOrderChangedNotifList = new Array();
  40389. Prim2DBase._zRebuildReentrency = false;
  40390. Prim2DBase._totalCount = 0;
  40391. __decorate([
  40392. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  40393. ], Prim2DBase.prototype, "actualPosition", null);
  40394. __decorate([
  40395. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  40396. ], Prim2DBase.prototype, "position", null);
  40397. __decorate([
  40398. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  40399. ], Prim2DBase.prototype, "size", null);
  40400. __decorate([
  40401. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  40402. ], Prim2DBase.prototype, "rotation", null);
  40403. __decorate([
  40404. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  40405. ], Prim2DBase.prototype, "scale", null);
  40406. __decorate([
  40407. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  40408. ], Prim2DBase.prototype, "origin", null);
  40409. __decorate([
  40410. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  40411. ], Prim2DBase.prototype, "levelVisible", null);
  40412. __decorate([
  40413. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  40414. ], Prim2DBase.prototype, "isVisible", null);
  40415. __decorate([
  40416. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  40417. ], Prim2DBase.prototype, "zOrder", null);
  40418. __decorate([
  40419. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  40420. ], Prim2DBase.prototype, "margin", null);
  40421. __decorate([
  40422. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  40423. ], Prim2DBase.prototype, "padding", null);
  40424. __decorate([
  40425. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  40426. ], Prim2DBase.prototype, "marginAlignment", null);
  40427. __decorate([
  40428. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  40429. ], Prim2DBase.prototype, "opacity", null);
  40430. Prim2DBase = __decorate([
  40431. BABYLON.className("Prim2DBase")
  40432. ], Prim2DBase);
  40433. return Prim2DBase;
  40434. }(BABYLON.SmartPropertyPrim));
  40435. BABYLON.Prim2DBase = Prim2DBase;
  40436. })(BABYLON || (BABYLON = {}));
  40437. var BABYLON;
  40438. (function (BABYLON) {
  40439. var GroupInstanceInfo = (function () {
  40440. function GroupInstanceInfo(owner, mrc, partCount) {
  40441. this._partCount = partCount;
  40442. this.owner = owner;
  40443. this.modelRenderCache = mrc;
  40444. this.modelRenderCache.addRef();
  40445. this.partIndexFromId = new BABYLON.StringDictionary();
  40446. this._usedShaderCategories = new Array(partCount);
  40447. this._strides = new Array(partCount);
  40448. this._opaqueData = null;
  40449. this._alphaTestData = null;
  40450. this._transparentData = null;
  40451. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  40452. }
  40453. GroupInstanceInfo.prototype.dispose = function () {
  40454. if (this._isDisposed) {
  40455. return false;
  40456. }
  40457. if (this.modelRenderCache) {
  40458. this.modelRenderCache.dispose();
  40459. }
  40460. var engine = this.owner.owner.engine;
  40461. if (this.opaqueData) {
  40462. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  40463. this.opaqueData = null;
  40464. }
  40465. this.partIndexFromId = null;
  40466. this._isDisposed = true;
  40467. return true;
  40468. };
  40469. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  40470. get: function () {
  40471. return this._opaqueData != null;
  40472. },
  40473. enumerable: true,
  40474. configurable: true
  40475. });
  40476. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  40477. get: function () {
  40478. return this._alphaTestData != null;
  40479. },
  40480. enumerable: true,
  40481. configurable: true
  40482. });
  40483. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  40484. get: function () {
  40485. return this._transparentData != null;
  40486. },
  40487. enumerable: true,
  40488. configurable: true
  40489. });
  40490. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  40491. get: function () {
  40492. if (!this._opaqueData) {
  40493. this._opaqueData = new Array(this._partCount);
  40494. for (var i = 0; i < this._partCount; i++) {
  40495. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  40496. }
  40497. }
  40498. return this._opaqueData;
  40499. },
  40500. enumerable: true,
  40501. configurable: true
  40502. });
  40503. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  40504. get: function () {
  40505. if (!this._alphaTestData) {
  40506. this._alphaTestData = new Array(this._partCount);
  40507. for (var i = 0; i < this._partCount; i++) {
  40508. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  40509. }
  40510. }
  40511. return this._alphaTestData;
  40512. },
  40513. enumerable: true,
  40514. configurable: true
  40515. });
  40516. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  40517. get: function () {
  40518. if (!this._transparentData) {
  40519. this._transparentData = new Array(this._partCount);
  40520. for (var i = 0; i < this._partCount; i++) {
  40521. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  40522. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  40523. }
  40524. }
  40525. return this._transparentData;
  40526. },
  40527. enumerable: true,
  40528. configurable: true
  40529. });
  40530. GroupInstanceInfo.prototype.sortTransparentData = function () {
  40531. if (!this.transparentOrderDirty) {
  40532. return;
  40533. }
  40534. for (var i = 0; i < this._transparentData.length; i++) {
  40535. var td = this._transparentData[i];
  40536. td._partData.sort();
  40537. }
  40538. this.transparentOrderDirty = false;
  40539. };
  40540. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  40541. get: function () {
  40542. return this._usedShaderCategories;
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  40548. get: function () {
  40549. return this._strides;
  40550. },
  40551. enumerable: true,
  40552. configurable: true
  40553. });
  40554. return GroupInstanceInfo;
  40555. }());
  40556. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  40557. var TransparentSegment = (function () {
  40558. function TransparentSegment() {
  40559. this.groupInsanceInfo = null;
  40560. this.startZ = 0;
  40561. this.endZ = 0;
  40562. this.startDataIndex = 0;
  40563. this.endDataIndex = 0;
  40564. this.partBuffers = null;
  40565. }
  40566. TransparentSegment.prototype.dispose = function (engine) {
  40567. if (this.partBuffers) {
  40568. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  40569. this.partBuffers.splice(0);
  40570. this.partBuffers = null;
  40571. }
  40572. };
  40573. return TransparentSegment;
  40574. }());
  40575. BABYLON.TransparentSegment = TransparentSegment;
  40576. var GroupInfoPartData = (function () {
  40577. function GroupInfoPartData(stride) {
  40578. this._partData = null;
  40579. this._partBuffer = null;
  40580. this._partBufferSize = 0;
  40581. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  40582. this._isDisposed = false;
  40583. }
  40584. GroupInfoPartData.prototype.dispose = function (engine) {
  40585. if (this._isDisposed) {
  40586. return false;
  40587. }
  40588. if (this._partBuffer) {
  40589. engine._releaseBuffer(this._partBuffer);
  40590. this._partBuffer = null;
  40591. }
  40592. this._partData = null;
  40593. this._isDisposed = true;
  40594. };
  40595. return GroupInfoPartData;
  40596. }());
  40597. BABYLON.GroupInfoPartData = GroupInfoPartData;
  40598. var TransparentGroupInfoPartData = (function (_super) {
  40599. __extends(TransparentGroupInfoPartData, _super);
  40600. function TransparentGroupInfoPartData(stride, zoff) {
  40601. _super.call(this, stride);
  40602. this._partData.compareValueOffset = zoff;
  40603. this._partData.sortingAscending = false;
  40604. }
  40605. return TransparentGroupInfoPartData;
  40606. }(GroupInfoPartData));
  40607. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  40608. var ModelRenderCache = (function () {
  40609. function ModelRenderCache(engine, modelKey) {
  40610. this._engine = engine;
  40611. this._modelKey = modelKey;
  40612. this._nextKey = 1;
  40613. this._refCounter = 1;
  40614. this._instancesData = new BABYLON.StringDictionary();
  40615. this._partData = null;
  40616. }
  40617. ModelRenderCache.prototype.dispose = function () {
  40618. if (--this._refCounter !== 0) {
  40619. return false;
  40620. }
  40621. // Remove the Model Render Cache from the global dictionary
  40622. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  40623. if (edata) {
  40624. edata.DisposeModelRenderCache(this);
  40625. }
  40626. return true;
  40627. };
  40628. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  40629. get: function () {
  40630. return this._refCounter <= 0;
  40631. },
  40632. enumerable: true,
  40633. configurable: true
  40634. });
  40635. ModelRenderCache.prototype.addRef = function () {
  40636. return ++this._refCounter;
  40637. };
  40638. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  40639. get: function () {
  40640. return this._modelKey;
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. /**
  40646. * Render the model instances
  40647. * @param instanceInfo
  40648. * @param context
  40649. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  40650. */
  40651. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  40652. return true;
  40653. };
  40654. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  40655. var key = this._nextKey.toString();
  40656. if (!this._instancesData.add(key, data)) {
  40657. throw Error("Key: " + key + " is already allocated");
  40658. }
  40659. ++this._nextKey;
  40660. return key;
  40661. };
  40662. ModelRenderCache.prototype.removeInstanceData = function (key) {
  40663. this._instancesData.remove(key);
  40664. };
  40665. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  40666. for (var i = 0; i < this._partData.length; i++) {
  40667. if (this._partData[i]._partId === partId) {
  40668. return i;
  40669. }
  40670. }
  40671. return null;
  40672. };
  40673. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  40674. var i = this.getPartIndexFromId(partId);
  40675. if (i === null) {
  40676. return null;
  40677. }
  40678. var ci = this._partsClassInfo[i];
  40679. var categories = this._partData[i]._partUsedCategories;
  40680. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  40681. return res;
  40682. };
  40683. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  40684. var pd = this._partData[partIndex];
  40685. var offset = (pd._partDataStride / 4) * elementCount;
  40686. var pci = this._partsClassInfo[partIndex];
  40687. var self = this;
  40688. pci.fullContent.forEach(function (k, v) {
  40689. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  40690. switch (v.dataType) {
  40691. case 4 /* float */:
  40692. {
  40693. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40694. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  40695. break;
  40696. }
  40697. case 0 /* Vector2 */:
  40698. {
  40699. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40700. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  40701. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  40702. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  40703. break;
  40704. }
  40705. case 5 /* Color3 */:
  40706. case 1 /* Vector3 */:
  40707. {
  40708. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40709. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  40710. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  40711. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  40712. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  40713. break;
  40714. }
  40715. case 6 /* Color4 */:
  40716. case 2 /* Vector4 */:
  40717. {
  40718. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40719. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  40720. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  40721. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  40722. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  40723. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  40724. break;
  40725. }
  40726. default:
  40727. }
  40728. }
  40729. });
  40730. };
  40731. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  40732. // let i = this.getPartIndexFromId(partId);
  40733. // if (i === null) {
  40734. // return null;
  40735. // }
  40736. // let pci = this._partsClassInfo[i];
  40737. // pci.fullContent.forEach((k, v) => {
  40738. // if (uniforms.indexOf(v.attributeName) !== -1) {
  40739. // v.uniformLocation = effect.getUniform(v.attributeName);
  40740. // }
  40741. // });
  40742. //}
  40743. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  40744. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  40745. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  40746. return ModelRenderCache;
  40747. }());
  40748. BABYLON.ModelRenderCache = ModelRenderCache;
  40749. var ModelRenderCachePartData = (function () {
  40750. function ModelRenderCachePartData() {
  40751. }
  40752. return ModelRenderCachePartData;
  40753. }());
  40754. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  40755. })(BABYLON || (BABYLON = {}));
  40756. var BABYLON;
  40757. (function (BABYLON) {
  40758. var InstanceClassInfo = (function () {
  40759. function InstanceClassInfo(base) {
  40760. this._baseInfo = base;
  40761. this._nextOffset = new BABYLON.StringDictionary();
  40762. this._attributes = new Array();
  40763. }
  40764. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  40765. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  40766. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  40767. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  40768. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  40769. if (push) {
  40770. this._attributes.push(propInfo);
  40771. }
  40772. };
  40773. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  40774. var catInline = ";" + categories.join(";") + ";";
  40775. var res = new Array();
  40776. var curInfo = this;
  40777. while (curInfo) {
  40778. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40779. var attrib = _a[_i];
  40780. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  40781. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40782. var index = effect.getAttributeLocationByName(attrib.attributeName);
  40783. var iai = new BABYLON.InstancingAttributeInfo();
  40784. iai.index = index;
  40785. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  40786. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  40787. iai.attributeName = attrib.attributeName;
  40788. res.push(iai);
  40789. }
  40790. }
  40791. curInfo = curInfo._baseInfo;
  40792. }
  40793. return res;
  40794. };
  40795. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  40796. var res = new Array();
  40797. var curInfo = this;
  40798. while (curInfo) {
  40799. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40800. var attrib = _a[_i];
  40801. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  40802. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40803. res.push(attrib.attributeName);
  40804. }
  40805. }
  40806. curInfo = curInfo._baseInfo;
  40807. }
  40808. return res;
  40809. };
  40810. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  40811. var curOffset = 0;
  40812. var curBase = this._baseInfo;
  40813. while (curBase) {
  40814. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  40815. curBase = curBase._baseInfo;
  40816. }
  40817. return curOffset;
  40818. };
  40819. return InstanceClassInfo;
  40820. }());
  40821. BABYLON.InstanceClassInfo = InstanceClassInfo;
  40822. var InstancePropInfo = (function () {
  40823. function InstancePropInfo() {
  40824. this.instanceOffset = new BABYLON.StringDictionary();
  40825. }
  40826. InstancePropInfo.prototype.setSize = function (val) {
  40827. if (val instanceof BABYLON.Vector2) {
  40828. this.size = 8;
  40829. this.dataType = 0 /* Vector2 */;
  40830. return;
  40831. }
  40832. if (val instanceof BABYLON.Vector3) {
  40833. this.size = 12;
  40834. this.dataType = 1 /* Vector3 */;
  40835. return;
  40836. }
  40837. if (val instanceof BABYLON.Vector4) {
  40838. this.size = 16;
  40839. this.dataType = 2 /* Vector4 */;
  40840. return;
  40841. }
  40842. if (val instanceof BABYLON.Matrix) {
  40843. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  40844. }
  40845. if (typeof (val) === "number") {
  40846. this.size = 4;
  40847. this.dataType = 4 /* float */;
  40848. return;
  40849. }
  40850. if (val instanceof BABYLON.Color3) {
  40851. this.size = 12;
  40852. this.dataType = 5 /* Color3 */;
  40853. return;
  40854. }
  40855. if (val instanceof BABYLON.Color4) {
  40856. this.size = 16;
  40857. this.dataType = 6 /* Color4 */;
  40858. return;
  40859. }
  40860. if (val instanceof BABYLON.Size) {
  40861. this.size = 8;
  40862. this.dataType = 7 /* Size */;
  40863. return;
  40864. }
  40865. return;
  40866. };
  40867. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  40868. switch (this.dataType) {
  40869. case 0 /* Vector2 */:
  40870. {
  40871. var v = val;
  40872. array[offset + 0] = v.x;
  40873. array[offset + 1] = v.y;
  40874. break;
  40875. }
  40876. case 1 /* Vector3 */:
  40877. {
  40878. var v = val;
  40879. array[offset + 0] = v.x;
  40880. array[offset + 1] = v.y;
  40881. array[offset + 2] = v.z;
  40882. break;
  40883. }
  40884. case 2 /* Vector4 */:
  40885. {
  40886. var v = val;
  40887. array[offset + 0] = v.x;
  40888. array[offset + 1] = v.y;
  40889. array[offset + 2] = v.z;
  40890. array[offset + 3] = v.w;
  40891. break;
  40892. }
  40893. case 5 /* Color3 */:
  40894. {
  40895. var v = val;
  40896. array[offset + 0] = v.r;
  40897. array[offset + 1] = v.g;
  40898. array[offset + 2] = v.b;
  40899. break;
  40900. }
  40901. case 6 /* Color4 */:
  40902. {
  40903. var v = val;
  40904. array[offset + 0] = v.r;
  40905. array[offset + 1] = v.g;
  40906. array[offset + 2] = v.b;
  40907. array[offset + 3] = v.a;
  40908. break;
  40909. }
  40910. case 4 /* float */:
  40911. {
  40912. var v = val;
  40913. array[offset] = v;
  40914. break;
  40915. }
  40916. case 3 /* Matrix */:
  40917. {
  40918. var v = val;
  40919. for (var i = 0; i < 16; i++) {
  40920. array[offset + i] = v.m[i];
  40921. }
  40922. break;
  40923. }
  40924. case 7 /* Size */:
  40925. {
  40926. var s = val;
  40927. array[offset + 0] = s.width;
  40928. array[offset + 1] = s.height;
  40929. break;
  40930. }
  40931. }
  40932. };
  40933. return InstancePropInfo;
  40934. }());
  40935. BABYLON.InstancePropInfo = InstancePropInfo;
  40936. function instanceData(category, shaderAttributeName) {
  40937. return function (target, propName, descriptor) {
  40938. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  40939. var node = dic.getLevelOf(target);
  40940. var instanceDataName = propName;
  40941. shaderAttributeName = shaderAttributeName || instanceDataName;
  40942. var info = node.levelContent.get(instanceDataName);
  40943. if (info) {
  40944. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  40945. }
  40946. info = new InstancePropInfo();
  40947. info.attributeName = shaderAttributeName;
  40948. info.category = category || null;
  40949. if (info.category) {
  40950. info.delimitedCategory = ";" + info.category + ";";
  40951. }
  40952. node.levelContent.add(instanceDataName, info);
  40953. descriptor.get = function () {
  40954. return null;
  40955. };
  40956. descriptor.set = function (val) {
  40957. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  40958. // Quit if it's the case, otherwise we could overwrite data somewhere...
  40959. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  40960. return;
  40961. }
  40962. if (!info.size) {
  40963. info.setSize(val);
  40964. node.classContent.mapProperty(info, true);
  40965. }
  40966. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  40967. node.classContent.mapProperty(info, false);
  40968. }
  40969. var obj = this;
  40970. if (obj.dataBuffer && obj.dataElements) {
  40971. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  40972. info.writeData(obj.dataBuffer.buffer, offset, val);
  40973. }
  40974. };
  40975. };
  40976. }
  40977. BABYLON.instanceData = instanceData;
  40978. var InstanceDataBase = (function () {
  40979. function InstanceDataBase(partId, dataElementCount) {
  40980. this.id = partId;
  40981. this.curElement = 0;
  40982. this.dataElementCount = dataElementCount;
  40983. this.renderMode = 0;
  40984. this.arrayLengthChanged = false;
  40985. }
  40986. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  40987. get: function () {
  40988. return null;
  40989. },
  40990. enumerable: true,
  40991. configurable: true
  40992. });
  40993. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  40994. get: function () {
  40995. return null;
  40996. },
  40997. enumerable: true,
  40998. configurable: true
  40999. });
  41000. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  41001. get: function () {
  41002. return null;
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  41008. get: function () {
  41009. return null;
  41010. },
  41011. enumerable: true,
  41012. configurable: true
  41013. });
  41014. InstanceDataBase.prototype.getClassTreeInfo = function () {
  41015. if (!this.typeInfo) {
  41016. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  41017. }
  41018. return this.typeInfo;
  41019. };
  41020. InstanceDataBase.prototype.allocElements = function () {
  41021. if (!this.dataBuffer) {
  41022. return;
  41023. }
  41024. var res = new Array(this.dataElementCount);
  41025. for (var i = 0; i < this.dataElementCount; i++) {
  41026. res[i] = this.dataBuffer.allocElement();
  41027. }
  41028. this.dataElements = res;
  41029. };
  41030. InstanceDataBase.prototype.freeElements = function () {
  41031. if (!this.dataElements) {
  41032. return;
  41033. }
  41034. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  41035. var ei = _a[_i];
  41036. this.dataBuffer.freeElement(ei);
  41037. }
  41038. this.dataElements = null;
  41039. };
  41040. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  41041. get: function () {
  41042. return this._dataElementCount;
  41043. },
  41044. set: function (value) {
  41045. if (value === this._dataElementCount) {
  41046. return;
  41047. }
  41048. this.arrayLengthChanged = true;
  41049. this.freeElements();
  41050. this._dataElementCount = value;
  41051. this.allocElements();
  41052. },
  41053. enumerable: true,
  41054. configurable: true
  41055. });
  41056. __decorate([
  41057. instanceData()
  41058. ], InstanceDataBase.prototype, "zBias", null);
  41059. __decorate([
  41060. instanceData()
  41061. ], InstanceDataBase.prototype, "transformX", null);
  41062. __decorate([
  41063. instanceData()
  41064. ], InstanceDataBase.prototype, "transformY", null);
  41065. __decorate([
  41066. instanceData()
  41067. ], InstanceDataBase.prototype, "opacity", null);
  41068. return InstanceDataBase;
  41069. }());
  41070. BABYLON.InstanceDataBase = InstanceDataBase;
  41071. var RenderablePrim2D = (function (_super) {
  41072. __extends(RenderablePrim2D, _super);
  41073. function RenderablePrim2D(settings) {
  41074. _super.call(this, settings);
  41075. this._isTransparent = false;
  41076. this._isAlphaTest = false;
  41077. this._transparentPrimitiveInfo = null;
  41078. }
  41079. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  41080. get: function () {
  41081. return this._isAlphaTest;
  41082. },
  41083. set: function (value) {
  41084. if (this._isAlphaTest === value) {
  41085. return;
  41086. }
  41087. this._isAlphaTest = value;
  41088. this._updateRenderMode();
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  41094. get: function () {
  41095. return this._isTransparent || (this._opacity < 1);
  41096. },
  41097. set: function (value) {
  41098. if (this._isTransparent === value) {
  41099. return;
  41100. }
  41101. this._isTransparent = value;
  41102. this._updateRenderMode();
  41103. },
  41104. enumerable: true,
  41105. configurable: true
  41106. });
  41107. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  41108. get: function () {
  41109. return this._renderMode;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. /**
  41115. * Dispose the primitive and its resources, remove it from its parent
  41116. */
  41117. RenderablePrim2D.prototype.dispose = function () {
  41118. if (!_super.prototype.dispose.call(this)) {
  41119. return false;
  41120. }
  41121. if (this._transparentPrimitiveInfo) {
  41122. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41123. this._transparentPrimitiveInfo = null;
  41124. }
  41125. if (this._modelRenderInstanceID) {
  41126. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41127. this._modelRenderInstanceID = null;
  41128. }
  41129. if (this._modelRenderCache) {
  41130. this._modelRenderCache.dispose();
  41131. this._modelRenderCache = null;
  41132. }
  41133. if (this._instanceDataParts) {
  41134. this._instanceDataParts.forEach(function (p) {
  41135. p.freeElements();
  41136. });
  41137. this._instanceDataParts = null;
  41138. }
  41139. return true;
  41140. };
  41141. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  41142. _super.prototype._prepareRenderPre.call(this, context);
  41143. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  41144. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  41145. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41146. this._modelRenderInstanceID = null;
  41147. }
  41148. // Need to create the model?
  41149. var setupModelRenderCache = false;
  41150. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  41151. setupModelRenderCache = this._createModelRenderCache();
  41152. }
  41153. var gii = null;
  41154. var newInstance = false;
  41155. // Need to create the instance data parts?
  41156. if (!this._modelRenderInstanceID) {
  41157. // Yes, flag it for later, more processing will have to be done
  41158. newInstance = true;
  41159. gii = this._createModelDataParts();
  41160. }
  41161. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  41162. if (setupModelRenderCache) {
  41163. this.setupModelRenderCache(this._modelRenderCache);
  41164. }
  41165. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  41166. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  41167. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  41168. this._updateInstanceDataParts(gii);
  41169. }
  41170. };
  41171. RenderablePrim2D.prototype._createModelRenderCache = function () {
  41172. var _this = this;
  41173. var setupModelRenderCache = false;
  41174. if (this._modelRenderCache) {
  41175. this._modelRenderCache.dispose();
  41176. }
  41177. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  41178. var mrc = _this.createModelRenderCache(key);
  41179. setupModelRenderCache = true;
  41180. return mrc;
  41181. });
  41182. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41183. // if this is still false it means the MRC already exists, so we add a reference to it
  41184. if (!setupModelRenderCache) {
  41185. this._modelRenderCache.addRef();
  41186. }
  41187. return setupModelRenderCache;
  41188. };
  41189. RenderablePrim2D.prototype._createModelDataParts = function () {
  41190. var _this = this;
  41191. // Create the instance data parts of the primitive and store them
  41192. var parts = this.createInstanceDataParts();
  41193. this._instanceDataParts = parts;
  41194. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  41195. if (!this._modelRenderCache._partData) {
  41196. this._setupModelRenderCache(parts);
  41197. }
  41198. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  41199. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  41200. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  41201. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  41202. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  41203. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  41204. var part = _this._instanceDataParts[j];
  41205. res.partIndexFromId.add(part.id.toString(), j);
  41206. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  41207. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  41208. }
  41209. return res;
  41210. });
  41211. // Get the GroupInfoDataPart corresponding to the render category of the part
  41212. var rm = 0;
  41213. var gipd = null;
  41214. if (this.isTransparent) {
  41215. gipd = gii.transparentData;
  41216. rm = BABYLON.Render2DContext.RenderModeTransparent;
  41217. }
  41218. else if (this.isAlphaTest) {
  41219. gipd = gii.alphaTestData;
  41220. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  41221. }
  41222. else {
  41223. gipd = gii.opaqueData;
  41224. rm = BABYLON.Render2DContext.RenderModeOpaque;
  41225. }
  41226. // For each instance data part of the primitive, allocate the instanced element it needs for render
  41227. for (var i = 0; i < parts.length; i++) {
  41228. var part = parts[i];
  41229. part.dataBuffer = gipd[i]._partData;
  41230. part.allocElements();
  41231. part.renderMode = rm;
  41232. }
  41233. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  41234. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  41235. return gii;
  41236. };
  41237. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  41238. var ctiArray = new Array();
  41239. this._modelRenderCache._partData = new Array();
  41240. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  41241. var dataPart = parts_1[_i];
  41242. var pd = new BABYLON.ModelRenderCachePartData();
  41243. this._modelRenderCache._partData.push(pd);
  41244. var cat = this.getUsedShaderCategories(dataPart);
  41245. var cti = dataPart.getClassTreeInfo();
  41246. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  41247. var curVisible = this.isVisible;
  41248. this.isVisible = true;
  41249. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  41250. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  41251. var joinCat = ";" + cat.join(";") + ";";
  41252. pd._partJoinedUsedCategories = joinCat;
  41253. InstanceClassInfo._CurCategories = joinCat;
  41254. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  41255. if (!this.refreshInstanceDataPart(dataPart)) {
  41256. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  41257. }
  41258. this.afterRefreshForLayoutConstruction(dataPart, obj);
  41259. this.isVisible = curVisible;
  41260. var size = 0;
  41261. cti.fullContent.forEach(function (k, v) {
  41262. if (!v.category || cat.indexOf(v.category) !== -1) {
  41263. if (v.attributeName === "zBias") {
  41264. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  41265. }
  41266. if (!v.size) {
  41267. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  41268. }
  41269. else {
  41270. size += v.size;
  41271. }
  41272. }
  41273. });
  41274. pd._partDataStride = size;
  41275. pd._partUsedCategories = cat;
  41276. pd._partId = dataPart.id;
  41277. ctiArray.push(cti);
  41278. }
  41279. this._modelRenderCache._partsClassInfo = ctiArray;
  41280. };
  41281. RenderablePrim2D.prototype.onZOrderChanged = function () {
  41282. if (this.isTransparent && this._transparentPrimitiveInfo) {
  41283. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  41284. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  41285. // Flag the transparentData dirty has will have to sort it again
  41286. gii.transparentOrderDirty = true;
  41287. }
  41288. };
  41289. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  41290. // Fetch the GroupInstanceInfo if we don't already have it
  41291. var rd = this.renderGroup._renderableData;
  41292. if (!gii) {
  41293. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  41294. }
  41295. var isTransparent = this.isTransparent;
  41296. var isAlphaTest = this.isAlphaTest;
  41297. var wereTransparent = false;
  41298. // Check a render mode change
  41299. var rmChanged = false;
  41300. if (this._instanceDataParts.length > 0) {
  41301. var firstPart = this._instanceDataParts[0];
  41302. var partRM = firstPart.renderMode;
  41303. var curRM = this.renderMode;
  41304. if (partRM !== curRM) {
  41305. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  41306. rmChanged = true;
  41307. var gipd = void 0;
  41308. switch (curRM) {
  41309. case BABYLON.Render2DContext.RenderModeTransparent:
  41310. gipd = gii.transparentData;
  41311. break;
  41312. case BABYLON.Render2DContext.RenderModeAlphaTest:
  41313. gipd = gii.alphaTestData;
  41314. break;
  41315. default:
  41316. gipd = gii.opaqueData;
  41317. }
  41318. for (var i = 0; i < this._instanceDataParts.length; i++) {
  41319. var part = this._instanceDataParts[i];
  41320. part.freeElements();
  41321. part.dataBuffer = gipd[i]._partData;
  41322. part.renderMode = curRM;
  41323. }
  41324. }
  41325. }
  41326. // Handle changes related to ZOffset
  41327. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  41328. if (isTransparent || wereTransparent) {
  41329. // Handle visibility change, which is also triggered when the primitive just got created
  41330. if (visChanged || rmChanged) {
  41331. if (this.isVisible && !wereTransparent) {
  41332. if (!this._transparentPrimitiveInfo) {
  41333. // Add the primitive to the list of transparent ones in the group that render is
  41334. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  41335. }
  41336. }
  41337. else {
  41338. if (this._transparentPrimitiveInfo) {
  41339. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41340. this._transparentPrimitiveInfo = null;
  41341. }
  41342. }
  41343. gii.transparentOrderDirty = true;
  41344. }
  41345. }
  41346. var rebuildTrans = false;
  41347. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  41348. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41349. var part = _a[_i];
  41350. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  41351. if (visChanged || !part.dataElements || rmChanged) {
  41352. part.allocElements();
  41353. }
  41354. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  41355. // Will return false if the instance should not be rendered (not visible or other any reasons)
  41356. part.arrayLengthChanged = false;
  41357. if (!this.refreshInstanceDataPart(part)) {
  41358. // Free the data element
  41359. if (part.dataElements) {
  41360. part.freeElements();
  41361. }
  41362. }
  41363. rebuildTrans = rebuildTrans || part.arrayLengthChanged;
  41364. }
  41365. this._instanceDirtyFlags = 0;
  41366. // Make the appropriate data dirty
  41367. if (isTransparent) {
  41368. gii.transparentDirty = true;
  41369. if (rebuildTrans) {
  41370. rd._transparentListChanged = true;
  41371. }
  41372. }
  41373. else if (isAlphaTest) {
  41374. gii.alphaTestDirty = true;
  41375. }
  41376. else {
  41377. gii.opaqueDirty = true;
  41378. }
  41379. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  41380. };
  41381. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  41382. var minOff = BABYLON.Prim2DBase._bigInt;
  41383. var maxOff = 0;
  41384. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41385. var part = _a[_i];
  41386. if (part) {
  41387. part.dataBuffer.pack();
  41388. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41389. var el = _c[_b];
  41390. minOff = Math.min(minOff, el.offset);
  41391. maxOff = Math.max(maxOff, el.offset);
  41392. }
  41393. ts.startDataIndex = minOff / part.dataBuffer.stride;
  41394. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41395. }
  41396. }
  41397. };
  41398. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  41399. var maxOff = 0;
  41400. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41401. var part = _a[_i];
  41402. if (part) {
  41403. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41404. var el = _c[_b];
  41405. maxOff = Math.max(maxOff, el.offset);
  41406. }
  41407. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41408. }
  41409. }
  41410. };
  41411. // This internal method is mainly used for transparency processing
  41412. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  41413. var length = this._instanceDataParts.length;
  41414. for (var i = 0; i < length; i++) {
  41415. var part = this._instanceDataParts[i];
  41416. if (part) {
  41417. var stride = part.dataBuffer.stride;
  41418. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  41419. // check if it's the last in the DFA
  41420. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  41421. return null;
  41422. }
  41423. // Return the Z of the next primitive that lies in the DFA
  41424. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41425. }
  41426. }
  41427. return null;
  41428. };
  41429. // This internal method is mainly used for transparency processing
  41430. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  41431. var length = this._instanceDataParts.length;
  41432. for (var i = 0; i < length; i++) {
  41433. var part = this._instanceDataParts[i];
  41434. if (part) {
  41435. var stride = part.dataBuffer.stride;
  41436. var firstElementOffset = part.dataElements[0].offset;
  41437. // check if it's the first in the DFA
  41438. if (firstElementOffset === 0) {
  41439. return null;
  41440. }
  41441. // Return the Z of the previous primitive that lies in the DFA
  41442. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41443. }
  41444. }
  41445. return null;
  41446. };
  41447. /**
  41448. * Transform a given point using the Primitive's origin setting.
  41449. * This method requires the Primitive's actualSize to be accurate
  41450. * @param p the point to transform
  41451. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  41452. * @param res an allocated Vector2 that will receive the transformed content
  41453. */
  41454. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  41455. var actualSize = this.actualSize;
  41456. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  41457. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  41458. };
  41459. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  41460. this.transformPointWithOriginByRef(p, originOffset, res);
  41461. return res;
  41462. };
  41463. /**
  41464. * Get the info for a given effect based on the dataPart metadata
  41465. * @param dataPartId partId in part list to get the info
  41466. * @param vertexBufferAttributes vertex buffer attributes to manually add
  41467. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  41468. */
  41469. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  41470. if (useInstanced === void 0) { useInstanced = null; }
  41471. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  41472. if (!dataPart) {
  41473. return null;
  41474. }
  41475. var instancedArray = this.owner.supportInstancedArray;
  41476. if (useInstanced != null) {
  41477. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  41478. if (useInstanced && instancedArray === false) {
  41479. return null;
  41480. }
  41481. // Use the caller's setting
  41482. instancedArray = useInstanced;
  41483. }
  41484. var cti = dataPart.getClassTreeInfo();
  41485. var categories = this.getUsedShaderCategories(dataPart);
  41486. var att = cti.classContent.getShaderAttributes(categories);
  41487. var defines = "";
  41488. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  41489. if (instancedArray) {
  41490. defines += "#define Instanced\n";
  41491. }
  41492. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  41493. };
  41494. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  41495. get: function () {
  41496. return this._modelRenderCache;
  41497. },
  41498. enumerable: true,
  41499. configurable: true
  41500. });
  41501. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  41502. return null;
  41503. };
  41504. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41505. };
  41506. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  41507. return null;
  41508. };
  41509. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  41510. return [];
  41511. };
  41512. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  41513. };
  41514. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  41515. };
  41516. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  41517. if (!this.isVisible) {
  41518. return false;
  41519. }
  41520. part.isVisible = this.isVisible;
  41521. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  41522. if (part.dataElementCount === 1) {
  41523. part.curElement = 0;
  41524. this.updateInstanceDataPart(part);
  41525. }
  41526. return true;
  41527. };
  41528. /**
  41529. * Update the instanceDataBase level properties of a part
  41530. * @param part the part to update
  41531. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  41532. */
  41533. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  41534. if (positionOffset === void 0) { positionOffset = null; }
  41535. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  41536. var size = this.renderGroup.viewportSize;
  41537. var zBias = this.actualZOffset;
  41538. var offX = 0;
  41539. var offY = 0;
  41540. // If there's an offset, apply the global transformation matrix on it to get a global offset
  41541. if (positionOffset) {
  41542. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  41543. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  41544. }
  41545. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  41546. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  41547. // So for X:
  41548. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  41549. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  41550. var w = size.width;
  41551. var h = size.height;
  41552. var invZBias = 1 / zBias;
  41553. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - 1);
  41554. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - 1);
  41555. part.transformX = tx;
  41556. part.transformY = ty;
  41557. part.opacity = this.actualOpacity;
  41558. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  41559. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  41560. };
  41561. RenderablePrim2D.prototype._updateRenderMode = function () {
  41562. if (this.isTransparent) {
  41563. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  41564. }
  41565. else if (this.isAlphaTest) {
  41566. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  41567. }
  41568. else {
  41569. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  41570. }
  41571. };
  41572. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41573. __decorate([
  41574. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  41575. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  41576. __decorate([
  41577. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  41578. ], RenderablePrim2D.prototype, "isTransparent", null);
  41579. RenderablePrim2D = __decorate([
  41580. BABYLON.className("RenderablePrim2D")
  41581. ], RenderablePrim2D);
  41582. return RenderablePrim2D;
  41583. }(BABYLON.Prim2DBase));
  41584. BABYLON.RenderablePrim2D = RenderablePrim2D;
  41585. })(BABYLON || (BABYLON = {}));
  41586. var BABYLON;
  41587. (function (BABYLON) {
  41588. var Shape2D = (function (_super) {
  41589. __extends(Shape2D, _super);
  41590. function Shape2D(settings) {
  41591. _super.call(this, settings);
  41592. if (!settings) {
  41593. settings = {};
  41594. }
  41595. var borderBrush = null;
  41596. if (settings.border) {
  41597. if (typeof (settings.border) === "string") {
  41598. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  41599. }
  41600. else {
  41601. borderBrush = settings.border;
  41602. }
  41603. }
  41604. var fillBrush = null;
  41605. if (settings.fill) {
  41606. if (typeof (settings.fill) === "string") {
  41607. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  41608. }
  41609. else {
  41610. fillBrush = settings.fill;
  41611. }
  41612. }
  41613. this.border = borderBrush;
  41614. this.fill = fillBrush;
  41615. this.borderThickness = settings.borderThickness;
  41616. }
  41617. Object.defineProperty(Shape2D.prototype, "border", {
  41618. get: function () {
  41619. return this._border;
  41620. },
  41621. set: function (value) {
  41622. this._border = value;
  41623. this._updateTransparencyStatus();
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. Object.defineProperty(Shape2D.prototype, "fill", {
  41629. /**
  41630. * Get/set the brush to render the Fill part of the Primitive
  41631. */
  41632. get: function () {
  41633. return this._fill;
  41634. },
  41635. set: function (value) {
  41636. this._fill = value;
  41637. this._updateTransparencyStatus();
  41638. },
  41639. enumerable: true,
  41640. configurable: true
  41641. });
  41642. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  41643. get: function () {
  41644. return this._borderThickness;
  41645. },
  41646. set: function (value) {
  41647. this._borderThickness = value;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  41653. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  41654. // Fill Part
  41655. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  41656. var fill = this.fill;
  41657. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41658. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  41659. }
  41660. if (fill instanceof BABYLON.GradientColorBrush2D) {
  41661. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  41662. }
  41663. }
  41664. // Border Part
  41665. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41666. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  41667. var border = this.border;
  41668. if (border instanceof BABYLON.SolidColorBrush2D) {
  41669. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  41670. }
  41671. if (border instanceof BABYLON.GradientColorBrush2D) {
  41672. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  41673. }
  41674. }
  41675. return cat;
  41676. };
  41677. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  41678. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  41679. return false;
  41680. }
  41681. // Fill Part
  41682. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  41683. var d = part;
  41684. if (this.fill) {
  41685. var fill = this.fill;
  41686. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41687. d.fillSolidColor = fill.color;
  41688. }
  41689. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  41690. d.fillGradientColor1 = fill.color1;
  41691. d.fillGradientColor2 = fill.color2;
  41692. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  41693. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41694. d.fillGradientTY = ty;
  41695. }
  41696. }
  41697. }
  41698. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41699. var d = part;
  41700. if (this.border) {
  41701. d.borderThickness = this.borderThickness;
  41702. var border = this.border;
  41703. if (border instanceof BABYLON.SolidColorBrush2D) {
  41704. d.borderSolidColor = border.color;
  41705. }
  41706. else if (border instanceof BABYLON.GradientColorBrush2D) {
  41707. d.borderGradientColor1 = border.color1;
  41708. d.borderGradientColor2 = border.color2;
  41709. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  41710. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41711. d.borderGradientTY = ty;
  41712. }
  41713. }
  41714. }
  41715. return true;
  41716. };
  41717. Shape2D.prototype._updateTransparencyStatus = function () {
  41718. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  41719. };
  41720. Shape2D.SHAPE2D_BORDERPARTID = 1;
  41721. Shape2D.SHAPE2D_FILLPARTID = 2;
  41722. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  41723. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  41724. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  41725. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  41726. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  41727. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  41728. __decorate([
  41729. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  41730. ], Shape2D.prototype, "border", null);
  41731. __decorate([
  41732. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  41733. ], Shape2D.prototype, "fill", null);
  41734. __decorate([
  41735. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  41736. ], Shape2D.prototype, "borderThickness", null);
  41737. Shape2D = __decorate([
  41738. BABYLON.className("Shape2D")
  41739. ], Shape2D);
  41740. return Shape2D;
  41741. }(BABYLON.RenderablePrim2D));
  41742. BABYLON.Shape2D = Shape2D;
  41743. var Shape2DInstanceData = (function (_super) {
  41744. __extends(Shape2DInstanceData, _super);
  41745. function Shape2DInstanceData() {
  41746. _super.apply(this, arguments);
  41747. }
  41748. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  41749. // FILL ATTRIBUTES
  41750. get: function () {
  41751. return null;
  41752. },
  41753. enumerable: true,
  41754. configurable: true
  41755. });
  41756. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  41757. get: function () {
  41758. return null;
  41759. },
  41760. enumerable: true,
  41761. configurable: true
  41762. });
  41763. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  41764. get: function () {
  41765. return null;
  41766. },
  41767. enumerable: true,
  41768. configurable: true
  41769. });
  41770. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  41771. get: function () {
  41772. return null;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  41778. // BORDER ATTRIBUTES
  41779. get: function () {
  41780. return null;
  41781. },
  41782. enumerable: true,
  41783. configurable: true
  41784. });
  41785. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  41786. get: function () {
  41787. return null;
  41788. },
  41789. enumerable: true,
  41790. configurable: true
  41791. });
  41792. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  41793. get: function () {
  41794. return null;
  41795. },
  41796. enumerable: true,
  41797. configurable: true
  41798. });
  41799. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  41800. get: function () {
  41801. return null;
  41802. },
  41803. enumerable: true,
  41804. configurable: true
  41805. });
  41806. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  41807. get: function () {
  41808. return null;
  41809. },
  41810. enumerable: true,
  41811. configurable: true
  41812. });
  41813. __decorate([
  41814. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  41815. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  41816. __decorate([
  41817. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41818. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  41819. __decorate([
  41820. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41821. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  41822. __decorate([
  41823. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41824. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  41825. __decorate([
  41826. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  41827. ], Shape2DInstanceData.prototype, "borderThickness", null);
  41828. __decorate([
  41829. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  41830. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  41831. __decorate([
  41832. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41833. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  41834. __decorate([
  41835. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41836. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  41837. __decorate([
  41838. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41839. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  41840. return Shape2DInstanceData;
  41841. }(BABYLON.InstanceDataBase));
  41842. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  41843. })(BABYLON || (BABYLON = {}));
  41844. var BABYLON;
  41845. (function (BABYLON) {
  41846. var Group2D = (function (_super) {
  41847. __extends(Group2D, _super);
  41848. /**
  41849. * Create an Logical or Renderable Group.
  41850. * @param settings a combination of settings, possible ones are
  41851. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  41852. * - children: an array of direct children
  41853. * - id a text identifier, for information purpose
  41854. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41855. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41856. * - scale: the initial scale of the primitive. default is 1
  41857. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  41858. * - origin: define the normalized origin point location, default [0.5;0.5]
  41859. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  41860. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  41861. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  41862. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  41863. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  41864. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41865. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41866. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41867. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41868. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41869. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41870. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41871. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41872. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41873. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41874. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41875. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41876. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41877. */
  41878. function Group2D(settings) {
  41879. if (settings == null) {
  41880. settings = {};
  41881. }
  41882. if (settings.origin == null) {
  41883. settings.origin = new BABYLON.Vector2(0, 0);
  41884. }
  41885. _super.call(this, settings);
  41886. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  41887. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  41888. if (this._trackedNode && this.owner) {
  41889. this.owner._registerTrackedNode(this);
  41890. }
  41891. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  41892. this.size = size;
  41893. this._viewportPosition = BABYLON.Vector2.Zero();
  41894. }
  41895. Group2D._createCachedCanvasGroup = function (owner) {
  41896. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  41897. return g;
  41898. };
  41899. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  41900. this._bindCacheTarget();
  41901. if (vertexData) {
  41902. var uv = vertexData.uvs;
  41903. var nodeuv = this._renderableData._cacheNodeUVs;
  41904. for (var i = 0; i < 4; i++) {
  41905. uv[i * 2 + 0] = nodeuv[i].x;
  41906. uv[i * 2 + 1] = nodeuv[i].y;
  41907. }
  41908. }
  41909. if (material) {
  41910. material.diffuseTexture = this._renderableData._cacheTexture;
  41911. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41912. }
  41913. this._renderableData._cacheTexture.hasAlpha = true;
  41914. this._unbindCacheTarget();
  41915. };
  41916. Object.defineProperty(Group2D.prototype, "cachedRect", {
  41917. /**
  41918. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  41919. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  41920. */
  41921. get: function () {
  41922. if (!this._renderableData) {
  41923. return null;
  41924. }
  41925. return this._renderableData._cacheNode;
  41926. },
  41927. enumerable: true,
  41928. configurable: true
  41929. });
  41930. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  41931. /**
  41932. * The UVs into the MapTexture that map the cached group
  41933. */
  41934. get: function () {
  41935. if (!this._renderableData) {
  41936. return null;
  41937. }
  41938. return this._renderableData._cacheNodeUVs;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  41944. get: function () {
  41945. if (!this._renderableData) {
  41946. return null;
  41947. }
  41948. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  41949. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  41950. }
  41951. return this._renderableData._cacheNodeUVsChangedObservable;
  41952. },
  41953. enumerable: true,
  41954. configurable: true
  41955. });
  41956. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  41957. /**
  41958. * Access the texture that maintains a cached version of the Group2D.
  41959. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  41960. */
  41961. get: function () {
  41962. if (!this._renderableData) {
  41963. return null;
  41964. }
  41965. return this._renderableData._cacheTexture;
  41966. },
  41967. enumerable: true,
  41968. configurable: true
  41969. });
  41970. /**
  41971. * Call this method to remove this Group and its children from the Canvas
  41972. */
  41973. Group2D.prototype.dispose = function () {
  41974. if (!_super.prototype.dispose.call(this)) {
  41975. return false;
  41976. }
  41977. if (this._trackedNode != null) {
  41978. this.owner._unregisterTrackedNode(this);
  41979. this._trackedNode = null;
  41980. }
  41981. if (this._renderableData) {
  41982. this._renderableData.dispose(this.owner.engine);
  41983. this._renderableData = null;
  41984. }
  41985. return true;
  41986. };
  41987. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  41988. /**
  41989. * @returns Returns true if the Group render content, false if it's a logical group only
  41990. */
  41991. get: function () {
  41992. return this._isRenderableGroup;
  41993. },
  41994. enumerable: true,
  41995. configurable: true
  41996. });
  41997. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  41998. /**
  41999. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  42000. */
  42001. get: function () {
  42002. return this._isCachedGroup;
  42003. },
  42004. enumerable: true,
  42005. configurable: true
  42006. });
  42007. Object.defineProperty(Group2D.prototype, "size", {
  42008. get: function () {
  42009. return this._size;
  42010. },
  42011. /**
  42012. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  42013. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  42014. */
  42015. set: function (val) {
  42016. this._size = val;
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. Object.defineProperty(Group2D.prototype, "viewportSize", {
  42022. get: function () {
  42023. return this._viewportSize;
  42024. },
  42025. enumerable: true,
  42026. configurable: true
  42027. });
  42028. Object.defineProperty(Group2D.prototype, "actualSize", {
  42029. get: function () {
  42030. // The computed size will be floor on both width and height
  42031. var actualSize;
  42032. // Return the size if set by the user
  42033. if (this._size) {
  42034. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  42035. }
  42036. else {
  42037. var m = this.boundingInfo.max();
  42038. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  42039. }
  42040. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  42041. if (!actualSize.equals(this._actualSize)) {
  42042. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  42043. this._actualSize = actualSize;
  42044. this.handleGroupChanged(Group2D.actualSizeProperty);
  42045. }
  42046. return actualSize;
  42047. },
  42048. enumerable: true,
  42049. configurable: true
  42050. });
  42051. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  42052. /**
  42053. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  42054. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  42055. */
  42056. get: function () {
  42057. return this._cacheBehavior;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Group2D.prototype._addPrimToDirtyList = function (prim) {
  42063. this._renderableData._primDirtyList.push(prim);
  42064. };
  42065. Group2D.prototype._renderCachedCanvas = function () {
  42066. this.owner._addGroupRenderCount(1);
  42067. this.updateCachedStates(true);
  42068. var context = new BABYLON.PrepareRender2DContext();
  42069. this._prepareGroupRender(context);
  42070. this._groupRender();
  42071. };
  42072. Object.defineProperty(Group2D.prototype, "trackedNode", {
  42073. /**
  42074. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  42075. */
  42076. get: function () {
  42077. return this._trackedNode;
  42078. },
  42079. set: function (val) {
  42080. if (val != null) {
  42081. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42082. this.owner._registerTrackedNode(this);
  42083. }
  42084. this._trackedNode = val;
  42085. }
  42086. else {
  42087. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42088. this.owner._unregisterTrackedNode(this);
  42089. }
  42090. this._trackedNode = null;
  42091. }
  42092. },
  42093. enumerable: true,
  42094. configurable: true
  42095. });
  42096. Group2D.prototype.levelIntersect = function (intersectInfo) {
  42097. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  42098. return true;
  42099. };
  42100. Group2D.prototype.updateLevelBoundingInfo = function () {
  42101. var size;
  42102. // If the size is set by the user, the boundingInfo is computed from this value
  42103. if (this.size) {
  42104. size = this.size;
  42105. }
  42106. else {
  42107. size = new BABYLON.Size(0, 0);
  42108. }
  42109. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  42110. };
  42111. // Method called only on renderable groups to prepare the rendering
  42112. Group2D.prototype._prepareGroupRender = function (context) {
  42113. var sortedDirtyList = null;
  42114. // Update the Global Transformation and visibility status of the changed primitives
  42115. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42116. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42117. this.updateCachedStatesOf(sortedDirtyList, true);
  42118. }
  42119. // Setup the size of the rendering viewport
  42120. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  42121. if (!this._isCachedGroup) {
  42122. // Compute the WebGL viewport's location/size
  42123. var t = this._globalTransform.getTranslation();
  42124. var s = this.actualSize.clone();
  42125. var rs = this.owner._renderingSize;
  42126. s.height = Math.min(s.height, rs.height - t.y);
  42127. s.width = Math.min(s.width, rs.width - t.x);
  42128. var x = t.x;
  42129. var y = t.y;
  42130. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  42131. this._viewportPosition.x = x;
  42132. this._viewportPosition.y = y;
  42133. var vw = s.width;
  42134. var vh = s.height;
  42135. if (!this._viewportSize) {
  42136. this._viewportSize = new BABYLON.Size(vw, vh);
  42137. }
  42138. else {
  42139. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  42140. context.forceRefreshPrimitive = true;
  42141. }
  42142. this._viewportSize.width = vw;
  42143. this._viewportSize.height = vh;
  42144. }
  42145. }
  42146. else {
  42147. var newSize = this.actualSize.clone();
  42148. if (!newSize.equals(this._viewportSize)) {
  42149. context.forceRefreshPrimitive = true;
  42150. }
  42151. this._viewportSize = newSize;
  42152. }
  42153. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42154. // If the group is cached, set the dirty flag to true because of the incoming changes
  42155. this._cacheGroupDirty = this._isCachedGroup;
  42156. // If it's a force refresh, prepare all the children
  42157. if (context.forceRefreshPrimitive) {
  42158. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42159. var p = _a[_i];
  42160. p._prepareRender(context);
  42161. }
  42162. }
  42163. else {
  42164. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  42165. // the hierarchyDepth in order to prepare primitives from top to bottom
  42166. if (!sortedDirtyList) {
  42167. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42168. }
  42169. sortedDirtyList.forEach(function (p) {
  42170. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  42171. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  42172. if (!p.isDisposed && p._needPrepare()) {
  42173. p._prepareRender(context);
  42174. }
  42175. });
  42176. // Everything is updated, clear the dirty list
  42177. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  42178. this._renderableData._primDirtyList.splice(0);
  42179. }
  42180. }
  42181. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  42182. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  42183. g._prepareGroupRender(context);
  42184. });
  42185. };
  42186. Group2D.prototype._groupRender = function () {
  42187. var _this = this;
  42188. var engine = this.owner.engine;
  42189. var failedCount = 0;
  42190. // First recurse to children render group to render them (in their cache or on screen)
  42191. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  42192. var childGroup = _a[_i];
  42193. childGroup._groupRender();
  42194. }
  42195. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  42196. if (!this.isCachedGroup || this._cacheGroupDirty) {
  42197. this.owner._addGroupRenderCount(1);
  42198. if (this.isCachedGroup) {
  42199. this._bindCacheTarget();
  42200. }
  42201. else {
  42202. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  42203. }
  42204. var curAlphaTest = engine.getAlphaTesting() === true;
  42205. var curDepthWrite = engine.getDepthWrite() === true;
  42206. // ===================================================================
  42207. // First pass, update the InstancedArray and render Opaque primitives
  42208. // Disable Alpha Testing, Enable Depth Write
  42209. engine.setAlphaTesting(false);
  42210. engine.setDepthWrite(true);
  42211. // For each different model of primitive to render
  42212. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  42213. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42214. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42215. var renderCount = _this._prepareContext(engine, context_1, v);
  42216. // If null is returned, there's no opaque data to render
  42217. if (renderCount === null) {
  42218. return;
  42219. }
  42220. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42221. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42222. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42223. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42224. // Update dirty flag/related
  42225. v.opaqueDirty = renderFailed;
  42226. failedCount += renderFailed ? 1 : 0;
  42227. }
  42228. });
  42229. // =======================================================================
  42230. // Second pass, update the InstancedArray and render AlphaTest primitives
  42231. // Enable Alpha Testing, Enable Depth Write
  42232. engine.setAlphaTesting(true);
  42233. engine.setDepthWrite(true);
  42234. // For each different model of primitive to render
  42235. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  42236. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42237. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42238. var renderCount = _this._prepareContext(engine, context_1, v);
  42239. // If null is returned, there's no opaque data to render
  42240. if (renderCount === null) {
  42241. return;
  42242. }
  42243. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42244. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42245. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42246. var renderFailed = !v.modelRenderCache.render(v, context_1);
  42247. // Update dirty flag/related
  42248. v.opaqueDirty = renderFailed;
  42249. failedCount += renderFailed ? 1 : 0;
  42250. }
  42251. });
  42252. // =======================================================================
  42253. // Third pass, transparent primitive rendering
  42254. // Enable Alpha Testing, Disable Depth Write
  42255. engine.setAlphaTesting(true);
  42256. engine.setDepthWrite(false);
  42257. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  42258. if (this._renderableData._transparentListChanged) {
  42259. this._updateTransparentData();
  42260. }
  42261. // From this point on we have up to date data to render, so let's go
  42262. failedCount += this._renderTransparentData();
  42263. // =======================================================================
  42264. // Unbind target/restore viewport setting, clear dirty flag, and quit
  42265. // The group's content is no longer dirty
  42266. this._cacheGroupDirty = failedCount !== 0;
  42267. if (this.isCachedGroup) {
  42268. this._unbindCacheTarget();
  42269. }
  42270. else {
  42271. if (curVP) {
  42272. engine.setViewport(curVP);
  42273. }
  42274. }
  42275. // Restore saved states
  42276. engine.setAlphaTesting(curAlphaTest);
  42277. engine.setDepthWrite(curDepthWrite);
  42278. }
  42279. };
  42280. Group2D.prototype._updateTransparentData = function () {
  42281. this.owner._addUpdateTransparentDataCount(1);
  42282. var rd = this._renderableData;
  42283. // Sort all the primitive from their depth, max (bottom) to min (top)
  42284. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  42285. var checkAndAddPrimInSegment = function (seg, tpiI) {
  42286. var tpi = rd._transparentPrimitives[tpiI];
  42287. // Fast rejection: if gii are different
  42288. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  42289. return false;
  42290. }
  42291. //let tpiZ = tpi._primitive.actualZOffset;
  42292. // We've made it so far, the tpi can be part of the segment, add it
  42293. tpi._transparentSegment = seg;
  42294. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  42295. return true;
  42296. };
  42297. // Free the existing TransparentSegments
  42298. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  42299. var ts = _a[_i];
  42300. ts.dispose(this.owner.engine);
  42301. }
  42302. rd._transparentSegments.splice(0);
  42303. var prevSeg = null;
  42304. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  42305. var tpi = rd._transparentPrimitives[tpiI];
  42306. // Check if the Data in which the primitive is stored is not sorted properly
  42307. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  42308. tpi._groupInstanceInfo.sortTransparentData();
  42309. }
  42310. // Reset the segment, we have to create/rebuild it
  42311. tpi._transparentSegment = null;
  42312. // If there's a previous valid segment, check if this prim can be part of it
  42313. if (prevSeg) {
  42314. checkAndAddPrimInSegment(prevSeg, tpiI);
  42315. }
  42316. // If we couldn't insert in the adjacent segments, he have to create one
  42317. if (!tpi._transparentSegment) {
  42318. var ts = new BABYLON.TransparentSegment();
  42319. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  42320. var prim = tpi._primitive;
  42321. ts.startZ = prim.actualZOffset;
  42322. prim._updateTransparentSegmentIndices(ts);
  42323. ts.endZ = ts.startZ;
  42324. tpi._transparentSegment = ts;
  42325. rd._transparentSegments.push(ts);
  42326. }
  42327. // Update prevSeg
  42328. prevSeg = tpi._transparentSegment;
  42329. }
  42330. //rd._firstChangedPrim = null;
  42331. rd._transparentListChanged = false;
  42332. };
  42333. Group2D.prototype._renderTransparentData = function () {
  42334. var failedCount = 0;
  42335. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  42336. var rd = this._renderableData;
  42337. var useInstanced = this.owner.supportInstancedArray;
  42338. var length = rd._transparentSegments.length;
  42339. for (var i = 0; i < length; i++) {
  42340. context.instancedBuffers = null;
  42341. var ts = rd._transparentSegments[i];
  42342. var gii = ts.groupInsanceInfo;
  42343. var mrc = gii.modelRenderCache;
  42344. var engine = this.owner.engine;
  42345. var count = ts.endDataIndex - ts.startDataIndex;
  42346. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  42347. // We don't want to create an Instanced Buffer for less that 5 prims
  42348. if (useInstanced && count >= 5) {
  42349. if (!ts.partBuffers) {
  42350. var buffers = new Array();
  42351. for (var j = 0; j < gii.transparentData.length; j++) {
  42352. var gitd = gii.transparentData[j];
  42353. var dfa = gitd._partData;
  42354. var data = dfa.pack();
  42355. var stride = dfa.stride;
  42356. var neededSize = count * stride * 4;
  42357. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42358. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42359. engine.updateArrayBuffer(segData);
  42360. buffers.push(buffer);
  42361. }
  42362. ts.partBuffers = buffers;
  42363. }
  42364. else if (gii.transparentDirty) {
  42365. for (var j = 0; j < gii.transparentData.length; j++) {
  42366. var gitd = gii.transparentData[j];
  42367. var dfa = gitd._partData;
  42368. var data = dfa.pack();
  42369. var stride = dfa.stride;
  42370. var buffer = ts.partBuffers[j];
  42371. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42372. engine.bindArrayBuffer(buffer);
  42373. engine.updateArrayBuffer(segData);
  42374. }
  42375. }
  42376. context.useInstancing = true;
  42377. context.instancesCount = count;
  42378. context.instancedBuffers = ts.partBuffers;
  42379. context.groupInfoPartData = gii.transparentData;
  42380. var renderFailed = !mrc.render(gii, context);
  42381. failedCount += renderFailed ? 1 : 0;
  42382. }
  42383. else {
  42384. context.useInstancing = false;
  42385. context.partDataStartIndex = ts.startDataIndex;
  42386. context.partDataEndIndex = ts.endDataIndex;
  42387. context.groupInfoPartData = gii.transparentData;
  42388. var renderFailed = !mrc.render(gii, context);
  42389. failedCount += renderFailed ? 1 : 0;
  42390. }
  42391. }
  42392. return failedCount;
  42393. };
  42394. Group2D.prototype._prepareContext = function (engine, context, gii) {
  42395. var gipd = null;
  42396. var setDirty;
  42397. var getDirty;
  42398. // Render Mode specifics
  42399. switch (context.renderMode) {
  42400. case BABYLON.Render2DContext.RenderModeOpaque:
  42401. {
  42402. if (!gii.hasOpaqueData) {
  42403. return null;
  42404. }
  42405. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  42406. getDirty = function () { return gii.opaqueDirty; };
  42407. context.groupInfoPartData = gii.opaqueData;
  42408. gipd = gii.opaqueData;
  42409. break;
  42410. }
  42411. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42412. {
  42413. if (!gii.hasAlphaTestData) {
  42414. return null;
  42415. }
  42416. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  42417. getDirty = function () { return gii.alphaTestDirty; };
  42418. context.groupInfoPartData = gii.alphaTestData;
  42419. gipd = gii.alphaTestData;
  42420. break;
  42421. }
  42422. default:
  42423. throw new Error("_prepareContext is only for opaque or alphaTest");
  42424. }
  42425. var renderCount = 0;
  42426. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  42427. // Skip it if instanced arrays are not supported
  42428. if (this.owner.supportInstancedArray) {
  42429. // Flag for instancing
  42430. context.useInstancing = true;
  42431. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  42432. for (var i = 0; i < gipd.length; i++) {
  42433. var pid = gipd[i];
  42434. // If the instances of the model was changed, pack the data
  42435. var array = pid._partData;
  42436. var instanceData_1 = array.pack();
  42437. renderCount += array.usedElementCount;
  42438. // Compute the size the instance buffer should have
  42439. var neededSize = array.usedElementCount * array.stride * 4;
  42440. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  42441. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  42442. if (pid._partBuffer) {
  42443. engine.deleteInstancesBuffer(pid._partBuffer);
  42444. }
  42445. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42446. pid._partBufferSize = neededSize;
  42447. setDirty(false);
  42448. // Update the WebGL buffer to match the new content of the instances data
  42449. engine.updateArrayBuffer(instanceData_1);
  42450. }
  42451. else if (getDirty()) {
  42452. // Update the WebGL buffer to match the new content of the instances data
  42453. engine.bindArrayBuffer(pid._partBuffer);
  42454. engine.updateArrayBuffer(instanceData_1);
  42455. }
  42456. }
  42457. setDirty(false);
  42458. }
  42459. else {
  42460. context.partDataStartIndex = 0;
  42461. // Find the first valid object to get the count
  42462. if (context.groupInfoPartData.length > 0) {
  42463. var i = 0;
  42464. while (!context.groupInfoPartData[i]) {
  42465. i++;
  42466. }
  42467. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  42468. }
  42469. }
  42470. return renderCount;
  42471. };
  42472. Group2D.prototype._setRenderingScale = function (scale) {
  42473. if (this._renderableData._renderingScale === scale) {
  42474. return;
  42475. }
  42476. this._renderableData._renderingScale = scale;
  42477. };
  42478. Group2D.prototype._bindCacheTarget = function () {
  42479. var curWidth;
  42480. var curHeight;
  42481. var rd = this._renderableData;
  42482. var rs = rd._renderingScale;
  42483. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  42484. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  42485. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  42486. if (rd._cacheNode) {
  42487. var size = rd._cacheNode.contentSize;
  42488. // Check if we have to deallocate because the size is too small
  42489. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  42490. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  42491. // For World space: no over-provisioning
  42492. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  42493. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  42494. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  42495. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  42496. rd._cacheTexture.freeRect(rd._cacheNode);
  42497. rd._cacheNode = null;
  42498. }
  42499. }
  42500. if (!rd._cacheNode) {
  42501. // Check if we have to allocate a rendering zone in the global cache texture
  42502. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  42503. rd._cacheNode = res.node;
  42504. rd._cacheTexture = res.texture;
  42505. rd._cacheRenderSprite = res.sprite;
  42506. sizeChanged = true;
  42507. }
  42508. if (sizeChanged) {
  42509. rd._cacheSize.copyFrom(Group2D._s);
  42510. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  42511. this.scale = this._renderableData._renderingScale;
  42512. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  42513. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  42514. }
  42515. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  42516. }
  42517. var n = rd._cacheNode;
  42518. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  42519. };
  42520. Group2D.prototype._unbindCacheTarget = function () {
  42521. if (this._renderableData._cacheTexture) {
  42522. this._renderableData._cacheTexture.unbindTexture();
  42523. }
  42524. };
  42525. Group2D.prototype.handleGroupChanged = function (prop) {
  42526. // This method is only for cachedGroup
  42527. var rd = this._renderableData;
  42528. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  42529. return;
  42530. }
  42531. // For now we only support these property changes
  42532. // TODO: add more! :)
  42533. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  42534. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  42535. }
  42536. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  42537. rd._cacheRenderSprite.rotation = this.rotation;
  42538. }
  42539. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  42540. rd._cacheRenderSprite.scale = this.scale;
  42541. }
  42542. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  42543. rd._cacheRenderSprite.origin = this.origin.clone();
  42544. }
  42545. else if (prop.id === Group2D.actualSizeProperty.id) {
  42546. rd._cacheRenderSprite.size = this.actualSize.clone();
  42547. }
  42548. };
  42549. Group2D.prototype.detectGroupStates = function () {
  42550. var isCanvas = this instanceof BABYLON.Canvas2D;
  42551. var canvasStrat = this.owner.cachingStrategy;
  42552. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  42553. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  42554. this._isRenderableGroup = isCanvas;
  42555. this._isCachedGroup = false;
  42556. }
  42557. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  42558. if (isCanvas) {
  42559. this._isRenderableGroup = true;
  42560. this._isCachedGroup = true;
  42561. }
  42562. else {
  42563. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  42564. this._isCachedGroup = false;
  42565. }
  42566. }
  42567. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42568. if (isCanvas) {
  42569. this._isRenderableGroup = true;
  42570. this._isCachedGroup = false;
  42571. }
  42572. else {
  42573. if (this.hierarchyDepth === 1) {
  42574. this._isRenderableGroup = true;
  42575. this._isCachedGroup = true;
  42576. }
  42577. else {
  42578. this._isRenderableGroup = false;
  42579. this._isCachedGroup = false;
  42580. }
  42581. }
  42582. }
  42583. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  42584. var gcb = this.cacheBehavior;
  42585. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  42586. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  42587. this._isCachedGroup = false;
  42588. }
  42589. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  42590. this._isRenderableGroup = true;
  42591. this._isCachedGroup = true;
  42592. }
  42593. }
  42594. if (this._isRenderableGroup) {
  42595. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  42596. if (!this._renderableData) {
  42597. this._renderableData = new RenderableGroupData();
  42598. }
  42599. }
  42600. // If the group is tagged as renderable we add it to the renderable tree
  42601. if (this._isCachedGroup) {
  42602. var cur = this.parent;
  42603. while (cur) {
  42604. if (cur instanceof Group2D && cur._isRenderableGroup) {
  42605. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  42606. cur._renderableData._childrenRenderableGroups.push(this);
  42607. }
  42608. break;
  42609. }
  42610. cur = cur.parent;
  42611. }
  42612. }
  42613. };
  42614. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42615. /**
  42616. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  42617. */
  42618. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  42619. /**
  42620. * When used, this group's content won't be cached, no matter which strategy used.
  42621. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  42622. */
  42623. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  42624. /**
  42625. * When used, the group's content will be cached in the nearest cached parent group/canvas
  42626. */
  42627. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  42628. Group2D._s = BABYLON.Size.Zero();
  42629. __decorate([
  42630. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  42631. ], Group2D.prototype, "size", null);
  42632. __decorate([
  42633. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  42634. ], Group2D.prototype, "actualSize", null);
  42635. Group2D = __decorate([
  42636. BABYLON.className("Group2D")
  42637. ], Group2D);
  42638. return Group2D;
  42639. }(BABYLON.Prim2DBase));
  42640. BABYLON.Group2D = Group2D;
  42641. var RenderableGroupData = (function () {
  42642. function RenderableGroupData() {
  42643. this._primDirtyList = new Array();
  42644. this._childrenRenderableGroups = new Array();
  42645. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  42646. this._transparentPrimitives = new Array();
  42647. this._transparentSegments = new Array();
  42648. this._transparentListChanged = false;
  42649. this._cacheNode = null;
  42650. this._cacheTexture = null;
  42651. this._cacheRenderSprite = null;
  42652. this._renderingScale = 1;
  42653. this._cacheNodeUVs = null;
  42654. this._cacheNodeUVsChangedObservable = null;
  42655. this._cacheSize = BABYLON.Size.Zero();
  42656. this._useMipMap = false;
  42657. this._anisotropicLevel = 1;
  42658. }
  42659. RenderableGroupData.prototype.dispose = function (engine) {
  42660. if (this._cacheRenderSprite) {
  42661. this._cacheRenderSprite.dispose();
  42662. this._cacheRenderSprite = null;
  42663. }
  42664. if (this._cacheTexture && this._cacheNode) {
  42665. this._cacheTexture.freeRect(this._cacheNode);
  42666. this._cacheTexture = null;
  42667. this._cacheNode = null;
  42668. }
  42669. if (this._primDirtyList) {
  42670. this._primDirtyList.splice(0);
  42671. this._primDirtyList = null;
  42672. }
  42673. if (this._renderGroupInstancesInfo) {
  42674. this._renderGroupInstancesInfo.forEach(function (k, v) {
  42675. v.dispose();
  42676. });
  42677. this._renderGroupInstancesInfo = null;
  42678. }
  42679. if (this._cacheNodeUVsChangedObservable) {
  42680. this._cacheNodeUVsChangedObservable.clear();
  42681. this._cacheNodeUVsChangedObservable = null;
  42682. }
  42683. if (this._transparentSegments) {
  42684. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  42685. var ts = _a[_i];
  42686. ts.dispose(engine);
  42687. }
  42688. this._transparentSegments.splice(0);
  42689. this._transparentSegments = null;
  42690. }
  42691. };
  42692. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  42693. var tpi = new TransparentPrimitiveInfo();
  42694. tpi._primitive = prim;
  42695. tpi._groupInstanceInfo = gii;
  42696. tpi._transparentSegment = null;
  42697. this._transparentPrimitives.push(tpi);
  42698. this._transparentListChanged = true;
  42699. return tpi;
  42700. };
  42701. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  42702. var index = this._transparentPrimitives.indexOf(tpi);
  42703. if (index !== -1) {
  42704. this._transparentPrimitives.splice(index, 1);
  42705. this._transparentListChanged = true;
  42706. }
  42707. };
  42708. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  42709. this._transparentListChanged = true;
  42710. //this.updateSmallestZChangedPrim(tpi);
  42711. };
  42712. return RenderableGroupData;
  42713. }());
  42714. BABYLON.RenderableGroupData = RenderableGroupData;
  42715. var TransparentPrimitiveInfo = (function () {
  42716. function TransparentPrimitiveInfo() {
  42717. }
  42718. return TransparentPrimitiveInfo;
  42719. }());
  42720. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  42721. })(BABYLON || (BABYLON = {}));
  42722. var BABYLON;
  42723. (function (BABYLON) {
  42724. var Rectangle2DRenderCache = (function (_super) {
  42725. __extends(Rectangle2DRenderCache, _super);
  42726. function Rectangle2DRenderCache(engine, modelKey) {
  42727. _super.call(this, engine, modelKey);
  42728. this.effectsReady = false;
  42729. this.fillVB = null;
  42730. this.fillIB = null;
  42731. this.fillIndicesCount = 0;
  42732. this.instancingFillAttributes = null;
  42733. this.effectFill = null;
  42734. this.effectFillInstanced = null;
  42735. this.borderVB = null;
  42736. this.borderIB = null;
  42737. this.borderIndicesCount = 0;
  42738. this.instancingBorderAttributes = null;
  42739. this.effectBorder = null;
  42740. this.effectBorderInstanced = null;
  42741. }
  42742. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  42743. // Do nothing if the shader is still loading/preparing
  42744. if (!this.effectsReady) {
  42745. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42746. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42747. return false;
  42748. }
  42749. this.effectsReady = true;
  42750. }
  42751. var canvas = instanceInfo.owner.owner;
  42752. var engine = canvas.engine;
  42753. var depthFunction = 0;
  42754. if (this.effectFill && this.effectBorder) {
  42755. depthFunction = engine.getDepthFunction();
  42756. engine.setDepthFunctionToLessOrEqual();
  42757. }
  42758. var curAlphaMode = engine.getAlphaMode();
  42759. if (this.effectFill) {
  42760. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42761. var pid = context.groupInfoPartData[partIndex];
  42762. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42763. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42764. }
  42765. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42766. engine.enableEffect(effect);
  42767. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42768. if (context.useInstancing) {
  42769. if (!this.instancingFillAttributes) {
  42770. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42771. }
  42772. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42773. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42774. canvas._addDrawCallCount(1, context.renderMode);
  42775. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  42776. engine.draw(true, 0, this.fillIndicesCount, count);
  42777. engine.unbindInstanceAttributes();
  42778. }
  42779. else {
  42780. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42781. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42782. this.setupUniforms(effect, partIndex, pid._partData, i);
  42783. engine.draw(true, 0, this.fillIndicesCount);
  42784. }
  42785. }
  42786. }
  42787. if (this.effectBorder) {
  42788. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42789. var pid = context.groupInfoPartData[partIndex];
  42790. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42791. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42792. }
  42793. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42794. engine.enableEffect(effect);
  42795. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42796. if (context.useInstancing) {
  42797. if (!this.instancingBorderAttributes) {
  42798. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42799. }
  42800. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42801. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42802. canvas._addDrawCallCount(1, context.renderMode);
  42803. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  42804. engine.draw(true, 0, this.borderIndicesCount, count);
  42805. engine.unbindInstanceAttributes();
  42806. }
  42807. else {
  42808. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42809. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42810. this.setupUniforms(effect, partIndex, pid._partData, i);
  42811. engine.draw(true, 0, this.borderIndicesCount);
  42812. }
  42813. }
  42814. }
  42815. engine.setAlphaMode(curAlphaMode);
  42816. if (this.effectFill && this.effectBorder) {
  42817. engine.setDepthFunction(depthFunction);
  42818. }
  42819. return true;
  42820. };
  42821. Rectangle2DRenderCache.prototype.dispose = function () {
  42822. if (!_super.prototype.dispose.call(this)) {
  42823. return false;
  42824. }
  42825. if (this.fillVB) {
  42826. this._engine._releaseBuffer(this.fillVB);
  42827. this.fillVB = null;
  42828. }
  42829. if (this.fillIB) {
  42830. this._engine._releaseBuffer(this.fillIB);
  42831. this.fillIB = null;
  42832. }
  42833. if (this.effectFill) {
  42834. this._engine._releaseEffect(this.effectFill);
  42835. this.effectFill = null;
  42836. }
  42837. if (this.effectFillInstanced) {
  42838. this._engine._releaseEffect(this.effectFillInstanced);
  42839. this.effectFillInstanced = null;
  42840. }
  42841. if (this.borderVB) {
  42842. this._engine._releaseBuffer(this.borderVB);
  42843. this.borderVB = null;
  42844. }
  42845. if (this.borderIB) {
  42846. this._engine._releaseBuffer(this.borderIB);
  42847. this.borderIB = null;
  42848. }
  42849. if (this.effectBorder) {
  42850. this._engine._releaseEffect(this.effectBorder);
  42851. this.effectBorder = null;
  42852. }
  42853. if (this.effectBorderInstanced) {
  42854. this._engine._releaseEffect(this.effectBorderInstanced);
  42855. this.effectBorderInstanced = null;
  42856. }
  42857. return true;
  42858. };
  42859. return Rectangle2DRenderCache;
  42860. }(BABYLON.ModelRenderCache));
  42861. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  42862. var Rectangle2DInstanceData = (function (_super) {
  42863. __extends(Rectangle2DInstanceData, _super);
  42864. function Rectangle2DInstanceData(partId) {
  42865. _super.call(this, partId, 1);
  42866. }
  42867. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  42868. get: function () {
  42869. return null;
  42870. },
  42871. enumerable: true,
  42872. configurable: true
  42873. });
  42874. __decorate([
  42875. BABYLON.instanceData()
  42876. ], Rectangle2DInstanceData.prototype, "properties", null);
  42877. return Rectangle2DInstanceData;
  42878. }(BABYLON.Shape2DInstanceData));
  42879. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  42880. var Rectangle2D = (function (_super) {
  42881. __extends(Rectangle2D, _super);
  42882. /**
  42883. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  42884. * @param settings a combination of settings, possible ones are
  42885. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42886. * - children: an array of direct children
  42887. * - id a text identifier, for information purpose
  42888. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  42889. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42890. * - scale: the initial scale of the primitive. default is 1
  42891. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  42892. * - origin: define the normalized origin point location, default [0.5;0.5]
  42893. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  42894. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  42895. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  42896. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  42897. * - borderThickness: the thickness of the drawn border, default is 1.
  42898. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42899. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  42900. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42901. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42902. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42903. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42904. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42905. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42906. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42907. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42908. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42909. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42910. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42911. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42912. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42913. */
  42914. function Rectangle2D(settings) {
  42915. // Avoid checking every time if the object exists
  42916. if (settings == null) {
  42917. settings = {};
  42918. }
  42919. _super.call(this, settings);
  42920. if (settings.size != null) {
  42921. this.size = settings.size;
  42922. }
  42923. else if (settings.width || settings.height) {
  42924. var size = new BABYLON.Size(settings.width, settings.height);
  42925. this.size = size;
  42926. }
  42927. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  42928. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  42929. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  42930. //this.size = size;
  42931. this.roundRadius = roundRadius;
  42932. this.borderThickness = borderThickness;
  42933. }
  42934. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  42935. get: function () {
  42936. if (this._actualSize) {
  42937. return this._actualSize;
  42938. }
  42939. return this.size;
  42940. },
  42941. set: function (value) {
  42942. this._actualSize = value;
  42943. },
  42944. enumerable: true,
  42945. configurable: true
  42946. });
  42947. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  42948. get: function () {
  42949. return this._notRounded;
  42950. },
  42951. set: function (value) {
  42952. this._notRounded = value;
  42953. },
  42954. enumerable: true,
  42955. configurable: true
  42956. });
  42957. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  42958. get: function () {
  42959. return this._roundRadius;
  42960. },
  42961. set: function (value) {
  42962. this._roundRadius = value;
  42963. this.notRounded = value === 0;
  42964. this._positioningDirty();
  42965. },
  42966. enumerable: true,
  42967. configurable: true
  42968. });
  42969. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  42970. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  42971. if (this.notRounded) {
  42972. return true;
  42973. }
  42974. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  42975. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  42976. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  42977. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  42978. var size = this.size;
  42979. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  42980. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  42981. var rr = this.roundRadius;
  42982. var rrs = rr * rr;
  42983. // Check if the point is in the bottom/left quarter area
  42984. Rectangle2D._i1.x = rr;
  42985. Rectangle2D._i1.y = rr;
  42986. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42987. // Compute the intersection point in the quarter local space
  42988. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42989. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42990. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42991. return Rectangle2D._i2.lengthSquared() <= rrs;
  42992. }
  42993. // Check if the point is in the top/left quarter area
  42994. Rectangle2D._i1.x = rr;
  42995. Rectangle2D._i1.y = size.height - rr;
  42996. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42997. // Compute the intersection point in the quarter local space
  42998. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42999. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43000. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43001. return Rectangle2D._i2.lengthSquared() <= rrs;
  43002. }
  43003. // Check if the point is in the top/right quarter area
  43004. Rectangle2D._i1.x = size.width - rr;
  43005. Rectangle2D._i1.y = size.height - rr;
  43006. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  43007. // Compute the intersection point in the quarter local space
  43008. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43009. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43010. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43011. return Rectangle2D._i2.lengthSquared() <= rrs;
  43012. }
  43013. // Check if the point is in the bottom/right quarter area
  43014. Rectangle2D._i1.x = size.width - rr;
  43015. Rectangle2D._i1.y = rr;
  43016. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  43017. // Compute the intersection point in the quarter local space
  43018. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  43019. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  43020. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  43021. return Rectangle2D._i2.lengthSquared() <= rrs;
  43022. }
  43023. // At any other locations the point is guarantied to be inside
  43024. return true;
  43025. };
  43026. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  43027. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43028. };
  43029. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  43030. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  43031. return renderCache;
  43032. };
  43033. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43034. var renderCache = modelRenderCache;
  43035. var engine = this.owner.engine;
  43036. // Need to create WebGL resources for fill part?
  43037. if (this.fill) {
  43038. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  43039. var vb = new Float32Array(vbSize);
  43040. for (var i = 0; i < vbSize; i++) {
  43041. vb[i] = i;
  43042. }
  43043. renderCache.fillVB = engine.createVertexBuffer(vb);
  43044. var triCount = vbSize - 1;
  43045. var ib = new Float32Array(triCount * 3);
  43046. for (var i = 0; i < triCount; i++) {
  43047. ib[i * 3 + 0] = 0;
  43048. ib[i * 3 + 2] = i + 1;
  43049. ib[i * 3 + 1] = i + 2;
  43050. }
  43051. ib[triCount * 3 - 2] = 1;
  43052. renderCache.fillIB = engine.createIndexBuffer(ib);
  43053. renderCache.fillIndicesCount = triCount * 3;
  43054. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43055. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43056. if (ei) {
  43057. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43058. }
  43059. // Get the non instanced version
  43060. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43061. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43062. }
  43063. // Need to create WebGL resource for border part?
  43064. if (this.border) {
  43065. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  43066. var vb = new Float32Array(vbSize);
  43067. for (var i = 0; i < vbSize; i++) {
  43068. vb[i] = i;
  43069. }
  43070. renderCache.borderVB = engine.createVertexBuffer(vb);
  43071. var triCount = vbSize;
  43072. var rs = triCount / 2;
  43073. var ib = new Float32Array(triCount * 3);
  43074. for (var i = 0; i < rs; i++) {
  43075. var r0 = i;
  43076. var r1 = (i + 1) % rs;
  43077. ib[i * 6 + 0] = rs + r1;
  43078. ib[i * 6 + 1] = rs + r0;
  43079. ib[i * 6 + 2] = r0;
  43080. ib[i * 6 + 3] = r1;
  43081. ib[i * 6 + 4] = rs + r1;
  43082. ib[i * 6 + 5] = r0;
  43083. }
  43084. renderCache.borderIB = engine.createIndexBuffer(ib);
  43085. renderCache.borderIndicesCount = triCount * 3;
  43086. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43087. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43088. if (ei) {
  43089. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43090. }
  43091. // Get the non instanced version
  43092. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43093. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43094. }
  43095. return renderCache;
  43096. };
  43097. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  43098. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  43099. // Fall back to default implementation if there's no round Radius
  43100. if (this._notRounded) {
  43101. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  43102. }
  43103. else {
  43104. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43105. initialContentPosition.x = initialContentPosition.y = rr;
  43106. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  43107. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  43108. }
  43109. };
  43110. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  43111. // Fall back to default implementation if there's no round Radius
  43112. if (this._notRounded) {
  43113. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  43114. }
  43115. else {
  43116. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43117. newPrimSize.copyFrom(primSize);
  43118. newPrimSize.width += rr * 2;
  43119. newPrimSize.height += rr * 2;
  43120. }
  43121. };
  43122. Rectangle2D.prototype.createInstanceDataParts = function () {
  43123. var res = new Array();
  43124. if (this.border) {
  43125. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43126. }
  43127. if (this.fill) {
  43128. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43129. }
  43130. return res;
  43131. };
  43132. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  43133. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43134. return false;
  43135. }
  43136. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43137. var d = part;
  43138. var size = this.actualSize;
  43139. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43140. }
  43141. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43142. var d = part;
  43143. var size = this.actualSize;
  43144. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43145. }
  43146. return true;
  43147. };
  43148. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  43149. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  43150. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  43151. Rectangle2D.roundSubdivisions = 16;
  43152. __decorate([
  43153. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  43154. ], Rectangle2D.prototype, "actualSize", null);
  43155. __decorate([
  43156. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  43157. ], Rectangle2D.prototype, "notRounded", null);
  43158. __decorate([
  43159. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  43160. ], Rectangle2D.prototype, "roundRadius", null);
  43161. Rectangle2D = __decorate([
  43162. BABYLON.className("Rectangle2D")
  43163. ], Rectangle2D);
  43164. return Rectangle2D;
  43165. }(BABYLON.Shape2D));
  43166. BABYLON.Rectangle2D = Rectangle2D;
  43167. })(BABYLON || (BABYLON = {}));
  43168. var BABYLON;
  43169. (function (BABYLON) {
  43170. var Ellipse2DRenderCache = (function (_super) {
  43171. __extends(Ellipse2DRenderCache, _super);
  43172. function Ellipse2DRenderCache(engine, modelKey) {
  43173. _super.call(this, engine, modelKey);
  43174. this.effectsReady = false;
  43175. this.fillVB = null;
  43176. this.fillIB = null;
  43177. this.fillIndicesCount = 0;
  43178. this.instancingFillAttributes = null;
  43179. this.effectFillInstanced = null;
  43180. this.effectFill = null;
  43181. this.borderVB = null;
  43182. this.borderIB = null;
  43183. this.borderIndicesCount = 0;
  43184. this.instancingBorderAttributes = null;
  43185. this.effectBorderInstanced = null;
  43186. this.effectBorder = null;
  43187. }
  43188. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  43189. // Do nothing if the shader is still loading/preparing
  43190. if (!this.effectsReady) {
  43191. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43192. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43193. return false;
  43194. }
  43195. this.effectsReady = true;
  43196. }
  43197. var canvas = instanceInfo.owner.owner;
  43198. var engine = canvas.engine;
  43199. var depthFunction = 0;
  43200. if (this.effectFill && this.effectBorder) {
  43201. depthFunction = engine.getDepthFunction();
  43202. engine.setDepthFunctionToLessOrEqual();
  43203. }
  43204. var curAlphaMode = engine.getAlphaMode();
  43205. if (this.effectFill) {
  43206. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43207. var pid = context.groupInfoPartData[partIndex];
  43208. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43209. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43210. }
  43211. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43212. engine.enableEffect(effect);
  43213. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43214. if (context.useInstancing) {
  43215. if (!this.instancingFillAttributes) {
  43216. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43217. }
  43218. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43219. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43220. canvas._addDrawCallCount(1, context.renderMode);
  43221. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43222. engine.draw(true, 0, this.fillIndicesCount, count);
  43223. engine.unbindInstanceAttributes();
  43224. }
  43225. else {
  43226. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43227. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43228. this.setupUniforms(effect, partIndex, pid._partData, i);
  43229. engine.draw(true, 0, this.fillIndicesCount);
  43230. }
  43231. }
  43232. }
  43233. if (this.effectBorder) {
  43234. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43235. var pid = context.groupInfoPartData[partIndex];
  43236. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43237. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43238. }
  43239. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43240. engine.enableEffect(effect);
  43241. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  43242. if (context.useInstancing) {
  43243. if (!this.instancingBorderAttributes) {
  43244. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43245. }
  43246. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43247. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43248. canvas._addDrawCallCount(1, context.renderMode);
  43249. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  43250. engine.draw(true, 0, this.borderIndicesCount, count);
  43251. engine.unbindInstanceAttributes();
  43252. }
  43253. else {
  43254. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43255. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43256. this.setupUniforms(effect, partIndex, pid._partData, i);
  43257. engine.draw(true, 0, this.borderIndicesCount);
  43258. }
  43259. }
  43260. }
  43261. engine.setAlphaMode(curAlphaMode);
  43262. if (this.effectFill && this.effectBorder) {
  43263. engine.setDepthFunction(depthFunction);
  43264. }
  43265. return true;
  43266. };
  43267. Ellipse2DRenderCache.prototype.dispose = function () {
  43268. if (!_super.prototype.dispose.call(this)) {
  43269. return false;
  43270. }
  43271. if (this.fillVB) {
  43272. this._engine._releaseBuffer(this.fillVB);
  43273. this.fillVB = null;
  43274. }
  43275. if (this.fillIB) {
  43276. this._engine._releaseBuffer(this.fillIB);
  43277. this.fillIB = null;
  43278. }
  43279. if (this.effectFill) {
  43280. this._engine._releaseEffect(this.effectFill);
  43281. this.effectFill = null;
  43282. }
  43283. if (this.effectFillInstanced) {
  43284. this._engine._releaseEffect(this.effectFillInstanced);
  43285. this.effectFillInstanced = null;
  43286. }
  43287. if (this.borderVB) {
  43288. this._engine._releaseBuffer(this.borderVB);
  43289. this.borderVB = null;
  43290. }
  43291. if (this.borderIB) {
  43292. this._engine._releaseBuffer(this.borderIB);
  43293. this.borderIB = null;
  43294. }
  43295. if (this.effectBorder) {
  43296. this._engine._releaseEffect(this.effectBorder);
  43297. this.effectBorder = null;
  43298. }
  43299. if (this.effectBorderInstanced) {
  43300. this._engine._releaseEffect(this.effectBorderInstanced);
  43301. this.effectBorderInstanced = null;
  43302. }
  43303. return true;
  43304. };
  43305. return Ellipse2DRenderCache;
  43306. }(BABYLON.ModelRenderCache));
  43307. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  43308. var Ellipse2DInstanceData = (function (_super) {
  43309. __extends(Ellipse2DInstanceData, _super);
  43310. function Ellipse2DInstanceData(partId) {
  43311. _super.call(this, partId, 1);
  43312. }
  43313. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  43314. get: function () {
  43315. return null;
  43316. },
  43317. enumerable: true,
  43318. configurable: true
  43319. });
  43320. __decorate([
  43321. BABYLON.instanceData()
  43322. ], Ellipse2DInstanceData.prototype, "properties", null);
  43323. return Ellipse2DInstanceData;
  43324. }(BABYLON.Shape2DInstanceData));
  43325. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  43326. var Ellipse2D = (function (_super) {
  43327. __extends(Ellipse2D, _super);
  43328. /**
  43329. * Create an Ellipse 2D Shape primitive
  43330. * @param settings a combination of settings, possible ones are
  43331. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  43332. * - children: an array of direct children
  43333. * - id: a text identifier, for information purpose
  43334. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43335. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43336. * - scale: the initial scale of the primitive. default is 1
  43337. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43338. * - origin: define the normalized origin point location, default [0.5;0.5]
  43339. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  43340. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  43341. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  43342. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  43343. * - borderThickness: the thickness of the drawn border, default is 1.
  43344. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43345. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43346. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43347. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43348. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43349. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43350. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43351. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43352. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43353. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43354. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43355. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43356. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43357. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43358. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43359. */
  43360. function Ellipse2D(settings) {
  43361. // Avoid checking every time if the object exists
  43362. if (settings == null) {
  43363. settings = {};
  43364. }
  43365. _super.call(this, settings);
  43366. if (settings.size != null) {
  43367. this.size = settings.size;
  43368. }
  43369. else if (settings.width || settings.height) {
  43370. var size = new BABYLON.Size(settings.width, settings.height);
  43371. this.size = size;
  43372. }
  43373. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  43374. this.subdivisions = sub;
  43375. }
  43376. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  43377. get: function () {
  43378. if (this._actualSize) {
  43379. return this._actualSize;
  43380. }
  43381. return this.size;
  43382. },
  43383. set: function (value) {
  43384. this._actualSize = value;
  43385. },
  43386. enumerable: true,
  43387. configurable: true
  43388. });
  43389. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  43390. get: function () {
  43391. return this._subdivisions;
  43392. },
  43393. set: function (value) {
  43394. this._subdivisions = value;
  43395. },
  43396. enumerable: true,
  43397. configurable: true
  43398. });
  43399. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  43400. var w = this.size.width / 2;
  43401. var h = this.size.height / 2;
  43402. var x = intersectInfo._localPickPosition.x - w;
  43403. var y = intersectInfo._localPickPosition.y - h;
  43404. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  43405. };
  43406. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  43407. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43408. };
  43409. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  43410. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  43411. return renderCache;
  43412. };
  43413. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43414. var renderCache = modelRenderCache;
  43415. var engine = this.owner.engine;
  43416. // Need to create WebGL resources for fill part?
  43417. if (this.fill) {
  43418. var vbSize = this.subdivisions + 1;
  43419. var vb = new Float32Array(vbSize);
  43420. for (var i = 0; i < vbSize; i++) {
  43421. vb[i] = i;
  43422. }
  43423. renderCache.fillVB = engine.createVertexBuffer(vb);
  43424. var triCount = vbSize - 1;
  43425. var ib = new Float32Array(triCount * 3);
  43426. for (var i = 0; i < triCount; i++) {
  43427. ib[i * 3 + 0] = 0;
  43428. ib[i * 3 + 2] = i + 1;
  43429. ib[i * 3 + 1] = i + 2;
  43430. }
  43431. ib[triCount * 3 - 2] = 1;
  43432. renderCache.fillIB = engine.createIndexBuffer(ib);
  43433. renderCache.fillIndicesCount = triCount * 3;
  43434. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43435. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43436. if (ei) {
  43437. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43438. }
  43439. // Get the non instanced version
  43440. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43441. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43442. }
  43443. // Need to create WebGL resource for border part?
  43444. if (this.border) {
  43445. var vbSize = this.subdivisions * 2;
  43446. var vb = new Float32Array(vbSize);
  43447. for (var i = 0; i < vbSize; i++) {
  43448. vb[i] = i;
  43449. }
  43450. renderCache.borderVB = engine.createVertexBuffer(vb);
  43451. var triCount = vbSize;
  43452. var rs = triCount / 2;
  43453. var ib = new Float32Array(triCount * 3);
  43454. for (var i = 0; i < rs; i++) {
  43455. var r0 = i;
  43456. var r1 = (i + 1) % rs;
  43457. ib[i * 6 + 0] = rs + r1;
  43458. ib[i * 6 + 1] = rs + r0;
  43459. ib[i * 6 + 2] = r0;
  43460. ib[i * 6 + 3] = r1;
  43461. ib[i * 6 + 4] = rs + r1;
  43462. ib[i * 6 + 5] = r0;
  43463. }
  43464. renderCache.borderIB = engine.createIndexBuffer(ib);
  43465. renderCache.borderIndicesCount = (triCount * 3);
  43466. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43467. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43468. if (ei) {
  43469. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43470. }
  43471. // Get the non instanced version
  43472. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43473. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43474. }
  43475. return renderCache;
  43476. };
  43477. Ellipse2D.prototype.createInstanceDataParts = function () {
  43478. var res = new Array();
  43479. if (this.border) {
  43480. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43481. }
  43482. if (this.fill) {
  43483. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43484. }
  43485. return res;
  43486. };
  43487. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  43488. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43489. return false;
  43490. }
  43491. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43492. var d = part;
  43493. var size = this.actualSize;
  43494. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43495. }
  43496. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43497. var d = part;
  43498. var size = this.actualSize;
  43499. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43500. }
  43501. return true;
  43502. };
  43503. __decorate([
  43504. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  43505. ], Ellipse2D.prototype, "actualSize", null);
  43506. __decorate([
  43507. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  43508. ], Ellipse2D.prototype, "subdivisions", null);
  43509. Ellipse2D = __decorate([
  43510. BABYLON.className("Ellipse2D")
  43511. ], Ellipse2D);
  43512. return Ellipse2D;
  43513. }(BABYLON.Shape2D));
  43514. BABYLON.Ellipse2D = Ellipse2D;
  43515. })(BABYLON || (BABYLON = {}));
  43516. var BABYLON;
  43517. (function (BABYLON) {
  43518. var Sprite2DRenderCache = (function (_super) {
  43519. __extends(Sprite2DRenderCache, _super);
  43520. function Sprite2DRenderCache() {
  43521. _super.apply(this, arguments);
  43522. this.effectsReady = false;
  43523. this.vb = null;
  43524. this.ib = null;
  43525. this.instancingAttributes = null;
  43526. this.texture = null;
  43527. this.effect = null;
  43528. this.effectInstanced = null;
  43529. }
  43530. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  43531. // Do nothing if the shader is still loading/preparing
  43532. if (!this.effectsReady) {
  43533. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43534. return false;
  43535. }
  43536. this.effectsReady = true;
  43537. }
  43538. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  43539. var canvas = instanceInfo.owner.owner;
  43540. var engine = canvas.engine;
  43541. var cur = engine.getAlphaMode();
  43542. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43543. engine.enableEffect(effect);
  43544. effect.setTexture("diffuseSampler", this.texture);
  43545. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43546. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43548. }
  43549. var pid = context.groupInfoPartData[0];
  43550. if (context.useInstancing) {
  43551. if (!this.instancingAttributes) {
  43552. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  43553. }
  43554. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43555. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43556. canvas._addDrawCallCount(1, context.renderMode);
  43557. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43558. engine.draw(true, 0, 6, count);
  43559. engine.unbindInstanceAttributes();
  43560. }
  43561. else {
  43562. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43563. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43564. this.setupUniforms(effect, 0, pid._partData, i);
  43565. engine.draw(true, 0, 6);
  43566. }
  43567. }
  43568. engine.setAlphaMode(cur);
  43569. return true;
  43570. };
  43571. Sprite2DRenderCache.prototype.dispose = function () {
  43572. if (!_super.prototype.dispose.call(this)) {
  43573. return false;
  43574. }
  43575. if (this.vb) {
  43576. this._engine._releaseBuffer(this.vb);
  43577. this.vb = null;
  43578. }
  43579. if (this.ib) {
  43580. this._engine._releaseBuffer(this.ib);
  43581. this.ib = null;
  43582. }
  43583. if (this.texture) {
  43584. this.texture.dispose();
  43585. this.texture = null;
  43586. }
  43587. if (this.effect) {
  43588. this._engine._releaseEffect(this.effect);
  43589. this.effect = null;
  43590. }
  43591. if (this.effectInstanced) {
  43592. this._engine._releaseEffect(this.effectInstanced);
  43593. this.effectInstanced = null;
  43594. }
  43595. return true;
  43596. };
  43597. return Sprite2DRenderCache;
  43598. }(BABYLON.ModelRenderCache));
  43599. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  43600. var Sprite2DInstanceData = (function (_super) {
  43601. __extends(Sprite2DInstanceData, _super);
  43602. function Sprite2DInstanceData(partId) {
  43603. _super.call(this, partId, 1);
  43604. }
  43605. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  43606. get: function () {
  43607. return null;
  43608. },
  43609. enumerable: true,
  43610. configurable: true
  43611. });
  43612. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  43613. get: function () {
  43614. return null;
  43615. },
  43616. enumerable: true,
  43617. configurable: true
  43618. });
  43619. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  43620. get: function () {
  43621. return null;
  43622. },
  43623. enumerable: true,
  43624. configurable: true
  43625. });
  43626. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  43627. // 3 floats being:
  43628. // - x: frame number to display
  43629. // - y: invertY setting
  43630. // - z: alignToPixel setting
  43631. get: function () {
  43632. return null;
  43633. },
  43634. enumerable: true,
  43635. configurable: true
  43636. });
  43637. __decorate([
  43638. BABYLON.instanceData()
  43639. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  43640. __decorate([
  43641. BABYLON.instanceData()
  43642. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  43643. __decorate([
  43644. BABYLON.instanceData()
  43645. ], Sprite2DInstanceData.prototype, "textureSize", null);
  43646. __decorate([
  43647. BABYLON.instanceData()
  43648. ], Sprite2DInstanceData.prototype, "properties", null);
  43649. return Sprite2DInstanceData;
  43650. }(BABYLON.InstanceDataBase));
  43651. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  43652. var Sprite2D = (function (_super) {
  43653. __extends(Sprite2D, _super);
  43654. /**
  43655. * Create an 2D Sprite primitive
  43656. * @param texture the texture that stores the sprite to render
  43657. * @param settings a combination of settings, possible ones are
  43658. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  43659. * - children: an array of direct children
  43660. * - id a text identifier, for information purpose
  43661. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43662. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43663. * - scale: the initial scale of the primitive. default is 1
  43664. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43665. * - origin: define the normalized origin point location, default [0.5;0.5]
  43666. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  43667. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  43668. * - invertY: if true the texture Y will be inverted, default is false.
  43669. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  43670. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  43671. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43672. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43673. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43674. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43675. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43676. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43677. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43678. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43679. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43680. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43681. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43682. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43683. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43684. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43685. */
  43686. function Sprite2D(texture, settings) {
  43687. var _this = this;
  43688. if (!settings) {
  43689. settings = {};
  43690. }
  43691. _super.call(this, settings);
  43692. this.texture = texture;
  43693. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43694. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43695. this.size = settings.spriteSize;
  43696. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  43697. this.spriteFrame = 0;
  43698. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  43699. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  43700. this.isAlphaTest = true;
  43701. if (settings.spriteSize == null) {
  43702. if (texture.isReady()) {
  43703. this.size = texture.getSize();
  43704. }
  43705. else {
  43706. texture.onLoadObservable.add(function () {
  43707. _this.size = texture.getSize();
  43708. });
  43709. }
  43710. }
  43711. }
  43712. Object.defineProperty(Sprite2D.prototype, "texture", {
  43713. get: function () {
  43714. return this._texture;
  43715. },
  43716. set: function (value) {
  43717. this._texture = value;
  43718. },
  43719. enumerable: true,
  43720. configurable: true
  43721. });
  43722. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  43723. get: function () {
  43724. if (this._actualSize) {
  43725. return this._actualSize;
  43726. }
  43727. return this.size;
  43728. },
  43729. set: function (value) {
  43730. this._actualSize = value;
  43731. },
  43732. enumerable: true,
  43733. configurable: true
  43734. });
  43735. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  43736. get: function () {
  43737. return this._location;
  43738. },
  43739. set: function (value) {
  43740. this._location = value;
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  43746. get: function () {
  43747. return this._spriteFrame;
  43748. },
  43749. set: function (value) {
  43750. this._spriteFrame = value;
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(Sprite2D.prototype, "invertY", {
  43756. get: function () {
  43757. return this._invertY;
  43758. },
  43759. set: function (value) {
  43760. this._invertY = value;
  43761. },
  43762. enumerable: true,
  43763. configurable: true
  43764. });
  43765. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  43766. /**
  43767. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  43768. */
  43769. get: function () {
  43770. return this._alignToPixel;
  43771. },
  43772. set: function (value) {
  43773. this._alignToPixel = value;
  43774. },
  43775. enumerable: true,
  43776. configurable: true
  43777. });
  43778. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  43779. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  43780. };
  43781. /**
  43782. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  43783. */
  43784. Sprite2D.prototype.getAnimatables = function () {
  43785. var res = new Array();
  43786. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  43787. res.push(this.texture);
  43788. }
  43789. return res;
  43790. };
  43791. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  43792. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  43793. return true;
  43794. };
  43795. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  43796. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  43797. return sprite;
  43798. };
  43799. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  43800. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  43801. return renderCache;
  43802. };
  43803. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43804. var renderCache = modelRenderCache;
  43805. var engine = this.owner.engine;
  43806. var vb = new Float32Array(4);
  43807. for (var i = 0; i < 4; i++) {
  43808. vb[i] = i;
  43809. }
  43810. renderCache.vb = engine.createVertexBuffer(vb);
  43811. var ib = new Float32Array(6);
  43812. ib[0] = 0;
  43813. ib[1] = 2;
  43814. ib[2] = 1;
  43815. ib[3] = 0;
  43816. ib[4] = 3;
  43817. ib[5] = 2;
  43818. renderCache.ib = engine.createIndexBuffer(ib);
  43819. renderCache.texture = this.texture;
  43820. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  43821. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  43822. if (ei) {
  43823. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43824. }
  43825. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  43826. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43827. return renderCache;
  43828. };
  43829. Sprite2D.prototype.createInstanceDataParts = function () {
  43830. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  43831. };
  43832. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43833. Sprite2D.layoutConstructMode = true;
  43834. };
  43835. // if obj contains something, we restore the _text property
  43836. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43837. Sprite2D.layoutConstructMode = false;
  43838. };
  43839. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  43840. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43841. return false;
  43842. }
  43843. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  43844. return false;
  43845. }
  43846. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  43847. var d = this._instanceDataParts[0];
  43848. if (Sprite2D.layoutConstructMode) {
  43849. d.topLeftUV = BABYLON.Vector2.Zero();
  43850. d.sizeUV = BABYLON.Vector2.Zero();
  43851. d.properties = BABYLON.Vector3.Zero();
  43852. d.textureSize = BABYLON.Vector2.Zero();
  43853. }
  43854. else {
  43855. var ts = this.texture.getBaseSize();
  43856. var sl = this.spriteLocation;
  43857. var ss = this.actualSize;
  43858. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  43859. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  43860. d.sizeUV = suv;
  43861. Sprite2D._prop.x = this.spriteFrame;
  43862. Sprite2D._prop.y = this.invertY ? 1 : 0;
  43863. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  43864. d.properties = Sprite2D._prop;
  43865. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43866. }
  43867. }
  43868. return true;
  43869. };
  43870. Sprite2D.SPRITE2D_MAINPARTID = 1;
  43871. Sprite2D._prop = BABYLON.Vector3.Zero();
  43872. Sprite2D.layoutConstructMode = false;
  43873. __decorate([
  43874. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  43875. ], Sprite2D.prototype, "texture", null);
  43876. __decorate([
  43877. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  43878. ], Sprite2D.prototype, "actualSize", null);
  43879. __decorate([
  43880. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  43881. ], Sprite2D.prototype, "spriteLocation", null);
  43882. __decorate([
  43883. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  43884. ], Sprite2D.prototype, "spriteFrame", null);
  43885. __decorate([
  43886. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  43887. ], Sprite2D.prototype, "invertY", null);
  43888. Sprite2D = __decorate([
  43889. BABYLON.className("Sprite2D")
  43890. ], Sprite2D);
  43891. return Sprite2D;
  43892. }(BABYLON.RenderablePrim2D));
  43893. BABYLON.Sprite2D = Sprite2D;
  43894. })(BABYLON || (BABYLON = {}));
  43895. var BABYLON;
  43896. (function (BABYLON) {
  43897. var Text2DRenderCache = (function (_super) {
  43898. __extends(Text2DRenderCache, _super);
  43899. function Text2DRenderCache() {
  43900. _super.apply(this, arguments);
  43901. this.effectsReady = false;
  43902. this.vb = null;
  43903. this.ib = null;
  43904. this.instancingAttributes = null;
  43905. this.fontTexture = null;
  43906. this.effect = null;
  43907. this.effectInstanced = null;
  43908. }
  43909. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  43910. // Do nothing if the shader is still loading/preparing
  43911. if (!this.effectsReady) {
  43912. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43913. return false;
  43914. }
  43915. this.effectsReady = true;
  43916. }
  43917. var canvas = instanceInfo.owner.owner;
  43918. var engine = canvas.engine;
  43919. this.fontTexture.update();
  43920. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43921. engine.enableEffect(effect);
  43922. effect.setTexture("diffuseSampler", this.fontTexture);
  43923. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43924. var curAlphaMode = engine.getAlphaMode();
  43925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43926. var pid = context.groupInfoPartData[0];
  43927. if (context.useInstancing) {
  43928. if (!this.instancingAttributes) {
  43929. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  43930. }
  43931. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43932. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43933. canvas._addDrawCallCount(1, context.renderMode);
  43934. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43935. engine.draw(true, 0, 6, count);
  43936. engine.unbindInstanceAttributes();
  43937. }
  43938. else {
  43939. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43940. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43941. this.setupUniforms(effect, 0, pid._partData, i);
  43942. engine.draw(true, 0, 6);
  43943. }
  43944. }
  43945. engine.setAlphaMode(curAlphaMode);
  43946. return true;
  43947. };
  43948. Text2DRenderCache.prototype.dispose = function () {
  43949. if (!_super.prototype.dispose.call(this)) {
  43950. return false;
  43951. }
  43952. if (this.vb) {
  43953. this._engine._releaseBuffer(this.vb);
  43954. this.vb = null;
  43955. }
  43956. if (this.ib) {
  43957. this._engine._releaseBuffer(this.ib);
  43958. this.ib = null;
  43959. }
  43960. if (this.fontTexture) {
  43961. this.fontTexture.dispose();
  43962. this.fontTexture = null;
  43963. }
  43964. if (this.effect) {
  43965. this._engine._releaseEffect(this.effect);
  43966. this.effect = null;
  43967. }
  43968. if (this.effectInstanced) {
  43969. this._engine._releaseEffect(this.effectInstanced);
  43970. this.effectInstanced = null;
  43971. }
  43972. return true;
  43973. };
  43974. return Text2DRenderCache;
  43975. }(BABYLON.ModelRenderCache));
  43976. BABYLON.Text2DRenderCache = Text2DRenderCache;
  43977. var Text2DInstanceData = (function (_super) {
  43978. __extends(Text2DInstanceData, _super);
  43979. function Text2DInstanceData(partId, dataElementCount) {
  43980. _super.call(this, partId, dataElementCount);
  43981. }
  43982. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  43983. get: function () {
  43984. return null;
  43985. },
  43986. enumerable: true,
  43987. configurable: true
  43988. });
  43989. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  43990. get: function () {
  43991. return null;
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  43997. get: function () {
  43998. return null;
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  44004. get: function () {
  44005. return null;
  44006. },
  44007. enumerable: true,
  44008. configurable: true
  44009. });
  44010. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  44011. get: function () {
  44012. return null;
  44013. },
  44014. enumerable: true,
  44015. configurable: true
  44016. });
  44017. __decorate([
  44018. BABYLON.instanceData()
  44019. ], Text2DInstanceData.prototype, "topLeftUV", null);
  44020. __decorate([
  44021. BABYLON.instanceData()
  44022. ], Text2DInstanceData.prototype, "sizeUV", null);
  44023. __decorate([
  44024. BABYLON.instanceData()
  44025. ], Text2DInstanceData.prototype, "textureSize", null);
  44026. __decorate([
  44027. BABYLON.instanceData()
  44028. ], Text2DInstanceData.prototype, "color", null);
  44029. __decorate([
  44030. BABYLON.instanceData()
  44031. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  44032. return Text2DInstanceData;
  44033. }(BABYLON.InstanceDataBase));
  44034. BABYLON.Text2DInstanceData = Text2DInstanceData;
  44035. var Text2D = (function (_super) {
  44036. __extends(Text2D, _super);
  44037. /**
  44038. * Create a Text primitive
  44039. * @param text the text to display
  44040. * @param settings a combination of settings, possible ones are
  44041. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  44042. * - children: an array of direct children
  44043. * - id a text identifier, for information purpose
  44044. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44045. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44046. * - scale: the initial scale of the primitive. default is 1
  44047. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44048. * - origin: define the normalized origin point location, default [0.5;0.5]
  44049. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  44050. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  44051. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  44052. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  44053. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  44054. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  44055. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44056. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44057. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44058. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44059. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44060. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44061. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44062. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44063. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44064. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44065. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44066. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44067. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44068. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44069. */
  44070. function Text2D(text, settings) {
  44071. if (!settings) {
  44072. settings = {};
  44073. }
  44074. _super.call(this, settings);
  44075. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  44076. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  44077. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  44078. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  44079. this._textSize = null;
  44080. this.text = text;
  44081. this.size = (settings.size == null) ? null : settings.size;
  44082. this.isTransparent = true;
  44083. }
  44084. Object.defineProperty(Text2D.prototype, "fontName", {
  44085. get: function () {
  44086. return this._fontName;
  44087. },
  44088. set: function (value) {
  44089. if (this._fontName) {
  44090. throw new Error("Font Name change is not supported right now.");
  44091. }
  44092. this._fontName = value;
  44093. },
  44094. enumerable: true,
  44095. configurable: true
  44096. });
  44097. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  44098. get: function () {
  44099. return this._defaultFontColor;
  44100. },
  44101. set: function (value) {
  44102. this._defaultFontColor = value;
  44103. },
  44104. enumerable: true,
  44105. configurable: true
  44106. });
  44107. Object.defineProperty(Text2D.prototype, "text", {
  44108. get: function () {
  44109. return this._text;
  44110. },
  44111. set: function (value) {
  44112. this._text = value;
  44113. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  44114. this._size = null;
  44115. this._updateCharCount();
  44116. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  44117. var s = this.textSize;
  44118. },
  44119. enumerable: true,
  44120. configurable: true
  44121. });
  44122. Object.defineProperty(Text2D.prototype, "size", {
  44123. get: function () {
  44124. if (this._size != null) {
  44125. return this._size;
  44126. }
  44127. return this.textSize;
  44128. },
  44129. set: function (value) {
  44130. this._size = value;
  44131. },
  44132. enumerable: true,
  44133. configurable: true
  44134. });
  44135. Object.defineProperty(Text2D.prototype, "actualSize", {
  44136. /**
  44137. * Get the actual size of the Text2D primitive
  44138. */
  44139. get: function () {
  44140. if (this._actualSize) {
  44141. return this._actualSize;
  44142. }
  44143. return this.size;
  44144. },
  44145. enumerable: true,
  44146. configurable: true
  44147. });
  44148. Object.defineProperty(Text2D.prototype, "textSize", {
  44149. /**
  44150. * Get the area that bounds the text associated to the primitive
  44151. */
  44152. get: function () {
  44153. if (!this._textSize) {
  44154. if (this.owner) {
  44155. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  44156. if (!newSize.equals(this._textSize)) {
  44157. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  44158. this._positioningDirty();
  44159. }
  44160. this._textSize = newSize;
  44161. }
  44162. else {
  44163. return Text2D.nullSize;
  44164. }
  44165. }
  44166. return this._textSize;
  44167. },
  44168. enumerable: true,
  44169. configurable: true
  44170. });
  44171. Object.defineProperty(Text2D.prototype, "fontTexture", {
  44172. get: function () {
  44173. if (this._fontTexture) {
  44174. return this._fontTexture;
  44175. }
  44176. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44177. return this._fontTexture;
  44178. },
  44179. enumerable: true,
  44180. configurable: true
  44181. });
  44182. /**
  44183. * Dispose the primitive, remove it from its parent
  44184. */
  44185. Text2D.prototype.dispose = function () {
  44186. if (!_super.prototype.dispose.call(this)) {
  44187. return false;
  44188. }
  44189. if (this._fontTexture) {
  44190. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44191. this._fontTexture = null;
  44192. }
  44193. return true;
  44194. };
  44195. Text2D.prototype.updateLevelBoundingInfo = function () {
  44196. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44197. };
  44198. Text2D.prototype.levelIntersect = function (intersectInfo) {
  44199. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  44200. return true;
  44201. };
  44202. Text2D.prototype.createModelRenderCache = function (modelKey) {
  44203. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  44204. return renderCache;
  44205. };
  44206. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44207. var renderCache = modelRenderCache;
  44208. var engine = this.owner.engine;
  44209. renderCache.fontTexture = this.fontTexture;
  44210. var vb = new Float32Array(4);
  44211. for (var i = 0; i < 4; i++) {
  44212. vb[i] = i;
  44213. }
  44214. renderCache.vb = engine.createVertexBuffer(vb);
  44215. var ib = new Float32Array(6);
  44216. ib[0] = 0;
  44217. ib[1] = 2;
  44218. ib[2] = 1;
  44219. ib[3] = 0;
  44220. ib[4] = 3;
  44221. ib[5] = 2;
  44222. renderCache.ib = engine.createIndexBuffer(ib);
  44223. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  44224. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  44225. if (ei) {
  44226. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44227. }
  44228. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  44229. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44230. return renderCache;
  44231. };
  44232. Text2D.prototype.createInstanceDataParts = function () {
  44233. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  44234. };
  44235. // Looks like a hack!? Yes! Because that's what it is!
  44236. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  44237. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  44238. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  44239. if (!this._charCount) {
  44240. var curText = this._text;
  44241. this.text = "A";
  44242. return curText;
  44243. }
  44244. };
  44245. // if obj contains something, we restore the _text property
  44246. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  44247. if (obj !== undefined) {
  44248. this.text = obj;
  44249. }
  44250. };
  44251. Text2D.prototype.refreshInstanceDataPart = function (part) {
  44252. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44253. return false;
  44254. }
  44255. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  44256. var d = part;
  44257. var texture = this.fontTexture;
  44258. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  44259. var ts = texture.getSize();
  44260. var offset = BABYLON.Vector2.Zero();
  44261. var lh = this.fontTexture.lineHeight;
  44262. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  44263. var charxpos = 0;
  44264. d.dataElementCount = this._charCount;
  44265. d.curElement = 0;
  44266. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  44267. var char = _a[_i];
  44268. // Line feed
  44269. if (char === "\n") {
  44270. offset.x = 0;
  44271. offset.y -= texture.lineHeight;
  44272. }
  44273. // Tabulation ?
  44274. if (char === "\t") {
  44275. var nextPos = charxpos + this._tabulationSize;
  44276. nextPos = nextPos - (nextPos % this._tabulationSize);
  44277. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  44278. charxpos = nextPos;
  44279. continue;
  44280. }
  44281. if (char < " ") {
  44282. continue;
  44283. }
  44284. this.updateInstanceDataPart(d, offset);
  44285. var ci = texture.getChar(char);
  44286. offset.x += ci.charWidth;
  44287. d.topLeftUV = ci.topLeftUV;
  44288. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  44289. d.sizeUV = suv;
  44290. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  44291. d.color = this.defaultFontColor;
  44292. d.superSampleFactor = superSampleFactor;
  44293. ++d.curElement;
  44294. }
  44295. }
  44296. return true;
  44297. };
  44298. Text2D.prototype._updateCharCount = function () {
  44299. var count = 0;
  44300. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  44301. var char = _a[_i];
  44302. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  44303. continue;
  44304. }
  44305. ++count;
  44306. }
  44307. this._charCount = count;
  44308. };
  44309. Text2D.TEXT2D_MAINPARTID = 1;
  44310. __decorate([
  44311. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  44312. ], Text2D.prototype, "fontName", null);
  44313. __decorate([
  44314. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  44315. ], Text2D.prototype, "defaultFontColor", null);
  44316. __decorate([
  44317. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  44318. ], Text2D.prototype, "text", null);
  44319. __decorate([
  44320. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  44321. ], Text2D.prototype, "size", null);
  44322. Text2D = __decorate([
  44323. BABYLON.className("Text2D")
  44324. ], Text2D);
  44325. return Text2D;
  44326. }(BABYLON.RenderablePrim2D));
  44327. BABYLON.Text2D = Text2D;
  44328. })(BABYLON || (BABYLON = {}));
  44329. var BABYLON;
  44330. (function (BABYLON) {
  44331. var Lines2DRenderCache = (function (_super) {
  44332. __extends(Lines2DRenderCache, _super);
  44333. function Lines2DRenderCache(engine, modelKey) {
  44334. _super.call(this, engine, modelKey);
  44335. this.effectsReady = false;
  44336. this.fillVB = null;
  44337. this.fillIB = null;
  44338. this.fillIndicesCount = 0;
  44339. this.instancingFillAttributes = null;
  44340. this.effectFill = null;
  44341. this.effectFillInstanced = null;
  44342. this.borderVB = null;
  44343. this.borderIB = null;
  44344. this.borderIndicesCount = 0;
  44345. this.instancingBorderAttributes = null;
  44346. this.effectBorder = null;
  44347. this.effectBorderInstanced = null;
  44348. }
  44349. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  44350. // Do nothing if the shader is still loading/preparing
  44351. if (!this.effectsReady) {
  44352. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44353. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44354. return false;
  44355. }
  44356. this.effectsReady = true;
  44357. }
  44358. var canvas = instanceInfo.owner.owner;
  44359. var engine = canvas.engine;
  44360. var depthFunction = 0;
  44361. if (this.effectFill && this.effectBorder) {
  44362. depthFunction = engine.getDepthFunction();
  44363. engine.setDepthFunctionToLessOrEqual();
  44364. }
  44365. var curAlphaMode = engine.getAlphaMode();
  44366. if (this.effectFill) {
  44367. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44368. var pid = context.groupInfoPartData[partIndex];
  44369. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44370. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44371. }
  44372. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44373. engine.enableEffect(effect);
  44374. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  44375. if (context.useInstancing) {
  44376. if (!this.instancingFillAttributes) {
  44377. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44378. }
  44379. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44380. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44381. canvas._addDrawCallCount(1, context.renderMode);
  44382. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44383. engine.draw(true, 0, this.fillIndicesCount, count);
  44384. engine.unbindInstanceAttributes();
  44385. }
  44386. else {
  44387. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44388. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44389. this.setupUniforms(effect, partIndex, pid._partData, i);
  44390. engine.draw(true, 0, this.fillIndicesCount);
  44391. }
  44392. }
  44393. }
  44394. if (this.effectBorder) {
  44395. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44396. var pid = context.groupInfoPartData[partIndex];
  44397. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44398. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44399. }
  44400. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44401. engine.enableEffect(effect);
  44402. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  44403. if (context.useInstancing) {
  44404. if (!this.instancingBorderAttributes) {
  44405. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44406. }
  44407. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44408. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44409. canvas._addDrawCallCount(1, context.renderMode);
  44410. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44411. engine.draw(true, 0, this.borderIndicesCount, count);
  44412. engine.unbindInstanceAttributes();
  44413. }
  44414. else {
  44415. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44416. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44417. this.setupUniforms(effect, partIndex, pid._partData, i);
  44418. engine.draw(true, 0, this.borderIndicesCount);
  44419. }
  44420. }
  44421. }
  44422. engine.setAlphaMode(curAlphaMode);
  44423. if (this.effectFill && this.effectBorder) {
  44424. engine.setDepthFunction(depthFunction);
  44425. }
  44426. return true;
  44427. };
  44428. Lines2DRenderCache.prototype.dispose = function () {
  44429. if (!_super.prototype.dispose.call(this)) {
  44430. return false;
  44431. }
  44432. if (this.fillVB) {
  44433. this._engine._releaseBuffer(this.fillVB);
  44434. this.fillVB = null;
  44435. }
  44436. if (this.fillIB) {
  44437. this._engine._releaseBuffer(this.fillIB);
  44438. this.fillIB = null;
  44439. }
  44440. if (this.effectFill) {
  44441. this._engine._releaseEffect(this.effectFill);
  44442. this.effectFill = null;
  44443. }
  44444. if (this.effectFillInstanced) {
  44445. this._engine._releaseEffect(this.effectFillInstanced);
  44446. this.effectFillInstanced = null;
  44447. }
  44448. if (this.borderVB) {
  44449. this._engine._releaseBuffer(this.borderVB);
  44450. this.borderVB = null;
  44451. }
  44452. if (this.borderIB) {
  44453. this._engine._releaseBuffer(this.borderIB);
  44454. this.borderIB = null;
  44455. }
  44456. if (this.effectBorder) {
  44457. this._engine._releaseEffect(this.effectBorder);
  44458. this.effectBorder = null;
  44459. }
  44460. if (this.effectBorderInstanced) {
  44461. this._engine._releaseEffect(this.effectBorderInstanced);
  44462. this.effectBorderInstanced = null;
  44463. }
  44464. return true;
  44465. };
  44466. return Lines2DRenderCache;
  44467. }(BABYLON.ModelRenderCache));
  44468. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  44469. var Lines2DInstanceData = (function (_super) {
  44470. __extends(Lines2DInstanceData, _super);
  44471. function Lines2DInstanceData(partId) {
  44472. _super.call(this, partId, 1);
  44473. }
  44474. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  44475. get: function () {
  44476. return null;
  44477. },
  44478. enumerable: true,
  44479. configurable: true
  44480. });
  44481. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  44482. get: function () {
  44483. return null;
  44484. },
  44485. enumerable: true,
  44486. configurable: true
  44487. });
  44488. __decorate([
  44489. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44490. ], Lines2DInstanceData.prototype, "boundingMin", null);
  44491. __decorate([
  44492. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44493. ], Lines2DInstanceData.prototype, "boundingMax", null);
  44494. return Lines2DInstanceData;
  44495. }(BABYLON.Shape2DInstanceData));
  44496. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  44497. var Lines2D = (function (_super) {
  44498. __extends(Lines2D, _super);
  44499. /**
  44500. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  44501. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  44502. * @param settings a combination of settings, possible ones are
  44503. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  44504. * - children: an array of direct children
  44505. * - id a text identifier, for information purpose
  44506. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44507. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44508. * - scale: the initial scale of the primitive. default is 1
  44509. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44510. * - origin: define the normalized origin point location, default [0.5;0.5]
  44511. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  44512. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  44513. * - startCap: Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  44514. * - endCap: Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  44515. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can be a string value (see Canvas2D.GetBrushFromString)
  44516. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  44517. * - borderThickness: the thickness of the drawn border, default is 1.
  44518. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44519. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44520. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44521. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44522. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44523. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44524. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44525. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44526. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44527. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44528. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44529. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44530. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44531. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44532. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44533. */
  44534. function Lines2D(points, settings) {
  44535. if (!settings) {
  44536. settings = {};
  44537. }
  44538. _super.call(this, settings);
  44539. this._fillVB = null;
  44540. this._fillIB = null;
  44541. this._borderVB = null;
  44542. this._borderIB = null;
  44543. this._size = BABYLON.Size.Zero();
  44544. this._boundingMin = null;
  44545. this._boundingMax = null;
  44546. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  44547. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  44548. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  44549. var closed = (settings.closed == null) ? false : settings.closed;
  44550. this.points = points;
  44551. this.fillThickness = fillThickness;
  44552. this.startCap = startCap;
  44553. this.endCap = endCap;
  44554. this.closed = closed;
  44555. }
  44556. Object.defineProperty(Lines2D, "NoCap", {
  44557. /**
  44558. * No Cap to apply on the extremity
  44559. */
  44560. get: function () { return Lines2D._noCap; },
  44561. enumerable: true,
  44562. configurable: true
  44563. });
  44564. Object.defineProperty(Lines2D, "RoundCap", {
  44565. /**
  44566. * A round cap, will use the line thickness as diameter
  44567. */
  44568. get: function () { return Lines2D._roundCap; },
  44569. enumerable: true,
  44570. configurable: true
  44571. });
  44572. Object.defineProperty(Lines2D, "TriangleCap", {
  44573. /**
  44574. * Creates a triangle at the extremity.
  44575. */
  44576. get: function () { return Lines2D._triangleCap; },
  44577. enumerable: true,
  44578. configurable: true
  44579. });
  44580. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  44581. /**
  44582. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  44583. */
  44584. get: function () { return Lines2D._squareAnchorCap; },
  44585. enumerable: true,
  44586. configurable: true
  44587. });
  44588. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  44589. /**
  44590. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  44591. */
  44592. get: function () { return Lines2D._roundAnchorCap; },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  44597. /**
  44598. * Creates a diamond anchor at the extremity.
  44599. */
  44600. get: function () { return Lines2D._diamondAnchorCap; },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. Object.defineProperty(Lines2D, "ArrowCap", {
  44605. /**
  44606. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  44607. */
  44608. get: function () { return Lines2D._arrowCap; },
  44609. enumerable: true,
  44610. configurable: true
  44611. });
  44612. Object.defineProperty(Lines2D.prototype, "points", {
  44613. get: function () {
  44614. return this._points;
  44615. },
  44616. set: function (value) {
  44617. this._points = value;
  44618. this._boundingBoxDirty();
  44619. },
  44620. enumerable: true,
  44621. configurable: true
  44622. });
  44623. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  44624. get: function () {
  44625. return this._fillThickness;
  44626. },
  44627. set: function (value) {
  44628. this._fillThickness = value;
  44629. },
  44630. enumerable: true,
  44631. configurable: true
  44632. });
  44633. Object.defineProperty(Lines2D.prototype, "closed", {
  44634. get: function () {
  44635. return this._closed;
  44636. },
  44637. set: function (value) {
  44638. this._closed = value;
  44639. },
  44640. enumerable: true,
  44641. configurable: true
  44642. });
  44643. Object.defineProperty(Lines2D.prototype, "startCap", {
  44644. get: function () {
  44645. return this._startCap;
  44646. },
  44647. set: function (value) {
  44648. this._startCap = value;
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. Object.defineProperty(Lines2D.prototype, "endCap", {
  44654. get: function () {
  44655. return this._endCap;
  44656. },
  44657. set: function (value) {
  44658. this._endCap = value;
  44659. },
  44660. enumerable: true,
  44661. configurable: true
  44662. });
  44663. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  44664. var _this = this;
  44665. if (this._contour == null) {
  44666. this._computeLines2D();
  44667. }
  44668. var pl = this.points.length;
  44669. var l = this.closed ? pl + 1 : pl;
  44670. var p = intersectInfo._localPickPosition;
  44671. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  44672. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  44673. for (var i = 1; i < l; i++) {
  44674. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  44675. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  44676. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  44677. return true;
  44678. }
  44679. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  44680. return true;
  44681. }
  44682. Lines2D._prevA.x = Lines2D._curA.x;
  44683. Lines2D._prevA.y = Lines2D._curA.y;
  44684. Lines2D._prevB.x = Lines2D._curB.x;
  44685. Lines2D._prevB.y = Lines2D._curB.y;
  44686. }
  44687. var capIntersect = function (tri, points) {
  44688. var l = tri.length;
  44689. for (var i = 0; i < l; i += 3) {
  44690. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  44691. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  44692. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  44693. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  44694. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  44695. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  44696. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  44697. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  44698. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  44699. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  44700. return true;
  44701. }
  44702. }
  44703. return false;
  44704. };
  44705. if (this._startCapTriIndices) {
  44706. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  44707. return true;
  44708. }
  44709. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  44710. return true;
  44711. }
  44712. }
  44713. return false;
  44714. };
  44715. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  44716. get: function () {
  44717. if (!this._boundingMin) {
  44718. this._computeLines2D();
  44719. }
  44720. return this._boundingMin;
  44721. },
  44722. enumerable: true,
  44723. configurable: true
  44724. });
  44725. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  44726. get: function () {
  44727. if (!this._boundingMax) {
  44728. this._computeLines2D();
  44729. }
  44730. return this._boundingMax;
  44731. },
  44732. enumerable: true,
  44733. configurable: true
  44734. });
  44735. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  44736. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  44737. // Remove the BORDER category, we don't use it in the VertexShader
  44738. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  44739. if (i !== -1) {
  44740. res.splice(i, 1);
  44741. }
  44742. return res;
  44743. };
  44744. Lines2D.prototype.updateLevelBoundingInfo = function () {
  44745. if (!this._boundingMin) {
  44746. this._computeLines2D();
  44747. }
  44748. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  44749. };
  44750. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  44751. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  44752. return renderCache;
  44753. };
  44754. ///////////////////////////////////////////////////////////////////////////////////
  44755. // Methods for Lines building
  44756. Lines2D.prototype._perp = function (v, res) {
  44757. res.x = v.y;
  44758. res.y = -v.x;
  44759. };
  44760. ;
  44761. Lines2D.prototype._direction = function (a, b, res) {
  44762. a.subtractToRef(b, res);
  44763. res.normalize();
  44764. };
  44765. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  44766. a.addToRef(b, tangent);
  44767. tangent.normalize();
  44768. miter.x = -tangent.y;
  44769. miter.y = tangent.x;
  44770. Lines2D._miterTps.x = -a.y;
  44771. Lines2D._miterTps.y = a.x;
  44772. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  44773. };
  44774. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  44775. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  44776. if (d === 0)
  44777. return false;
  44778. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  44779. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  44780. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  44781. return false;
  44782. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  44783. return false;
  44784. return true;
  44785. };
  44786. Lines2D.prototype._updateMinMax = function (array, offset) {
  44787. if (offset >= array.length) {
  44788. return;
  44789. }
  44790. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  44791. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  44792. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  44793. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  44794. };
  44795. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  44796. var borderMode = borderThickness != null && !isNaN(borderThickness);
  44797. var off = index * (borderMode ? 8 : 4);
  44798. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  44799. if (off >= array.length) {
  44800. return;
  44801. }
  44802. // Store start/end normal, we need it for the cap construction
  44803. if (index === 0) {
  44804. this._perp(n, Lines2D._startDir);
  44805. }
  44806. else if (index === max - 1) {
  44807. this._perp(n, Lines2D._endDir);
  44808. Lines2D._endDir.x *= -1;
  44809. Lines2D._endDir.y *= -1;
  44810. }
  44811. var swap = false;
  44812. array[off + 0] = p.x + n.x * halfThickness;
  44813. array[off + 1] = p.y + n.y * halfThickness;
  44814. array[off + 2] = p.x + n.x * -halfThickness;
  44815. array[off + 3] = p.y + n.y * -halfThickness;
  44816. this._updateMinMax(array, off);
  44817. this._updateMinMax(array, off + 2);
  44818. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  44819. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  44820. if (detectFlip !== undefined) {
  44821. // Flip if intersect
  44822. var flipOff = detectFlip * (borderMode ? 8 : 4);
  44823. if (this._intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  44824. swap = true;
  44825. var tps = array[off + 0];
  44826. array[off + 0] = array[off + 2];
  44827. array[off + 2] = tps;
  44828. tps = array[off + 1];
  44829. array[off + 1] = array[off + 3];
  44830. array[off + 3] = tps;
  44831. }
  44832. }
  44833. if (borderMode) {
  44834. var t = halfThickness + borderThickness;
  44835. array[off + 4] = p.x + n.x * (swap ? -t : t);
  44836. array[off + 5] = p.y + n.y * (swap ? -t : t);
  44837. array[off + 6] = p.x + n.x * (swap ? t : -t);
  44838. array[off + 7] = p.y + n.y * (swap ? t : -t);
  44839. this._updateMinMax(array, off + 4);
  44840. this._updateMinMax(array, off + 6);
  44841. }
  44842. if (contour) {
  44843. off += borderMode ? 4 : 0;
  44844. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  44845. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  44846. }
  44847. };
  44848. Lines2D.prototype._getCapSize = function (type, border) {
  44849. if (border === void 0) { border = false; }
  44850. var sd = Lines2D._roundCapSubDiv;
  44851. // If no array given, we call this to get the size
  44852. var vbsize = 0, ibsize = 0;
  44853. switch (type) {
  44854. case Lines2D.NoCap:
  44855. {
  44856. // If the line is not close and we're computing border, we add the size to generate the edge border
  44857. if (!this.closed && border) {
  44858. vbsize = 4;
  44859. ibsize = 6;
  44860. }
  44861. else {
  44862. vbsize = ibsize = 0;
  44863. }
  44864. break;
  44865. }
  44866. case Lines2D.RoundCap:
  44867. {
  44868. if (border) {
  44869. vbsize = sd;
  44870. ibsize = (sd - 2) * 3;
  44871. }
  44872. else {
  44873. vbsize = (sd / 2) + 1;
  44874. ibsize = (sd / 2) * 3;
  44875. }
  44876. break;
  44877. }
  44878. case Lines2D.ArrowCap:
  44879. {
  44880. if (border) {
  44881. vbsize = 12;
  44882. ibsize = 24;
  44883. }
  44884. else {
  44885. vbsize = 3;
  44886. ibsize = 3;
  44887. }
  44888. break;
  44889. }
  44890. case Lines2D.TriangleCap:
  44891. {
  44892. if (border) {
  44893. vbsize = 6;
  44894. ibsize = 12;
  44895. }
  44896. else {
  44897. vbsize = 3;
  44898. ibsize = 3;
  44899. }
  44900. break;
  44901. }
  44902. case Lines2D.DiamondAnchorCap:
  44903. {
  44904. if (border) {
  44905. vbsize = 10;
  44906. ibsize = 24;
  44907. }
  44908. else {
  44909. vbsize = 5;
  44910. ibsize = 9;
  44911. }
  44912. break;
  44913. }
  44914. case Lines2D.SquareAnchorCap:
  44915. {
  44916. if (border) {
  44917. vbsize = 12;
  44918. ibsize = 30;
  44919. }
  44920. else {
  44921. vbsize = 4;
  44922. ibsize = 6;
  44923. }
  44924. break;
  44925. }
  44926. case Lines2D.RoundAnchorCap:
  44927. {
  44928. if (border) {
  44929. vbsize = sd * 2;
  44930. ibsize = (sd - 1) * 6;
  44931. }
  44932. else {
  44933. vbsize = sd + 1;
  44934. ibsize = (sd + 1) * 3;
  44935. }
  44936. break;
  44937. }
  44938. }
  44939. return { vbsize: vbsize * 2, ibsize: ibsize };
  44940. };
  44941. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  44942. var c = Math.cos(rotation);
  44943. var s = Math.sin(rotation);
  44944. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  44945. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  44946. var offset = baseOffset + (index * 2);
  44947. vb[offset + 0] = Lines2D._tpsV.x;
  44948. vb[offset + 1] = Lines2D._tpsV.y;
  44949. if (contour) {
  44950. contour.push(Lines2D._tpsV.x);
  44951. contour.push(Lines2D._tpsV.y);
  44952. }
  44953. this._updateMinMax(vb, offset);
  44954. return (baseOffset + index * 2) / 2;
  44955. };
  44956. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  44957. ib[baseOffset + index] = vertexIndex;
  44958. };
  44959. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  44960. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  44961. var sd = Lines2D._roundCapSubDiv;
  44962. var dir = new BABYLON.Vector2(1, 0);
  44963. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  44964. var ht = thickness / 2;
  44965. var t = thickness;
  44966. var borderMode = borderThickness != null;
  44967. var bt = borderThickness;
  44968. switch (type) {
  44969. case Lines2D.NoCap:
  44970. if (borderMode && !this.closed) {
  44971. var vi = 0;
  44972. var ii = 0;
  44973. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  44974. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  44975. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  44976. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  44977. this._storeIndex(ib, ibi, ii++, v1);
  44978. this._storeIndex(ib, ibi, ii++, v2);
  44979. this._storeIndex(ib, ibi, ii++, v3);
  44980. this._storeIndex(ib, ibi, ii++, v1);
  44981. this._storeIndex(ib, ibi, ii++, v3);
  44982. this._storeIndex(ib, ibi, ii++, v4);
  44983. }
  44984. break;
  44985. case Lines2D.ArrowCap:
  44986. ht *= 2;
  44987. case Lines2D.TriangleCap:
  44988. {
  44989. if (borderMode) {
  44990. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  44991. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  44992. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  44993. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  44994. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  44995. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  44996. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  44997. var ii = 0;
  44998. this._storeIndex(ib, ibi, ii++, v1);
  44999. this._storeIndex(ib, ibi, ii++, v4);
  45000. this._storeIndex(ib, ibi, ii++, v5);
  45001. this._storeIndex(ib, ibi, ii++, v1);
  45002. this._storeIndex(ib, ibi, ii++, v5);
  45003. this._storeIndex(ib, ibi, ii++, v2);
  45004. this._storeIndex(ib, ibi, ii++, v6);
  45005. this._storeIndex(ib, ibi, ii++, v3);
  45006. this._storeIndex(ib, ibi, ii++, v2);
  45007. this._storeIndex(ib, ibi, ii++, v6);
  45008. this._storeIndex(ib, ibi, ii++, v2);
  45009. this._storeIndex(ib, ibi, ii++, v5);
  45010. if (type === Lines2D.ArrowCap) {
  45011. var rht = thickness / 2;
  45012. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  45013. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  45014. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  45015. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  45016. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  45017. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  45018. this._storeIndex(ib, ibi, ii++, v7);
  45019. this._storeIndex(ib, ibi, ii++, v8);
  45020. this._storeIndex(ib, ibi, ii++, v9);
  45021. this._storeIndex(ib, ibi, ii++, v7);
  45022. this._storeIndex(ib, ibi, ii++, v9);
  45023. this._storeIndex(ib, ibi, ii++, v4);
  45024. this._storeIndex(ib, ibi, ii++, v10);
  45025. this._storeIndex(ib, ibi, ii++, v12);
  45026. this._storeIndex(ib, ibi, ii++, v11);
  45027. this._storeIndex(ib, ibi, ii++, v10);
  45028. this._storeIndex(ib, ibi, ii++, v6);
  45029. this._storeIndex(ib, ibi, ii++, v12);
  45030. }
  45031. }
  45032. else {
  45033. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  45034. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  45035. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  45036. this._storeIndex(ib, ibi, 0, v1);
  45037. this._storeIndex(ib, ibi, 1, v2);
  45038. this._storeIndex(ib, ibi, 2, v3);
  45039. }
  45040. break;
  45041. }
  45042. case Lines2D.RoundCap:
  45043. {
  45044. if (borderMode) {
  45045. var curA = -Math.PI / 2;
  45046. var incA = Math.PI / (sd / 2 - 1);
  45047. var ii = 0;
  45048. for (var i = 0; i < (sd / 2); i++) {
  45049. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45050. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  45051. if (i > 0) {
  45052. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45053. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45054. this._storeIndex(ib, ibi, ii++, v2);
  45055. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45056. this._storeIndex(ib, ibi, ii++, v2);
  45057. this._storeIndex(ib, ibi, ii++, v1);
  45058. }
  45059. curA += incA;
  45060. }
  45061. }
  45062. else {
  45063. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  45064. var curA = -Math.PI / 2;
  45065. var incA = Math.PI / (sd / 2 - 1);
  45066. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45067. curA += incA;
  45068. for (var i = 1; i < (sd / 2); i++) {
  45069. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  45070. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45071. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45072. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45073. curA += incA;
  45074. }
  45075. }
  45076. break;
  45077. }
  45078. case Lines2D.SquareAnchorCap:
  45079. {
  45080. var vi = 0;
  45081. var c = borderMode ? null : contour;
  45082. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  45083. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  45084. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  45085. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  45086. if (borderMode) {
  45087. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  45088. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  45089. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  45090. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  45091. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  45092. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  45093. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  45094. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  45095. var ii = 0;
  45096. this._storeIndex(ib, ibi, ii++, v6);
  45097. this._storeIndex(ib, ibi, ii++, v1);
  45098. this._storeIndex(ib, ibi, ii++, v5);
  45099. this._storeIndex(ib, ibi, ii++, v6);
  45100. this._storeIndex(ib, ibi, ii++, v7);
  45101. this._storeIndex(ib, ibi, ii++, v1);
  45102. this._storeIndex(ib, ibi, ii++, v1);
  45103. this._storeIndex(ib, ibi, ii++, v7);
  45104. this._storeIndex(ib, ibi, ii++, v8);
  45105. this._storeIndex(ib, ibi, ii++, v1);
  45106. this._storeIndex(ib, ibi, ii++, v8);
  45107. this._storeIndex(ib, ibi, ii++, v2);
  45108. this._storeIndex(ib, ibi, ii++, v2);
  45109. this._storeIndex(ib, ibi, ii++, v8);
  45110. this._storeIndex(ib, ibi, ii++, v9);
  45111. this._storeIndex(ib, ibi, ii++, v2);
  45112. this._storeIndex(ib, ibi, ii++, v9);
  45113. this._storeIndex(ib, ibi, ii++, v3);
  45114. this._storeIndex(ib, ibi, ii++, v3);
  45115. this._storeIndex(ib, ibi, ii++, v9);
  45116. this._storeIndex(ib, ibi, ii++, v10);
  45117. this._storeIndex(ib, ibi, ii++, v3);
  45118. this._storeIndex(ib, ibi, ii++, v10);
  45119. this._storeIndex(ib, ibi, ii++, v4);
  45120. this._storeIndex(ib, ibi, ii++, v10);
  45121. this._storeIndex(ib, ibi, ii++, v11);
  45122. this._storeIndex(ib, ibi, ii++, v4);
  45123. this._storeIndex(ib, ibi, ii++, v11);
  45124. this._storeIndex(ib, ibi, ii++, v12);
  45125. this._storeIndex(ib, ibi, ii++, v4);
  45126. }
  45127. else {
  45128. this._storeIndex(ib, ibi, 0, v1);
  45129. this._storeIndex(ib, ibi, 1, v2);
  45130. this._storeIndex(ib, ibi, 2, v3);
  45131. this._storeIndex(ib, ibi, 3, v1);
  45132. this._storeIndex(ib, ibi, 4, v3);
  45133. this._storeIndex(ib, ibi, 5, v4);
  45134. }
  45135. break;
  45136. }
  45137. case Lines2D.RoundAnchorCap:
  45138. {
  45139. var cpos = Math.sqrt(t * t - ht * ht);
  45140. var center = new BABYLON.Vector2(cpos, 0);
  45141. var curA = BABYLON.Tools.ToRadians(-150);
  45142. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  45143. if (borderMode) {
  45144. var ii = 0;
  45145. for (var i = 0; i < sd; i++) {
  45146. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45147. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  45148. if (i > 0) {
  45149. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45150. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45151. this._storeIndex(ib, ibi, ii++, v2);
  45152. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45153. this._storeIndex(ib, ibi, ii++, v2);
  45154. this._storeIndex(ib, ibi, ii++, v1);
  45155. }
  45156. curA += incA;
  45157. }
  45158. }
  45159. else {
  45160. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  45161. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45162. curA += incA;
  45163. for (var i = 1; i < sd; i++) {
  45164. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  45165. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45166. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45167. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45168. curA += incA;
  45169. }
  45170. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  45171. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  45172. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  45173. }
  45174. break;
  45175. }
  45176. case Lines2D.DiamondAnchorCap:
  45177. {
  45178. var vi = 0;
  45179. var c = borderMode ? null : contour;
  45180. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  45181. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  45182. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  45183. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  45184. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  45185. if (borderMode) {
  45186. var f = Math.sqrt(bt * bt * 2);
  45187. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  45188. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  45189. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  45190. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  45191. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  45192. var ii = 0;
  45193. this._storeIndex(ib, ibi, ii++, v6);
  45194. this._storeIndex(ib, ibi, ii++, v7);
  45195. this._storeIndex(ib, ibi, ii++, v1);
  45196. this._storeIndex(ib, ibi, ii++, v1);
  45197. this._storeIndex(ib, ibi, ii++, v7);
  45198. this._storeIndex(ib, ibi, ii++, v2);
  45199. this._storeIndex(ib, ibi, ii++, v2);
  45200. this._storeIndex(ib, ibi, ii++, v7);
  45201. this._storeIndex(ib, ibi, ii++, v8);
  45202. this._storeIndex(ib, ibi, ii++, v2);
  45203. this._storeIndex(ib, ibi, ii++, v8);
  45204. this._storeIndex(ib, ibi, ii++, v3);
  45205. this._storeIndex(ib, ibi, ii++, v3);
  45206. this._storeIndex(ib, ibi, ii++, v8);
  45207. this._storeIndex(ib, ibi, ii++, v9);
  45208. this._storeIndex(ib, ibi, ii++, v3);
  45209. this._storeIndex(ib, ibi, ii++, v9);
  45210. this._storeIndex(ib, ibi, ii++, v4);
  45211. this._storeIndex(ib, ibi, ii++, v4);
  45212. this._storeIndex(ib, ibi, ii++, v9);
  45213. this._storeIndex(ib, ibi, ii++, v10);
  45214. this._storeIndex(ib, ibi, ii++, v4);
  45215. this._storeIndex(ib, ibi, ii++, v10);
  45216. this._storeIndex(ib, ibi, ii++, v5);
  45217. }
  45218. else {
  45219. this._storeIndex(ib, ibi, 0, v1);
  45220. this._storeIndex(ib, ibi, 1, v2);
  45221. this._storeIndex(ib, ibi, 2, v3);
  45222. this._storeIndex(ib, ibi, 3, v1);
  45223. this._storeIndex(ib, ibi, 4, v3);
  45224. this._storeIndex(ib, ibi, 5, v5);
  45225. this._storeIndex(ib, ibi, 6, v5);
  45226. this._storeIndex(ib, ibi, 7, v3);
  45227. this._storeIndex(ib, ibi, 8, v4);
  45228. }
  45229. break;
  45230. }
  45231. }
  45232. return null;
  45233. };
  45234. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  45235. var lineA = BABYLON.Vector2.Zero();
  45236. var lineB = BABYLON.Vector2.Zero();
  45237. var tangent = BABYLON.Vector2.Zero();
  45238. var miter = BABYLON.Vector2.Zero();
  45239. var curNormal = null;
  45240. if (this.closed) {
  45241. this.points.push(this.points[0]);
  45242. }
  45243. var total = this.points.length;
  45244. for (var i = 1; i < total; i++) {
  45245. var last = this.points[i - 1];
  45246. var cur = this.points[i];
  45247. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  45248. this._direction(cur, last, lineA);
  45249. if (!curNormal) {
  45250. curNormal = BABYLON.Vector2.Zero();
  45251. this._perp(lineA, curNormal);
  45252. }
  45253. if (i === 1) {
  45254. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  45255. }
  45256. if (!next) {
  45257. this._perp(lineA, curNormal);
  45258. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  45259. }
  45260. else {
  45261. this._direction(next, cur, lineB);
  45262. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  45263. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  45264. }
  45265. }
  45266. if (this.points.length > 2 && this.closed) {
  45267. var last2 = this.points[total - 2];
  45268. var cur2 = this.points[0];
  45269. var next2 = this.points[1];
  45270. this._direction(cur2, last2, lineA);
  45271. this._direction(next2, cur2, lineB);
  45272. this._perp(lineA, curNormal);
  45273. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  45274. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  45275. // Patch contour
  45276. if (contour) {
  45277. var off = (bt == null) ? 0 : 4;
  45278. contour[0].x = vb[off + 0];
  45279. contour[0].y = vb[off + 1];
  45280. contour[1].x = vb[off + 2];
  45281. contour[1].y = vb[off + 3];
  45282. }
  45283. }
  45284. // Remove the point we added at the beginning
  45285. if (this.closed) {
  45286. this.points.splice(total - 1);
  45287. }
  45288. };
  45289. // Methods for Lines building
  45290. ///////////////////////////////////////////////////////////////////////////////////
  45291. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45292. var renderCache = modelRenderCache;
  45293. var engine = this.owner.engine;
  45294. if (this._fillVB === null) {
  45295. this._computeLines2D();
  45296. }
  45297. // Need to create WebGL resources for fill part?
  45298. if (this.fill) {
  45299. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  45300. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  45301. renderCache.fillIndicesCount = this._fillIB.length;
  45302. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  45303. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  45304. if (ei) {
  45305. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45306. }
  45307. // Get the non instanced version
  45308. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  45309. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45310. }
  45311. // Need to create WebGL resources for border part?
  45312. if (this.border) {
  45313. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  45314. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  45315. renderCache.borderIndicesCount = this._borderIB.length;
  45316. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  45317. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  45318. if (ei) {
  45319. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45320. }
  45321. // Get the non instanced version
  45322. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  45323. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45324. }
  45325. this._fillVB = null;
  45326. this._fillIB = null;
  45327. this._borderVB = null;
  45328. this._borderIB = null;
  45329. return renderCache;
  45330. };
  45331. Lines2D.prototype._computeLines2D = function () {
  45332. // Init min/max because their being computed here
  45333. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  45334. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  45335. var contour = new Array();
  45336. var startCapContour = new Array();
  45337. var endCapContour = new Array();
  45338. // Need to create WebGL resources for fill part?
  45339. if (this.fill) {
  45340. var startCapInfo = this._getCapSize(this.startCap);
  45341. var endCapInfo = this._getCapSize(this.endCap);
  45342. var count = this.points.length;
  45343. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45344. this._fillVB = new Float32Array(vbSize);
  45345. var vb = this._fillVB;
  45346. var ht = this.fillThickness / 2;
  45347. var total = this.points.length;
  45348. this._buildLine(vb, this.border ? null : contour, ht);
  45349. var max = total * 2;
  45350. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  45351. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45352. var ib = this._fillIB;
  45353. for (var i = 0; i < triCount; i += 2) {
  45354. ib[i * 3 + 0] = i + 0;
  45355. ib[i * 3 + 1] = i + 1;
  45356. ib[i * 3 + 2] = (i + 2) % max;
  45357. ib[i * 3 + 3] = i + 1;
  45358. ib[i * 3 + 4] = (i + 3) % max;
  45359. ib[i * 3 + 5] = (i + 2) % max;
  45360. }
  45361. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  45362. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D._endDir, this.border ? null : startCapContour);
  45363. }
  45364. // Need to create WebGL resources for border part?
  45365. if (this.border) {
  45366. var startCapInfo = this._getCapSize(this.startCap, true);
  45367. var endCapInfo = this._getCapSize(this.endCap, true);
  45368. var count = this.points.length;
  45369. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45370. this._borderVB = new Float32Array(vbSize);
  45371. var vb = this._borderVB;
  45372. var ht = this.fillThickness / 2;
  45373. var bt = this.borderThickness;
  45374. var total = this.points.length;
  45375. this._buildLine(vb, contour, ht, bt);
  45376. var max = total * 2 * 2;
  45377. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  45378. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45379. var ib = this._borderIB;
  45380. for (var i = 0; i < triCount; i += 4) {
  45381. ib[i * 3 + 0] = i + 0;
  45382. ib[i * 3 + 1] = i + 2;
  45383. ib[i * 3 + 2] = (i + 6) % max;
  45384. ib[i * 3 + 3] = i + 0;
  45385. ib[i * 3 + 4] = (i + 6) % max;
  45386. ib[i * 3 + 5] = (i + 4) % max;
  45387. ib[i * 3 + 6] = i + 3;
  45388. ib[i * 3 + 7] = i + 1;
  45389. ib[i * 3 + 8] = (i + 5) % max;
  45390. ib[i * 3 + 9] = i + 3;
  45391. ib[i * 3 + 10] = (i + 5) % max;
  45392. ib[i * 3 + 11] = (i + 7) % max;
  45393. }
  45394. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  45395. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D._endDir, endCapContour);
  45396. }
  45397. this._contour = contour;
  45398. if (startCapContour.length > 0) {
  45399. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  45400. this._startCapTriIndices = startCapTri;
  45401. this._startCapContour = startCapContour;
  45402. }
  45403. if (endCapContour.length > 0) {
  45404. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  45405. this._endCapContour = endCapContour;
  45406. this._endCapTriIndices = endCapTri;
  45407. }
  45408. var bs = this._boundingMax.subtract(this._boundingMin);
  45409. this._size.width = bs.x;
  45410. this._size.height = bs.y;
  45411. };
  45412. Object.defineProperty(Lines2D.prototype, "size", {
  45413. get: function () {
  45414. if (this._size == null) {
  45415. this._computeLines2D();
  45416. }
  45417. return this._size;
  45418. },
  45419. enumerable: true,
  45420. configurable: true
  45421. });
  45422. Lines2D.prototype.createInstanceDataParts = function () {
  45423. var res = new Array();
  45424. if (this.border) {
  45425. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45426. }
  45427. if (this.fill) {
  45428. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45429. }
  45430. return res;
  45431. };
  45432. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  45433. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45434. return false;
  45435. }
  45436. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45437. var d = part;
  45438. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  45439. d.boundingMin = this.boundingMin;
  45440. d.boundingMax = this.boundingMax;
  45441. }
  45442. }
  45443. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45444. var d = part;
  45445. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  45446. d.boundingMin = this.boundingMin;
  45447. d.boundingMax = this.boundingMax;
  45448. }
  45449. }
  45450. return true;
  45451. };
  45452. Lines2D._prevA = BABYLON.Vector2.Zero();
  45453. Lines2D._prevB = BABYLON.Vector2.Zero();
  45454. Lines2D._curA = BABYLON.Vector2.Zero();
  45455. Lines2D._curB = BABYLON.Vector2.Zero();
  45456. Lines2D._miterTps = BABYLON.Vector2.Zero();
  45457. Lines2D._startDir = BABYLON.Vector2.Zero();
  45458. Lines2D._endDir = BABYLON.Vector2.Zero();
  45459. Lines2D._tpsV = BABYLON.Vector2.Zero();
  45460. Lines2D._noCap = 0;
  45461. Lines2D._roundCap = 1;
  45462. Lines2D._triangleCap = 2;
  45463. Lines2D._squareAnchorCap = 3;
  45464. Lines2D._roundAnchorCap = 4;
  45465. Lines2D._diamondAnchorCap = 5;
  45466. Lines2D._arrowCap = 6;
  45467. Lines2D._roundCapSubDiv = 36;
  45468. __decorate([
  45469. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  45470. ], Lines2D.prototype, "points", null);
  45471. __decorate([
  45472. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  45473. ], Lines2D.prototype, "fillThickness", null);
  45474. __decorate([
  45475. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  45476. ], Lines2D.prototype, "closed", null);
  45477. __decorate([
  45478. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  45479. ], Lines2D.prototype, "startCap", null);
  45480. __decorate([
  45481. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  45482. ], Lines2D.prototype, "endCap", null);
  45483. Lines2D = __decorate([
  45484. BABYLON.className("Lines2D")
  45485. ], Lines2D);
  45486. return Lines2D;
  45487. }(BABYLON.Shape2D));
  45488. BABYLON.Lines2D = Lines2D;
  45489. })(BABYLON || (BABYLON = {}));
  45490. var BABYLON;
  45491. (function (BABYLON) {
  45492. // This class contains data that lifetime is bounding to the Babylon Engine object
  45493. var Canvas2DEngineBoundData = (function () {
  45494. function Canvas2DEngineBoundData() {
  45495. this._modelCache = new BABYLON.StringDictionary();
  45496. }
  45497. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  45498. return this._modelCache.getOrAddWithFactory(key, factory);
  45499. };
  45500. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  45501. if (!modelRenderCache.isDisposed) {
  45502. return false;
  45503. }
  45504. this._modelCache.remove(modelRenderCache.modelKey);
  45505. return true;
  45506. };
  45507. return Canvas2DEngineBoundData;
  45508. }());
  45509. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  45510. var Canvas2D = (function (_super) {
  45511. __extends(Canvas2D, _super);
  45512. function Canvas2D(scene, settings) {
  45513. var _this = this;
  45514. _super.call(this, settings);
  45515. /**
  45516. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  45517. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  45518. */
  45519. this.worldSpaceToNodeLocal = function (worldPos) {
  45520. var node = _this._worldSpaceNode;
  45521. if (!node) {
  45522. return;
  45523. }
  45524. var mtx = node.getWorldMatrix().clone();
  45525. mtx.invert();
  45526. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  45527. var res = new BABYLON.Vector2(v.x, v.y);
  45528. var size = _this.actualSize;
  45529. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  45530. res.y += size.height * 0.5;
  45531. return res;
  45532. };
  45533. /**
  45534. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  45535. */
  45536. this.worldSpaceCacheChanged = function () {
  45537. var plane = _this.worldSpaceCanvasNode;
  45538. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  45539. vd.uvs = new Float32Array(8);
  45540. var material = plane.material;
  45541. var tex = _this._renderableData._cacheTexture;
  45542. if (material.diffuseTexture !== tex) {
  45543. material.diffuseTexture = tex;
  45544. tex.hasAlpha = true;
  45545. }
  45546. var nodeuv = _this._renderableData._cacheNodeUVs;
  45547. for (var i = 0; i < 4; i++) {
  45548. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  45549. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  45550. }
  45551. vd.applyToMesh(plane);
  45552. };
  45553. this._notifDebugMode = false;
  45554. this._mapCounter = 0;
  45555. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  45556. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  45557. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  45558. this._groupRenderCounter = new BABYLON.PerfCounter();
  45559. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  45560. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  45561. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  45562. this._updateLayoutCounter = new BABYLON.PerfCounter();
  45563. this._updatePositioningCounter = new BABYLON.PerfCounter();
  45564. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  45565. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  45566. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  45567. this._profileInfoText = null;
  45568. BABYLON.Prim2DBase._isCanvasInit = false;
  45569. if (!settings) {
  45570. settings = {};
  45571. }
  45572. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  45573. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  45574. this._background.zOrder = 1.0;
  45575. this._background.isPickable = false;
  45576. this._background.origin = BABYLON.Vector2.Zero();
  45577. this._background.levelVisible = false;
  45578. if (settings.backgroundRoundRadius != null) {
  45579. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  45580. }
  45581. if (settings.backgroundBorder != null) {
  45582. if (typeof (settings.backgroundBorder) === "string") {
  45583. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  45584. }
  45585. else {
  45586. this.backgroundBorder = settings.backgroundBorder;
  45587. }
  45588. }
  45589. if (settings.backgroundBorderThickNess != null) {
  45590. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  45591. }
  45592. if (settings.backgroundFill != null) {
  45593. if (typeof (settings.backgroundFill) === "string") {
  45594. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  45595. }
  45596. else {
  45597. this.backgroundFill = settings.backgroundFill;
  45598. }
  45599. }
  45600. this._background._patchHierarchy(this);
  45601. }
  45602. var engine = scene.getEngine();
  45603. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  45604. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  45605. this._capturedPointers = new BABYLON.StringDictionary();
  45606. this._pickStartingPosition = BABYLON.Vector2.Zero();
  45607. this._hierarchyLevelMaxSiblingCount = 50;
  45608. this._hierarchyDepth = 0;
  45609. this._zOrder = 0;
  45610. this._zMax = 1;
  45611. this._scene = scene;
  45612. this._engine = engine;
  45613. this._renderingSize = new BABYLON.Size(0, 0);
  45614. this._trackedGroups = new Array();
  45615. this._maxAdaptiveWorldSpaceCanvasSize = null;
  45616. this._groupCacheMaps = new BABYLON.StringDictionary();
  45617. this._patchHierarchy(this);
  45618. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  45619. this._fitRenderingDevice = !settings.size;
  45620. if (!settings.size) {
  45621. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  45622. }
  45623. // Register scene dispose to also dispose the canvas when it'll happens
  45624. scene.onDisposeObservable.add(function (d, s) {
  45625. _this.dispose();
  45626. });
  45627. if (this._isScreenSpace) {
  45628. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  45629. _this._engine.clear(null, false, true);
  45630. _this._render();
  45631. });
  45632. }
  45633. else {
  45634. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  45635. _this._render();
  45636. });
  45637. }
  45638. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  45639. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  45640. this._setupInteraction(enableInteraction);
  45641. }
  45642. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  45643. get: function () {
  45644. return this._drawCallsOpaqueCounter;
  45645. },
  45646. enumerable: true,
  45647. configurable: true
  45648. });
  45649. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  45650. get: function () {
  45651. return this._drawCallsAlphaTestCounter;
  45652. },
  45653. enumerable: true,
  45654. configurable: true
  45655. });
  45656. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  45657. get: function () {
  45658. return this._drawCallsTransparentCounter;
  45659. },
  45660. enumerable: true,
  45661. configurable: true
  45662. });
  45663. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  45664. get: function () {
  45665. return this._groupRenderCounter;
  45666. },
  45667. enumerable: true,
  45668. configurable: true
  45669. });
  45670. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  45671. get: function () {
  45672. return this._updateTransparentDataCounter;
  45673. },
  45674. enumerable: true,
  45675. configurable: true
  45676. });
  45677. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  45678. get: function () {
  45679. return this._cachedGroupRenderCounter;
  45680. },
  45681. enumerable: true,
  45682. configurable: true
  45683. });
  45684. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  45685. get: function () {
  45686. return this._updateCachedStateCounter;
  45687. },
  45688. enumerable: true,
  45689. configurable: true
  45690. });
  45691. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  45692. get: function () {
  45693. return this._updateLayoutCounter;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  45699. get: function () {
  45700. return this._updatePositioningCounter;
  45701. },
  45702. enumerable: true,
  45703. configurable: true
  45704. });
  45705. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  45706. get: function () {
  45707. return this._updateLocalTransformCounter;
  45708. },
  45709. enumerable: true,
  45710. configurable: true
  45711. });
  45712. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  45713. get: function () {
  45714. return this._updateGlobalTransformCounter;
  45715. },
  45716. enumerable: true,
  45717. configurable: true
  45718. });
  45719. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  45720. get: function () {
  45721. return this._boundingInfoRecomputeCounter;
  45722. },
  45723. enumerable: true,
  45724. configurable: true
  45725. });
  45726. Canvas2D.prototype._canvasPreInit = function (settings) {
  45727. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  45728. this._cachingStrategy = cachingStrategy;
  45729. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  45730. };
  45731. Canvas2D.prototype._setupInteraction = function (enable) {
  45732. var _this = this;
  45733. // No change detection
  45734. if (enable === this._interactionEnabled) {
  45735. return;
  45736. }
  45737. // Set the new state
  45738. this._interactionEnabled = enable;
  45739. // ScreenSpace mode
  45740. if (this._isScreenSpace) {
  45741. // Disable interaction
  45742. if (!enable) {
  45743. if (this._scenePrePointerObserver) {
  45744. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  45745. this._scenePrePointerObserver = null;
  45746. }
  45747. return;
  45748. }
  45749. // Enable Interaction
  45750. // Register the observable
  45751. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  45752. var hs = 1 / _this.engine.getHardwareScalingLevel();
  45753. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  45754. _this._handlePointerEventForInteraction(e, localPos, s);
  45755. });
  45756. }
  45757. else {
  45758. var scene = this.scene;
  45759. if (enable) {
  45760. scene.constantlyUpdateMeshUnderPointer = true;
  45761. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  45762. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  45763. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  45764. _this._handlePointerEventForInteraction(e, localPos, s);
  45765. }
  45766. });
  45767. }
  45768. else {
  45769. if (this._scenePointerObserver) {
  45770. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  45771. this._scenePointerObserver = null;
  45772. }
  45773. }
  45774. }
  45775. };
  45776. /**
  45777. * Internal method, you should use the Prim2DBase version instead
  45778. */
  45779. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  45780. if (this.isPointerCaptured(pointerId)) {
  45781. return false;
  45782. }
  45783. // Try to capture the pointer on the HTML side
  45784. try {
  45785. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  45786. }
  45787. catch (e) {
  45788. }
  45789. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45790. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  45791. this._capturedPointers.add(pointerId.toString(), primitive);
  45792. return true;
  45793. };
  45794. /**
  45795. * Internal method, you should use the Prim2DBase version instead
  45796. */
  45797. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  45798. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  45799. return false;
  45800. }
  45801. // Try to release the pointer on the HTML side
  45802. try {
  45803. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  45804. }
  45805. catch (e) {
  45806. }
  45807. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45808. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  45809. this._capturedPointers.remove(pointerId.toString());
  45810. return true;
  45811. };
  45812. /**
  45813. * Determine if the given pointer is captured or not
  45814. * @param pointerId the Id of the pointer
  45815. * @return true if it's captured, false otherwise
  45816. */
  45817. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  45818. return this._capturedPointers.contains(pointerId.toString());
  45819. };
  45820. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  45821. // Avoid unnecessary lookup
  45822. if (this._capturedPointers.count === 0) {
  45823. return null;
  45824. }
  45825. return this._capturedPointers.get(pointerId.toString());
  45826. };
  45827. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  45828. // Dispose check
  45829. if (this.isDisposed) {
  45830. return;
  45831. }
  45832. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  45833. this._updatePointerInfo(eventData, localPosition);
  45834. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45835. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  45836. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  45837. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  45838. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  45839. this._updateOverStatus();
  45840. // Check if we have nothing to raise
  45841. if (!this._actualOverPrimitive && !capturedPrim) {
  45842. return;
  45843. }
  45844. // Update the relatedTarget info with the over primitive or the captured one (if any)
  45845. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  45846. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  45847. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  45848. // Analyze the pointer event type and fire proper events on the primitive
  45849. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45850. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  45851. }
  45852. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45853. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  45854. }
  45855. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  45856. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  45857. }
  45858. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  45859. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  45860. }
  45861. };
  45862. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  45863. var pii = this._primPointerInfo;
  45864. if (!pii.canvasPointerPos) {
  45865. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  45866. }
  45867. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  45868. var engine = this._scene.getEngine();
  45869. if (this._isScreenSpace) {
  45870. var cameraViewport = camera.viewport;
  45871. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45872. // Moving coordinates to local viewport world
  45873. var x = localPosition.x - viewport.x;
  45874. var y = localPosition.y - viewport.y;
  45875. pii.canvasPointerPos.x = x - this.actualPosition.x;
  45876. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  45877. }
  45878. else {
  45879. pii.canvasPointerPos.x = localPosition.x;
  45880. pii.canvasPointerPos.y = localPosition.y;
  45881. }
  45882. pii.mouseWheelDelta = 0;
  45883. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45884. var event = eventData.event;
  45885. if (event.wheelDelta) {
  45886. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  45887. }
  45888. else if (event.detail) {
  45889. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  45890. }
  45891. }
  45892. else {
  45893. var pe = eventData.event;
  45894. pii.ctrlKey = pe.ctrlKey;
  45895. pii.altKey = pe.altKey;
  45896. pii.shiftKey = pe.shiftKey;
  45897. pii.metaKey = pe.metaKey;
  45898. pii.button = pe.button;
  45899. pii.buttons = pe.buttons;
  45900. pii.pointerId = pe.pointerId;
  45901. pii.width = pe.width;
  45902. pii.height = pe.height;
  45903. pii.presssure = pe.pressure;
  45904. pii.tilt.x = pe.tiltX;
  45905. pii.tilt.y = pe.tiltY;
  45906. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  45907. }
  45908. };
  45909. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  45910. if (this.scene.getRenderId() === this._intersectionRenderId) {
  45911. return;
  45912. }
  45913. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  45914. if (!this._globalTransform) {
  45915. this.updateCachedStates(true);
  45916. }
  45917. var ii = Canvas2D._interInfo;
  45918. ii.pickPosition.x = mouseLocalPos.x;
  45919. ii.pickPosition.y = mouseLocalPos.y;
  45920. ii.findFirstOnly = false;
  45921. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  45922. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  45923. this._previousIntersectionList = this._actualIntersectionList;
  45924. this._actualIntersectionList = null;
  45925. this._previousOverPrimitive = this._actualOverPrimitive;
  45926. this._actualOverPrimitive = null;
  45927. return;
  45928. }
  45929. this.intersect(ii);
  45930. this._previousIntersectionList = this._actualIntersectionList;
  45931. this._actualIntersectionList = ii.intersectedPrimitives;
  45932. this._previousOverPrimitive = this._actualOverPrimitive;
  45933. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  45934. this._intersectionRenderId = this.scene.getRenderId();
  45935. };
  45936. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  45937. Canvas2D.prototype._updateOverStatus = function () {
  45938. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  45939. return;
  45940. }
  45941. // Detect a change of over
  45942. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  45943. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  45944. if (prevPrim !== actualPrim) {
  45945. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  45946. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45947. // Notify the previous "over" prim that the pointer is no longer over it
  45948. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  45949. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  45950. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  45951. }
  45952. // Notify the new "over" prim that the pointer is over it
  45953. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  45954. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  45955. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  45956. }
  45957. }
  45958. this._hoverStatusRenderId = this.scene.getRenderId();
  45959. };
  45960. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  45961. if (this._primPointerInfo.isCaptured) {
  45962. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  45963. }
  45964. else {
  45965. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  45966. var pii = _a[_i];
  45967. if (pii.prim === prim) {
  45968. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  45969. return;
  45970. }
  45971. }
  45972. }
  45973. };
  45974. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  45975. if (!this._notifDebugMode) {
  45976. return;
  45977. }
  45978. var debug = "";
  45979. for (var i = 0; i < prim.hierarchyDepth; i++) {
  45980. debug += " ";
  45981. }
  45982. var pii = this._primPointerInfo;
  45983. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  45984. console.log(debug);
  45985. };
  45986. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  45987. var ppi = this._primPointerInfo;
  45988. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  45989. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  45990. this._notifParents(prim, mask);
  45991. }
  45992. var bubbleCancelled = false;
  45993. var cur = prim;
  45994. while (cur) {
  45995. // Only trigger the observers if the primitive is intersected (except for out)
  45996. if (!bubbleCancelled) {
  45997. this._updatePrimPointerPos(cur);
  45998. // Exec the observers
  45999. this._debugExecObserver(cur, mask);
  46000. cur._pointerEventObservable.notifyObservers(ppi, mask);
  46001. this._triggerActionManager(cur, ppi, mask, eventData);
  46002. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  46003. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  46004. if (ppi.cancelBubble) {
  46005. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  46006. return;
  46007. }
  46008. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  46009. bubbleCancelled = true;
  46010. }
  46011. }
  46012. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  46013. if (bubbleCancelled) {
  46014. this._updatePrimPointerPos(cur);
  46015. }
  46016. // Trigger a PointerEnter corresponding to the PointerOver
  46017. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  46018. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  46019. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  46020. }
  46021. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  46022. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  46023. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  46024. }
  46025. // Loop to the parent
  46026. cur = cur.parent;
  46027. }
  46028. };
  46029. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  46030. var _this = this;
  46031. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  46032. if (!this._globalTransform) {
  46033. this.updateCachedStates(true);
  46034. }
  46035. // Process Trigger related to PointerDown
  46036. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  46037. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  46038. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  46039. this._pickStartingTime = new Date().getTime();
  46040. this._pickedDownPrim = null;
  46041. if (prim.actionManager) {
  46042. this._pickedDownPrim = prim;
  46043. if (prim.actionManager.hasPickTriggers) {
  46044. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46045. switch (eventData.button) {
  46046. case 0:
  46047. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  46048. break;
  46049. case 1:
  46050. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  46051. break;
  46052. case 2:
  46053. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  46054. break;
  46055. }
  46056. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  46057. }
  46058. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  46059. window.setTimeout(function () {
  46060. var ppi = _this._primPointerInfo;
  46061. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  46062. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  46063. var ii = new BABYLON.IntersectInfo2D();
  46064. ii.pickPosition = ppi.canvasPointerPos.clone();
  46065. ii.findFirstOnly = false;
  46066. _this.intersect(ii);
  46067. if (ii.isPrimIntersected(prim) !== null) {
  46068. if (prim.actionManager) {
  46069. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  46070. _this._pickStartingTime = 0;
  46071. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  46072. }
  46073. }
  46074. }
  46075. }, BABYLON.ActionManager.LongPressDelay);
  46076. }
  46077. }
  46078. }
  46079. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  46080. this._pickStartingTime = 0;
  46081. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46082. if (prim.actionManager) {
  46083. // OnPickUpTrigger
  46084. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  46085. // OnPickTrigger
  46086. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  46087. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  46088. }
  46089. }
  46090. // OnPickOutTrigger
  46091. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  46092. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  46093. }
  46094. }
  46095. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  46096. if (prim.actionManager) {
  46097. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46098. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  46099. }
  46100. }
  46101. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  46102. if (prim.actionManager) {
  46103. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46104. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  46105. }
  46106. }
  46107. };
  46108. Canvas2D.prototype._notifParents = function (prim, mask) {
  46109. var pii = this._primPointerInfo;
  46110. var curPrim = this;
  46111. while (curPrim) {
  46112. this._updatePrimPointerPos(curPrim);
  46113. // Fire the proper notification
  46114. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  46115. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  46116. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  46117. }
  46118. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  46119. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  46120. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  46121. }
  46122. curPrim = curPrim.parent;
  46123. }
  46124. };
  46125. /**
  46126. * Don't forget to call the dispose method when you're done with the Canvas instance.
  46127. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  46128. */
  46129. Canvas2D.prototype.dispose = function () {
  46130. if (!_super.prototype.dispose.call(this)) {
  46131. return false;
  46132. }
  46133. if (this._profilingCanvas) {
  46134. this._profilingCanvas.dispose();
  46135. this._profilingCanvas = null;
  46136. }
  46137. if (this.interactionEnabled) {
  46138. this._setupInteraction(false);
  46139. }
  46140. if (this._beforeRenderObserver) {
  46141. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  46142. this._beforeRenderObserver = null;
  46143. }
  46144. if (this._afterRenderObserver) {
  46145. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  46146. this._afterRenderObserver = null;
  46147. }
  46148. if (this._groupCacheMaps) {
  46149. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  46150. this._groupCacheMaps = null;
  46151. }
  46152. };
  46153. Object.defineProperty(Canvas2D.prototype, "scene", {
  46154. /**
  46155. * Accessor to the Scene that owns the Canvas
  46156. * @returns The instance of the Scene object
  46157. */
  46158. get: function () {
  46159. return this._scene;
  46160. },
  46161. enumerable: true,
  46162. configurable: true
  46163. });
  46164. Object.defineProperty(Canvas2D.prototype, "engine", {
  46165. /**
  46166. * Accessor to the Engine that drives the Scene used by this Canvas
  46167. * @returns The instance of the Engine object
  46168. */
  46169. get: function () {
  46170. return this._engine;
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  46176. /**
  46177. * Accessor of the Caching Strategy used by this Canvas.
  46178. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  46179. * @returns the value corresponding to the used strategy.
  46180. */
  46181. get: function () {
  46182. return this._cachingStrategy;
  46183. },
  46184. enumerable: true,
  46185. configurable: true
  46186. });
  46187. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  46188. /**
  46189. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  46190. * @returns {}
  46191. */
  46192. get: function () {
  46193. return this._isScreenSpace;
  46194. },
  46195. enumerable: true,
  46196. configurable: true
  46197. });
  46198. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  46199. /**
  46200. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  46201. */
  46202. get: function () {
  46203. return this._worldSpaceNode;
  46204. },
  46205. set: function (val) {
  46206. this._worldSpaceNode = val;
  46207. },
  46208. enumerable: true,
  46209. configurable: true
  46210. });
  46211. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  46212. /**
  46213. * Check if the WebGL Instanced Array extension is supported or not
  46214. */
  46215. get: function () {
  46216. return this._supprtInstancedArray;
  46217. },
  46218. enumerable: true,
  46219. configurable: true
  46220. });
  46221. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  46222. /**
  46223. * Property that defines the fill object used to draw the background of the Canvas.
  46224. * Note that Canvas with a Caching Strategy of
  46225. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  46226. */
  46227. get: function () {
  46228. if (!this._background || !this._background.isVisible) {
  46229. return null;
  46230. }
  46231. return this._background.fill;
  46232. },
  46233. set: function (value) {
  46234. this.checkBackgroundAvailability();
  46235. if (value === this._background.fill) {
  46236. return;
  46237. }
  46238. this._background.fill = value;
  46239. this._background.levelVisible = true;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  46245. /**
  46246. * Property that defines the border object used to draw the background of the Canvas.
  46247. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  46248. */
  46249. get: function () {
  46250. if (!this._background || !this._background.isVisible) {
  46251. return null;
  46252. }
  46253. return this._background.border;
  46254. },
  46255. set: function (value) {
  46256. this.checkBackgroundAvailability();
  46257. if (value === this._background.border) {
  46258. return;
  46259. }
  46260. this._background.border = value;
  46261. this._background.levelVisible = true;
  46262. },
  46263. enumerable: true,
  46264. configurable: true
  46265. });
  46266. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  46267. /**
  46268. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  46269. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  46270. */
  46271. get: function () {
  46272. if (!this._background || !this._background.isVisible) {
  46273. return null;
  46274. }
  46275. return this._background.borderThickness;
  46276. },
  46277. set: function (value) {
  46278. this.checkBackgroundAvailability();
  46279. if (value === this._background.borderThickness) {
  46280. return;
  46281. }
  46282. this._background.borderThickness = value;
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  46288. /**
  46289. * You can set the roundRadius of the background
  46290. * @returns The current roundRadius
  46291. */
  46292. get: function () {
  46293. if (!this._background || !this._background.isVisible) {
  46294. return null;
  46295. }
  46296. return this._background.roundRadius;
  46297. },
  46298. set: function (value) {
  46299. this.checkBackgroundAvailability();
  46300. if (value === this._background.roundRadius) {
  46301. return;
  46302. }
  46303. this._background.roundRadius = value;
  46304. this._background.levelVisible = true;
  46305. },
  46306. enumerable: true,
  46307. configurable: true
  46308. });
  46309. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  46310. /**
  46311. * Enable/Disable interaction for this Canvas
  46312. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  46313. */
  46314. get: function () {
  46315. return this._interactionEnabled;
  46316. },
  46317. set: function (enable) {
  46318. this._setupInteraction(enable);
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  46324. /**
  46325. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  46326. * @returns {}
  46327. */
  46328. get: function () {
  46329. return this.__engineData;
  46330. },
  46331. enumerable: true,
  46332. configurable: true
  46333. });
  46334. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  46335. if (this._profilingCanvas) {
  46336. return this._profilingCanvas;
  46337. }
  46338. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  46339. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  46340. new BABYLON.Rectangle2D({
  46341. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  46342. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  46343. ]
  46344. })
  46345. ]
  46346. });
  46347. this._profileInfoText = canvas.findById("ProfileInfoText");
  46348. this._profilingCanvas = canvas;
  46349. return canvas;
  46350. };
  46351. Canvas2D.prototype.checkBackgroundAvailability = function () {
  46352. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46353. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  46354. }
  46355. };
  46356. Canvas2D.prototype._initPerfMetrics = function () {
  46357. this._drawCallsOpaqueCounter.fetchNewFrame();
  46358. this._drawCallsAlphaTestCounter.fetchNewFrame();
  46359. this._drawCallsTransparentCounter.fetchNewFrame();
  46360. this._groupRenderCounter.fetchNewFrame();
  46361. this._updateTransparentDataCounter.fetchNewFrame();
  46362. this._cachedGroupRenderCounter.fetchNewFrame();
  46363. this._updateCachedStateCounter.fetchNewFrame();
  46364. this._updateLayoutCounter.fetchNewFrame();
  46365. this._updatePositioningCounter.fetchNewFrame();
  46366. this._updateLocalTransformCounter.fetchNewFrame();
  46367. this._updateGlobalTransformCounter.fetchNewFrame();
  46368. this._boundingInfoRecomputeCounter.fetchNewFrame();
  46369. };
  46370. Canvas2D.prototype._fetchPerfMetrics = function () {
  46371. this._drawCallsOpaqueCounter.addCount(0, true);
  46372. this._drawCallsAlphaTestCounter.addCount(0, true);
  46373. this._drawCallsTransparentCounter.addCount(0, true);
  46374. this._groupRenderCounter.addCount(0, true);
  46375. this._updateTransparentDataCounter.addCount(0, true);
  46376. this._cachedGroupRenderCounter.addCount(0, true);
  46377. this._updateCachedStateCounter.addCount(0, true);
  46378. this._updateLayoutCounter.addCount(0, true);
  46379. this._updatePositioningCounter.addCount(0, true);
  46380. this._updateLocalTransformCounter.addCount(0, true);
  46381. this._updateGlobalTransformCounter.addCount(0, true);
  46382. this._boundingInfoRecomputeCounter.addCount(0, true);
  46383. };
  46384. Canvas2D.prototype._updateProfileCanvas = function () {
  46385. if (this._profileInfoText == null) {
  46386. return;
  46387. }
  46388. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  46389. var p = "Draw Calls:\n" +
  46390. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  46391. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  46392. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  46393. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  46394. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  46395. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  46396. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  46397. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  46398. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  46399. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  46400. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  46401. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  46402. this._profileInfoText.text = p;
  46403. };
  46404. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  46405. switch (renderMode) {
  46406. case BABYLON.Render2DContext.RenderModeOpaque:
  46407. this._drawCallsOpaqueCounter.addCount(count, false);
  46408. return;
  46409. case BABYLON.Render2DContext.RenderModeAlphaTest:
  46410. this._drawCallsAlphaTestCounter.addCount(count, false);
  46411. return;
  46412. case BABYLON.Render2DContext.RenderModeTransparent:
  46413. this._drawCallsTransparentCounter.addCount(count, false);
  46414. return;
  46415. }
  46416. };
  46417. Canvas2D.prototype._addGroupRenderCount = function (count) {
  46418. this._groupRenderCounter.addCount(count, false);
  46419. };
  46420. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  46421. this._updateTransparentDataCounter.addCount(count, false);
  46422. };
  46423. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  46424. this._cachedGroupRenderCounter.addCount(count, false);
  46425. };
  46426. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  46427. this._updateCachedStateCounter.addCount(count, false);
  46428. };
  46429. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  46430. this._updateLayoutCounter.addCount(count, false);
  46431. };
  46432. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  46433. this._updatePositioningCounter.addCount(count, false);
  46434. };
  46435. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  46436. this._updateLocalTransformCounter.addCount(count, false);
  46437. };
  46438. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  46439. this._updateGlobalTransformCounter.addCount(count, false);
  46440. };
  46441. Canvas2D.prototype.onPrimBecomesDirty = function () {
  46442. this._addPrimToDirtyList(this);
  46443. };
  46444. Canvas2D.prototype._updateTrackedNodes = function () {
  46445. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46446. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46447. var rh = this.engine.getRenderHeight();
  46448. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  46449. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  46450. var group = _a[_i];
  46451. if (group.isDisposed || !group.isVisible) {
  46452. continue;
  46453. }
  46454. var node = group.trackedNode;
  46455. var worldMtx = node.getWorldMatrix();
  46456. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  46457. group.x = Math.round(proj.x);
  46458. group.y = Math.round(rh - proj.y);
  46459. }
  46460. };
  46461. /**
  46462. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  46463. */
  46464. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  46465. this._updateCanvasState(forceRecompute);
  46466. };
  46467. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  46468. if (this._globalTransformStep < 2) {
  46469. return;
  46470. }
  46471. var n = this.worldSpaceCanvasNode;
  46472. var bi = n.getBoundingInfo().boundingBox;
  46473. var v = bi.vectorsWorld;
  46474. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46475. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46476. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  46477. var projPoints = new Array(4);
  46478. for (var i = 0; i < 4; i++) {
  46479. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  46480. }
  46481. var left = projPoints[3].subtract(projPoints[0]).length();
  46482. var top = projPoints[3].subtract(projPoints[1]).length();
  46483. var right = projPoints[1].subtract(projPoints[2]).length();
  46484. var bottom = projPoints[2].subtract(projPoints[0]).length();
  46485. var w = Math.round(Math.max(top, bottom));
  46486. var h = Math.round(Math.max(right, left));
  46487. var isW = w > h;
  46488. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  46489. var edge = Math.max(w, h);
  46490. if (edge < 256) {
  46491. edge = 256;
  46492. }
  46493. else {
  46494. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  46495. }
  46496. // Clip values if needed
  46497. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  46498. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  46499. if (newScale !== this.scale) {
  46500. var scale = newScale;
  46501. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  46502. this._setRenderingScale(scale);
  46503. }
  46504. };
  46505. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  46506. // Check if the update has already been made for this render Frame
  46507. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  46508. return;
  46509. }
  46510. // Detect a change of rendering size
  46511. var renderingSizeChanged = false;
  46512. var newWidth = this.engine.getRenderWidth();
  46513. if (newWidth !== this._renderingSize.width) {
  46514. renderingSizeChanged = true;
  46515. }
  46516. this._renderingSize.width = newWidth;
  46517. var newHeight = this.engine.getRenderHeight();
  46518. if (newHeight !== this._renderingSize.height) {
  46519. renderingSizeChanged = true;
  46520. }
  46521. this._renderingSize.height = newHeight;
  46522. // If the canvas fit the rendering size and it changed, update
  46523. if (renderingSizeChanged && this._fitRenderingDevice) {
  46524. this.size = this._renderingSize;
  46525. if (this._background) {
  46526. this._background.size = this.size;
  46527. }
  46528. // Dirty the Layout at the Canvas level to recompute as the size changed
  46529. this._setLayoutDirty();
  46530. }
  46531. var context = new BABYLON.PrepareRender2DContext();
  46532. ++this._globalTransformProcessStep;
  46533. this.updateCachedStates(false);
  46534. this._prepareGroupRender(context);
  46535. this._updateRenderId = this.scene.getRenderId();
  46536. };
  46537. /**
  46538. * Method that renders the Canvas, you should not invoke
  46539. */
  46540. Canvas2D.prototype._render = function () {
  46541. this._initPerfMetrics();
  46542. this._updateTrackedNodes();
  46543. this._updateCanvasState(false);
  46544. if (!this._isScreenSpace) {
  46545. this._updateAdaptiveSizeWorldCanvas();
  46546. }
  46547. this._updateCanvasState(false);
  46548. if (this._primPointerInfo.canvasPointerPos) {
  46549. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  46550. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  46551. }
  46552. this.engine.setState(false);
  46553. this._groupRender();
  46554. if (!this._isScreenSpace) {
  46555. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  46556. this.worldSpaceCacheChanged();
  46557. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  46558. }
  46559. }
  46560. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  46561. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  46562. this._cachedCanvasGroup._renderCachedCanvas();
  46563. }
  46564. this._fetchPerfMetrics();
  46565. this._updateProfileCanvas();
  46566. };
  46567. /**
  46568. * Internal method that allocate a cache for the given group.
  46569. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  46570. * @param group The group to allocate the cache of.
  46571. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  46572. */
  46573. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  46574. if (useMipMap === void 0) { useMipMap = false; }
  46575. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  46576. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  46577. // Determine size
  46578. var size = group.actualSize;
  46579. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  46580. if (minSize) {
  46581. size.width = Math.max(minSize.width, size.width);
  46582. size.height = Math.max(minSize.height, size.height);
  46583. }
  46584. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  46585. // Try to find a spot in one of the cached texture
  46586. var res = null;
  46587. var map;
  46588. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  46589. var _map = mapArray_1[_i];
  46590. map = _map;
  46591. var node = map.allocateRect(size);
  46592. if (node) {
  46593. res = { node: node, texture: map };
  46594. break;
  46595. }
  46596. }
  46597. // Couldn't find a map that could fit the rect, create a new map for it
  46598. if (!res) {
  46599. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  46600. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  46601. if (size.width > mapSize.width || size.height > mapSize.height) {
  46602. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  46603. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  46604. }
  46605. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  46606. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  46607. map.anisotropicFilteringLevel = 4;
  46608. mapArray.splice(0, 0, map);
  46609. var node = map.allocateRect(size);
  46610. res = { node: node, texture: map };
  46611. }
  46612. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  46613. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  46614. if (group !== this || this._isScreenSpace) {
  46615. var node = res.node;
  46616. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  46617. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  46618. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  46619. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  46620. sprite.zOrder = 1;
  46621. sprite.origin = BABYLON.Vector2.Zero();
  46622. }
  46623. else {
  46624. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  46625. sprite.origin = group.origin.clone();
  46626. res.sprite = sprite;
  46627. }
  46628. }
  46629. return res;
  46630. };
  46631. /**
  46632. * Internal method used to register a Scene Node to track position for the given group
  46633. * Do not invoke this method, for internal purpose only.
  46634. * @param group the group to track its associated Scene Node
  46635. */
  46636. Canvas2D.prototype._registerTrackedNode = function (group) {
  46637. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46638. return;
  46639. }
  46640. this._trackedGroups.push(group);
  46641. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46642. };
  46643. /**
  46644. * Internal method used to unregister a tracked Scene Node
  46645. * Do not invoke this method, it's for internal purpose only.
  46646. * @param group the group to unregister its tracked Scene Node from.
  46647. */
  46648. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  46649. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46650. return;
  46651. }
  46652. var i = this._trackedGroups.indexOf(group);
  46653. if (i !== -1) {
  46654. this._trackedGroups.splice(i, 1);
  46655. }
  46656. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46657. };
  46658. /**
  46659. * Get a Solid Color Brush instance matching the given color.
  46660. * @param color The color to retrieve
  46661. * @return A shared instance of the SolidColorBrush2D class that use the given color
  46662. */
  46663. Canvas2D.GetSolidColorBrush = function (color) {
  46664. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  46665. };
  46666. /**
  46667. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  46668. * @param color The color to retrieve
  46669. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  46670. */
  46671. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  46672. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  46673. };
  46674. /**
  46675. * Get a Gradient Color Brush
  46676. * @param color1 starting color
  46677. * @param color2 engine color
  46678. * @param translation translation vector to apply. default is [0;0]
  46679. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  46680. * @param scale scaling factor to apply. default is 1.
  46681. */
  46682. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  46683. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  46684. if (rotation === void 0) { rotation = 0; }
  46685. if (scale === void 0) { scale = 1; }
  46686. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  46687. };
  46688. /**
  46689. * Create a solid or gradient brush from a string value.
  46690. * @param brushString should be either
  46691. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  46692. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  46693. */
  46694. Canvas2D.GetBrushFromString = function (brushString) {
  46695. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  46696. brushString = brushString.trim();
  46697. var split = brushString.split(",");
  46698. // Solid, formatted as: "[solid:]#FF808080"
  46699. if (split.length === 1) {
  46700. var value = null;
  46701. if (brushString.indexOf("solid:") === 0) {
  46702. value = brushString.substr(6).trim();
  46703. }
  46704. else if (brushString.indexOf("#") === 0) {
  46705. value = brushString;
  46706. }
  46707. else {
  46708. return null;
  46709. }
  46710. return Canvas2D.GetSolidColorBrushFromHex(value);
  46711. }
  46712. else {
  46713. if (split[0].indexOf("gradient:") === 0) {
  46714. split[0] = split[0].substr(9).trim();
  46715. }
  46716. try {
  46717. var start = BABYLON.Color4.FromHexString(split[0].trim());
  46718. var end = BABYLON.Color4.FromHexString(split[1].trim());
  46719. var t = BABYLON.Vector2.Zero();
  46720. if (split.length > 2) {
  46721. var v = split[2].trim();
  46722. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  46723. return null;
  46724. }
  46725. var sep = v.indexOf(":");
  46726. var x = parseFloat(v.substr(1, sep));
  46727. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  46728. t = new BABYLON.Vector2(x, y);
  46729. }
  46730. var r = 0;
  46731. if (split.length > 3) {
  46732. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  46733. }
  46734. var s = 1;
  46735. if (split.length > 4) {
  46736. s = parseFloat(split[4].trim());
  46737. }
  46738. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  46739. }
  46740. catch (e) {
  46741. return null;
  46742. }
  46743. }
  46744. };
  46745. /**
  46746. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  46747. * This strategy doesn't allow primitives added directly as children of the Canvas.
  46748. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  46749. */
  46750. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  46751. /**
  46752. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  46753. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  46754. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  46755. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  46756. */
  46757. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  46758. /**
  46759. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  46760. */
  46761. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  46762. /**
  46763. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  46764. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  46765. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  46766. */
  46767. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  46768. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  46769. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  46770. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  46771. Canvas2D._m = BABYLON.Matrix.Identity();
  46772. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  46773. /**
  46774. * Define the default size used for both the width and height of a MapTexture to allocate.
  46775. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  46776. */
  46777. Canvas2D._groupTextureCacheSize = 1024;
  46778. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  46779. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  46780. Canvas2D = __decorate([
  46781. BABYLON.className("Canvas2D")
  46782. ], Canvas2D);
  46783. return Canvas2D;
  46784. }(BABYLON.Group2D));
  46785. BABYLON.Canvas2D = Canvas2D;
  46786. var WorldSpaceCanvas2D = (function (_super) {
  46787. __extends(WorldSpaceCanvas2D, _super);
  46788. /**
  46789. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  46790. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  46791. * @param scene the Scene that owns the Canvas
  46792. * @param size the dimension of the Canvas in World Space
  46793. * @param settings a combination of settings, possible ones are
  46794. * - children: an array of direct children primitives
  46795. * - id: a text identifier, for information purpose only, default is null.
  46796. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  46797. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  46798. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  46799. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  46800. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  46801. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46802. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46803. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46804. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46805. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46806. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  46807. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  46808. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46809. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46810. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46811. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46812. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46813. */
  46814. function WorldSpaceCanvas2D(scene, size, settings) {
  46815. BABYLON.Prim2DBase._isCanvasInit = true;
  46816. var s = settings;
  46817. s.isScreenSpace = false;
  46818. s.size = size.clone();
  46819. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  46820. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  46821. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  46822. }
  46823. _super.call(this, scene, settings);
  46824. BABYLON.Prim2DBase._isCanvasInit = false;
  46825. this._renderableData._useMipMap = true;
  46826. this._renderableData._anisotropicLevel = 8;
  46827. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  46828. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  46829. //}
  46830. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  46831. var id = settings ? settings.id || null : null;
  46832. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  46833. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  46834. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  46835. if (settings.maxAdaptiveCanvasSize == null) {
  46836. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  46837. }
  46838. else {
  46839. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  46840. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  46841. }
  46842. if (createWorldSpaceNode) {
  46843. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  46844. var vertexData = BABYLON.VertexData.CreatePlane({
  46845. width: size.width,
  46846. height: size.height,
  46847. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  46848. });
  46849. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  46850. this.applyCachedTexture(vertexData, mtl);
  46851. vertexData.applyToMesh(plane, true);
  46852. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  46853. mtl.disableLighting = true;
  46854. mtl.useAlphaFromDiffuseTexture = true;
  46855. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  46856. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  46857. plane.material = mtl;
  46858. this._worldSpaceNode = plane;
  46859. }
  46860. else {
  46861. this._worldSpaceNode = settings.customWorldSpaceNode;
  46862. this.applyCachedTexture(null, null);
  46863. }
  46864. }
  46865. WorldSpaceCanvas2D = __decorate([
  46866. BABYLON.className("WorldSpaceCanvas2D")
  46867. ], WorldSpaceCanvas2D);
  46868. return WorldSpaceCanvas2D;
  46869. }(Canvas2D));
  46870. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  46871. var ScreenSpaceCanvas2D = (function (_super) {
  46872. __extends(ScreenSpaceCanvas2D, _super);
  46873. /**
  46874. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  46875. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  46876. * All caching strategies will be available.
  46877. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  46878. * @param scene the Scene that owns the Canvas
  46879. * @param settings a combination of settings, possible ones are
  46880. * - children: an array of direct children primitives
  46881. * - id: a text identifier, for information purpose only
  46882. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  46883. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  46884. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  46885. * - width: the width of the Canvas. you can alternatively use the size setting.
  46886. * - height: the height of the Canvas. you can alternatively use the size setting.
  46887. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  46888. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  46889. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  46890. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46891. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46892. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46893. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46894. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46895. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  46896. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46897. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46898. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46899. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46900. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  46901. */
  46902. function ScreenSpaceCanvas2D(scene, settings) {
  46903. BABYLON.Prim2DBase._isCanvasInit = true;
  46904. _super.call(this, scene, settings);
  46905. }
  46906. ScreenSpaceCanvas2D = __decorate([
  46907. BABYLON.className("ScreenSpaceCanvas2D")
  46908. ], ScreenSpaceCanvas2D);
  46909. return ScreenSpaceCanvas2D;
  46910. }(Canvas2D));
  46911. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  46912. })(BABYLON || (BABYLON = {}));
  46913. var BABYLON;
  46914. (function (BABYLON) {
  46915. /**
  46916. * This is the class that is used to display a World Space Canvas into a 3D scene
  46917. */
  46918. var WorldSpaceCanvas2DNode = (function (_super) {
  46919. __extends(WorldSpaceCanvas2DNode, _super);
  46920. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  46921. _super.call(this, name, scene);
  46922. this._canvas = canvas;
  46923. }
  46924. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  46925. _super.prototype.dispose.call(this);
  46926. if (this._canvas) {
  46927. this._canvas.dispose();
  46928. this._canvas = null;
  46929. }
  46930. };
  46931. return WorldSpaceCanvas2DNode;
  46932. }(BABYLON.Mesh));
  46933. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  46934. })(BABYLON || (BABYLON = {}));
  46935. var BABYLON;
  46936. (function (BABYLON) {
  46937. var ShaderMaterial = (function (_super) {
  46938. __extends(ShaderMaterial, _super);
  46939. function ShaderMaterial(name, scene, shaderPath, options) {
  46940. _super.call(this, name, scene);
  46941. this._textures = {};
  46942. this._textureArrays = {};
  46943. this._floats = {};
  46944. this._floatsArrays = {};
  46945. this._colors3 = {};
  46946. this._colors4 = {};
  46947. this._vectors2 = {};
  46948. this._vectors3 = {};
  46949. this._vectors4 = {};
  46950. this._matrices = {};
  46951. this._matrices3x3 = {};
  46952. this._matrices2x2 = {};
  46953. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46954. this._shaderPath = shaderPath;
  46955. options.needAlphaBlending = options.needAlphaBlending || false;
  46956. options.needAlphaTesting = options.needAlphaTesting || false;
  46957. options.attributes = options.attributes || ["position", "normal", "uv"];
  46958. options.uniforms = options.uniforms || ["worldViewProjection"];
  46959. options.samplers = options.samplers || [];
  46960. options.defines = options.defines || [];
  46961. this._options = options;
  46962. }
  46963. ShaderMaterial.prototype.needAlphaBlending = function () {
  46964. return this._options.needAlphaBlending;
  46965. };
  46966. ShaderMaterial.prototype.needAlphaTesting = function () {
  46967. return this._options.needAlphaTesting;
  46968. };
  46969. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46970. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46971. this._options.uniforms.push(uniformName);
  46972. }
  46973. };
  46974. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46975. if (this._options.samplers.indexOf(name) === -1) {
  46976. this._options.samplers.push(name);
  46977. }
  46978. this._textures[name] = texture;
  46979. return this;
  46980. };
  46981. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46982. if (this._options.samplers.indexOf(name) === -1) {
  46983. this._options.samplers.push(name);
  46984. }
  46985. this._checkUniform(name);
  46986. this._textureArrays[name] = textures;
  46987. return this;
  46988. };
  46989. ShaderMaterial.prototype.setFloat = function (name, value) {
  46990. this._checkUniform(name);
  46991. this._floats[name] = value;
  46992. return this;
  46993. };
  46994. ShaderMaterial.prototype.setFloats = function (name, value) {
  46995. this._checkUniform(name);
  46996. this._floatsArrays[name] = value;
  46997. return this;
  46998. };
  46999. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47000. this._checkUniform(name);
  47001. this._colors3[name] = value;
  47002. return this;
  47003. };
  47004. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47005. this._checkUniform(name);
  47006. this._colors4[name] = value;
  47007. return this;
  47008. };
  47009. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47010. this._checkUniform(name);
  47011. this._vectors2[name] = value;
  47012. return this;
  47013. };
  47014. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47015. this._checkUniform(name);
  47016. this._vectors3[name] = value;
  47017. return this;
  47018. };
  47019. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47020. this._checkUniform(name);
  47021. this._vectors4[name] = value;
  47022. return this;
  47023. };
  47024. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47025. this._checkUniform(name);
  47026. this._matrices[name] = value;
  47027. return this;
  47028. };
  47029. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47030. this._checkUniform(name);
  47031. this._matrices3x3[name] = value;
  47032. return this;
  47033. };
  47034. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47035. this._checkUniform(name);
  47036. this._matrices2x2[name] = value;
  47037. return this;
  47038. };
  47039. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47040. var scene = this.getScene();
  47041. var engine = scene.getEngine();
  47042. if (!this.checkReadyOnEveryCall) {
  47043. if (this._renderId === scene.getRenderId()) {
  47044. return true;
  47045. }
  47046. }
  47047. // Instances
  47048. var defines = [];
  47049. var fallbacks = new BABYLON.EffectFallbacks();
  47050. if (useInstances) {
  47051. defines.push("#define INSTANCES");
  47052. }
  47053. for (var index = 0; index < this._options.defines.length; index++) {
  47054. defines.push(this._options.defines[index]);
  47055. }
  47056. // Bones
  47057. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47058. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47059. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47060. fallbacks.addCPUSkinningFallback(0, mesh);
  47061. }
  47062. // Alpha test
  47063. if (engine.getAlphaTesting()) {
  47064. defines.push("#define ALPHATEST");
  47065. }
  47066. var previousEffect = this._effect;
  47067. var join = defines.join("\n");
  47068. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  47069. if (!this._effect.isReady()) {
  47070. return false;
  47071. }
  47072. if (previousEffect !== this._effect) {
  47073. scene.resetCachedMaterial();
  47074. }
  47075. this._renderId = scene.getRenderId();
  47076. return true;
  47077. };
  47078. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47079. var scene = this.getScene();
  47080. if (this._options.uniforms.indexOf("world") !== -1) {
  47081. this._effect.setMatrix("world", world);
  47082. }
  47083. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47084. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47085. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47086. }
  47087. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47088. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47089. }
  47090. };
  47091. ShaderMaterial.prototype.bind = function (world, mesh) {
  47092. // Std values
  47093. this.bindOnlyWorldMatrix(world);
  47094. if (this.getScene().getCachedMaterial() !== this) {
  47095. if (this._options.uniforms.indexOf("view") !== -1) {
  47096. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47097. }
  47098. if (this._options.uniforms.indexOf("projection") !== -1) {
  47099. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47100. }
  47101. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47102. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47103. }
  47104. // Bones
  47105. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47106. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47107. }
  47108. var name;
  47109. // Texture
  47110. for (name in this._textures) {
  47111. this._effect.setTexture(name, this._textures[name]);
  47112. }
  47113. // Texture arrays
  47114. for (name in this._textureArrays) {
  47115. this._effect.setTextureArray(name, this._textureArrays[name]);
  47116. }
  47117. // Float
  47118. for (name in this._floats) {
  47119. this._effect.setFloat(name, this._floats[name]);
  47120. }
  47121. // Float s
  47122. for (name in this._floatsArrays) {
  47123. this._effect.setArray(name, this._floatsArrays[name]);
  47124. }
  47125. // Color3
  47126. for (name in this._colors3) {
  47127. this._effect.setColor3(name, this._colors3[name]);
  47128. }
  47129. // Color4
  47130. for (name in this._colors4) {
  47131. var color = this._colors4[name];
  47132. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47133. }
  47134. // Vector2
  47135. for (name in this._vectors2) {
  47136. this._effect.setVector2(name, this._vectors2[name]);
  47137. }
  47138. // Vector3
  47139. for (name in this._vectors3) {
  47140. this._effect.setVector3(name, this._vectors3[name]);
  47141. }
  47142. // Vector4
  47143. for (name in this._vectors4) {
  47144. this._effect.setVector4(name, this._vectors4[name]);
  47145. }
  47146. // Matrix
  47147. for (name in this._matrices) {
  47148. this._effect.setMatrix(name, this._matrices[name]);
  47149. }
  47150. // Matrix 3x3
  47151. for (name in this._matrices3x3) {
  47152. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47153. }
  47154. // Matrix 2x2
  47155. for (name in this._matrices2x2) {
  47156. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47157. }
  47158. }
  47159. _super.prototype.bind.call(this, world, mesh);
  47160. };
  47161. ShaderMaterial.prototype.clone = function (name) {
  47162. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47163. return newShaderMaterial;
  47164. };
  47165. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47166. if (forceDisposeTextures) {
  47167. var name;
  47168. for (name in this._textures) {
  47169. this._textures[name].dispose();
  47170. }
  47171. for (name in this._textureArrays) {
  47172. var array = this._textureArrays[name];
  47173. for (var index = 0; index < array.length; index++) {
  47174. array[index].dispose();
  47175. }
  47176. }
  47177. }
  47178. this._textures = {};
  47179. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47180. };
  47181. ShaderMaterial.prototype.serialize = function () {
  47182. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47183. serializationObject.customType = "BABYLON.ShaderMaterial";
  47184. serializationObject.options = this._options;
  47185. serializationObject.shaderPath = this._shaderPath;
  47186. var name;
  47187. // Texture
  47188. serializationObject.textures = {};
  47189. for (name in this._textures) {
  47190. serializationObject.textures[name] = this._textures[name].serialize();
  47191. }
  47192. // Texture arrays
  47193. serializationObject.textureArrays = {};
  47194. for (name in this._textureArrays) {
  47195. serializationObject.textureArrays[name] = [];
  47196. var array = this._textureArrays[name];
  47197. for (var index = 0; index < array.length; index++) {
  47198. serializationObject.textureArrays[name].push(array[index].serialize());
  47199. }
  47200. }
  47201. // Float
  47202. serializationObject.floats = {};
  47203. for (name in this._floats) {
  47204. serializationObject.floats[name] = this._floats[name];
  47205. }
  47206. // Float s
  47207. serializationObject.floatArrays = {};
  47208. for (name in this._floatsArrays) {
  47209. serializationObject.floatArrays[name] = this._floatsArrays[name];
  47210. }
  47211. // Color3
  47212. serializationObject.colors3 = {};
  47213. for (name in this._colors3) {
  47214. serializationObject.colors3[name] = this._colors3[name].asArray();
  47215. }
  47216. // Color4
  47217. serializationObject.colors4 = {};
  47218. for (name in this._colors4) {
  47219. serializationObject.colors4[name] = this._colors4[name].asArray();
  47220. }
  47221. // Vector2
  47222. serializationObject.vectors2 = {};
  47223. for (name in this._vectors2) {
  47224. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47225. }
  47226. // Vector3
  47227. serializationObject.vectors3 = {};
  47228. for (name in this._vectors3) {
  47229. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47230. }
  47231. // Vector4
  47232. serializationObject.vectors4 = {};
  47233. for (name in this._vectors4) {
  47234. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47235. }
  47236. // Matrix
  47237. serializationObject.matrices = {};
  47238. for (name in this._matrices) {
  47239. serializationObject.matrices[name] = this._matrices[name].asArray();
  47240. }
  47241. // Matrix 3x3
  47242. serializationObject.matrices3x3 = {};
  47243. for (name in this._matrices3x3) {
  47244. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47245. }
  47246. // Matrix 2x2
  47247. serializationObject.matrices2x2 = {};
  47248. for (name in this._matrices2x2) {
  47249. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47250. }
  47251. return serializationObject;
  47252. };
  47253. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47254. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47255. var name;
  47256. // Texture
  47257. for (name in source.textures) {
  47258. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47259. }
  47260. // Texture arrays
  47261. for (name in source.textureArrays) {
  47262. var array = source.textureArrays[name];
  47263. var textureArray = new Array();
  47264. for (var index = 0; index < array.length; index++) {
  47265. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47266. }
  47267. material.setTextureArray(name, textureArray);
  47268. }
  47269. // Float
  47270. for (name in source.floats) {
  47271. material.setFloat(name, source.floats[name]);
  47272. }
  47273. // Float s
  47274. for (name in source.floatsArrays) {
  47275. material.setFloats(name, source.floatsArrays[name]);
  47276. }
  47277. // Color3
  47278. for (name in source.colors3) {
  47279. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47280. }
  47281. // Color4
  47282. for (name in source.colors4) {
  47283. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47284. }
  47285. // Vector2
  47286. for (name in source.vectors2) {
  47287. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47288. }
  47289. // Vector3
  47290. for (name in source.vectors3) {
  47291. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47292. }
  47293. // Vector4
  47294. for (name in source.vectors4) {
  47295. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47296. }
  47297. // Matrix
  47298. for (name in source.matrices) {
  47299. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47300. }
  47301. // Matrix 3x3
  47302. for (name in source.matrices3x3) {
  47303. material.setMatrix3x3(name, source.matrices3x3[name]);
  47304. }
  47305. // Matrix 2x2
  47306. for (name in source.matrices2x2) {
  47307. material.setMatrix2x2(name, source.matrices2x2[name]);
  47308. }
  47309. return material;
  47310. };
  47311. return ShaderMaterial;
  47312. }(BABYLON.Material));
  47313. BABYLON.ShaderMaterial = ShaderMaterial;
  47314. })(BABYLON || (BABYLON = {}));
  47315. var BABYLON;
  47316. (function (BABYLON) {
  47317. var Internals;
  47318. (function (Internals) {
  47319. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  47320. // All values and structures referenced from:
  47321. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  47322. var DDS_MAGIC = 0x20534444;
  47323. 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;
  47324. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  47325. 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;
  47326. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  47327. function FourCCToInt32(value) {
  47328. return value.charCodeAt(0) +
  47329. (value.charCodeAt(1) << 8) +
  47330. (value.charCodeAt(2) << 16) +
  47331. (value.charCodeAt(3) << 24);
  47332. }
  47333. function Int32ToFourCC(value) {
  47334. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  47335. }
  47336. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  47337. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  47338. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  47339. var headerLengthInt = 31; // The header length in 32 bit ints
  47340. // Offsets into the header array
  47341. var off_magic = 0;
  47342. var off_size = 1;
  47343. var off_flags = 2;
  47344. var off_height = 3;
  47345. var off_width = 4;
  47346. var off_mipmapCount = 7;
  47347. var off_pfFlags = 20;
  47348. var off_pfFourCC = 21;
  47349. var off_RGBbpp = 22;
  47350. var off_RMask = 23;
  47351. var off_GMask = 24;
  47352. var off_BMask = 25;
  47353. var off_AMask = 26;
  47354. var off_caps1 = 27;
  47355. var off_caps2 = 28;
  47356. ;
  47357. var DDSTools = (function () {
  47358. function DDSTools() {
  47359. }
  47360. DDSTools.GetDDSInfo = function (arrayBuffer) {
  47361. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  47362. var mipmapCount = 1;
  47363. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  47364. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47365. }
  47366. return {
  47367. width: header[off_width],
  47368. height: header[off_height],
  47369. mipmapCount: mipmapCount,
  47370. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  47371. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  47372. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  47373. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  47374. };
  47375. };
  47376. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47377. var byteArray = new Uint8Array(dataLength);
  47378. var srcData = new Uint8Array(arrayBuffer);
  47379. var index = 0;
  47380. for (var y = height - 1; y >= 0; y--) {
  47381. for (var x = 0; x < width; x++) {
  47382. var srcPos = dataOffset + (x + y * width) * 4;
  47383. byteArray[index + 2] = srcData[srcPos];
  47384. byteArray[index + 1] = srcData[srcPos + 1];
  47385. byteArray[index] = srcData[srcPos + 2];
  47386. byteArray[index + 3] = srcData[srcPos + 3];
  47387. index += 4;
  47388. }
  47389. }
  47390. return byteArray;
  47391. };
  47392. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47393. var byteArray = new Uint8Array(dataLength);
  47394. var srcData = new Uint8Array(arrayBuffer);
  47395. var index = 0;
  47396. for (var y = height - 1; y >= 0; y--) {
  47397. for (var x = 0; x < width; x++) {
  47398. var srcPos = dataOffset + (x + y * width) * 3;
  47399. byteArray[index + 2] = srcData[srcPos];
  47400. byteArray[index + 1] = srcData[srcPos + 1];
  47401. byteArray[index] = srcData[srcPos + 2];
  47402. index += 3;
  47403. }
  47404. }
  47405. return byteArray;
  47406. };
  47407. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47408. var byteArray = new Uint8Array(dataLength);
  47409. var srcData = new Uint8Array(arrayBuffer);
  47410. var index = 0;
  47411. for (var y = height - 1; y >= 0; y--) {
  47412. for (var x = 0; x < width; x++) {
  47413. var srcPos = dataOffset + (x + y * width);
  47414. byteArray[index] = srcData[srcPos];
  47415. index++;
  47416. }
  47417. }
  47418. return byteArray;
  47419. };
  47420. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  47421. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  47422. if (header[off_magic] != DDS_MAGIC) {
  47423. BABYLON.Tools.Error("Invalid magic number in DDS header");
  47424. return;
  47425. }
  47426. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  47427. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  47428. return;
  47429. }
  47430. if (info.isFourCC) {
  47431. fourCC = header[off_pfFourCC];
  47432. switch (fourCC) {
  47433. case FOURCC_DXT1:
  47434. blockBytes = 8;
  47435. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47436. break;
  47437. case FOURCC_DXT3:
  47438. blockBytes = 16;
  47439. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47440. break;
  47441. case FOURCC_DXT5:
  47442. blockBytes = 16;
  47443. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47444. break;
  47445. default:
  47446. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  47447. return;
  47448. }
  47449. }
  47450. mipmapCount = 1;
  47451. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  47452. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47453. }
  47454. var bpp = header[off_RGBbpp];
  47455. for (var face = 0; face < faces; face++) {
  47456. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  47457. width = header[off_width];
  47458. height = header[off_height];
  47459. dataOffset = header[off_size] + 4;
  47460. for (i = 0; i < mipmapCount; ++i) {
  47461. if (info.isRGB) {
  47462. if (bpp === 24) {
  47463. dataLength = width * height * 3;
  47464. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47465. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  47466. }
  47467. else {
  47468. dataLength = width * height * 4;
  47469. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47470. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  47471. }
  47472. }
  47473. else if (info.isLuminance) {
  47474. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  47475. var unpaddedRowSize = width;
  47476. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  47477. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  47478. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47479. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  47480. }
  47481. else {
  47482. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  47483. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  47484. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  47485. }
  47486. dataOffset += dataLength;
  47487. width *= 0.5;
  47488. height *= 0.5;
  47489. width = Math.max(1.0, width);
  47490. height = Math.max(1.0, height);
  47491. }
  47492. }
  47493. };
  47494. return DDSTools;
  47495. }());
  47496. Internals.DDSTools = DDSTools;
  47497. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47498. })(BABYLON || (BABYLON = {}));
  47499. var BABYLON;
  47500. (function (BABYLON) {
  47501. var CannonJSPlugin = (function () {
  47502. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  47503. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  47504. if (iterations === void 0) { iterations = 10; }
  47505. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  47506. this.name = "CannonJSPlugin";
  47507. this._physicsMaterials = [];
  47508. this._fixedTimeStep = 1 / 60;
  47509. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47510. this._currentCollisionGroup = 2;
  47511. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  47512. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  47513. this._tmpPosition = BABYLON.Vector3.Zero();
  47514. this._tmpQuaternion = new BABYLON.Quaternion();
  47515. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  47516. this._tmpDeltaRotation = new BABYLON.Quaternion();
  47517. this._tmpUnityRotation = new BABYLON.Quaternion();
  47518. if (!this.isSupported()) {
  47519. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  47520. return;
  47521. }
  47522. this.world = new CANNON.World();
  47523. this.world.broadphase = new CANNON.NaiveBroadphase();
  47524. this.world.solver.iterations = iterations;
  47525. }
  47526. CannonJSPlugin.prototype.setGravity = function (gravity) {
  47527. this.world.gravity.copy(gravity);
  47528. };
  47529. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  47530. this._fixedTimeStep = timeStep;
  47531. };
  47532. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  47533. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  47534. };
  47535. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47536. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47537. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47538. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47539. };
  47540. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47541. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47542. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47543. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47544. };
  47545. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47546. //parent-child relationship. Does this impostor has a parent impostor?
  47547. if (impostor.parent) {
  47548. if (impostor.physicsBody) {
  47549. this.removePhysicsBody(impostor);
  47550. //TODO is that needed?
  47551. impostor.forceUpdate();
  47552. }
  47553. return;
  47554. }
  47555. //should a new body be created for this impostor?
  47556. if (impostor.isBodyInitRequired()) {
  47557. var shape = this._createShape(impostor);
  47558. //unregister events, if body is being changed
  47559. var oldBody = impostor.physicsBody;
  47560. if (oldBody) {
  47561. this.removePhysicsBody(impostor);
  47562. }
  47563. //create the body and material
  47564. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  47565. var bodyCreationObject = {
  47566. mass: impostor.getParam("mass"),
  47567. material: material
  47568. };
  47569. // A simple extend, in case native options were used.
  47570. var nativeOptions = impostor.getParam("nativeOptions");
  47571. for (var key in nativeOptions) {
  47572. if (nativeOptions.hasOwnProperty(key)) {
  47573. bodyCreationObject[key] = nativeOptions[key];
  47574. }
  47575. }
  47576. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  47577. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  47578. this.world.addEventListener("preStep", impostor.beforeStep);
  47579. this.world.addEventListener("postStep", impostor.afterStep);
  47580. impostor.physicsBody.addShape(shape);
  47581. this.world.add(impostor.physicsBody);
  47582. //try to keep the body moving in the right direction by taking old properties.
  47583. //Should be tested!
  47584. if (oldBody) {
  47585. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  47586. impostor.physicsBody[param].copy(oldBody[param]);
  47587. });
  47588. }
  47589. this._processChildMeshes(impostor);
  47590. }
  47591. //now update the body's transformation
  47592. this._updatePhysicsBodyTransformation(impostor);
  47593. };
  47594. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47595. var _this = this;
  47596. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47597. if (meshChildren.length) {
  47598. var processMesh = function (localPosition, mesh) {
  47599. var childImpostor = mesh.getPhysicsImpostor();
  47600. if (childImpostor) {
  47601. var parent = childImpostor.parent;
  47602. if (parent !== mainImpostor) {
  47603. var localPosition = mesh.position;
  47604. if (childImpostor.physicsBody) {
  47605. _this.removePhysicsBody(childImpostor);
  47606. childImpostor.physicsBody = null;
  47607. }
  47608. childImpostor.parent = mainImpostor;
  47609. childImpostor.resetUpdateFlags();
  47610. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47611. //Add the mass of the children.
  47612. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47613. }
  47614. }
  47615. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47616. };
  47617. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47618. }
  47619. };
  47620. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47621. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47622. this.world.removeEventListener("preStep", impostor.beforeStep);
  47623. this.world.removeEventListener("postStep", impostor.afterStep);
  47624. this.world.remove(impostor.physicsBody);
  47625. };
  47626. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47627. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47628. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47629. if (!mainBody || !connectedBody) {
  47630. return;
  47631. }
  47632. var constraint;
  47633. var jointData = impostorJoint.joint.jointData;
  47634. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47635. var constraintData = {
  47636. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47637. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47638. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47639. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47640. maxForce: jointData.nativeParams.maxForce,
  47641. collideConnected: !!jointData.collision
  47642. };
  47643. //Not needed, Cannon has a collideConnected flag
  47644. /*if (!jointData.collision) {
  47645. //add 1st body to a collision group of its own, if it is not in 1
  47646. if (mainBody.collisionFilterGroup === 1) {
  47647. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  47648. this._currentCollisionGroup <<= 1;
  47649. }
  47650. if (connectedBody.collisionFilterGroup === 1) {
  47651. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  47652. this._currentCollisionGroup <<= 1;
  47653. }
  47654. //add their mask to the collisionFilterMask of each other:
  47655. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  47656. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  47657. }*/
  47658. switch (impostorJoint.joint.type) {
  47659. case BABYLON.PhysicsJoint.HingeJoint:
  47660. case BABYLON.PhysicsJoint.Hinge2Joint:
  47661. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47662. break;
  47663. case BABYLON.PhysicsJoint.DistanceJoint:
  47664. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47665. break;
  47666. case BABYLON.PhysicsJoint.SpringJoint:
  47667. var springData = jointData;
  47668. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47669. restLength: springData.length,
  47670. stiffness: springData.stiffness,
  47671. damping: springData.damping,
  47672. localAnchorA: constraintData.pivotA,
  47673. localAnchorB: constraintData.pivotB
  47674. });
  47675. break;
  47676. case BABYLON.PhysicsJoint.LockJoint:
  47677. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47678. break;
  47679. case BABYLON.PhysicsJoint.PointToPointJoint:
  47680. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47681. default:
  47682. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47683. break;
  47684. }
  47685. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47686. constraint.collideConnected = !!jointData.collision;
  47687. impostorJoint.joint.physicsJoint = constraint;
  47688. //don't add spring as constraint, as it is not one.
  47689. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47690. this.world.addConstraint(constraint);
  47691. }
  47692. else {
  47693. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47694. constraint.applyForce();
  47695. });
  47696. }
  47697. };
  47698. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47699. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47700. };
  47701. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47702. var index;
  47703. var mat;
  47704. for (index = 0; index < this._physicsMaterials.length; index++) {
  47705. mat = this._physicsMaterials[index];
  47706. if (mat.friction === friction && mat.restitution === restitution) {
  47707. return mat;
  47708. }
  47709. }
  47710. var currentMat = new CANNON.Material(name);
  47711. currentMat.friction = friction;
  47712. currentMat.restitution = restitution;
  47713. this._physicsMaterials.push(currentMat);
  47714. return currentMat;
  47715. };
  47716. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47717. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47718. };
  47719. CannonJSPlugin.prototype._createShape = function (impostor) {
  47720. var object = impostor.object;
  47721. var returnValue;
  47722. var extendSize = impostor.getObjectExtendSize();
  47723. switch (impostor.type) {
  47724. case BABYLON.PhysicsEngine.SphereImpostor:
  47725. var radiusX = extendSize.x;
  47726. var radiusY = extendSize.y;
  47727. var radiusZ = extendSize.z;
  47728. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47729. break;
  47730. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47731. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47732. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47733. break;
  47734. case BABYLON.PhysicsImpostor.BoxImpostor:
  47735. var box = extendSize.scale(0.5);
  47736. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47737. break;
  47738. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47739. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47740. returnValue = new CANNON.Plane();
  47741. break;
  47742. case BABYLON.PhysicsImpostor.MeshImpostor:
  47743. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47744. var rawFaces = object.getIndices ? object.getIndices() : [];
  47745. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47746. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47747. break;
  47748. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47749. returnValue = this._createHeightmap(object);
  47750. break;
  47751. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47752. returnValue = new CANNON.Particle();
  47753. break;
  47754. }
  47755. return returnValue;
  47756. };
  47757. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47758. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47759. var matrix = [];
  47760. //For now pointDepth will not be used and will be automatically calculated.
  47761. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47762. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47763. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47764. var elementSize = dim * 2 / arraySize;
  47765. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47766. for (var i = 0; i < pos.length; i = i + 3) {
  47767. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47768. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47769. var y = pos[i + 1] + minY;
  47770. if (!matrix[x]) {
  47771. matrix[x] = [];
  47772. }
  47773. if (!matrix[x][z]) {
  47774. matrix[x][z] = y;
  47775. }
  47776. matrix[x][z] = Math.max(y, matrix[x][z]);
  47777. }
  47778. for (var x = 0; x <= arraySize; ++x) {
  47779. if (!matrix[x]) {
  47780. var loc = 1;
  47781. while (!matrix[(x + loc) % arraySize]) {
  47782. loc++;
  47783. }
  47784. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47785. }
  47786. for (var z = 0; z <= arraySize; ++z) {
  47787. if (!matrix[x][z]) {
  47788. var loc = 1;
  47789. var newValue;
  47790. while (newValue === undefined) {
  47791. newValue = matrix[x][(z + loc++) % arraySize];
  47792. }
  47793. matrix[x][z] = newValue;
  47794. }
  47795. }
  47796. }
  47797. var shape = new CANNON.Heightfield(matrix, {
  47798. elementSize: elementSize
  47799. });
  47800. //For future reference, needed for body transformation
  47801. shape.minY = minY;
  47802. return shape;
  47803. };
  47804. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47805. var object = impostor.object;
  47806. //make sure it is updated...
  47807. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47808. // The delta between the mesh position and the mesh bounding box center
  47809. var center = impostor.getObjectCenter();
  47810. var extendSize = impostor.getObjectExtendSize();
  47811. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47812. this._tmpPosition.copyFrom(center);
  47813. var quaternion = object.rotationQuaternion;
  47814. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47815. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47816. //-90 DEG in X, precalculated
  47817. quaternion = quaternion.multiply(this._minus90X);
  47818. //Invert! (Precalculated, 90 deg in X)
  47819. //No need to clone. this will never change.
  47820. impostor.setDeltaRotation(this._plus90X);
  47821. }
  47822. //If it is a heightfield, if should be centered.
  47823. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  47824. var mesh = object;
  47825. //calculate the correct body position:
  47826. var rotationQuaternion = mesh.rotationQuaternion;
  47827. mesh.rotationQuaternion = this._tmpUnityRotation;
  47828. mesh.computeWorldMatrix(true);
  47829. //get original center with no rotation
  47830. var c = center.clone();
  47831. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47832. //rotation is back
  47833. mesh.rotationQuaternion = rotationQuaternion;
  47834. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47835. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47836. mesh.setPivotMatrix(p);
  47837. mesh.computeWorldMatrix(true);
  47838. //calculate the translation
  47839. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47840. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47841. //add it inverted to the delta
  47842. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47843. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47844. mesh.setPivotMatrix(oldPivot);
  47845. mesh.computeWorldMatrix(true);
  47846. }
  47847. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  47848. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47849. this._tmpPosition.copyFrom(object.position);
  47850. }
  47851. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47852. //Now update the impostor object
  47853. impostor.physicsBody.position.copy(this._tmpPosition);
  47854. impostor.physicsBody.quaternion.copy(quaternion);
  47855. };
  47856. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47857. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47858. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47859. };
  47860. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47861. impostor.physicsBody.position.copy(newPosition);
  47862. impostor.physicsBody.quaternion.copy(newRotation);
  47863. };
  47864. CannonJSPlugin.prototype.isSupported = function () {
  47865. return window.CANNON !== undefined;
  47866. };
  47867. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47868. impostor.physicsBody.velocity.copy(velocity);
  47869. };
  47870. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47871. impostor.physicsBody.angularVelocity.copy(velocity);
  47872. };
  47873. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47874. var v = impostor.physicsBody.velocity;
  47875. if (!v)
  47876. return null;
  47877. return new BABYLON.Vector3(v.x, v.y, v.z);
  47878. };
  47879. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47880. var v = impostor.physicsBody.angularVelocity;
  47881. if (!v)
  47882. return null;
  47883. return new BABYLON.Vector3(v.x, v.y, v.z);
  47884. };
  47885. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47886. impostor.physicsBody.mass = mass;
  47887. impostor.physicsBody.updateMassProperties();
  47888. };
  47889. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47890. impostor.physicsBody.sleep();
  47891. };
  47892. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47893. impostor.physicsBody.wakeUp();
  47894. };
  47895. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47896. joint.physicsJoint.distance = maxDistance;
  47897. };
  47898. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47899. if (!motorIndex) {
  47900. joint.physicsJoint.enableMotor();
  47901. }
  47902. };
  47903. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47904. if (!motorIndex) {
  47905. joint.physicsJoint.disableMotor();
  47906. }
  47907. };
  47908. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47909. if (!motorIndex) {
  47910. joint.physicsJoint.enableMotor();
  47911. joint.physicsJoint.setMotorSpeed(speed);
  47912. if (maxForce) {
  47913. this.setLimit(joint, maxForce);
  47914. }
  47915. }
  47916. };
  47917. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47918. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47919. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47920. };
  47921. CannonJSPlugin.prototype.dispose = function () {
  47922. //nothing to do, actually.
  47923. };
  47924. return CannonJSPlugin;
  47925. }());
  47926. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47927. })(BABYLON || (BABYLON = {}));
  47928. var BABYLON;
  47929. (function (BABYLON) {
  47930. var OimoJSPlugin = (function () {
  47931. function OimoJSPlugin(iterations) {
  47932. this.name = "OimoJSPlugin";
  47933. this._tmpImpostorsArray = [];
  47934. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47935. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47936. this.world.clear();
  47937. //making sure no stats are calculated
  47938. this.world.isNoStat = true;
  47939. }
  47940. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47941. this.world.gravity.copy(gravity);
  47942. };
  47943. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47944. this.world.timeStep = timeStep;
  47945. };
  47946. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47947. var _this = this;
  47948. impostors.forEach(function (impostor) {
  47949. impostor.beforeStep();
  47950. });
  47951. this.world.step();
  47952. impostors.forEach(function (impostor) {
  47953. impostor.afterStep();
  47954. //update the ordered impostors array
  47955. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47956. });
  47957. //check for collisions
  47958. var contact = this.world.contacts;
  47959. while (contact !== null) {
  47960. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47961. contact = contact.next;
  47962. continue;
  47963. }
  47964. //is this body colliding with any other? get the impostor
  47965. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47966. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47967. if (!mainImpostor || !collidingImpostor) {
  47968. contact = contact.next;
  47969. continue;
  47970. }
  47971. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47972. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47973. contact = contact.next;
  47974. }
  47975. };
  47976. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47977. var mass = impostor.physicsBody.massInfo.mass;
  47978. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  47979. };
  47980. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47981. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  47982. this.applyImpulse(impostor, force, contactPoint);
  47983. };
  47984. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47985. var _this = this;
  47986. //parent-child relationship. Does this impostor has a parent impostor?
  47987. if (impostor.parent) {
  47988. if (impostor.physicsBody) {
  47989. this.removePhysicsBody(impostor);
  47990. //TODO is that needed?
  47991. impostor.forceUpdate();
  47992. }
  47993. return;
  47994. }
  47995. if (impostor.isBodyInitRequired()) {
  47996. var bodyConfig = {
  47997. name: impostor.uniqueId,
  47998. //Oimo must have mass, also for static objects.
  47999. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  48000. size: [],
  48001. type: [],
  48002. pos: [],
  48003. rot: [],
  48004. move: impostor.getParam("mass") !== 0,
  48005. //Supporting older versions of Oimo
  48006. world: this.world
  48007. };
  48008. var impostors = [impostor];
  48009. function addToArray(parent) {
  48010. if (!parent.getChildMeshes)
  48011. return;
  48012. parent.getChildMeshes().forEach(function (m) {
  48013. if (m.physicsImpostor) {
  48014. impostors.push(m.physicsImpostor);
  48015. m.physicsImpostor._init();
  48016. }
  48017. });
  48018. }
  48019. addToArray(impostor.object);
  48020. function checkWithEpsilon(value) {
  48021. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  48022. }
  48023. impostors.forEach(function (i) {
  48024. //get the correct bounding box
  48025. var oldQuaternion = i.object.rotationQuaternion;
  48026. var rot = new OIMO.Euler().setFromQuaternion({
  48027. x: impostor.object.rotationQuaternion.x,
  48028. y: impostor.object.rotationQuaternion.y,
  48029. z: impostor.object.rotationQuaternion.z,
  48030. s: impostor.object.rotationQuaternion.w
  48031. });
  48032. var extendSize = i.getObjectExtendSize();
  48033. if (i === impostor) {
  48034. var center = impostor.getObjectCenter();
  48035. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  48036. //Can also use Array.prototype.push.apply
  48037. bodyConfig.pos.push(center.x);
  48038. bodyConfig.pos.push(center.y);
  48039. bodyConfig.pos.push(center.z);
  48040. //tmp solution
  48041. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  48042. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  48043. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  48044. }
  48045. else {
  48046. bodyConfig.pos.push(i.object.position.x);
  48047. bodyConfig.pos.push(i.object.position.y);
  48048. bodyConfig.pos.push(i.object.position.z);
  48049. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  48050. bodyConfig.rot.push(0);
  48051. bodyConfig.rot.push(0);
  48052. bodyConfig.rot.push(0);
  48053. }
  48054. // register mesh
  48055. switch (i.type) {
  48056. case BABYLON.PhysicsImpostor.ParticleImpostor:
  48057. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  48058. case BABYLON.PhysicsImpostor.SphereImpostor:
  48059. var radiusX = extendSize.x;
  48060. var radiusY = extendSize.y;
  48061. var radiusZ = extendSize.z;
  48062. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  48063. bodyConfig.type.push('sphere');
  48064. //due to the way oimo works with compounds, add 3 times
  48065. bodyConfig.size.push(size);
  48066. bodyConfig.size.push(size);
  48067. bodyConfig.size.push(size);
  48068. break;
  48069. case BABYLON.PhysicsImpostor.CylinderImpostor:
  48070. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  48071. var sizeY = checkWithEpsilon(extendSize.y);
  48072. bodyConfig.type.push('cylinder');
  48073. bodyConfig.size.push(sizeX);
  48074. bodyConfig.size.push(sizeY);
  48075. //due to the way oimo works with compounds, add one more value.
  48076. bodyConfig.size.push(sizeY);
  48077. break;
  48078. case BABYLON.PhysicsImpostor.PlaneImpostor:
  48079. case BABYLON.PhysicsImpostor.BoxImpostor:
  48080. default:
  48081. var sizeX = checkWithEpsilon(extendSize.x);
  48082. var sizeY = checkWithEpsilon(extendSize.y);
  48083. var sizeZ = checkWithEpsilon(extendSize.z);
  48084. bodyConfig.type.push('box');
  48085. bodyConfig.size.push(sizeX);
  48086. bodyConfig.size.push(sizeY);
  48087. bodyConfig.size.push(sizeZ);
  48088. break;
  48089. }
  48090. //actually not needed, but hey...
  48091. i.object.rotationQuaternion = oldQuaternion;
  48092. });
  48093. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  48094. }
  48095. else {
  48096. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  48097. }
  48098. impostor.setDeltaPosition(this._tmpPositionVector);
  48099. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  48100. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  48101. };
  48102. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48103. //impostor.physicsBody.dispose();
  48104. //Same as : (older oimo versions)
  48105. this.world.removeRigidBody(impostor.physicsBody);
  48106. };
  48107. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48108. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48109. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48110. if (!mainBody || !connectedBody) {
  48111. return;
  48112. }
  48113. var jointData = impostorJoint.joint.jointData;
  48114. var options = jointData.nativeParams || {};
  48115. var type;
  48116. var nativeJointData = {
  48117. body1: mainBody,
  48118. body2: connectedBody,
  48119. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  48120. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  48121. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  48122. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  48123. min: options.min,
  48124. max: options.max,
  48125. collision: options.collision || jointData.collision,
  48126. spring: options.spring,
  48127. //supporting older version of Oimo
  48128. world: this.world
  48129. };
  48130. switch (impostorJoint.joint.type) {
  48131. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  48132. type = "jointBall";
  48133. break;
  48134. case BABYLON.PhysicsJoint.SpringJoint:
  48135. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  48136. var springData = jointData;
  48137. nativeJointData.min = springData.length || nativeJointData.min;
  48138. //Max should also be set, just make sure it is at least min
  48139. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  48140. case BABYLON.PhysicsJoint.DistanceJoint:
  48141. type = "jointDistance";
  48142. nativeJointData.max = jointData.maxDistance;
  48143. break;
  48144. case BABYLON.PhysicsJoint.PrismaticJoint:
  48145. type = "jointPrisme";
  48146. break;
  48147. case BABYLON.PhysicsJoint.SliderJoint:
  48148. type = "jointSlide";
  48149. break;
  48150. case BABYLON.PhysicsJoint.WheelJoint:
  48151. type = "jointWheel";
  48152. break;
  48153. case BABYLON.PhysicsJoint.HingeJoint:
  48154. default:
  48155. type = "jointHinge";
  48156. break;
  48157. }
  48158. nativeJointData.type = type;
  48159. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  48160. };
  48161. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  48162. //Bug in Oimo prevents us from disposing a joint in the playground
  48163. //joint.joint.physicsJoint.dispose();
  48164. //So we will bruteforce it!
  48165. try {
  48166. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  48167. }
  48168. catch (e) {
  48169. BABYLON.Tools.Warn(e);
  48170. }
  48171. };
  48172. OimoJSPlugin.prototype.isSupported = function () {
  48173. return OIMO !== undefined;
  48174. };
  48175. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  48176. if (!impostor.physicsBody.sleeping) {
  48177. //TODO check that
  48178. if (impostor.physicsBody.shapes.next) {
  48179. var parentShape = this._getLastShape(impostor.physicsBody);
  48180. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  48181. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  48182. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  48183. }
  48184. else {
  48185. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  48186. }
  48187. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  48188. impostor.object.rotationQuaternion.normalize();
  48189. }
  48190. };
  48191. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48192. var body = impostor.physicsBody;
  48193. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  48194. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  48195. body.syncShapes();
  48196. body.awake();
  48197. };
  48198. OimoJSPlugin.prototype._getLastShape = function (body) {
  48199. var lastShape = body.shapes;
  48200. while (lastShape.next) {
  48201. lastShape = lastShape.next;
  48202. }
  48203. return lastShape;
  48204. };
  48205. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48206. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  48207. };
  48208. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48209. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  48210. };
  48211. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48212. var v = impostor.physicsBody.linearVelocity;
  48213. if (!v)
  48214. return null;
  48215. return new BABYLON.Vector3(v.x, v.y, v.z);
  48216. };
  48217. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48218. var v = impostor.physicsBody.angularVelocity;
  48219. if (!v)
  48220. return null;
  48221. return new BABYLON.Vector3(v.x, v.y, v.z);
  48222. };
  48223. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48224. var staticBody = mass === 0;
  48225. //this will actually set the body's density and not its mass.
  48226. //But this is how oimo treats the mass variable.
  48227. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  48228. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  48229. };
  48230. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  48231. impostor.physicsBody.sleep();
  48232. };
  48233. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  48234. impostor.physicsBody.awake();
  48235. };
  48236. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48237. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  48238. if (minDistance !== void 0) {
  48239. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  48240. }
  48241. };
  48242. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48243. //TODO separate rotational and transational motors.
  48244. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48245. if (motor) {
  48246. motor.setMotor(speed, maxForce);
  48247. }
  48248. };
  48249. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  48250. //TODO separate rotational and transational motors.
  48251. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48252. if (motor) {
  48253. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  48254. }
  48255. };
  48256. OimoJSPlugin.prototype.dispose = function () {
  48257. this.world.clear();
  48258. };
  48259. return OimoJSPlugin;
  48260. }());
  48261. BABYLON.OimoJSPlugin = OimoJSPlugin;
  48262. })(BABYLON || (BABYLON = {}));
  48263. var BABYLON;
  48264. (function (BABYLON) {
  48265. var DisplayPassPostProcess = (function (_super) {
  48266. __extends(DisplayPassPostProcess, _super);
  48267. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48268. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  48269. }
  48270. return DisplayPassPostProcess;
  48271. }(BABYLON.PostProcess));
  48272. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48273. })(BABYLON || (BABYLON = {}));
  48274. var BABYLON;
  48275. (function (BABYLON) {
  48276. var SimplificationSettings = (function () {
  48277. function SimplificationSettings(quality, distance, optimizeMesh) {
  48278. this.quality = quality;
  48279. this.distance = distance;
  48280. this.optimizeMesh = optimizeMesh;
  48281. }
  48282. return SimplificationSettings;
  48283. }());
  48284. BABYLON.SimplificationSettings = SimplificationSettings;
  48285. var SimplificationQueue = (function () {
  48286. function SimplificationQueue() {
  48287. this.running = false;
  48288. this._simplificationArray = [];
  48289. }
  48290. SimplificationQueue.prototype.addTask = function (task) {
  48291. this._simplificationArray.push(task);
  48292. };
  48293. SimplificationQueue.prototype.executeNext = function () {
  48294. var task = this._simplificationArray.pop();
  48295. if (task) {
  48296. this.running = true;
  48297. this.runSimplification(task);
  48298. }
  48299. else {
  48300. this.running = false;
  48301. }
  48302. };
  48303. SimplificationQueue.prototype.runSimplification = function (task) {
  48304. var _this = this;
  48305. if (task.parallelProcessing) {
  48306. //parallel simplifier
  48307. task.settings.forEach(function (setting) {
  48308. var simplifier = _this.getSimplifier(task);
  48309. simplifier.simplify(setting, function (newMesh) {
  48310. task.mesh.addLODLevel(setting.distance, newMesh);
  48311. newMesh.isVisible = true;
  48312. //check if it is the last
  48313. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  48314. //all done, run the success callback.
  48315. task.successCallback();
  48316. }
  48317. _this.executeNext();
  48318. });
  48319. });
  48320. }
  48321. else {
  48322. //single simplifier.
  48323. var simplifier = this.getSimplifier(task);
  48324. var runDecimation = function (setting, callback) {
  48325. simplifier.simplify(setting, function (newMesh) {
  48326. task.mesh.addLODLevel(setting.distance, newMesh);
  48327. newMesh.isVisible = true;
  48328. //run the next quality level
  48329. callback();
  48330. });
  48331. };
  48332. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  48333. runDecimation(task.settings[loop.index], function () {
  48334. loop.executeNext();
  48335. });
  48336. }, function () {
  48337. //execution ended, run the success callback.
  48338. if (task.successCallback) {
  48339. task.successCallback();
  48340. }
  48341. _this.executeNext();
  48342. });
  48343. }
  48344. };
  48345. SimplificationQueue.prototype.getSimplifier = function (task) {
  48346. switch (task.simplificationType) {
  48347. case SimplificationType.QUADRATIC:
  48348. default:
  48349. return new QuadraticErrorSimplification(task.mesh);
  48350. }
  48351. };
  48352. return SimplificationQueue;
  48353. }());
  48354. BABYLON.SimplificationQueue = SimplificationQueue;
  48355. /**
  48356. * The implemented types of simplification.
  48357. * At the moment only Quadratic Error Decimation is implemented.
  48358. */
  48359. (function (SimplificationType) {
  48360. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  48361. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  48362. var SimplificationType = BABYLON.SimplificationType;
  48363. var DecimationTriangle = (function () {
  48364. function DecimationTriangle(vertices) {
  48365. this.vertices = vertices;
  48366. this.error = new Array(4);
  48367. this.deleted = false;
  48368. this.isDirty = false;
  48369. this.deletePending = false;
  48370. this.borderFactor = 0;
  48371. }
  48372. return DecimationTriangle;
  48373. }());
  48374. BABYLON.DecimationTriangle = DecimationTriangle;
  48375. var DecimationVertex = (function () {
  48376. function DecimationVertex(position, id) {
  48377. this.position = position;
  48378. this.id = id;
  48379. this.isBorder = true;
  48380. this.q = new QuadraticMatrix();
  48381. this.triangleCount = 0;
  48382. this.triangleStart = 0;
  48383. this.originalOffsets = [];
  48384. }
  48385. DecimationVertex.prototype.updatePosition = function (newPosition) {
  48386. this.position.copyFrom(newPosition);
  48387. };
  48388. return DecimationVertex;
  48389. }());
  48390. BABYLON.DecimationVertex = DecimationVertex;
  48391. var QuadraticMatrix = (function () {
  48392. function QuadraticMatrix(data) {
  48393. this.data = new Array(10);
  48394. for (var i = 0; i < 10; ++i) {
  48395. if (data && data[i]) {
  48396. this.data[i] = data[i];
  48397. }
  48398. else {
  48399. this.data[i] = 0;
  48400. }
  48401. }
  48402. }
  48403. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  48404. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  48405. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  48406. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  48407. return det;
  48408. };
  48409. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  48410. for (var i = 0; i < 10; ++i) {
  48411. this.data[i] += matrix.data[i];
  48412. }
  48413. };
  48414. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  48415. for (var i = 0; i < 10; ++i) {
  48416. this.data[i] += data[i];
  48417. }
  48418. };
  48419. QuadraticMatrix.prototype.add = function (matrix) {
  48420. var m = new QuadraticMatrix();
  48421. for (var i = 0; i < 10; ++i) {
  48422. m.data[i] = this.data[i] + matrix.data[i];
  48423. }
  48424. return m;
  48425. };
  48426. QuadraticMatrix.FromData = function (a, b, c, d) {
  48427. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  48428. };
  48429. //returning an array to avoid garbage collection
  48430. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  48431. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  48432. };
  48433. return QuadraticMatrix;
  48434. }());
  48435. BABYLON.QuadraticMatrix = QuadraticMatrix;
  48436. var Reference = (function () {
  48437. function Reference(vertexId, triangleId) {
  48438. this.vertexId = vertexId;
  48439. this.triangleId = triangleId;
  48440. }
  48441. return Reference;
  48442. }());
  48443. BABYLON.Reference = Reference;
  48444. /**
  48445. * An implementation of the Quadratic Error simplification algorithm.
  48446. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  48447. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  48448. * @author RaananW
  48449. */
  48450. var QuadraticErrorSimplification = (function () {
  48451. function QuadraticErrorSimplification(_mesh) {
  48452. this._mesh = _mesh;
  48453. this.initialized = false;
  48454. this.syncIterations = 5000;
  48455. this.aggressiveness = 7;
  48456. this.decimationIterations = 100;
  48457. this.boundingBoxEpsilon = BABYLON.Epsilon;
  48458. }
  48459. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  48460. var _this = this;
  48461. this.initDecimatedMesh();
  48462. //iterating through the submeshes array, one after the other.
  48463. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  48464. _this.initWithMesh(loop.index, function () {
  48465. _this.runDecimation(settings, loop.index, function () {
  48466. loop.executeNext();
  48467. });
  48468. }, settings.optimizeMesh);
  48469. }, function () {
  48470. setTimeout(function () {
  48471. successCallback(_this._reconstructedMesh);
  48472. }, 0);
  48473. });
  48474. };
  48475. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  48476. var _this = this;
  48477. var gCount = 0;
  48478. triangle.vertices.forEach(function (vertex) {
  48479. var count = 0;
  48480. var vPos = vertex.position;
  48481. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  48482. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  48483. ++count;
  48484. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  48485. ++count;
  48486. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  48487. ++count;
  48488. if (count > 1) {
  48489. ++gCount;
  48490. }
  48491. ;
  48492. });
  48493. if (gCount > 1) {
  48494. console.log(triangle, gCount);
  48495. }
  48496. return gCount > 1;
  48497. };
  48498. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  48499. var _this = this;
  48500. var targetCount = ~~(this.triangles.length * settings.quality);
  48501. var deletedTriangles = 0;
  48502. var triangleCount = this.triangles.length;
  48503. var iterationFunction = function (iteration, callback) {
  48504. setTimeout(function () {
  48505. if (iteration % 5 === 0) {
  48506. _this.updateMesh(iteration === 0);
  48507. }
  48508. for (var i = 0; i < _this.triangles.length; ++i) {
  48509. _this.triangles[i].isDirty = false;
  48510. }
  48511. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  48512. var trianglesIterator = function (i) {
  48513. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  48514. var t = _this.triangles[tIdx];
  48515. if (!t)
  48516. return;
  48517. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  48518. return;
  48519. }
  48520. for (var j = 0; j < 3; ++j) {
  48521. if (t.error[j] < threshold) {
  48522. var deleted0 = [];
  48523. var deleted1 = [];
  48524. var v0 = t.vertices[j];
  48525. var v1 = t.vertices[(j + 1) % 3];
  48526. if (v0.isBorder || v1.isBorder)
  48527. continue;
  48528. var p = BABYLON.Vector3.Zero();
  48529. var n = BABYLON.Vector3.Zero();
  48530. var uv = BABYLON.Vector2.Zero();
  48531. var color = new BABYLON.Color4(0, 0, 0, 1);
  48532. _this.calculateError(v0, v1, p, n, uv, color);
  48533. var delTr = [];
  48534. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  48535. continue;
  48536. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  48537. continue;
  48538. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  48539. continue;
  48540. var uniqueArray = [];
  48541. delTr.forEach(function (deletedT) {
  48542. if (uniqueArray.indexOf(deletedT) === -1) {
  48543. deletedT.deletePending = true;
  48544. uniqueArray.push(deletedT);
  48545. }
  48546. });
  48547. if (uniqueArray.length % 2 !== 0) {
  48548. continue;
  48549. }
  48550. v0.q = v1.q.add(v0.q);
  48551. v0.updatePosition(p);
  48552. var tStart = _this.references.length;
  48553. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  48554. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  48555. var tCount = _this.references.length - tStart;
  48556. if (tCount <= v0.triangleCount) {
  48557. if (tCount) {
  48558. for (var c = 0; c < tCount; c++) {
  48559. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  48560. }
  48561. }
  48562. }
  48563. else {
  48564. v0.triangleStart = tStart;
  48565. }
  48566. v0.triangleCount = tCount;
  48567. break;
  48568. }
  48569. }
  48570. };
  48571. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  48572. }, 0);
  48573. };
  48574. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  48575. if (triangleCount - deletedTriangles <= targetCount)
  48576. loop.breakLoop();
  48577. else {
  48578. iterationFunction(loop.index, function () {
  48579. loop.executeNext();
  48580. });
  48581. }
  48582. }, function () {
  48583. setTimeout(function () {
  48584. //reconstruct this part of the mesh
  48585. _this.reconstructMesh(submeshIndex);
  48586. successCallback();
  48587. }, 0);
  48588. });
  48589. };
  48590. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  48591. var _this = this;
  48592. this.vertices = [];
  48593. this.triangles = [];
  48594. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48595. var indices = this._mesh.getIndices();
  48596. var submesh = this._mesh.subMeshes[submeshIndex];
  48597. var findInVertices = function (positionToSearch) {
  48598. if (optimizeMesh) {
  48599. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48600. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48601. return _this.vertices[ii];
  48602. }
  48603. }
  48604. }
  48605. return null;
  48606. };
  48607. var vertexReferences = [];
  48608. var vertexInit = function (i) {
  48609. var offset = i + submesh.verticesStart;
  48610. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48611. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48612. vertex.originalOffsets.push(offset);
  48613. if (vertex.id === _this.vertices.length) {
  48614. _this.vertices.push(vertex);
  48615. }
  48616. vertexReferences.push(vertex.id);
  48617. };
  48618. //var totalVertices = mesh.getTotalVertices();
  48619. var totalVertices = submesh.verticesCount;
  48620. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48621. var indicesInit = function (i) {
  48622. var offset = (submesh.indexStart / 3) + i;
  48623. var pos = (offset * 3);
  48624. var i0 = indices[pos + 0];
  48625. var i1 = indices[pos + 1];
  48626. var i2 = indices[pos + 2];
  48627. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48628. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48629. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48630. var triangle = new DecimationTriangle([v0, v1, v2]);
  48631. triangle.originalOffset = pos;
  48632. _this.triangles.push(triangle);
  48633. };
  48634. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48635. _this.init(callback);
  48636. });
  48637. });
  48638. };
  48639. QuadraticErrorSimplification.prototype.init = function (callback) {
  48640. var _this = this;
  48641. var triangleInit1 = function (i) {
  48642. var t = _this.triangles[i];
  48643. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48644. for (var j = 0; j < 3; j++) {
  48645. 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))));
  48646. }
  48647. };
  48648. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48649. var triangleInit2 = function (i) {
  48650. var t = _this.triangles[i];
  48651. for (var j = 0; j < 3; ++j) {
  48652. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48653. }
  48654. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48655. };
  48656. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48657. _this.initialized = true;
  48658. callback();
  48659. });
  48660. });
  48661. };
  48662. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48663. var newTriangles = [];
  48664. var i;
  48665. for (i = 0; i < this.vertices.length; ++i) {
  48666. this.vertices[i].triangleCount = 0;
  48667. }
  48668. var t;
  48669. var j;
  48670. for (i = 0; i < this.triangles.length; ++i) {
  48671. if (!this.triangles[i].deleted) {
  48672. t = this.triangles[i];
  48673. for (j = 0; j < 3; ++j) {
  48674. t.vertices[j].triangleCount = 1;
  48675. }
  48676. newTriangles.push(t);
  48677. }
  48678. }
  48679. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48680. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48681. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48682. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48683. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48684. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48685. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48686. var vertexCount = 0;
  48687. for (i = 0; i < this.vertices.length; ++i) {
  48688. var vertex = this.vertices[i];
  48689. vertex.id = vertexCount;
  48690. if (vertex.triangleCount) {
  48691. vertex.originalOffsets.forEach(function (originalOffset) {
  48692. newPositionData.push(vertex.position.x);
  48693. newPositionData.push(vertex.position.y);
  48694. newPositionData.push(vertex.position.z);
  48695. newNormalData.push(normalData[originalOffset * 3]);
  48696. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48697. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48698. if (uvs && uvs.length) {
  48699. newUVsData.push(uvs[(originalOffset * 2)]);
  48700. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48701. }
  48702. else if (colorsData && colorsData.length) {
  48703. newColorsData.push(colorsData[(originalOffset * 4)]);
  48704. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48705. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48706. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48707. }
  48708. ++vertexCount;
  48709. });
  48710. }
  48711. }
  48712. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48713. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48714. var submeshesArray = this._reconstructedMesh.subMeshes;
  48715. this._reconstructedMesh.subMeshes = [];
  48716. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48717. var originalIndices = this._mesh.getIndices();
  48718. for (i = 0; i < newTriangles.length; ++i) {
  48719. t = newTriangles[i]; //now get the new referencing point for each vertex
  48720. [0, 1, 2].forEach(function (idx) {
  48721. var id = originalIndices[t.originalOffset + idx];
  48722. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48723. if (offset < 0)
  48724. offset = 0;
  48725. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48726. });
  48727. }
  48728. //overwriting the old vertex buffers and indices.
  48729. this._reconstructedMesh.setIndices(newIndicesArray);
  48730. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48731. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48732. if (newUVsData.length > 0)
  48733. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48734. if (newColorsData.length > 0)
  48735. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48736. //create submesh
  48737. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48738. if (submeshIndex > 0) {
  48739. this._reconstructedMesh.subMeshes = [];
  48740. submeshesArray.forEach(function (submesh) {
  48741. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48742. });
  48743. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48744. }
  48745. };
  48746. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48747. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48748. this._reconstructedMesh.material = this._mesh.material;
  48749. this._reconstructedMesh.parent = this._mesh.parent;
  48750. this._reconstructedMesh.isVisible = false;
  48751. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48752. };
  48753. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48754. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48755. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48756. if (t.deleted)
  48757. continue;
  48758. var s = this.references[vertex1.triangleStart + i].vertexId;
  48759. var v1 = t.vertices[(s + 1) % 3];
  48760. var v2 = t.vertices[(s + 2) % 3];
  48761. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48762. deletedArray[i] = true;
  48763. delTr.push(t);
  48764. continue;
  48765. }
  48766. var d1 = v1.position.subtract(point);
  48767. d1 = d1.normalize();
  48768. var d2 = v2.position.subtract(point);
  48769. d2 = d2.normalize();
  48770. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48771. return true;
  48772. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48773. deletedArray[i] = false;
  48774. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48775. return true;
  48776. }
  48777. return false;
  48778. };
  48779. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48780. var newDeleted = deletedTriangles;
  48781. for (var i = 0; i < vertex.triangleCount; ++i) {
  48782. var ref = this.references[vertex.triangleStart + i];
  48783. var t = this.triangles[ref.triangleId];
  48784. if (t.deleted)
  48785. continue;
  48786. if (deletedArray[i] && t.deletePending) {
  48787. t.deleted = true;
  48788. newDeleted++;
  48789. continue;
  48790. }
  48791. t.vertices[ref.vertexId] = origVertex;
  48792. t.isDirty = true;
  48793. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48794. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48795. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48796. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48797. this.references.push(ref);
  48798. }
  48799. return newDeleted;
  48800. };
  48801. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48802. for (var i = 0; i < this.vertices.length; ++i) {
  48803. var vCount = [];
  48804. var vId = [];
  48805. var v = this.vertices[i];
  48806. var j;
  48807. for (j = 0; j < v.triangleCount; ++j) {
  48808. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48809. for (var ii = 0; ii < 3; ii++) {
  48810. var ofs = 0;
  48811. var vv = triangle.vertices[ii];
  48812. while (ofs < vCount.length) {
  48813. if (vId[ofs] === vv.id)
  48814. break;
  48815. ++ofs;
  48816. }
  48817. if (ofs === vCount.length) {
  48818. vCount.push(1);
  48819. vId.push(vv.id);
  48820. }
  48821. else {
  48822. vCount[ofs]++;
  48823. }
  48824. }
  48825. }
  48826. for (j = 0; j < vCount.length; ++j) {
  48827. if (vCount[j] === 1) {
  48828. this.vertices[vId[j]].isBorder = true;
  48829. }
  48830. else {
  48831. this.vertices[vId[j]].isBorder = false;
  48832. }
  48833. }
  48834. }
  48835. };
  48836. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48837. if (identifyBorders === void 0) { identifyBorders = false; }
  48838. var i;
  48839. if (!identifyBorders) {
  48840. var newTrianglesVector = [];
  48841. for (i = 0; i < this.triangles.length; ++i) {
  48842. if (!this.triangles[i].deleted) {
  48843. newTrianglesVector.push(this.triangles[i]);
  48844. }
  48845. }
  48846. this.triangles = newTrianglesVector;
  48847. }
  48848. for (i = 0; i < this.vertices.length; ++i) {
  48849. this.vertices[i].triangleCount = 0;
  48850. this.vertices[i].triangleStart = 0;
  48851. }
  48852. var t;
  48853. var j;
  48854. var v;
  48855. for (i = 0; i < this.triangles.length; ++i) {
  48856. t = this.triangles[i];
  48857. for (j = 0; j < 3; ++j) {
  48858. v = t.vertices[j];
  48859. v.triangleCount++;
  48860. }
  48861. }
  48862. var tStart = 0;
  48863. for (i = 0; i < this.vertices.length; ++i) {
  48864. this.vertices[i].triangleStart = tStart;
  48865. tStart += this.vertices[i].triangleCount;
  48866. this.vertices[i].triangleCount = 0;
  48867. }
  48868. var newReferences = new Array(this.triangles.length * 3);
  48869. for (i = 0; i < this.triangles.length; ++i) {
  48870. t = this.triangles[i];
  48871. for (j = 0; j < 3; ++j) {
  48872. v = t.vertices[j];
  48873. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48874. v.triangleCount++;
  48875. }
  48876. }
  48877. this.references = newReferences;
  48878. if (identifyBorders) {
  48879. this.identifyBorder();
  48880. }
  48881. };
  48882. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48883. var x = point.x;
  48884. var y = point.y;
  48885. var z = point.z;
  48886. 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
  48887. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48888. };
  48889. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48890. var q = vertex1.q.add(vertex2.q);
  48891. var border = vertex1.isBorder && vertex2.isBorder;
  48892. var error = 0;
  48893. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48894. if (qDet !== 0 && !border) {
  48895. if (!pointResult) {
  48896. pointResult = BABYLON.Vector3.Zero();
  48897. }
  48898. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48899. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48900. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48901. error = this.vertexError(q, pointResult);
  48902. }
  48903. else {
  48904. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48905. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48906. var error1 = this.vertexError(q, vertex1.position);
  48907. var error2 = this.vertexError(q, vertex2.position);
  48908. var error3 = this.vertexError(q, p3);
  48909. error = Math.min(error1, error2, error3);
  48910. if (error === error1) {
  48911. if (pointResult) {
  48912. pointResult.copyFrom(vertex1.position);
  48913. }
  48914. }
  48915. else if (error === error2) {
  48916. if (pointResult) {
  48917. pointResult.copyFrom(vertex2.position);
  48918. }
  48919. }
  48920. else {
  48921. if (pointResult) {
  48922. pointResult.copyFrom(p3);
  48923. }
  48924. }
  48925. }
  48926. return error;
  48927. };
  48928. return QuadraticErrorSimplification;
  48929. }());
  48930. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48931. })(BABYLON || (BABYLON = {}));
  48932. var BABYLON;
  48933. (function (BABYLON) {
  48934. var serializedGeometries = [];
  48935. var serializeGeometry = function (geometry, serializationGeometries) {
  48936. if (serializedGeometries[geometry.id]) {
  48937. return;
  48938. }
  48939. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48940. serializationGeometries.boxes.push(geometry.serialize());
  48941. }
  48942. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48943. serializationGeometries.spheres.push(geometry.serialize());
  48944. }
  48945. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48946. serializationGeometries.cylinders.push(geometry.serialize());
  48947. }
  48948. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48949. serializationGeometries.toruses.push(geometry.serialize());
  48950. }
  48951. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48952. serializationGeometries.grounds.push(geometry.serialize());
  48953. }
  48954. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48955. serializationGeometries.planes.push(geometry.serialize());
  48956. }
  48957. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48958. serializationGeometries.torusKnots.push(geometry.serialize());
  48959. }
  48960. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48961. throw new Error("Unknown primitive type");
  48962. }
  48963. else {
  48964. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48965. }
  48966. serializedGeometries[geometry.id] = true;
  48967. };
  48968. var serializeMesh = function (mesh, serializationScene) {
  48969. var serializationObject = {};
  48970. serializationObject.name = mesh.name;
  48971. serializationObject.id = mesh.id;
  48972. if (BABYLON.Tags.HasTags(mesh)) {
  48973. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  48974. }
  48975. serializationObject.position = mesh.position.asArray();
  48976. if (mesh.rotationQuaternion) {
  48977. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  48978. }
  48979. else if (mesh.rotation) {
  48980. serializationObject.rotation = mesh.rotation.asArray();
  48981. }
  48982. serializationObject.scaling = mesh.scaling.asArray();
  48983. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  48984. serializationObject.isEnabled = mesh.isEnabled();
  48985. serializationObject.isVisible = mesh.isVisible;
  48986. serializationObject.infiniteDistance = mesh.infiniteDistance;
  48987. serializationObject.pickable = mesh.isPickable;
  48988. serializationObject.receiveShadows = mesh.receiveShadows;
  48989. serializationObject.billboardMode = mesh.billboardMode;
  48990. serializationObject.visibility = mesh.visibility;
  48991. serializationObject.checkCollisions = mesh.checkCollisions;
  48992. // Parent
  48993. if (mesh.parent) {
  48994. serializationObject.parentId = mesh.parent.id;
  48995. }
  48996. // Geometry
  48997. var geometry = mesh._geometry;
  48998. if (geometry) {
  48999. var geometryId = geometry.id;
  49000. serializationObject.geometryId = geometryId;
  49001. if (!mesh.getScene().getGeometryByID(geometryId)) {
  49002. // 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
  49003. serializeGeometry(geometry, serializationScene.geometries);
  49004. }
  49005. // SubMeshes
  49006. serializationObject.subMeshes = [];
  49007. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49008. var subMesh = mesh.subMeshes[subIndex];
  49009. serializationObject.subMeshes.push({
  49010. materialIndex: subMesh.materialIndex,
  49011. verticesStart: subMesh.verticesStart,
  49012. verticesCount: subMesh.verticesCount,
  49013. indexStart: subMesh.indexStart,
  49014. indexCount: subMesh.indexCount
  49015. });
  49016. }
  49017. }
  49018. // Material
  49019. if (mesh.material) {
  49020. serializationObject.materialId = mesh.material.id;
  49021. }
  49022. else {
  49023. mesh.material = null;
  49024. }
  49025. // Skeleton
  49026. if (mesh.skeleton) {
  49027. serializationObject.skeletonId = mesh.skeleton.id;
  49028. }
  49029. // Physics
  49030. //TODO implement correct serialization for physics impostors.
  49031. if (mesh.getPhysicsImpostor()) {
  49032. serializationObject.physicsMass = mesh.getPhysicsMass();
  49033. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  49034. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  49035. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  49036. }
  49037. // Instances
  49038. serializationObject.instances = [];
  49039. for (var index = 0; index < mesh.instances.length; index++) {
  49040. var instance = mesh.instances[index];
  49041. var serializationInstance = {
  49042. name: instance.name,
  49043. position: instance.position.asArray(),
  49044. scaling: instance.scaling.asArray()
  49045. };
  49046. if (instance.rotationQuaternion) {
  49047. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  49048. }
  49049. else if (instance.rotation) {
  49050. serializationInstance.rotation = instance.rotation.asArray();
  49051. }
  49052. serializationObject.instances.push(serializationInstance);
  49053. // Animations
  49054. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  49055. serializationInstance.ranges = instance.serializeAnimationRanges();
  49056. }
  49057. // Animations
  49058. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  49059. serializationObject.ranges = mesh.serializeAnimationRanges();
  49060. // Layer mask
  49061. serializationObject.layerMask = mesh.layerMask;
  49062. // Action Manager
  49063. if (mesh.actionManager) {
  49064. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  49065. }
  49066. return serializationObject;
  49067. };
  49068. var finalizeSingleMesh = function (mesh, serializationObject) {
  49069. //only works if the mesh is already loaded
  49070. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49071. //serialize material
  49072. if (mesh.material) {
  49073. if (mesh.material instanceof BABYLON.StandardMaterial) {
  49074. serializationObject.materials = serializationObject.materials || [];
  49075. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49076. serializationObject.materials.push(mesh.material.serialize());
  49077. }
  49078. }
  49079. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  49080. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  49081. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49082. serializationObject.multiMaterials.push(mesh.material.serialize());
  49083. }
  49084. }
  49085. }
  49086. //serialize geometry
  49087. var geometry = mesh._geometry;
  49088. if (geometry) {
  49089. if (!serializationObject.geometries) {
  49090. serializationObject.geometries = {};
  49091. serializationObject.geometries.boxes = [];
  49092. serializationObject.geometries.spheres = [];
  49093. serializationObject.geometries.cylinders = [];
  49094. serializationObject.geometries.toruses = [];
  49095. serializationObject.geometries.grounds = [];
  49096. serializationObject.geometries.planes = [];
  49097. serializationObject.geometries.torusKnots = [];
  49098. serializationObject.geometries.vertexData = [];
  49099. }
  49100. serializeGeometry(geometry, serializationObject.geometries);
  49101. }
  49102. // Skeletons
  49103. if (mesh.skeleton) {
  49104. serializationObject.skeletons = serializationObject.skeletons || [];
  49105. serializationObject.skeletons.push(mesh.skeleton.serialize());
  49106. }
  49107. //serialize the actual mesh
  49108. serializationObject.meshes = serializationObject.meshes || [];
  49109. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49110. }
  49111. };
  49112. var SceneSerializer = (function () {
  49113. function SceneSerializer() {
  49114. }
  49115. SceneSerializer.ClearCache = function () {
  49116. serializedGeometries = [];
  49117. };
  49118. SceneSerializer.Serialize = function (scene) {
  49119. var serializationObject = {};
  49120. // Scene
  49121. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  49122. serializationObject.autoClear = scene.autoClear;
  49123. serializationObject.clearColor = scene.clearColor.asArray();
  49124. serializationObject.ambientColor = scene.ambientColor.asArray();
  49125. serializationObject.gravity = scene.gravity.asArray();
  49126. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  49127. serializationObject.workerCollisions = scene.workerCollisions;
  49128. // Fog
  49129. if (scene.fogMode && scene.fogMode !== 0) {
  49130. serializationObject.fogMode = scene.fogMode;
  49131. serializationObject.fogColor = scene.fogColor.asArray();
  49132. serializationObject.fogStart = scene.fogStart;
  49133. serializationObject.fogEnd = scene.fogEnd;
  49134. serializationObject.fogDensity = scene.fogDensity;
  49135. }
  49136. //Physics
  49137. if (scene.isPhysicsEnabled()) {
  49138. serializationObject.physicsEnabled = true;
  49139. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  49140. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  49141. }
  49142. // Lights
  49143. serializationObject.lights = [];
  49144. var index;
  49145. var light;
  49146. for (index = 0; index < scene.lights.length; index++) {
  49147. light = scene.lights[index];
  49148. serializationObject.lights.push(light.serialize());
  49149. }
  49150. // Cameras
  49151. serializationObject.cameras = [];
  49152. for (index = 0; index < scene.cameras.length; index++) {
  49153. var camera = scene.cameras[index];
  49154. serializationObject.cameras.push(camera.serialize());
  49155. }
  49156. if (scene.activeCamera) {
  49157. serializationObject.activeCameraID = scene.activeCamera.id;
  49158. }
  49159. // Animations
  49160. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  49161. // Materials
  49162. serializationObject.materials = [];
  49163. serializationObject.multiMaterials = [];
  49164. var material;
  49165. for (index = 0; index < scene.materials.length; index++) {
  49166. material = scene.materials[index];
  49167. serializationObject.materials.push(material.serialize());
  49168. }
  49169. // MultiMaterials
  49170. serializationObject.multiMaterials = [];
  49171. for (index = 0; index < scene.multiMaterials.length; index++) {
  49172. var multiMaterial = scene.multiMaterials[index];
  49173. serializationObject.multiMaterials.push(multiMaterial.serialize());
  49174. }
  49175. // Skeletons
  49176. serializationObject.skeletons = [];
  49177. for (index = 0; index < scene.skeletons.length; index++) {
  49178. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  49179. }
  49180. // Geometries
  49181. serializationObject.geometries = {};
  49182. serializationObject.geometries.boxes = [];
  49183. serializationObject.geometries.spheres = [];
  49184. serializationObject.geometries.cylinders = [];
  49185. serializationObject.geometries.toruses = [];
  49186. serializationObject.geometries.grounds = [];
  49187. serializationObject.geometries.planes = [];
  49188. serializationObject.geometries.torusKnots = [];
  49189. serializationObject.geometries.vertexData = [];
  49190. serializedGeometries = [];
  49191. var geometries = scene.getGeometries();
  49192. for (index = 0; index < geometries.length; index++) {
  49193. var geometry = geometries[index];
  49194. if (geometry.isReady()) {
  49195. serializeGeometry(geometry, serializationObject.geometries);
  49196. }
  49197. }
  49198. // Meshes
  49199. serializationObject.meshes = [];
  49200. for (index = 0; index < scene.meshes.length; index++) {
  49201. var abstractMesh = scene.meshes[index];
  49202. if (abstractMesh instanceof BABYLON.Mesh) {
  49203. var mesh = abstractMesh;
  49204. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49205. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49206. }
  49207. }
  49208. }
  49209. // Particles Systems
  49210. serializationObject.particleSystems = [];
  49211. for (index = 0; index < scene.particleSystems.length; index++) {
  49212. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  49213. }
  49214. // Lens flares
  49215. serializationObject.lensFlareSystems = [];
  49216. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  49217. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  49218. }
  49219. // Shadows
  49220. serializationObject.shadowGenerators = [];
  49221. for (index = 0; index < scene.lights.length; index++) {
  49222. light = scene.lights[index];
  49223. if (light.getShadowGenerator()) {
  49224. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  49225. }
  49226. }
  49227. // Action Manager
  49228. if (scene.actionManager) {
  49229. serializationObject.actions = scene.actionManager.serialize("scene");
  49230. }
  49231. // Audio
  49232. serializationObject.sounds = [];
  49233. for (index = 0; index < scene.soundTracks.length; index++) {
  49234. var soundtrack = scene.soundTracks[index];
  49235. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  49236. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  49237. }
  49238. }
  49239. return serializationObject;
  49240. };
  49241. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  49242. if (withParents === void 0) { withParents = false; }
  49243. if (withChildren === void 0) { withChildren = false; }
  49244. var serializationObject = {};
  49245. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  49246. if (withParents || withChildren) {
  49247. //deliberate for loop! not for each, appended should be processed as well.
  49248. for (var i = 0; i < toSerialize.length; ++i) {
  49249. if (withChildren) {
  49250. toSerialize[i].getDescendants().forEach(function (node) {
  49251. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  49252. toSerialize.push(node);
  49253. }
  49254. });
  49255. }
  49256. //make sure the array doesn't contain the object already
  49257. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  49258. toSerialize.push(toSerialize[i].parent);
  49259. }
  49260. }
  49261. }
  49262. toSerialize.forEach(function (mesh) {
  49263. finalizeSingleMesh(mesh, serializationObject);
  49264. });
  49265. return serializationObject;
  49266. };
  49267. return SceneSerializer;
  49268. }());
  49269. BABYLON.SceneSerializer = SceneSerializer;
  49270. })(BABYLON || (BABYLON = {}));
  49271. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  49272. // Huge respect for a such great lib.
  49273. // Earcut license:
  49274. // Copyright (c) 2016, Mapbox
  49275. //
  49276. // Permission to use, copy, modify, and/or distribute this software for any purpose
  49277. // with or without fee is hereby granted, provided that the above copyright notice
  49278. // and this permission notice appear in all copies.
  49279. //
  49280. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  49281. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49282. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  49283. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  49284. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  49285. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  49286. // THIS SOFTWARE.
  49287. var Earcut;
  49288. (function (Earcut) {
  49289. /**
  49290. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  49291. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  49292. * @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).
  49293. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  49294. */
  49295. function earcut(data, holeIndices, dim) {
  49296. dim = dim || 2;
  49297. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  49298. if (!outerNode)
  49299. return triangles;
  49300. var minX, minY, maxX, maxY, x, y, size;
  49301. if (hasHoles)
  49302. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  49303. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  49304. if (data.length > 80 * dim) {
  49305. minX = maxX = data[0];
  49306. minY = maxY = data[1];
  49307. for (var i = dim; i < outerLen; i += dim) {
  49308. x = data[i];
  49309. y = data[i + 1];
  49310. if (x < minX)
  49311. minX = x;
  49312. if (y < minY)
  49313. minY = y;
  49314. if (x > maxX)
  49315. maxX = x;
  49316. if (y > maxY)
  49317. maxY = y;
  49318. }
  49319. // minX, minY and size are later used to transform coords into integers for z-order calculation
  49320. size = Math.max(maxX - minX, maxY - minY);
  49321. }
  49322. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  49323. return triangles;
  49324. }
  49325. Earcut.earcut = earcut;
  49326. // create a circular doubly linked list from polygon points in the specified winding order
  49327. function linkedList(data, start, end, dim, clockwise) {
  49328. var i, last;
  49329. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  49330. for (i = start; i < end; i += dim)
  49331. last = insertNode(i, data[i], data[i + 1], last);
  49332. }
  49333. else {
  49334. for (i = end - dim; i >= start; i -= dim)
  49335. last = insertNode(i, data[i], data[i + 1], last);
  49336. }
  49337. if (last && equals(last, last.next)) {
  49338. removeNode(last);
  49339. last = last.next;
  49340. }
  49341. return last;
  49342. }
  49343. // eliminate colinear or duplicate points
  49344. function filterPoints(start, end) {
  49345. if (!start)
  49346. return start;
  49347. if (!end)
  49348. end = start;
  49349. var p = start, again;
  49350. do {
  49351. again = false;
  49352. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  49353. removeNode(p);
  49354. p = end = p.prev;
  49355. if (p === p.next)
  49356. return null;
  49357. again = true;
  49358. }
  49359. else {
  49360. p = p.next;
  49361. }
  49362. } while (again || p !== end);
  49363. return end;
  49364. }
  49365. // main ear slicing loop which triangulates a polygon (given as a linked list)
  49366. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  49367. if (!ear)
  49368. return;
  49369. // interlink polygon nodes in z-order
  49370. if (!pass && size)
  49371. indexCurve(ear, minX, minY, size);
  49372. var stop = ear, prev, next;
  49373. // iterate through ears, slicing them one by one
  49374. while (ear.prev !== ear.next) {
  49375. prev = ear.prev;
  49376. next = ear.next;
  49377. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  49378. // cut off the triangle
  49379. triangles.push(prev.i / dim);
  49380. triangles.push(ear.i / dim);
  49381. triangles.push(next.i / dim);
  49382. removeNode(ear);
  49383. // skipping the next vertice leads to less sliver triangles
  49384. ear = next.next;
  49385. stop = next.next;
  49386. continue;
  49387. }
  49388. ear = next;
  49389. // if we looped through the whole remaining polygon and can't find any more ears
  49390. if (ear === stop) {
  49391. // try filtering points and slicing again
  49392. if (!pass) {
  49393. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  49394. }
  49395. else if (pass === 1) {
  49396. ear = cureLocalIntersections(ear, triangles, dim);
  49397. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  49398. }
  49399. else if (pass === 2) {
  49400. splitEarcut(ear, triangles, dim, minX, minY, size);
  49401. }
  49402. break;
  49403. }
  49404. }
  49405. }
  49406. // check whether a polygon node forms a valid ear with adjacent nodes
  49407. function isEar(ear) {
  49408. var a = ear.prev, b = ear, c = ear.next;
  49409. if (area(a, b, c) >= 0)
  49410. return false; // reflex, can't be an ear
  49411. // now make sure we don't have other points inside the potential ear
  49412. var p = ear.next.next;
  49413. while (p !== ear.prev) {
  49414. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49415. area(p.prev, p, p.next) >= 0)
  49416. return false;
  49417. p = p.next;
  49418. }
  49419. return true;
  49420. }
  49421. function isEarHashed(ear, minX, minY, size) {
  49422. var a = ear.prev, b = ear, c = ear.next;
  49423. if (area(a, b, c) >= 0)
  49424. return false; // reflex, can't be an ear
  49425. // triangle bbox; min & max are calculated like this for speed
  49426. 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);
  49427. // z-order range for the current triangle bbox;
  49428. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  49429. // first look for points inside the triangle in increasing z-order
  49430. var p = ear.nextZ;
  49431. while (p && p.z <= maxZ) {
  49432. if (p !== ear.prev &&
  49433. p !== ear.next &&
  49434. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49435. area(p.prev, p, p.next) >= 0)
  49436. return false;
  49437. p = p.nextZ;
  49438. }
  49439. // then look for points in decreasing z-order
  49440. p = ear.prevZ;
  49441. while (p && p.z >= minZ) {
  49442. if (p !== ear.prev &&
  49443. p !== ear.next &&
  49444. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49445. area(p.prev, p, p.next) >= 0)
  49446. return false;
  49447. p = p.prevZ;
  49448. }
  49449. return true;
  49450. }
  49451. // go through all polygon nodes and cure small local self-intersections
  49452. function cureLocalIntersections(start, triangles, dim) {
  49453. var p = start;
  49454. do {
  49455. var a = p.prev, b = p.next.next;
  49456. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  49457. triangles.push(a.i / dim);
  49458. triangles.push(p.i / dim);
  49459. triangles.push(b.i / dim);
  49460. // remove two nodes involved
  49461. removeNode(p);
  49462. removeNode(p.next);
  49463. p = start = b;
  49464. }
  49465. p = p.next;
  49466. } while (p !== start);
  49467. return p;
  49468. }
  49469. // try splitting polygon into two and triangulate them independently
  49470. function splitEarcut(start, triangles, dim, minX, minY, size) {
  49471. // look for a valid diagonal that divides the polygon into two
  49472. var a = start;
  49473. do {
  49474. var b = a.next.next;
  49475. while (b !== a.prev) {
  49476. if (a.i !== b.i && isValidDiagonal(a, b)) {
  49477. // split the polygon in two by the diagonal
  49478. var c = splitPolygon(a, b);
  49479. // filter colinear points around the cuts
  49480. a = filterPoints(a, a.next);
  49481. c = filterPoints(c, c.next);
  49482. // run earcut on each half
  49483. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  49484. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  49485. return;
  49486. }
  49487. b = b.next;
  49488. }
  49489. a = a.next;
  49490. } while (a !== start);
  49491. }
  49492. // link every hole into the outer loop, producing a single-ring polygon without holes
  49493. function eliminateHoles(data, holeIndices, outerNode, dim) {
  49494. var queue = [], i, len, start, end, list;
  49495. for (i = 0, len = holeIndices.length; i < len; i++) {
  49496. start = holeIndices[i] * dim;
  49497. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49498. list = linkedList(data, start, end, dim, false);
  49499. if (list === list.next)
  49500. list.steiner = true;
  49501. queue.push(getLeftmost(list));
  49502. }
  49503. queue.sort(compareX);
  49504. // process holes from left to right
  49505. for (i = 0; i < queue.length; i++) {
  49506. eliminateHole(queue[i], outerNode);
  49507. outerNode = filterPoints(outerNode, outerNode.next);
  49508. }
  49509. return outerNode;
  49510. }
  49511. function compareX(a, b) {
  49512. return a.x - b.x;
  49513. }
  49514. // find a bridge between vertices that connects hole with an outer ring and and link it
  49515. function eliminateHole(hole, outerNode) {
  49516. outerNode = findHoleBridge(hole, outerNode);
  49517. if (outerNode) {
  49518. var b = splitPolygon(outerNode, hole);
  49519. filterPoints(b, b.next);
  49520. }
  49521. }
  49522. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  49523. function findHoleBridge(hole, outerNode) {
  49524. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  49525. // find a segment intersected by a ray from the hole's leftmost point to the left;
  49526. // segment's endpoint with lesser x will be potential connection point
  49527. do {
  49528. if (hy <= p.y && hy >= p.next.y) {
  49529. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  49530. if (x <= hx && x > qx) {
  49531. qx = x;
  49532. if (x === hx) {
  49533. if (hy === p.y)
  49534. return p;
  49535. if (hy === p.next.y)
  49536. return p.next;
  49537. }
  49538. m = p.x < p.next.x ? p : p.next;
  49539. }
  49540. }
  49541. p = p.next;
  49542. } while (p !== outerNode);
  49543. if (!m)
  49544. return null;
  49545. if (hx === qx)
  49546. return m.prev; // hole touches outer segment; pick lower endpoint
  49547. // look for points inside the triangle of hole point, segment intersection and endpoint;
  49548. // if there are no points found, we have a valid connection;
  49549. // otherwise choose the point of the minimum angle with the ray as connection point
  49550. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  49551. p = m.next;
  49552. while (p !== stop) {
  49553. if (hx >= p.x &&
  49554. p.x >= mx &&
  49555. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  49556. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  49557. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  49558. m = p;
  49559. tanMin = tan;
  49560. }
  49561. }
  49562. p = p.next;
  49563. }
  49564. return m;
  49565. }
  49566. // interlink polygon nodes in z-order
  49567. function indexCurve(start, minX, minY, size) {
  49568. var p = start;
  49569. do {
  49570. if (p.z === null)
  49571. p.z = zOrder(p.x, p.y, minX, minY, size);
  49572. p.prevZ = p.prev;
  49573. p.nextZ = p.next;
  49574. p = p.next;
  49575. } while (p !== start);
  49576. p.prevZ.nextZ = null;
  49577. p.prevZ = null;
  49578. sortLinked(p);
  49579. }
  49580. // Simon Tatham's linked list merge sort algorithm
  49581. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  49582. function sortLinked(list) {
  49583. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  49584. do {
  49585. p = list;
  49586. list = null;
  49587. tail = null;
  49588. numMerges = 0;
  49589. while (p) {
  49590. numMerges++;
  49591. q = p;
  49592. pSize = 0;
  49593. for (i = 0; i < inSize; i++) {
  49594. pSize++;
  49595. q = q.nextZ;
  49596. if (!q)
  49597. break;
  49598. }
  49599. qSize = inSize;
  49600. while (pSize > 0 || (qSize > 0 && q)) {
  49601. if (pSize === 0) {
  49602. e = q;
  49603. q = q.nextZ;
  49604. qSize--;
  49605. }
  49606. else if (qSize === 0 || !q) {
  49607. e = p;
  49608. p = p.nextZ;
  49609. pSize--;
  49610. }
  49611. else if (p.z <= q.z) {
  49612. e = p;
  49613. p = p.nextZ;
  49614. pSize--;
  49615. }
  49616. else {
  49617. e = q;
  49618. q = q.nextZ;
  49619. qSize--;
  49620. }
  49621. if (tail)
  49622. tail.nextZ = e;
  49623. else
  49624. list = e;
  49625. e.prevZ = tail;
  49626. tail = e;
  49627. }
  49628. p = q;
  49629. }
  49630. tail.nextZ = null;
  49631. inSize *= 2;
  49632. } while (numMerges > 1);
  49633. return list;
  49634. }
  49635. // z-order of a point given coords and size of the data bounding box
  49636. function zOrder(x, y, minX, minY, size) {
  49637. // coords are transformed into non-negative 15-bit integer range
  49638. x = 32767 * (x - minX) / size;
  49639. y = 32767 * (y - minY) / size;
  49640. x = (x | (x << 8)) & 0x00FF00FF;
  49641. x = (x | (x << 4)) & 0x0F0F0F0F;
  49642. x = (x | (x << 2)) & 0x33333333;
  49643. x = (x | (x << 1)) & 0x55555555;
  49644. y = (y | (y << 8)) & 0x00FF00FF;
  49645. y = (y | (y << 4)) & 0x0F0F0F0F;
  49646. y = (y | (y << 2)) & 0x33333333;
  49647. y = (y | (y << 1)) & 0x55555555;
  49648. return x | (y << 1);
  49649. }
  49650. // find the leftmost node of a polygon ring
  49651. function getLeftmost(start) {
  49652. var p = start, leftmost = start;
  49653. do {
  49654. if (p.x < leftmost.x)
  49655. leftmost = p;
  49656. p = p.next;
  49657. } while (p !== start);
  49658. return leftmost;
  49659. }
  49660. // check if a point lies within a convex triangle
  49661. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49662. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49663. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49664. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49665. }
  49666. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49667. function isValidDiagonal(a, b) {
  49668. return a.next.i !== b.i &&
  49669. a.prev.i !== b.i &&
  49670. !intersectsPolygon(a, b) &&
  49671. locallyInside(a, b) &&
  49672. locallyInside(b, a) &&
  49673. middleInside(a, b);
  49674. }
  49675. // signed area of a triangle
  49676. function area(p, q, r) {
  49677. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49678. }
  49679. // check if two points are equal
  49680. function equals(p1, p2) {
  49681. return p1.x === p2.x && p1.y === p2.y;
  49682. }
  49683. // check if two segments intersect
  49684. function intersects(p1, q1, p2, q2) {
  49685. if ((equals(p1, q1) && equals(p2, q2)) ||
  49686. (equals(p1, q2) && equals(p2, q1)))
  49687. return true;
  49688. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49689. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49690. }
  49691. // check if a polygon diagonal intersects any polygon segments
  49692. function intersectsPolygon(a, b) {
  49693. var p = a;
  49694. do {
  49695. if (p.i !== a.i &&
  49696. p.next.i !== a.i &&
  49697. p.i !== b.i &&
  49698. p.next.i !== b.i &&
  49699. intersects(p, p.next, a, b))
  49700. return true;
  49701. p = p.next;
  49702. } while (p !== a);
  49703. return false;
  49704. }
  49705. // check if a polygon diagonal is locally inside the polygon
  49706. function locallyInside(a, b) {
  49707. return area(a.prev, a, a.next) < 0
  49708. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49709. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49710. }
  49711. // check if the middle point of a polygon diagonal is inside the polygon
  49712. function middleInside(a, b) {
  49713. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49714. do {
  49715. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49716. inside = !inside;
  49717. p = p.next;
  49718. } while (p !== a);
  49719. return inside;
  49720. }
  49721. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49722. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49723. function splitPolygon(a, b) {
  49724. 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;
  49725. a.next = b;
  49726. b.prev = a;
  49727. a2.next = an;
  49728. an.prev = a2;
  49729. b2.next = a2;
  49730. a2.prev = b2;
  49731. bp.next = b2;
  49732. b2.prev = bp;
  49733. return b2;
  49734. }
  49735. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49736. function insertNode(i, x, y, last) {
  49737. var p = new Node(i, x, y);
  49738. if (!last) {
  49739. p.prev = p;
  49740. p.next = p;
  49741. }
  49742. else {
  49743. p.next = last.next;
  49744. p.prev = last;
  49745. last.next.prev = p;
  49746. last.next = p;
  49747. }
  49748. return p;
  49749. }
  49750. function removeNode(p) {
  49751. p.next.prev = p.prev;
  49752. p.prev.next = p.next;
  49753. if (p.prevZ)
  49754. p.prevZ.nextZ = p.nextZ;
  49755. if (p.nextZ)
  49756. p.nextZ.prevZ = p.prevZ;
  49757. }
  49758. function Node(i, x, y) {
  49759. // vertice index in coordinates array
  49760. this.i = i;
  49761. // vertex coordinates
  49762. this.x = x;
  49763. this.y = y;
  49764. // previous and next vertice nodes in a polygon ring
  49765. this.prev = null;
  49766. this.next = null;
  49767. // z-order curve value
  49768. this.z = null;
  49769. // previous and next nodes in z-order
  49770. this.prevZ = null;
  49771. this.nextZ = null;
  49772. // indicates whether this is a steiner point
  49773. this.steiner = false;
  49774. }
  49775. /**
  49776. * return a percentage difference between the polygon area and its triangulation area;
  49777. * used to verify correctness of triangulation
  49778. */
  49779. function deviation(data, holeIndices, dim, triangles) {
  49780. var hasHoles = holeIndices && holeIndices.length;
  49781. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49782. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49783. if (hasHoles) {
  49784. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49785. var start = holeIndices[i] * dim;
  49786. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49787. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49788. }
  49789. }
  49790. var trianglesArea = 0;
  49791. for (i = 0; i < triangles.length; i += 3) {
  49792. var a = triangles[i] * dim;
  49793. var b = triangles[i + 1] * dim;
  49794. var c = triangles[i + 2] * dim;
  49795. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49796. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49797. }
  49798. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49799. }
  49800. Earcut.deviation = deviation;
  49801. ;
  49802. function signedArea(data, start, end, dim) {
  49803. var sum = 0;
  49804. for (var i = start, j = end - dim; i < end; i += dim) {
  49805. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49806. j = i;
  49807. }
  49808. return sum;
  49809. }
  49810. /**
  49811. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49812. */
  49813. function flatten(data) {
  49814. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49815. for (var i = 0; i < data.length; i++) {
  49816. for (var j = 0; j < data[i].length; j++) {
  49817. for (var d = 0; d < dim; d++)
  49818. result.vertices.push(data[i][j][d]);
  49819. }
  49820. if (i > 0) {
  49821. holeIndex += data[i - 1].length;
  49822. result.holes.push(holeIndex);
  49823. }
  49824. }
  49825. return result;
  49826. }
  49827. Earcut.flatten = flatten;
  49828. ;
  49829. })(Earcut || (Earcut = {}));
  49830. var BABYLON;
  49831. (function (BABYLON) {
  49832. // Unique ID when we import meshes from Babylon to CSG
  49833. var currentCSGMeshId = 0;
  49834. // # class Vertex
  49835. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49836. // one to provide additional features like texture coordinates and vertex
  49837. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49838. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49839. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49840. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49841. // is not used anywhere else.
  49842. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49843. var Vertex = (function () {
  49844. function Vertex(pos, normal, uv) {
  49845. this.pos = pos;
  49846. this.normal = normal;
  49847. this.uv = uv;
  49848. }
  49849. Vertex.prototype.clone = function () {
  49850. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49851. };
  49852. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49853. // orientation of a polygon is flipped.
  49854. Vertex.prototype.flip = function () {
  49855. this.normal = this.normal.scale(-1);
  49856. };
  49857. // Create a new vertex between this vertex and `other` by linearly
  49858. // interpolating all properties using a parameter of `t`. Subclasses should
  49859. // override this to interpolate additional properties.
  49860. Vertex.prototype.interpolate = function (other, t) {
  49861. 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));
  49862. };
  49863. return Vertex;
  49864. }());
  49865. // # class Plane
  49866. // Represents a plane in 3D space.
  49867. var Plane = (function () {
  49868. function Plane(normal, w) {
  49869. this.normal = normal;
  49870. this.w = w;
  49871. }
  49872. Plane.FromPoints = function (a, b, c) {
  49873. var v0 = c.subtract(a);
  49874. var v1 = b.subtract(a);
  49875. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  49876. return null;
  49877. }
  49878. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  49879. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  49880. };
  49881. Plane.prototype.clone = function () {
  49882. return new Plane(this.normal.clone(), this.w);
  49883. };
  49884. Plane.prototype.flip = function () {
  49885. this.normal.scaleInPlace(-1);
  49886. this.w = -this.w;
  49887. };
  49888. // Split `polygon` by this plane if needed, then put the polygon or polygon
  49889. // fragments in the appropriate lists. Coplanar polygons go into either
  49890. // `coplanarFront` or `coplanarBack` depending on their orientation with
  49891. // respect to this plane. Polygons in front or in back of this plane go into
  49892. // either `front` or `back`.
  49893. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  49894. var COPLANAR = 0;
  49895. var FRONT = 1;
  49896. var BACK = 2;
  49897. var SPANNING = 3;
  49898. // Classify each point as well as the entire polygon into one of the above
  49899. // four classes.
  49900. var polygonType = 0;
  49901. var types = [];
  49902. var i;
  49903. var t;
  49904. for (i = 0; i < polygon.vertices.length; i++) {
  49905. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  49906. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  49907. polygonType |= type;
  49908. types.push(type);
  49909. }
  49910. // Put the polygon in the correct list, splitting it when necessary.
  49911. switch (polygonType) {
  49912. case COPLANAR:
  49913. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  49914. break;
  49915. case FRONT:
  49916. front.push(polygon);
  49917. break;
  49918. case BACK:
  49919. back.push(polygon);
  49920. break;
  49921. case SPANNING:
  49922. var f = [], b = [];
  49923. for (i = 0; i < polygon.vertices.length; i++) {
  49924. var j = (i + 1) % polygon.vertices.length;
  49925. var ti = types[i], tj = types[j];
  49926. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49927. if (ti !== BACK)
  49928. f.push(vi);
  49929. if (ti !== FRONT)
  49930. b.push(ti !== BACK ? vi.clone() : vi);
  49931. if ((ti | tj) === SPANNING) {
  49932. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49933. var v = vi.interpolate(vj, t);
  49934. f.push(v);
  49935. b.push(v.clone());
  49936. }
  49937. }
  49938. var poly;
  49939. if (f.length >= 3) {
  49940. poly = new Polygon(f, polygon.shared);
  49941. if (poly.plane)
  49942. front.push(poly);
  49943. }
  49944. if (b.length >= 3) {
  49945. poly = new Polygon(b, polygon.shared);
  49946. if (poly.plane)
  49947. back.push(poly);
  49948. }
  49949. break;
  49950. }
  49951. };
  49952. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49953. // point is on the plane.
  49954. Plane.EPSILON = 1e-5;
  49955. return Plane;
  49956. }());
  49957. // # class Polygon
  49958. // Represents a convex polygon. The vertices used to initialize a polygon must
  49959. // be coplanar and form a convex loop.
  49960. //
  49961. // Each convex polygon has a `shared` property, which is shared between all
  49962. // polygons that are clones of each other or were split from the same polygon.
  49963. // This can be used to define per-polygon properties (such as surface color).
  49964. var Polygon = (function () {
  49965. function Polygon(vertices, shared) {
  49966. this.vertices = vertices;
  49967. this.shared = shared;
  49968. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49969. }
  49970. Polygon.prototype.clone = function () {
  49971. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49972. return new Polygon(vertices, this.shared);
  49973. };
  49974. Polygon.prototype.flip = function () {
  49975. this.vertices.reverse().map(function (v) { v.flip(); });
  49976. this.plane.flip();
  49977. };
  49978. return Polygon;
  49979. }());
  49980. // # class Node
  49981. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  49982. // by picking a polygon to split along. That polygon (and all other coplanar
  49983. // polygons) are added directly to that node and the other polygons are added to
  49984. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  49985. // no distinction between internal and leaf nodes.
  49986. var Node = (function () {
  49987. function Node(polygons) {
  49988. this.plane = null;
  49989. this.front = null;
  49990. this.back = null;
  49991. this.polygons = [];
  49992. if (polygons) {
  49993. this.build(polygons);
  49994. }
  49995. }
  49996. Node.prototype.clone = function () {
  49997. var node = new Node();
  49998. node.plane = this.plane && this.plane.clone();
  49999. node.front = this.front && this.front.clone();
  50000. node.back = this.back && this.back.clone();
  50001. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  50002. return node;
  50003. };
  50004. // Convert solid space to empty space and empty space to solid space.
  50005. Node.prototype.invert = function () {
  50006. for (var i = 0; i < this.polygons.length; i++) {
  50007. this.polygons[i].flip();
  50008. }
  50009. if (this.plane) {
  50010. this.plane.flip();
  50011. }
  50012. if (this.front) {
  50013. this.front.invert();
  50014. }
  50015. if (this.back) {
  50016. this.back.invert();
  50017. }
  50018. var temp = this.front;
  50019. this.front = this.back;
  50020. this.back = temp;
  50021. };
  50022. // Recursively remove all polygons in `polygons` that are inside this BSP
  50023. // tree.
  50024. Node.prototype.clipPolygons = function (polygons) {
  50025. if (!this.plane)
  50026. return polygons.slice();
  50027. var front = [], back = [];
  50028. for (var i = 0; i < polygons.length; i++) {
  50029. this.plane.splitPolygon(polygons[i], front, back, front, back);
  50030. }
  50031. if (this.front) {
  50032. front = this.front.clipPolygons(front);
  50033. }
  50034. if (this.back) {
  50035. back = this.back.clipPolygons(back);
  50036. }
  50037. else {
  50038. back = [];
  50039. }
  50040. return front.concat(back);
  50041. };
  50042. // Remove all polygons in this BSP tree that are inside the other BSP tree
  50043. // `bsp`.
  50044. Node.prototype.clipTo = function (bsp) {
  50045. this.polygons = bsp.clipPolygons(this.polygons);
  50046. if (this.front)
  50047. this.front.clipTo(bsp);
  50048. if (this.back)
  50049. this.back.clipTo(bsp);
  50050. };
  50051. // Return a list of all polygons in this BSP tree.
  50052. Node.prototype.allPolygons = function () {
  50053. var polygons = this.polygons.slice();
  50054. if (this.front)
  50055. polygons = polygons.concat(this.front.allPolygons());
  50056. if (this.back)
  50057. polygons = polygons.concat(this.back.allPolygons());
  50058. return polygons;
  50059. };
  50060. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  50061. // new polygons are filtered down to the bottom of the tree and become new
  50062. // nodes there. Each set of polygons is partitioned using the first polygon
  50063. // (no heuristic is used to pick a good split).
  50064. Node.prototype.build = function (polygons) {
  50065. if (!polygons.length)
  50066. return;
  50067. if (!this.plane)
  50068. this.plane = polygons[0].plane.clone();
  50069. var front = [], back = [];
  50070. for (var i = 0; i < polygons.length; i++) {
  50071. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  50072. }
  50073. if (front.length) {
  50074. if (!this.front)
  50075. this.front = new Node();
  50076. this.front.build(front);
  50077. }
  50078. if (back.length) {
  50079. if (!this.back)
  50080. this.back = new Node();
  50081. this.back.build(back);
  50082. }
  50083. };
  50084. return Node;
  50085. }());
  50086. var CSG = (function () {
  50087. function CSG() {
  50088. this.polygons = new Array();
  50089. }
  50090. // Convert BABYLON.Mesh to BABYLON.CSG
  50091. CSG.FromMesh = function (mesh) {
  50092. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  50093. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  50094. if (mesh instanceof BABYLON.Mesh) {
  50095. mesh.computeWorldMatrix(true);
  50096. matrix = mesh.getWorldMatrix();
  50097. meshPosition = mesh.position.clone();
  50098. meshRotation = mesh.rotation.clone();
  50099. if (mesh.rotationQuaternion) {
  50100. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  50101. }
  50102. meshScaling = mesh.scaling.clone();
  50103. }
  50104. else {
  50105. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  50106. }
  50107. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50108. var subMeshes = mesh.subMeshes;
  50109. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  50110. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  50111. vertices = [];
  50112. for (var j = 0; j < 3; j++) {
  50113. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  50114. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  50115. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  50116. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  50117. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  50118. vertex = new Vertex(position, normal, uv);
  50119. vertices.push(vertex);
  50120. }
  50121. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  50122. // To handle the case of degenerated triangle
  50123. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  50124. if (polygon.plane)
  50125. polygons.push(polygon);
  50126. }
  50127. }
  50128. var csg = CSG.FromPolygons(polygons);
  50129. csg.matrix = matrix;
  50130. csg.position = meshPosition;
  50131. csg.rotation = meshRotation;
  50132. csg.scaling = meshScaling;
  50133. csg.rotationQuaternion = meshRotationQuaternion;
  50134. currentCSGMeshId++;
  50135. return csg;
  50136. };
  50137. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  50138. CSG.FromPolygons = function (polygons) {
  50139. var csg = new CSG();
  50140. csg.polygons = polygons;
  50141. return csg;
  50142. };
  50143. CSG.prototype.clone = function () {
  50144. var csg = new CSG();
  50145. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  50146. csg.copyTransformAttributes(this);
  50147. return csg;
  50148. };
  50149. CSG.prototype.toPolygons = function () {
  50150. return this.polygons;
  50151. };
  50152. CSG.prototype.union = function (csg) {
  50153. var a = new Node(this.clone().polygons);
  50154. var b = new Node(csg.clone().polygons);
  50155. a.clipTo(b);
  50156. b.clipTo(a);
  50157. b.invert();
  50158. b.clipTo(a);
  50159. b.invert();
  50160. a.build(b.allPolygons());
  50161. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50162. };
  50163. CSG.prototype.unionInPlace = function (csg) {
  50164. var a = new Node(this.polygons);
  50165. var b = new Node(csg.polygons);
  50166. a.clipTo(b);
  50167. b.clipTo(a);
  50168. b.invert();
  50169. b.clipTo(a);
  50170. b.invert();
  50171. a.build(b.allPolygons());
  50172. this.polygons = a.allPolygons();
  50173. };
  50174. CSG.prototype.subtract = function (csg) {
  50175. var a = new Node(this.clone().polygons);
  50176. var b = new Node(csg.clone().polygons);
  50177. a.invert();
  50178. a.clipTo(b);
  50179. b.clipTo(a);
  50180. b.invert();
  50181. b.clipTo(a);
  50182. b.invert();
  50183. a.build(b.allPolygons());
  50184. a.invert();
  50185. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50186. };
  50187. CSG.prototype.subtractInPlace = function (csg) {
  50188. var a = new Node(this.polygons);
  50189. var b = new Node(csg.polygons);
  50190. a.invert();
  50191. a.clipTo(b);
  50192. b.clipTo(a);
  50193. b.invert();
  50194. b.clipTo(a);
  50195. b.invert();
  50196. a.build(b.allPolygons());
  50197. a.invert();
  50198. this.polygons = a.allPolygons();
  50199. };
  50200. CSG.prototype.intersect = function (csg) {
  50201. var a = new Node(this.clone().polygons);
  50202. var b = new Node(csg.clone().polygons);
  50203. a.invert();
  50204. b.clipTo(a);
  50205. b.invert();
  50206. a.clipTo(b);
  50207. b.clipTo(a);
  50208. a.build(b.allPolygons());
  50209. a.invert();
  50210. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50211. };
  50212. CSG.prototype.intersectInPlace = function (csg) {
  50213. var a = new Node(this.polygons);
  50214. var b = new Node(csg.polygons);
  50215. a.invert();
  50216. b.clipTo(a);
  50217. b.invert();
  50218. a.clipTo(b);
  50219. b.clipTo(a);
  50220. a.build(b.allPolygons());
  50221. a.invert();
  50222. this.polygons = a.allPolygons();
  50223. };
  50224. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  50225. // not modified.
  50226. CSG.prototype.inverse = function () {
  50227. var csg = this.clone();
  50228. csg.inverseInPlace();
  50229. return csg;
  50230. };
  50231. CSG.prototype.inverseInPlace = function () {
  50232. this.polygons.map(function (p) { p.flip(); });
  50233. };
  50234. // This is used to keep meshes transformations so they can be restored
  50235. // when we build back a Babylon Mesh
  50236. // NB : All CSG operations are performed in world coordinates
  50237. CSG.prototype.copyTransformAttributes = function (csg) {
  50238. this.matrix = csg.matrix;
  50239. this.position = csg.position;
  50240. this.rotation = csg.rotation;
  50241. this.scaling = csg.scaling;
  50242. this.rotationQuaternion = csg.rotationQuaternion;
  50243. return this;
  50244. };
  50245. // Build Raw mesh from CSG
  50246. // Coordinates here are in world space
  50247. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  50248. var matrix = this.matrix.clone();
  50249. matrix.invert();
  50250. 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;
  50251. if (keepSubMeshes) {
  50252. // Sort Polygons, since subMeshes are indices range
  50253. polygons.sort(function (a, b) {
  50254. if (a.shared.meshId === b.shared.meshId) {
  50255. return a.shared.subMeshId - b.shared.subMeshId;
  50256. }
  50257. else {
  50258. return a.shared.meshId - b.shared.meshId;
  50259. }
  50260. });
  50261. }
  50262. for (var i = 0, il = polygons.length; i < il; i++) {
  50263. polygon = polygons[i];
  50264. // Building SubMeshes
  50265. if (!subMesh_dict[polygon.shared.meshId]) {
  50266. subMesh_dict[polygon.shared.meshId] = {};
  50267. }
  50268. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  50269. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  50270. indexStart: +Infinity,
  50271. indexEnd: -Infinity,
  50272. materialIndex: polygon.shared.materialIndex
  50273. };
  50274. }
  50275. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  50276. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  50277. polygonIndices[0] = 0;
  50278. polygonIndices[1] = j - 1;
  50279. polygonIndices[2] = j;
  50280. for (var k = 0; k < 3; k++) {
  50281. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  50282. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  50283. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  50284. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  50285. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  50286. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  50287. // Check if 2 points can be merged
  50288. if (!(typeof vertex_idx !== 'undefined' &&
  50289. normals[vertex_idx * 3] === localNormal.x &&
  50290. normals[vertex_idx * 3 + 1] === localNormal.y &&
  50291. normals[vertex_idx * 3 + 2] === localNormal.z &&
  50292. uvs[vertex_idx * 2] === uv.x &&
  50293. uvs[vertex_idx * 2 + 1] === uv.y)) {
  50294. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  50295. uvs.push(uv.x, uv.y);
  50296. normals.push(normal.x, normal.y, normal.z);
  50297. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  50298. }
  50299. indices.push(vertex_idx);
  50300. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  50301. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  50302. currentIndex++;
  50303. }
  50304. }
  50305. }
  50306. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  50307. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  50308. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  50309. mesh.setIndices(indices);
  50310. if (keepSubMeshes) {
  50311. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  50312. var materialIndexOffset = 0, materialMaxIndex;
  50313. mesh.subMeshes = new Array();
  50314. for (var m in subMesh_dict) {
  50315. materialMaxIndex = -1;
  50316. for (var sm in subMesh_dict[m]) {
  50317. subMesh_obj = subMesh_dict[m][sm];
  50318. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  50319. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  50320. }
  50321. materialIndexOffset += ++materialMaxIndex;
  50322. }
  50323. }
  50324. return mesh;
  50325. };
  50326. // Build Mesh from CSG taking material and transforms into account
  50327. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  50328. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  50329. mesh.material = material;
  50330. mesh.position.copyFrom(this.position);
  50331. mesh.rotation.copyFrom(this.rotation);
  50332. if (this.rotationQuaternion) {
  50333. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  50334. }
  50335. mesh.scaling.copyFrom(this.scaling);
  50336. mesh.computeWorldMatrix(true);
  50337. return mesh;
  50338. };
  50339. return CSG;
  50340. }());
  50341. BABYLON.CSG = CSG;
  50342. })(BABYLON || (BABYLON = {}));
  50343. var BABYLON;
  50344. (function (BABYLON) {
  50345. var VRDistortionCorrectionPostProcess = (function (_super) {
  50346. __extends(VRDistortionCorrectionPostProcess, _super);
  50347. //ANY
  50348. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  50349. var _this = this;
  50350. _super.call(this, name, "vrDistortionCorrection", [
  50351. 'LensCenter',
  50352. 'Scale',
  50353. 'ScaleIn',
  50354. 'HmdWarpParam'
  50355. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  50356. this._isRightEye = isRightEye;
  50357. this._distortionFactors = vrMetrics.distortionK;
  50358. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  50359. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  50360. this.onSizeChangedObservable.add(function () {
  50361. _this.aspectRatio = _this.width * .5 / _this.height;
  50362. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  50363. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  50364. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  50365. });
  50366. this.onApplyObservable.add(function (effect) {
  50367. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  50368. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  50369. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  50370. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  50371. });
  50372. }
  50373. return VRDistortionCorrectionPostProcess;
  50374. }(BABYLON.PostProcess));
  50375. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  50376. })(BABYLON || (BABYLON = {}));
  50377. // Mainly based on these 2 articles :
  50378. // 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
  50379. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  50380. var BABYLON;
  50381. (function (BABYLON) {
  50382. (function (JoystickAxis) {
  50383. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  50384. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  50385. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  50386. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  50387. var JoystickAxis = BABYLON.JoystickAxis;
  50388. var VirtualJoystick = (function () {
  50389. function VirtualJoystick(leftJoystick) {
  50390. var _this = this;
  50391. if (leftJoystick) {
  50392. this._leftJoystick = true;
  50393. }
  50394. else {
  50395. this._leftJoystick = false;
  50396. }
  50397. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  50398. VirtualJoystick._globalJoystickIndex++;
  50399. // By default left & right arrow keys are moving the X
  50400. // and up & down keys are moving the Y
  50401. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50402. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50403. this.reverseLeftRight = false;
  50404. this.reverseUpDown = false;
  50405. // collections of pointers
  50406. this._touches = new BABYLON.StringDictionary();
  50407. this.deltaPosition = BABYLON.Vector3.Zero();
  50408. this._joystickSensibility = 25;
  50409. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50410. this._rotationSpeed = 25;
  50411. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  50412. this._rotateOnAxisRelativeToMesh = false;
  50413. this._onResize = function (evt) {
  50414. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50415. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50416. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  50417. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  50418. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  50419. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  50420. };
  50421. // injecting a canvas element on top of the canvas 3D game
  50422. if (!VirtualJoystick.vjCanvas) {
  50423. window.addEventListener("resize", this._onResize, false);
  50424. VirtualJoystick.vjCanvas = document.createElement("canvas");
  50425. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50426. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50427. VirtualJoystick.vjCanvas.width = window.innerWidth;
  50428. VirtualJoystick.vjCanvas.height = window.innerHeight;
  50429. VirtualJoystick.vjCanvas.style.width = "100%";
  50430. VirtualJoystick.vjCanvas.style.height = "100%";
  50431. VirtualJoystick.vjCanvas.style.position = "absolute";
  50432. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  50433. VirtualJoystick.vjCanvas.style.top = "0px";
  50434. VirtualJoystick.vjCanvas.style.left = "0px";
  50435. VirtualJoystick.vjCanvas.style.zIndex = "5";
  50436. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  50437. // Support for jQuery PEP polyfill
  50438. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  50439. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  50440. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  50441. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50442. document.body.appendChild(VirtualJoystick.vjCanvas);
  50443. }
  50444. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  50445. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  50446. this.pressed = false;
  50447. // default joystick color
  50448. this._joystickColor = "cyan";
  50449. this._joystickPointerID = -1;
  50450. // current joystick position
  50451. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  50452. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  50453. // origin joystick position
  50454. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  50455. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  50456. this._onPointerDownHandlerRef = function (evt) {
  50457. _this._onPointerDown(evt);
  50458. };
  50459. this._onPointerMoveHandlerRef = function (evt) {
  50460. _this._onPointerMove(evt);
  50461. };
  50462. this._onPointerOutHandlerRef = function (evt) {
  50463. _this._onPointerUp(evt);
  50464. };
  50465. this._onPointerUpHandlerRef = function (evt) {
  50466. _this._onPointerUp(evt);
  50467. };
  50468. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  50469. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  50470. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  50471. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  50472. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  50473. evt.preventDefault(); // Disables system menu
  50474. }, false);
  50475. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50476. }
  50477. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  50478. this._joystickSensibility = newJoystickSensibility;
  50479. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50480. };
  50481. VirtualJoystick.prototype._onPointerDown = function (e) {
  50482. var positionOnScreenCondition;
  50483. e.preventDefault();
  50484. if (this._leftJoystick === true) {
  50485. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  50486. }
  50487. else {
  50488. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  50489. }
  50490. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  50491. // First contact will be dedicated to the virtual joystick
  50492. this._joystickPointerID = e.pointerId;
  50493. this._joystickPointerStartPos.x = e.clientX;
  50494. this._joystickPointerStartPos.y = e.clientY;
  50495. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  50496. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  50497. this._deltaJoystickVector.x = 0;
  50498. this._deltaJoystickVector.y = 0;
  50499. this.pressed = true;
  50500. this._touches.add(e.pointerId.toString(), e);
  50501. }
  50502. else {
  50503. // You can only trigger the action buttons with a joystick declared
  50504. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  50505. this._action();
  50506. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  50507. }
  50508. }
  50509. };
  50510. VirtualJoystick.prototype._onPointerMove = function (e) {
  50511. // If the current pointer is the one associated to the joystick (first touch contact)
  50512. if (this._joystickPointerID == e.pointerId) {
  50513. this._joystickPointerPos.x = e.clientX;
  50514. this._joystickPointerPos.y = e.clientY;
  50515. this._deltaJoystickVector = this._joystickPointerPos.clone();
  50516. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  50517. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  50518. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  50519. switch (this._axisTargetedByLeftAndRight) {
  50520. case JoystickAxis.X:
  50521. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  50522. break;
  50523. case JoystickAxis.Y:
  50524. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  50525. break;
  50526. case JoystickAxis.Z:
  50527. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  50528. break;
  50529. }
  50530. var directionUpDown = this.reverseUpDown ? 1 : -1;
  50531. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  50532. switch (this._axisTargetedByUpAndDown) {
  50533. case JoystickAxis.X:
  50534. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  50535. break;
  50536. case JoystickAxis.Y:
  50537. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  50538. break;
  50539. case JoystickAxis.Z:
  50540. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  50541. break;
  50542. }
  50543. }
  50544. else {
  50545. var data = this._touches.get(e.pointerId.toString());
  50546. if (data) {
  50547. data.x = e.clientX;
  50548. data.y = e.clientY;
  50549. }
  50550. }
  50551. };
  50552. VirtualJoystick.prototype._onPointerUp = function (e) {
  50553. if (this._joystickPointerID == e.pointerId) {
  50554. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  50555. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  50556. this._joystickPointerID = -1;
  50557. this.pressed = false;
  50558. }
  50559. else {
  50560. var touch = this._touches.get(e.pointerId.toString());
  50561. if (touch) {
  50562. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50563. }
  50564. }
  50565. this._deltaJoystickVector.x = 0;
  50566. this._deltaJoystickVector.y = 0;
  50567. this._touches.remove(e.pointerId.toString());
  50568. };
  50569. /**
  50570. * Change the color of the virtual joystick
  50571. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  50572. */
  50573. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  50574. this._joystickColor = newColor;
  50575. };
  50576. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  50577. this._action = action;
  50578. };
  50579. // Define which axis you'd like to control for left & right
  50580. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  50581. switch (axis) {
  50582. case JoystickAxis.X:
  50583. case JoystickAxis.Y:
  50584. case JoystickAxis.Z:
  50585. this._axisTargetedByLeftAndRight = axis;
  50586. break;
  50587. default:
  50588. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50589. break;
  50590. }
  50591. };
  50592. // Define which axis you'd like to control for up & down
  50593. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  50594. switch (axis) {
  50595. case JoystickAxis.X:
  50596. case JoystickAxis.Y:
  50597. case JoystickAxis.Z:
  50598. this._axisTargetedByUpAndDown = axis;
  50599. break;
  50600. default:
  50601. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50602. break;
  50603. }
  50604. };
  50605. VirtualJoystick.prototype._clearCanvas = function () {
  50606. if (this._leftJoystick) {
  50607. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  50608. }
  50609. else {
  50610. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  50611. }
  50612. };
  50613. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  50614. var _this = this;
  50615. if (this.pressed) {
  50616. this._touches.forEach(function (touch) {
  50617. if (touch.pointerId === _this._joystickPointerID) {
  50618. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  50619. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  50620. VirtualJoystick.vjCanvasContext.beginPath();
  50621. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50622. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50623. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  50624. VirtualJoystick.vjCanvasContext.stroke();
  50625. VirtualJoystick.vjCanvasContext.closePath();
  50626. VirtualJoystick.vjCanvasContext.beginPath();
  50627. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50628. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50629. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  50630. VirtualJoystick.vjCanvasContext.stroke();
  50631. VirtualJoystick.vjCanvasContext.closePath();
  50632. VirtualJoystick.vjCanvasContext.beginPath();
  50633. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50634. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  50635. VirtualJoystick.vjCanvasContext.stroke();
  50636. VirtualJoystick.vjCanvasContext.closePath();
  50637. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  50638. }
  50639. else {
  50640. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50641. VirtualJoystick.vjCanvasContext.beginPath();
  50642. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  50643. VirtualJoystick.vjCanvasContext.beginPath();
  50644. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  50645. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50646. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  50647. VirtualJoystick.vjCanvasContext.stroke();
  50648. VirtualJoystick.vjCanvasContext.closePath();
  50649. touch.prevX = touch.x;
  50650. touch.prevY = touch.y;
  50651. }
  50652. ;
  50653. });
  50654. }
  50655. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50656. };
  50657. VirtualJoystick.prototype.releaseCanvas = function () {
  50658. if (VirtualJoystick.vjCanvas) {
  50659. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50660. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50661. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50662. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50663. window.removeEventListener("resize", this._onResize);
  50664. document.body.removeChild(VirtualJoystick.vjCanvas);
  50665. VirtualJoystick.vjCanvas = null;
  50666. }
  50667. };
  50668. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50669. VirtualJoystick._globalJoystickIndex = 0;
  50670. return VirtualJoystick;
  50671. }());
  50672. BABYLON.VirtualJoystick = VirtualJoystick;
  50673. })(BABYLON || (BABYLON = {}));
  50674. var BABYLON;
  50675. (function (BABYLON) {
  50676. // We're mainly based on the logic defined into the FreeCamera code
  50677. var VirtualJoysticksCamera = (function (_super) {
  50678. __extends(VirtualJoysticksCamera, _super);
  50679. function VirtualJoysticksCamera(name, position, scene) {
  50680. _super.call(this, name, position, scene);
  50681. this.inputs.addVirtualJoystick();
  50682. }
  50683. return VirtualJoysticksCamera;
  50684. }(BABYLON.FreeCamera));
  50685. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50686. })(BABYLON || (BABYLON = {}));
  50687. var BABYLON;
  50688. (function (BABYLON) {
  50689. var FreeCameraVirtualJoystickInput = (function () {
  50690. function FreeCameraVirtualJoystickInput() {
  50691. }
  50692. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50693. return this._leftjoystick;
  50694. };
  50695. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50696. return this._rightjoystick;
  50697. };
  50698. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50699. if (this._leftjoystick) {
  50700. var camera = this.camera;
  50701. var speed = camera._computeLocalCameraSpeed() * 50;
  50702. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50703. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50704. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50705. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50706. if (!this._leftjoystick.pressed) {
  50707. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50708. }
  50709. if (!this._rightjoystick.pressed) {
  50710. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50711. }
  50712. }
  50713. };
  50714. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50715. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50716. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50717. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50718. this._leftjoystick.setJoystickSensibility(0.15);
  50719. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50720. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50721. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50722. this._rightjoystick.reverseUpDown = true;
  50723. this._rightjoystick.setJoystickSensibility(0.05);
  50724. this._rightjoystick.setJoystickColor("yellow");
  50725. };
  50726. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50727. this._leftjoystick.releaseCanvas();
  50728. this._rightjoystick.releaseCanvas();
  50729. };
  50730. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50731. return "FreeCameraVirtualJoystickInput";
  50732. };
  50733. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50734. return "virtualJoystick";
  50735. };
  50736. return FreeCameraVirtualJoystickInput;
  50737. }());
  50738. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50739. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50740. })(BABYLON || (BABYLON = {}));
  50741. var BABYLON;
  50742. (function (BABYLON) {
  50743. var AnaglyphPostProcess = (function (_super) {
  50744. __extends(AnaglyphPostProcess, _super);
  50745. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50746. var _this = this;
  50747. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  50748. this._passedProcess = rigCameras[0]._rigPostProcess;
  50749. this.onApplyObservable.add(function (effect) {
  50750. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50751. });
  50752. }
  50753. return AnaglyphPostProcess;
  50754. }(BABYLON.PostProcess));
  50755. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50756. })(BABYLON || (BABYLON = {}));
  50757. var BABYLON;
  50758. (function (BABYLON) {
  50759. var OutlineRenderer = (function () {
  50760. function OutlineRenderer(scene) {
  50761. this._scene = scene;
  50762. }
  50763. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50764. var _this = this;
  50765. if (useOverlay === void 0) { useOverlay = false; }
  50766. var scene = this._scene;
  50767. var engine = this._scene.getEngine();
  50768. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50769. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50770. return;
  50771. }
  50772. var mesh = subMesh.getRenderingMesh();
  50773. var material = subMesh.getMaterial();
  50774. engine.enableEffect(this._effect);
  50775. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50776. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50777. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50778. // Bones
  50779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50780. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50781. }
  50782. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50783. // Alpha test
  50784. if (material && material.needAlphaTesting()) {
  50785. var alphaTexture = material.getAlphaTestTexture();
  50786. this._effect.setTexture("diffuseSampler", alphaTexture);
  50787. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50788. }
  50789. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50790. };
  50791. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50792. var defines = [];
  50793. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50794. var mesh = subMesh.getMesh();
  50795. var material = subMesh.getMaterial();
  50796. // Alpha test
  50797. if (material && material.needAlphaTesting()) {
  50798. defines.push("#define ALPHATEST");
  50799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50800. attribs.push(BABYLON.VertexBuffer.UVKind);
  50801. defines.push("#define UV1");
  50802. }
  50803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50805. defines.push("#define UV2");
  50806. }
  50807. }
  50808. // Bones
  50809. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50812. if (mesh.numBoneInfluencers > 4) {
  50813. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50814. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50815. }
  50816. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50817. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50818. }
  50819. else {
  50820. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50821. }
  50822. // Instances
  50823. if (useInstances) {
  50824. defines.push("#define INSTANCES");
  50825. attribs.push("world0");
  50826. attribs.push("world1");
  50827. attribs.push("world2");
  50828. attribs.push("world3");
  50829. }
  50830. // Get correct effect
  50831. var join = defines.join("\n");
  50832. if (this._cachedDefines !== join) {
  50833. this._cachedDefines = join;
  50834. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50835. }
  50836. return this._effect.isReady();
  50837. };
  50838. return OutlineRenderer;
  50839. }());
  50840. BABYLON.OutlineRenderer = OutlineRenderer;
  50841. })(BABYLON || (BABYLON = {}));
  50842. var BABYLON;
  50843. (function (BABYLON) {
  50844. var MeshAssetTask = (function () {
  50845. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50846. this.name = name;
  50847. this.meshesNames = meshesNames;
  50848. this.rootUrl = rootUrl;
  50849. this.sceneFilename = sceneFilename;
  50850. this.isCompleted = false;
  50851. }
  50852. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50853. var _this = this;
  50854. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50855. _this.loadedMeshes = meshes;
  50856. _this.loadedParticleSystems = particleSystems;
  50857. _this.loadedSkeletons = skeletons;
  50858. _this.isCompleted = true;
  50859. if (_this.onSuccess) {
  50860. _this.onSuccess(_this);
  50861. }
  50862. onSuccess();
  50863. }, null, function () {
  50864. if (_this.onError) {
  50865. _this.onError(_this);
  50866. }
  50867. onError();
  50868. });
  50869. };
  50870. return MeshAssetTask;
  50871. }());
  50872. BABYLON.MeshAssetTask = MeshAssetTask;
  50873. var TextFileAssetTask = (function () {
  50874. function TextFileAssetTask(name, url) {
  50875. this.name = name;
  50876. this.url = url;
  50877. this.isCompleted = false;
  50878. }
  50879. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50880. var _this = this;
  50881. BABYLON.Tools.LoadFile(this.url, function (data) {
  50882. _this.text = data;
  50883. _this.isCompleted = true;
  50884. if (_this.onSuccess) {
  50885. _this.onSuccess(_this);
  50886. }
  50887. onSuccess();
  50888. }, null, scene.database, false, function () {
  50889. if (_this.onError) {
  50890. _this.onError(_this);
  50891. }
  50892. onError();
  50893. });
  50894. };
  50895. return TextFileAssetTask;
  50896. }());
  50897. BABYLON.TextFileAssetTask = TextFileAssetTask;
  50898. var BinaryFileAssetTask = (function () {
  50899. function BinaryFileAssetTask(name, url) {
  50900. this.name = name;
  50901. this.url = url;
  50902. this.isCompleted = false;
  50903. }
  50904. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50905. var _this = this;
  50906. BABYLON.Tools.LoadFile(this.url, function (data) {
  50907. _this.data = data;
  50908. _this.isCompleted = true;
  50909. if (_this.onSuccess) {
  50910. _this.onSuccess(_this);
  50911. }
  50912. onSuccess();
  50913. }, null, scene.database, true, function () {
  50914. if (_this.onError) {
  50915. _this.onError(_this);
  50916. }
  50917. onError();
  50918. });
  50919. };
  50920. return BinaryFileAssetTask;
  50921. }());
  50922. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50923. var ImageAssetTask = (function () {
  50924. function ImageAssetTask(name, url) {
  50925. this.name = name;
  50926. this.url = url;
  50927. this.isCompleted = false;
  50928. }
  50929. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50930. var _this = this;
  50931. var img = new Image();
  50932. img.onload = function () {
  50933. _this.image = img;
  50934. _this.isCompleted = true;
  50935. if (_this.onSuccess) {
  50936. _this.onSuccess(_this);
  50937. }
  50938. onSuccess();
  50939. };
  50940. img.onerror = function () {
  50941. if (_this.onError) {
  50942. _this.onError(_this);
  50943. }
  50944. onError();
  50945. };
  50946. img.src = this.url;
  50947. };
  50948. return ImageAssetTask;
  50949. }());
  50950. BABYLON.ImageAssetTask = ImageAssetTask;
  50951. var TextureAssetTask = (function () {
  50952. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50954. this.name = name;
  50955. this.url = url;
  50956. this.noMipmap = noMipmap;
  50957. this.invertY = invertY;
  50958. this.samplingMode = samplingMode;
  50959. this.isCompleted = false;
  50960. }
  50961. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50962. var _this = this;
  50963. var onload = function () {
  50964. _this.isCompleted = true;
  50965. if (_this.onSuccess) {
  50966. _this.onSuccess(_this);
  50967. }
  50968. onSuccess();
  50969. };
  50970. var onerror = function () {
  50971. if (_this.onError) {
  50972. _this.onError(_this);
  50973. }
  50974. onError();
  50975. };
  50976. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  50977. };
  50978. return TextureAssetTask;
  50979. }());
  50980. BABYLON.TextureAssetTask = TextureAssetTask;
  50981. var AssetsManager = (function () {
  50982. function AssetsManager(scene) {
  50983. this._tasks = new Array();
  50984. this._waitingTasksCount = 0;
  50985. this.useDefaultLoadingScreen = true;
  50986. this._scene = scene;
  50987. }
  50988. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  50989. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  50990. this._tasks.push(task);
  50991. return task;
  50992. };
  50993. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  50994. var task = new TextFileAssetTask(taskName, url);
  50995. this._tasks.push(task);
  50996. return task;
  50997. };
  50998. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  50999. var task = new BinaryFileAssetTask(taskName, url);
  51000. this._tasks.push(task);
  51001. return task;
  51002. };
  51003. AssetsManager.prototype.addImageTask = function (taskName, url) {
  51004. var task = new ImageAssetTask(taskName, url);
  51005. this._tasks.push(task);
  51006. return task;
  51007. };
  51008. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  51009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51010. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  51011. this._tasks.push(task);
  51012. return task;
  51013. };
  51014. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  51015. this._waitingTasksCount--;
  51016. if (this._waitingTasksCount === 0) {
  51017. if (this.onFinish) {
  51018. this.onFinish(this._tasks);
  51019. }
  51020. this._scene.getEngine().hideLoadingUI();
  51021. }
  51022. };
  51023. AssetsManager.prototype._runTask = function (task) {
  51024. var _this = this;
  51025. task.run(this._scene, function () {
  51026. if (_this.onTaskSuccess) {
  51027. _this.onTaskSuccess(task);
  51028. }
  51029. _this._decreaseWaitingTasksCount();
  51030. }, function () {
  51031. if (_this.onTaskError) {
  51032. _this.onTaskError(task);
  51033. }
  51034. _this._decreaseWaitingTasksCount();
  51035. });
  51036. };
  51037. AssetsManager.prototype.reset = function () {
  51038. this._tasks = new Array();
  51039. return this;
  51040. };
  51041. AssetsManager.prototype.load = function () {
  51042. this._waitingTasksCount = this._tasks.length;
  51043. if (this._waitingTasksCount === 0) {
  51044. if (this.onFinish) {
  51045. this.onFinish(this._tasks);
  51046. }
  51047. return this;
  51048. }
  51049. if (this.useDefaultLoadingScreen) {
  51050. this._scene.getEngine().displayLoadingUI();
  51051. }
  51052. for (var index = 0; index < this._tasks.length; index++) {
  51053. var task = this._tasks[index];
  51054. this._runTask(task);
  51055. }
  51056. return this;
  51057. };
  51058. return AssetsManager;
  51059. }());
  51060. BABYLON.AssetsManager = AssetsManager;
  51061. })(BABYLON || (BABYLON = {}));
  51062. var BABYLON;
  51063. (function (BABYLON) {
  51064. var VRCameraMetrics = (function () {
  51065. function VRCameraMetrics() {
  51066. this.compensateDistortion = true;
  51067. }
  51068. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  51069. get: function () {
  51070. return this.hResolution / (2 * this.vResolution);
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  51076. get: function () {
  51077. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  51078. },
  51079. enumerable: true,
  51080. configurable: true
  51081. });
  51082. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  51083. get: function () {
  51084. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51085. var h = (4 * meters) / this.hScreenSize;
  51086. return BABYLON.Matrix.Translation(h, 0, 0);
  51087. },
  51088. enumerable: true,
  51089. configurable: true
  51090. });
  51091. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  51092. get: function () {
  51093. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51094. var h = (4 * meters) / this.hScreenSize;
  51095. return BABYLON.Matrix.Translation(-h, 0, 0);
  51096. },
  51097. enumerable: true,
  51098. configurable: true
  51099. });
  51100. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  51101. get: function () {
  51102. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  51108. get: function () {
  51109. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  51110. },
  51111. enumerable: true,
  51112. configurable: true
  51113. });
  51114. VRCameraMetrics.GetDefault = function () {
  51115. var result = new VRCameraMetrics();
  51116. result.hResolution = 1280;
  51117. result.vResolution = 800;
  51118. result.hScreenSize = 0.149759993;
  51119. result.vScreenSize = 0.0935999975;
  51120. result.vScreenCenter = 0.0467999987,
  51121. result.eyeToScreenDistance = 0.0410000011;
  51122. result.lensSeparationDistance = 0.0635000020;
  51123. result.interpupillaryDistance = 0.0640000030;
  51124. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  51125. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  51126. result.postProcessScaleFactor = 1.714605507808412;
  51127. result.lensCenterOffset = 0.151976421;
  51128. return result;
  51129. };
  51130. return VRCameraMetrics;
  51131. }());
  51132. BABYLON.VRCameraMetrics = VRCameraMetrics;
  51133. })(BABYLON || (BABYLON = {}));
  51134. var BABYLON;
  51135. (function (BABYLON) {
  51136. var VRDeviceOrientationFreeCamera = (function (_super) {
  51137. __extends(VRDeviceOrientationFreeCamera, _super);
  51138. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  51139. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51140. _super.call(this, name, position, scene);
  51141. this.rotationQuaternion = new BABYLON.Quaternion();
  51142. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51143. metrics.compensateDistortion = compensateDistortion;
  51144. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51145. this.inputs.addDeviceOrientation();
  51146. }
  51147. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  51148. return "VRDeviceOrientationFreeCamera";
  51149. };
  51150. return VRDeviceOrientationFreeCamera;
  51151. }(BABYLON.FreeCamera));
  51152. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  51153. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  51154. __extends(VRDeviceOrientationArcRotateCamera, _super);
  51155. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  51156. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51157. _super.call(this, name, alpha, beta, radius, target, scene);
  51158. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51159. metrics.compensateDistortion = compensateDistortion;
  51160. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51161. this.inputs.addVRDeviceOrientation();
  51162. }
  51163. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  51164. return "VRDeviceOrientationArcRotateCamera";
  51165. };
  51166. return VRDeviceOrientationArcRotateCamera;
  51167. }(BABYLON.ArcRotateCamera));
  51168. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  51169. })(BABYLON || (BABYLON = {}));
  51170. var BABYLON;
  51171. (function (BABYLON) {
  51172. var WebVRFreeCamera = (function (_super) {
  51173. __extends(WebVRFreeCamera, _super);
  51174. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  51175. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51176. _super.call(this, name, position, scene);
  51177. this._hmdDevice = null;
  51178. this._sensorDevice = null;
  51179. this._cacheState = null;
  51180. this._vrEnabled = false;
  51181. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51182. metrics.compensateDistortion = compensateDistortion;
  51183. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51184. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  51185. this.rotationQuaternion = new BABYLON.Quaternion();
  51186. }
  51187. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  51188. var size = devices.length;
  51189. var i = 0;
  51190. // Reset devices.
  51191. this._sensorDevice = null;
  51192. this._hmdDevice = null;
  51193. // Search for a HmdDevice.
  51194. while (i < size && this._hmdDevice === null) {
  51195. if (devices[i] instanceof HMDVRDevice) {
  51196. this._hmdDevice = devices[i];
  51197. }
  51198. i++;
  51199. }
  51200. i = 0;
  51201. while (i < size && this._sensorDevice === null) {
  51202. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  51203. this._sensorDevice = devices[i];
  51204. }
  51205. i++;
  51206. }
  51207. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  51208. };
  51209. WebVRFreeCamera.prototype._checkInputs = function () {
  51210. if (this._vrEnabled) {
  51211. this._cacheState = this._sensorDevice.getState();
  51212. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  51213. //Flip in XY plane
  51214. this.rotationQuaternion.z *= -1;
  51215. this.rotationQuaternion.w *= -1;
  51216. }
  51217. _super.prototype._checkInputs.call(this);
  51218. };
  51219. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  51220. _super.prototype.attachControl.call(this, element, noPreventDefault);
  51221. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  51222. if (navigator.getVRDevices) {
  51223. navigator.getVRDevices().then(this._getWebVRDevices);
  51224. }
  51225. else if (navigator.mozGetVRDevices) {
  51226. navigator.mozGetVRDevices(this._getWebVRDevices);
  51227. }
  51228. };
  51229. WebVRFreeCamera.prototype.detachControl = function (element) {
  51230. _super.prototype.detachControl.call(this, element);
  51231. this._vrEnabled = false;
  51232. };
  51233. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  51234. if (!this._hmdDevice)
  51235. return;
  51236. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  51237. };
  51238. WebVRFreeCamera.prototype.getTypeName = function () {
  51239. return "WebVRFreeCamera";
  51240. };
  51241. return WebVRFreeCamera;
  51242. }(BABYLON.FreeCamera));
  51243. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51244. })(BABYLON || (BABYLON = {}));
  51245. var BABYLON;
  51246. (function (BABYLON) {
  51247. // Standard optimizations
  51248. var SceneOptimization = (function () {
  51249. function SceneOptimization(priority) {
  51250. if (priority === void 0) { priority = 0; }
  51251. this.priority = priority;
  51252. this.apply = function (scene) {
  51253. return true; // Return true if everything that can be done was applied
  51254. };
  51255. }
  51256. return SceneOptimization;
  51257. }());
  51258. BABYLON.SceneOptimization = SceneOptimization;
  51259. var TextureOptimization = (function (_super) {
  51260. __extends(TextureOptimization, _super);
  51261. function TextureOptimization(priority, maximumSize) {
  51262. var _this = this;
  51263. if (priority === void 0) { priority = 0; }
  51264. if (maximumSize === void 0) { maximumSize = 1024; }
  51265. _super.call(this, priority);
  51266. this.priority = priority;
  51267. this.maximumSize = maximumSize;
  51268. this.apply = function (scene) {
  51269. var allDone = true;
  51270. for (var index = 0; index < scene.textures.length; index++) {
  51271. var texture = scene.textures[index];
  51272. if (!texture.canRescale) {
  51273. continue;
  51274. }
  51275. var currentSize = texture.getSize();
  51276. var maxDimension = Math.max(currentSize.width, currentSize.height);
  51277. if (maxDimension > _this.maximumSize) {
  51278. texture.scale(0.5);
  51279. allDone = false;
  51280. }
  51281. }
  51282. return allDone;
  51283. };
  51284. }
  51285. return TextureOptimization;
  51286. }(SceneOptimization));
  51287. BABYLON.TextureOptimization = TextureOptimization;
  51288. var HardwareScalingOptimization = (function (_super) {
  51289. __extends(HardwareScalingOptimization, _super);
  51290. function HardwareScalingOptimization(priority, maximumScale) {
  51291. var _this = this;
  51292. if (priority === void 0) { priority = 0; }
  51293. if (maximumScale === void 0) { maximumScale = 2; }
  51294. _super.call(this, priority);
  51295. this.priority = priority;
  51296. this.maximumScale = maximumScale;
  51297. this._currentScale = 1;
  51298. this.apply = function (scene) {
  51299. _this._currentScale++;
  51300. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  51301. return _this._currentScale >= _this.maximumScale;
  51302. };
  51303. }
  51304. return HardwareScalingOptimization;
  51305. }(SceneOptimization));
  51306. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  51307. var ShadowsOptimization = (function (_super) {
  51308. __extends(ShadowsOptimization, _super);
  51309. function ShadowsOptimization() {
  51310. _super.apply(this, arguments);
  51311. this.apply = function (scene) {
  51312. scene.shadowsEnabled = false;
  51313. return true;
  51314. };
  51315. }
  51316. return ShadowsOptimization;
  51317. }(SceneOptimization));
  51318. BABYLON.ShadowsOptimization = ShadowsOptimization;
  51319. var PostProcessesOptimization = (function (_super) {
  51320. __extends(PostProcessesOptimization, _super);
  51321. function PostProcessesOptimization() {
  51322. _super.apply(this, arguments);
  51323. this.apply = function (scene) {
  51324. scene.postProcessesEnabled = false;
  51325. return true;
  51326. };
  51327. }
  51328. return PostProcessesOptimization;
  51329. }(SceneOptimization));
  51330. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  51331. var LensFlaresOptimization = (function (_super) {
  51332. __extends(LensFlaresOptimization, _super);
  51333. function LensFlaresOptimization() {
  51334. _super.apply(this, arguments);
  51335. this.apply = function (scene) {
  51336. scene.lensFlaresEnabled = false;
  51337. return true;
  51338. };
  51339. }
  51340. return LensFlaresOptimization;
  51341. }(SceneOptimization));
  51342. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  51343. var ParticlesOptimization = (function (_super) {
  51344. __extends(ParticlesOptimization, _super);
  51345. function ParticlesOptimization() {
  51346. _super.apply(this, arguments);
  51347. this.apply = function (scene) {
  51348. scene.particlesEnabled = false;
  51349. return true;
  51350. };
  51351. }
  51352. return ParticlesOptimization;
  51353. }(SceneOptimization));
  51354. BABYLON.ParticlesOptimization = ParticlesOptimization;
  51355. var RenderTargetsOptimization = (function (_super) {
  51356. __extends(RenderTargetsOptimization, _super);
  51357. function RenderTargetsOptimization() {
  51358. _super.apply(this, arguments);
  51359. this.apply = function (scene) {
  51360. scene.renderTargetsEnabled = false;
  51361. return true;
  51362. };
  51363. }
  51364. return RenderTargetsOptimization;
  51365. }(SceneOptimization));
  51366. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  51367. var MergeMeshesOptimization = (function (_super) {
  51368. __extends(MergeMeshesOptimization, _super);
  51369. function MergeMeshesOptimization() {
  51370. var _this = this;
  51371. _super.apply(this, arguments);
  51372. this._canBeMerged = function (abstractMesh) {
  51373. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  51374. return false;
  51375. }
  51376. var mesh = abstractMesh;
  51377. if (!mesh.isVisible || !mesh.isEnabled()) {
  51378. return false;
  51379. }
  51380. if (mesh.instances.length > 0) {
  51381. return false;
  51382. }
  51383. if (mesh.skeleton || mesh.hasLODLevels) {
  51384. return false;
  51385. }
  51386. if (mesh.parent) {
  51387. return false;
  51388. }
  51389. return true;
  51390. };
  51391. this.apply = function (scene, updateSelectionTree) {
  51392. var globalPool = scene.meshes.slice(0);
  51393. var globalLength = globalPool.length;
  51394. for (var index = 0; index < globalLength; index++) {
  51395. var currentPool = new Array();
  51396. var current = globalPool[index];
  51397. // Checks
  51398. if (!_this._canBeMerged(current)) {
  51399. continue;
  51400. }
  51401. currentPool.push(current);
  51402. // Find compatible meshes
  51403. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  51404. var otherMesh = globalPool[subIndex];
  51405. if (!_this._canBeMerged(otherMesh)) {
  51406. continue;
  51407. }
  51408. if (otherMesh.material !== current.material) {
  51409. continue;
  51410. }
  51411. if (otherMesh.checkCollisions !== current.checkCollisions) {
  51412. continue;
  51413. }
  51414. currentPool.push(otherMesh);
  51415. globalLength--;
  51416. globalPool.splice(subIndex, 1);
  51417. subIndex--;
  51418. }
  51419. if (currentPool.length < 2) {
  51420. continue;
  51421. }
  51422. // Merge meshes
  51423. BABYLON.Mesh.MergeMeshes(currentPool);
  51424. }
  51425. if (updateSelectionTree != undefined) {
  51426. if (updateSelectionTree) {
  51427. scene.createOrUpdateSelectionOctree();
  51428. }
  51429. }
  51430. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  51431. scene.createOrUpdateSelectionOctree();
  51432. }
  51433. return true;
  51434. };
  51435. }
  51436. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51437. get: function () {
  51438. return MergeMeshesOptimization._UpdateSelectionTree;
  51439. },
  51440. set: function (value) {
  51441. MergeMeshesOptimization._UpdateSelectionTree = value;
  51442. },
  51443. enumerable: true,
  51444. configurable: true
  51445. });
  51446. MergeMeshesOptimization._UpdateSelectionTree = false;
  51447. return MergeMeshesOptimization;
  51448. }(SceneOptimization));
  51449. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51450. // Options
  51451. var SceneOptimizerOptions = (function () {
  51452. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51453. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51454. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51455. this.targetFrameRate = targetFrameRate;
  51456. this.trackerDuration = trackerDuration;
  51457. this.optimizations = new Array();
  51458. }
  51459. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51460. var result = new SceneOptimizerOptions(targetFrameRate);
  51461. var priority = 0;
  51462. result.optimizations.push(new MergeMeshesOptimization(priority));
  51463. result.optimizations.push(new ShadowsOptimization(priority));
  51464. result.optimizations.push(new LensFlaresOptimization(priority));
  51465. // Next priority
  51466. priority++;
  51467. result.optimizations.push(new PostProcessesOptimization(priority));
  51468. result.optimizations.push(new ParticlesOptimization(priority));
  51469. // Next priority
  51470. priority++;
  51471. result.optimizations.push(new TextureOptimization(priority, 1024));
  51472. return result;
  51473. };
  51474. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51475. var result = new SceneOptimizerOptions(targetFrameRate);
  51476. var priority = 0;
  51477. result.optimizations.push(new MergeMeshesOptimization(priority));
  51478. result.optimizations.push(new ShadowsOptimization(priority));
  51479. result.optimizations.push(new LensFlaresOptimization(priority));
  51480. // Next priority
  51481. priority++;
  51482. result.optimizations.push(new PostProcessesOptimization(priority));
  51483. result.optimizations.push(new ParticlesOptimization(priority));
  51484. // Next priority
  51485. priority++;
  51486. result.optimizations.push(new TextureOptimization(priority, 512));
  51487. // Next priority
  51488. priority++;
  51489. result.optimizations.push(new RenderTargetsOptimization(priority));
  51490. // Next priority
  51491. priority++;
  51492. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51493. return result;
  51494. };
  51495. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51496. var result = new SceneOptimizerOptions(targetFrameRate);
  51497. var priority = 0;
  51498. result.optimizations.push(new MergeMeshesOptimization(priority));
  51499. result.optimizations.push(new ShadowsOptimization(priority));
  51500. result.optimizations.push(new LensFlaresOptimization(priority));
  51501. // Next priority
  51502. priority++;
  51503. result.optimizations.push(new PostProcessesOptimization(priority));
  51504. result.optimizations.push(new ParticlesOptimization(priority));
  51505. // Next priority
  51506. priority++;
  51507. result.optimizations.push(new TextureOptimization(priority, 256));
  51508. // Next priority
  51509. priority++;
  51510. result.optimizations.push(new RenderTargetsOptimization(priority));
  51511. // Next priority
  51512. priority++;
  51513. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51514. return result;
  51515. };
  51516. return SceneOptimizerOptions;
  51517. }());
  51518. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51519. // Scene optimizer tool
  51520. var SceneOptimizer = (function () {
  51521. function SceneOptimizer() {
  51522. }
  51523. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51524. // TODO: add an epsilon
  51525. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51526. if (onSuccess) {
  51527. onSuccess();
  51528. }
  51529. return;
  51530. }
  51531. // Apply current level of optimizations
  51532. var allDone = true;
  51533. var noOptimizationApplied = true;
  51534. for (var index = 0; index < options.optimizations.length; index++) {
  51535. var optimization = options.optimizations[index];
  51536. if (optimization.priority === currentPriorityLevel) {
  51537. noOptimizationApplied = false;
  51538. allDone = allDone && optimization.apply(scene);
  51539. }
  51540. }
  51541. // If no optimization was applied, this is a failure :(
  51542. if (noOptimizationApplied) {
  51543. if (onFailure) {
  51544. onFailure();
  51545. }
  51546. return;
  51547. }
  51548. // If all optimizations were done, move to next level
  51549. if (allDone) {
  51550. currentPriorityLevel++;
  51551. }
  51552. // Let's the system running for a specific amount of time before checking FPS
  51553. scene.executeWhenReady(function () {
  51554. setTimeout(function () {
  51555. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51556. }, options.trackerDuration);
  51557. });
  51558. };
  51559. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51560. if (!options) {
  51561. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51562. }
  51563. // Let's the system running for a specific amount of time before checking FPS
  51564. scene.executeWhenReady(function () {
  51565. setTimeout(function () {
  51566. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51567. }, options.trackerDuration);
  51568. });
  51569. };
  51570. return SceneOptimizer;
  51571. }());
  51572. BABYLON.SceneOptimizer = SceneOptimizer;
  51573. })(BABYLON || (BABYLON = {}));
  51574. var BABYLON;
  51575. (function (BABYLON) {
  51576. var Internals;
  51577. (function (Internals) {
  51578. var MeshLODLevel = (function () {
  51579. function MeshLODLevel(distance, mesh) {
  51580. this.distance = distance;
  51581. this.mesh = mesh;
  51582. }
  51583. return MeshLODLevel;
  51584. }());
  51585. Internals.MeshLODLevel = MeshLODLevel;
  51586. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51587. })(BABYLON || (BABYLON = {}));
  51588. var BABYLON;
  51589. (function (BABYLON) {
  51590. var RawTexture = (function (_super) {
  51591. __extends(RawTexture, _super);
  51592. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51594. if (invertY === void 0) { invertY = false; }
  51595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51596. _super.call(this, null, scene, !generateMipMaps, invertY);
  51597. this.format = format;
  51598. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51599. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51600. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51601. }
  51602. RawTexture.prototype.update = function (data) {
  51603. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51604. };
  51605. // Statics
  51606. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51607. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51608. if (invertY === void 0) { invertY = false; }
  51609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51610. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51611. };
  51612. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51614. if (invertY === void 0) { invertY = false; }
  51615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51616. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51617. };
  51618. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51619. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51620. if (invertY === void 0) { invertY = false; }
  51621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51622. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51623. };
  51624. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51625. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51626. if (invertY === void 0) { invertY = false; }
  51627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51628. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51629. };
  51630. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51631. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51632. if (invertY === void 0) { invertY = false; }
  51633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51634. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51635. };
  51636. return RawTexture;
  51637. }(BABYLON.Texture));
  51638. BABYLON.RawTexture = RawTexture;
  51639. })(BABYLON || (BABYLON = {}));
  51640. var BABYLON;
  51641. (function (BABYLON) {
  51642. var IndexedVector2 = (function (_super) {
  51643. __extends(IndexedVector2, _super);
  51644. function IndexedVector2(original, index) {
  51645. _super.call(this, original.x, original.y);
  51646. this.index = index;
  51647. }
  51648. return IndexedVector2;
  51649. }(BABYLON.Vector2));
  51650. var PolygonPoints = (function () {
  51651. function PolygonPoints() {
  51652. this.elements = new Array();
  51653. }
  51654. PolygonPoints.prototype.add = function (originalPoints) {
  51655. var _this = this;
  51656. var result = new Array();
  51657. originalPoints.forEach(function (point) {
  51658. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51659. var newPoint = new IndexedVector2(point, _this.elements.length);
  51660. result.push(newPoint);
  51661. _this.elements.push(newPoint);
  51662. }
  51663. });
  51664. return result;
  51665. };
  51666. PolygonPoints.prototype.computeBounds = function () {
  51667. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51668. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51669. this.elements.forEach(function (point) {
  51670. // x
  51671. if (point.x < lmin.x) {
  51672. lmin.x = point.x;
  51673. }
  51674. else if (point.x > lmax.x) {
  51675. lmax.x = point.x;
  51676. }
  51677. // y
  51678. if (point.y < lmin.y) {
  51679. lmin.y = point.y;
  51680. }
  51681. else if (point.y > lmax.y) {
  51682. lmax.y = point.y;
  51683. }
  51684. });
  51685. return {
  51686. min: lmin,
  51687. max: lmax,
  51688. width: lmax.x - lmin.x,
  51689. height: lmax.y - lmin.y
  51690. };
  51691. };
  51692. return PolygonPoints;
  51693. }());
  51694. var Polygon = (function () {
  51695. function Polygon() {
  51696. }
  51697. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51698. return [
  51699. new BABYLON.Vector2(xmin, ymin),
  51700. new BABYLON.Vector2(xmax, ymin),
  51701. new BABYLON.Vector2(xmax, ymax),
  51702. new BABYLON.Vector2(xmin, ymax)
  51703. ];
  51704. };
  51705. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51706. if (cx === void 0) { cx = 0; }
  51707. if (cy === void 0) { cy = 0; }
  51708. if (numberOfSides === void 0) { numberOfSides = 32; }
  51709. var result = new Array();
  51710. var angle = 0;
  51711. var increment = (Math.PI * 2) / numberOfSides;
  51712. for (var i = 0; i < numberOfSides; i++) {
  51713. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51714. angle -= increment;
  51715. }
  51716. return result;
  51717. };
  51718. Polygon.Parse = function (input) {
  51719. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51720. var i, result = [];
  51721. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51722. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51723. }
  51724. return result;
  51725. };
  51726. Polygon.StartingAt = function (x, y) {
  51727. return BABYLON.Path2.StartingAt(x, y);
  51728. };
  51729. return Polygon;
  51730. }());
  51731. BABYLON.Polygon = Polygon;
  51732. var PolygonMeshBuilder = (function () {
  51733. function PolygonMeshBuilder(name, contours, scene) {
  51734. this._points = new PolygonPoints();
  51735. this._outlinepoints = new PolygonPoints();
  51736. this._holes = [];
  51737. this._epoints = new Array();
  51738. this._eholes = new Array();
  51739. this._name = name;
  51740. this._scene = scene;
  51741. var points;
  51742. if (contours instanceof BABYLON.Path2) {
  51743. points = contours.getPoints();
  51744. }
  51745. else {
  51746. points = contours;
  51747. }
  51748. this._addToepoint(points);
  51749. this._points.add(points);
  51750. this._outlinepoints.add(points);
  51751. }
  51752. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51753. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  51754. var p = points_1[_i];
  51755. this._epoints.push(p.x, p.y);
  51756. }
  51757. };
  51758. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51759. this._points.add(hole);
  51760. var holepoints = new PolygonPoints();
  51761. holepoints.add(hole);
  51762. this._holes.push(holepoints);
  51763. this._eholes.push(this._epoints.length / 2);
  51764. this._addToepoint(hole);
  51765. return this;
  51766. };
  51767. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51768. var _this = this;
  51769. if (updatable === void 0) { updatable = false; }
  51770. var result = new BABYLON.Mesh(this._name, this._scene);
  51771. var normals = [];
  51772. var positions = [];
  51773. var uvs = [];
  51774. var bounds = this._points.computeBounds();
  51775. this._points.elements.forEach(function (p) {
  51776. normals.push(0, 1.0, 0);
  51777. positions.push(p.x, 0, p.y);
  51778. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51779. });
  51780. var indices = [];
  51781. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51782. for (var i = 0; i < res.length; i++) {
  51783. indices.push(res[i]);
  51784. }
  51785. if (depth > 0) {
  51786. var positionscount = (positions.length / 3); //get the current pointcount
  51787. this._points.elements.forEach(function (p) {
  51788. normals.push(0, -1.0, 0);
  51789. positions.push(p.x, -depth, p.y);
  51790. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51791. });
  51792. var totalCount = indices.length;
  51793. for (var i = 0; i < totalCount; i += 3) {
  51794. var i0 = indices[i + 0];
  51795. var i1 = indices[i + 1];
  51796. var i2 = indices[i + 2];
  51797. indices.push(i2 + positionscount);
  51798. indices.push(i1 + positionscount);
  51799. indices.push(i0 + positionscount);
  51800. }
  51801. //Add the sides
  51802. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51803. this._holes.forEach(function (hole) {
  51804. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51805. });
  51806. }
  51807. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51808. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51809. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51810. result.setIndices(indices);
  51811. return result;
  51812. };
  51813. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51814. var StartIndex = positions.length / 3;
  51815. var ulength = 0;
  51816. for (var i = 0; i < points.elements.length; i++) {
  51817. var p = points.elements[i];
  51818. var p1;
  51819. if ((i + 1) > points.elements.length - 1) {
  51820. p1 = points.elements[0];
  51821. }
  51822. else {
  51823. p1 = points.elements[i + 1];
  51824. }
  51825. positions.push(p.x, 0, p.y);
  51826. positions.push(p.x, -depth, p.y);
  51827. positions.push(p1.x, 0, p1.y);
  51828. positions.push(p1.x, -depth, p1.y);
  51829. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51830. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51831. var v3 = v2.subtract(v1);
  51832. var v4 = new BABYLON.Vector3(0, 1, 0);
  51833. var vn = BABYLON.Vector3.Cross(v3, v4);
  51834. vn = vn.normalize();
  51835. uvs.push(ulength / bounds.width, 0);
  51836. uvs.push(ulength / bounds.width, 1);
  51837. ulength += v3.length();
  51838. uvs.push((ulength / bounds.width), 0);
  51839. uvs.push((ulength / bounds.width), 1);
  51840. if (!flip) {
  51841. normals.push(-vn.x, -vn.y, -vn.z);
  51842. normals.push(-vn.x, -vn.y, -vn.z);
  51843. normals.push(-vn.x, -vn.y, -vn.z);
  51844. normals.push(-vn.x, -vn.y, -vn.z);
  51845. indices.push(StartIndex);
  51846. indices.push(StartIndex + 1);
  51847. indices.push(StartIndex + 2);
  51848. indices.push(StartIndex + 1);
  51849. indices.push(StartIndex + 3);
  51850. indices.push(StartIndex + 2);
  51851. }
  51852. else {
  51853. normals.push(vn.x, vn.y, vn.z);
  51854. normals.push(vn.x, vn.y, vn.z);
  51855. normals.push(vn.x, vn.y, vn.z);
  51856. normals.push(vn.x, vn.y, vn.z);
  51857. indices.push(StartIndex);
  51858. indices.push(StartIndex + 2);
  51859. indices.push(StartIndex + 1);
  51860. indices.push(StartIndex + 1);
  51861. indices.push(StartIndex + 2);
  51862. indices.push(StartIndex + 3);
  51863. }
  51864. StartIndex += 4;
  51865. }
  51866. ;
  51867. };
  51868. return PolygonMeshBuilder;
  51869. }());
  51870. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51871. })(BABYLON || (BABYLON = {}));
  51872. var BABYLON;
  51873. (function (BABYLON) {
  51874. var Octree = (function () {
  51875. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51876. if (maxDepth === void 0) { maxDepth = 2; }
  51877. this.maxDepth = maxDepth;
  51878. this.dynamicContent = new Array();
  51879. this._maxBlockCapacity = maxBlockCapacity || 64;
  51880. this._selectionContent = new BABYLON.SmartArray(1024);
  51881. this._creationFunc = creationFunc;
  51882. }
  51883. // Methods
  51884. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51885. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51886. };
  51887. Octree.prototype.addMesh = function (entry) {
  51888. for (var index = 0; index < this.blocks.length; index++) {
  51889. var block = this.blocks[index];
  51890. block.addEntry(entry);
  51891. }
  51892. };
  51893. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51894. this._selectionContent.reset();
  51895. for (var index = 0; index < this.blocks.length; index++) {
  51896. var block = this.blocks[index];
  51897. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51898. }
  51899. if (allowDuplicate) {
  51900. this._selectionContent.concat(this.dynamicContent);
  51901. }
  51902. else {
  51903. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51904. }
  51905. return this._selectionContent;
  51906. };
  51907. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51908. this._selectionContent.reset();
  51909. for (var index = 0; index < this.blocks.length; index++) {
  51910. var block = this.blocks[index];
  51911. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51912. }
  51913. if (allowDuplicate) {
  51914. this._selectionContent.concat(this.dynamicContent);
  51915. }
  51916. else {
  51917. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51918. }
  51919. return this._selectionContent;
  51920. };
  51921. Octree.prototype.intersectsRay = function (ray) {
  51922. this._selectionContent.reset();
  51923. for (var index = 0; index < this.blocks.length; index++) {
  51924. var block = this.blocks[index];
  51925. block.intersectsRay(ray, this._selectionContent);
  51926. }
  51927. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51928. return this._selectionContent;
  51929. };
  51930. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51931. target.blocks = new Array();
  51932. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51933. // Segmenting space
  51934. for (var x = 0; x < 2; x++) {
  51935. for (var y = 0; y < 2; y++) {
  51936. for (var z = 0; z < 2; z++) {
  51937. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51938. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51939. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51940. block.addEntries(entries);
  51941. target.blocks.push(block);
  51942. }
  51943. }
  51944. }
  51945. };
  51946. Octree.CreationFuncForMeshes = function (entry, block) {
  51947. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51948. block.entries.push(entry);
  51949. }
  51950. };
  51951. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51952. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51953. block.entries.push(entry);
  51954. }
  51955. };
  51956. return Octree;
  51957. }());
  51958. BABYLON.Octree = Octree;
  51959. })(BABYLON || (BABYLON = {}));
  51960. var BABYLON;
  51961. (function (BABYLON) {
  51962. var OctreeBlock = (function () {
  51963. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51964. this.entries = new Array();
  51965. this._boundingVectors = new Array();
  51966. this._capacity = capacity;
  51967. this._depth = depth;
  51968. this._maxDepth = maxDepth;
  51969. this._creationFunc = creationFunc;
  51970. this._minPoint = minPoint;
  51971. this._maxPoint = maxPoint;
  51972. this._boundingVectors.push(minPoint.clone());
  51973. this._boundingVectors.push(maxPoint.clone());
  51974. this._boundingVectors.push(minPoint.clone());
  51975. this._boundingVectors[2].x = maxPoint.x;
  51976. this._boundingVectors.push(minPoint.clone());
  51977. this._boundingVectors[3].y = maxPoint.y;
  51978. this._boundingVectors.push(minPoint.clone());
  51979. this._boundingVectors[4].z = maxPoint.z;
  51980. this._boundingVectors.push(maxPoint.clone());
  51981. this._boundingVectors[5].z = minPoint.z;
  51982. this._boundingVectors.push(maxPoint.clone());
  51983. this._boundingVectors[6].x = minPoint.x;
  51984. this._boundingVectors.push(maxPoint.clone());
  51985. this._boundingVectors[7].y = minPoint.y;
  51986. }
  51987. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  51988. // Property
  51989. get: function () {
  51990. return this._capacity;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  51996. get: function () {
  51997. return this._minPoint;
  51998. },
  51999. enumerable: true,
  52000. configurable: true
  52001. });
  52002. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  52003. get: function () {
  52004. return this._maxPoint;
  52005. },
  52006. enumerable: true,
  52007. configurable: true
  52008. });
  52009. // Methods
  52010. OctreeBlock.prototype.addEntry = function (entry) {
  52011. if (this.blocks) {
  52012. for (var index = 0; index < this.blocks.length; index++) {
  52013. var block = this.blocks[index];
  52014. block.addEntry(entry);
  52015. }
  52016. return;
  52017. }
  52018. this._creationFunc(entry, this);
  52019. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  52020. this.createInnerBlocks();
  52021. }
  52022. };
  52023. OctreeBlock.prototype.addEntries = function (entries) {
  52024. for (var index = 0; index < entries.length; index++) {
  52025. var mesh = entries[index];
  52026. this.addEntry(mesh);
  52027. }
  52028. };
  52029. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  52030. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  52031. if (this.blocks) {
  52032. for (var index = 0; index < this.blocks.length; index++) {
  52033. var block = this.blocks[index];
  52034. block.select(frustumPlanes, selection, allowDuplicate);
  52035. }
  52036. return;
  52037. }
  52038. if (allowDuplicate) {
  52039. selection.concat(this.entries);
  52040. }
  52041. else {
  52042. selection.concatWithNoDuplicate(this.entries);
  52043. }
  52044. }
  52045. };
  52046. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  52047. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  52048. if (this.blocks) {
  52049. for (var index = 0; index < this.blocks.length; index++) {
  52050. var block = this.blocks[index];
  52051. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  52052. }
  52053. return;
  52054. }
  52055. if (allowDuplicate) {
  52056. selection.concat(this.entries);
  52057. }
  52058. else {
  52059. selection.concatWithNoDuplicate(this.entries);
  52060. }
  52061. }
  52062. };
  52063. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  52064. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  52065. if (this.blocks) {
  52066. for (var index = 0; index < this.blocks.length; index++) {
  52067. var block = this.blocks[index];
  52068. block.intersectsRay(ray, selection);
  52069. }
  52070. return;
  52071. }
  52072. selection.concatWithNoDuplicate(this.entries);
  52073. }
  52074. };
  52075. OctreeBlock.prototype.createInnerBlocks = function () {
  52076. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  52077. };
  52078. return OctreeBlock;
  52079. }());
  52080. BABYLON.OctreeBlock = OctreeBlock;
  52081. })(BABYLON || (BABYLON = {}));
  52082. var BABYLON;
  52083. (function (BABYLON) {
  52084. var BlurPostProcess = (function (_super) {
  52085. __extends(BlurPostProcess, _super);
  52086. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  52087. var _this = this;
  52088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52089. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  52090. this.direction = direction;
  52091. this.blurWidth = blurWidth;
  52092. this.onApplyObservable.add(function (effect) {
  52093. effect.setFloat2("screenSize", _this.width, _this.height);
  52094. effect.setVector2("direction", _this.direction);
  52095. effect.setFloat("blurWidth", _this.blurWidth);
  52096. });
  52097. }
  52098. return BlurPostProcess;
  52099. }(BABYLON.PostProcess));
  52100. BABYLON.BlurPostProcess = BlurPostProcess;
  52101. })(BABYLON || (BABYLON = {}));
  52102. var BABYLON;
  52103. (function (BABYLON) {
  52104. var RefractionPostProcess = (function (_super) {
  52105. __extends(RefractionPostProcess, _super);
  52106. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  52107. var _this = this;
  52108. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  52109. this.color = color;
  52110. this.depth = depth;
  52111. this.colorLevel = colorLevel;
  52112. this.onActivateObservable.add(function (cam) {
  52113. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  52114. });
  52115. this.onApplyObservable.add(function (effect) {
  52116. effect.setColor3("baseColor", _this.color);
  52117. effect.setFloat("depth", _this.depth);
  52118. effect.setFloat("colorLevel", _this.colorLevel);
  52119. effect.setTexture("refractionSampler", _this._refRexture);
  52120. });
  52121. }
  52122. // Methods
  52123. RefractionPostProcess.prototype.dispose = function (camera) {
  52124. if (this._refRexture) {
  52125. this._refRexture.dispose();
  52126. }
  52127. _super.prototype.dispose.call(this, camera);
  52128. };
  52129. return RefractionPostProcess;
  52130. }(BABYLON.PostProcess));
  52131. BABYLON.RefractionPostProcess = RefractionPostProcess;
  52132. })(BABYLON || (BABYLON = {}));
  52133. var BABYLON;
  52134. (function (BABYLON) {
  52135. var BlackAndWhitePostProcess = (function (_super) {
  52136. __extends(BlackAndWhitePostProcess, _super);
  52137. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  52138. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  52139. }
  52140. return BlackAndWhitePostProcess;
  52141. }(BABYLON.PostProcess));
  52142. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  52143. })(BABYLON || (BABYLON = {}));
  52144. var BABYLON;
  52145. (function (BABYLON) {
  52146. var ConvolutionPostProcess = (function (_super) {
  52147. __extends(ConvolutionPostProcess, _super);
  52148. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  52149. var _this = this;
  52150. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  52151. this.kernel = kernel;
  52152. this.onApply = function (effect) {
  52153. effect.setFloat2("screenSize", _this.width, _this.height);
  52154. effect.setArray("kernel", _this.kernel);
  52155. };
  52156. }
  52157. // Statics
  52158. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52159. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52160. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52161. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52162. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52163. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52164. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52165. return ConvolutionPostProcess;
  52166. }(BABYLON.PostProcess));
  52167. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52168. })(BABYLON || (BABYLON = {}));
  52169. var BABYLON;
  52170. (function (BABYLON) {
  52171. var FilterPostProcess = (function (_super) {
  52172. __extends(FilterPostProcess, _super);
  52173. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52174. var _this = this;
  52175. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  52176. this.kernelMatrix = kernelMatrix;
  52177. this.onApply = function (effect) {
  52178. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52179. };
  52180. }
  52181. return FilterPostProcess;
  52182. }(BABYLON.PostProcess));
  52183. BABYLON.FilterPostProcess = FilterPostProcess;
  52184. })(BABYLON || (BABYLON = {}));
  52185. var BABYLON;
  52186. (function (BABYLON) {
  52187. var FxaaPostProcess = (function (_super) {
  52188. __extends(FxaaPostProcess, _super);
  52189. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52190. var _this = this;
  52191. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  52192. this.onSizeChangedObservable.add(function () {
  52193. _this.texelWidth = 1.0 / _this.width;
  52194. _this.texelHeight = 1.0 / _this.height;
  52195. });
  52196. this.onApplyObservable.add(function (effect) {
  52197. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52198. });
  52199. }
  52200. return FxaaPostProcess;
  52201. }(BABYLON.PostProcess));
  52202. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52203. })(BABYLON || (BABYLON = {}));
  52204. var BABYLON;
  52205. (function (BABYLON) {
  52206. var StereoscopicInterlacePostProcess = (function (_super) {
  52207. __extends(StereoscopicInterlacePostProcess, _super);
  52208. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52209. var _this = this;
  52210. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  52211. this._passedProcess = rigCameras[0]._rigPostProcess;
  52212. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  52213. this.onSizeChangedObservable.add(function () {
  52214. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52215. });
  52216. this.onApplyObservable.add(function (effect) {
  52217. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52218. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52219. });
  52220. }
  52221. return StereoscopicInterlacePostProcess;
  52222. }(BABYLON.PostProcess));
  52223. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52224. })(BABYLON || (BABYLON = {}));
  52225. var BABYLON;
  52226. (function (BABYLON) {
  52227. var LensFlare = (function () {
  52228. function LensFlare(size, position, color, imgUrl, system) {
  52229. this.size = size;
  52230. this.position = position;
  52231. this.dispose = function () {
  52232. if (this.texture) {
  52233. this.texture.dispose();
  52234. }
  52235. // Remove from scene
  52236. var index = this._system.lensFlares.indexOf(this);
  52237. this._system.lensFlares.splice(index, 1);
  52238. };
  52239. this.color = color || new BABYLON.Color3(1, 1, 1);
  52240. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52241. this._system = system;
  52242. system.lensFlares.push(this);
  52243. }
  52244. return LensFlare;
  52245. }());
  52246. BABYLON.LensFlare = LensFlare;
  52247. })(BABYLON || (BABYLON = {}));
  52248. var BABYLON;
  52249. (function (BABYLON) {
  52250. var LensFlareSystem = (function () {
  52251. function LensFlareSystem(name, emitter, scene) {
  52252. this.name = name;
  52253. this.lensFlares = new Array();
  52254. this.borderLimit = 300;
  52255. this.layerMask = 0x0FFFFFFF;
  52256. this._vertexBuffers = {};
  52257. this._isEnabled = true;
  52258. this._scene = scene;
  52259. this._emitter = emitter;
  52260. this.id = name;
  52261. scene.lensFlareSystems.push(this);
  52262. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52263. var engine = scene.getEngine();
  52264. // VBO
  52265. var vertices = [];
  52266. vertices.push(1, 1);
  52267. vertices.push(-1, 1);
  52268. vertices.push(-1, -1);
  52269. vertices.push(1, -1);
  52270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52271. // Indices
  52272. var indices = [];
  52273. indices.push(0);
  52274. indices.push(1);
  52275. indices.push(2);
  52276. indices.push(0);
  52277. indices.push(2);
  52278. indices.push(3);
  52279. this._indexBuffer = engine.createIndexBuffer(indices);
  52280. // Effects
  52281. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52282. }
  52283. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52284. get: function () {
  52285. return this._isEnabled;
  52286. },
  52287. set: function (value) {
  52288. this._isEnabled = value;
  52289. },
  52290. enumerable: true,
  52291. configurable: true
  52292. });
  52293. LensFlareSystem.prototype.getScene = function () {
  52294. return this._scene;
  52295. };
  52296. LensFlareSystem.prototype.getEmitter = function () {
  52297. return this._emitter;
  52298. };
  52299. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52300. this._emitter = newEmitter;
  52301. };
  52302. LensFlareSystem.prototype.getEmitterPosition = function () {
  52303. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52304. };
  52305. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52306. var position = this.getEmitterPosition();
  52307. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52308. this._positionX = position.x;
  52309. this._positionY = position.y;
  52310. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52311. if (position.z > 0) {
  52312. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52313. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52314. return true;
  52315. }
  52316. }
  52317. return false;
  52318. };
  52319. LensFlareSystem.prototype._isVisible = function () {
  52320. if (!this._isEnabled) {
  52321. return false;
  52322. }
  52323. var emitterPosition = this.getEmitterPosition();
  52324. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  52325. var distance = direction.length();
  52326. direction.normalize();
  52327. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  52328. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52329. return !pickInfo.hit || pickInfo.distance > distance;
  52330. };
  52331. LensFlareSystem.prototype.render = function () {
  52332. if (!this._effect.isReady())
  52333. return false;
  52334. var engine = this._scene.getEngine();
  52335. var viewport = this._scene.activeCamera.viewport;
  52336. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52337. // Position
  52338. if (!this.computeEffectivePosition(globalViewport)) {
  52339. return false;
  52340. }
  52341. // Visibility
  52342. if (!this._isVisible()) {
  52343. return false;
  52344. }
  52345. // Intensity
  52346. var awayX;
  52347. var awayY;
  52348. if (this._positionX < this.borderLimit + globalViewport.x) {
  52349. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52350. }
  52351. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52352. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52353. }
  52354. else {
  52355. awayX = 0;
  52356. }
  52357. if (this._positionY < this.borderLimit + globalViewport.y) {
  52358. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52359. }
  52360. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52361. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52362. }
  52363. else {
  52364. awayY = 0;
  52365. }
  52366. var away = (awayX > awayY) ? awayX : awayY;
  52367. if (away > this.borderLimit) {
  52368. away = this.borderLimit;
  52369. }
  52370. var intensity = 1.0 - (away / this.borderLimit);
  52371. if (intensity < 0) {
  52372. return false;
  52373. }
  52374. if (intensity > 1.0) {
  52375. intensity = 1.0;
  52376. }
  52377. // Position
  52378. var centerX = globalViewport.x + globalViewport.width / 2;
  52379. var centerY = globalViewport.y + globalViewport.height / 2;
  52380. var distX = centerX - this._positionX;
  52381. var distY = centerY - this._positionY;
  52382. // Effects
  52383. engine.enableEffect(this._effect);
  52384. engine.setState(false);
  52385. engine.setDepthBuffer(false);
  52386. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52387. // VBOs
  52388. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52389. // Flares
  52390. for (var index = 0; index < this.lensFlares.length; index++) {
  52391. var flare = this.lensFlares[index];
  52392. var x = centerX - (distX * flare.position);
  52393. var y = centerY - (distY * flare.position);
  52394. var cw = flare.size;
  52395. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52396. var cx = 2 * (x / globalViewport.width) - 1.0;
  52397. var cy = 1.0 - 2 * (y / globalViewport.height);
  52398. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52399. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52400. // Texture
  52401. this._effect.setTexture("textureSampler", flare.texture);
  52402. // Color
  52403. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52404. // Draw order
  52405. engine.draw(true, 0, 6);
  52406. }
  52407. engine.setDepthBuffer(true);
  52408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52409. return true;
  52410. };
  52411. LensFlareSystem.prototype.dispose = function () {
  52412. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52413. if (vertexBuffer) {
  52414. vertexBuffer.dispose();
  52415. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52416. }
  52417. if (this._indexBuffer) {
  52418. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52419. this._indexBuffer = null;
  52420. }
  52421. while (this.lensFlares.length) {
  52422. this.lensFlares[0].dispose();
  52423. }
  52424. // Remove from scene
  52425. var index = this._scene.lensFlareSystems.indexOf(this);
  52426. this._scene.lensFlareSystems.splice(index, 1);
  52427. };
  52428. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52429. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52430. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52431. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52432. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52433. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52434. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52435. var parsedFlare = parsedLensFlareSystem.flares[index];
  52436. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52437. }
  52438. return lensFlareSystem;
  52439. };
  52440. LensFlareSystem.prototype.serialize = function () {
  52441. var serializationObject = {};
  52442. serializationObject.id = this.id;
  52443. serializationObject.name = this.name;
  52444. serializationObject.emitterId = this.getEmitter().id;
  52445. serializationObject.borderLimit = this.borderLimit;
  52446. serializationObject.flares = [];
  52447. for (var index = 0; index < this.lensFlares.length; index++) {
  52448. var flare = this.lensFlares[index];
  52449. serializationObject.flares.push({
  52450. size: flare.size,
  52451. position: flare.position,
  52452. color: flare.color.asArray(),
  52453. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52454. });
  52455. }
  52456. return serializationObject;
  52457. };
  52458. return LensFlareSystem;
  52459. }());
  52460. BABYLON.LensFlareSystem = LensFlareSystem;
  52461. })(BABYLON || (BABYLON = {}));
  52462. var BABYLON;
  52463. (function (BABYLON) {
  52464. // We're mainly based on the logic defined into the FreeCamera code
  52465. var DeviceOrientationCamera = (function (_super) {
  52466. __extends(DeviceOrientationCamera, _super);
  52467. //-- end properties for backward compatibility for inputs
  52468. function DeviceOrientationCamera(name, position, scene) {
  52469. _super.call(this, name, position, scene);
  52470. this.inputs.addDeviceOrientation();
  52471. }
  52472. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  52473. //-- Begin properties for backward compatibility for inputs
  52474. get: function () {
  52475. return 0;
  52476. },
  52477. set: function (value) {
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  52483. get: function () {
  52484. return 0;
  52485. },
  52486. set: function (value) {
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. DeviceOrientationCamera.prototype.getTypeName = function () {
  52492. return "DeviceOrientationCamera";
  52493. };
  52494. return DeviceOrientationCamera;
  52495. }(BABYLON.FreeCamera));
  52496. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52497. })(BABYLON || (BABYLON = {}));
  52498. var BABYLON;
  52499. (function (BABYLON) {
  52500. // We're mainly based on the logic defined into the FreeCamera code
  52501. var UniversalCamera = (function (_super) {
  52502. __extends(UniversalCamera, _super);
  52503. //-- end properties for backward compatibility for inputs
  52504. function UniversalCamera(name, position, scene) {
  52505. _super.call(this, name, position, scene);
  52506. this.inputs.addGamepad();
  52507. }
  52508. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52509. //-- Begin properties for backward compatibility for inputs
  52510. get: function () {
  52511. var gamepad = this.inputs.attached["gamepad"];
  52512. if (gamepad)
  52513. return gamepad.gamepadAngularSensibility;
  52514. },
  52515. set: function (value) {
  52516. var gamepad = this.inputs.attached["gamepad"];
  52517. if (gamepad)
  52518. gamepad.gamepadAngularSensibility = value;
  52519. },
  52520. enumerable: true,
  52521. configurable: true
  52522. });
  52523. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52524. get: function () {
  52525. var gamepad = this.inputs.attached["gamepad"];
  52526. if (gamepad)
  52527. return gamepad.gamepadMoveSensibility;
  52528. },
  52529. set: function (value) {
  52530. var gamepad = this.inputs.attached["gamepad"];
  52531. if (gamepad)
  52532. gamepad.gamepadMoveSensibility = value;
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. UniversalCamera.prototype.getTypeName = function () {
  52538. return "UniversalCamera";
  52539. };
  52540. return UniversalCamera;
  52541. }(BABYLON.TouchCamera));
  52542. BABYLON.UniversalCamera = UniversalCamera;
  52543. })(BABYLON || (BABYLON = {}));
  52544. var BABYLON;
  52545. (function (BABYLON) {
  52546. var Gamepads = (function () {
  52547. function Gamepads(ongamedpadconnected) {
  52548. var _this = this;
  52549. this.babylonGamepads = [];
  52550. this.oneGamepadConnected = false;
  52551. this.isMonitoring = false;
  52552. this.gamepadEventSupported = 'GamepadEvent' in window;
  52553. this.gamepadSupportAvailable = (navigator.getGamepads ||
  52554. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  52555. this._callbackGamepadConnected = ongamedpadconnected;
  52556. if (this.gamepadSupportAvailable) {
  52557. // Checking if the gamepad connected event is supported (like in Firefox)
  52558. if (this.gamepadEventSupported) {
  52559. this._onGamepadConnectedEvent = function (evt) {
  52560. _this._onGamepadConnected(evt);
  52561. };
  52562. this._onGamepadDisonnectedEvent = function (evt) {
  52563. _this._onGamepadDisconnected(evt);
  52564. };
  52565. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52566. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52567. }
  52568. else {
  52569. this._startMonitoringGamepads();
  52570. }
  52571. }
  52572. }
  52573. Gamepads.prototype.dispose = function () {
  52574. if (Gamepads.gamepadDOMInfo) {
  52575. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52576. }
  52577. if (this._onGamepadConnectedEvent) {
  52578. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52579. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52580. this._onGamepadConnectedEvent = null;
  52581. this._onGamepadDisonnectedEvent = null;
  52582. }
  52583. };
  52584. Gamepads.prototype._onGamepadConnected = function (evt) {
  52585. var newGamepad = this._addNewGamepad(evt.gamepad);
  52586. if (this._callbackGamepadConnected)
  52587. this._callbackGamepadConnected(newGamepad);
  52588. this._startMonitoringGamepads();
  52589. };
  52590. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52591. if (!this.oneGamepadConnected) {
  52592. this.oneGamepadConnected = true;
  52593. if (Gamepads.gamepadDOMInfo) {
  52594. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52595. Gamepads.gamepadDOMInfo = null;
  52596. }
  52597. }
  52598. var newGamepad;
  52599. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52600. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  52601. }
  52602. else {
  52603. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52604. }
  52605. this.babylonGamepads.push(newGamepad);
  52606. return newGamepad;
  52607. };
  52608. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52609. // Remove the gamepad from the list of gamepads to monitor.
  52610. for (var i in this.babylonGamepads) {
  52611. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52612. this.babylonGamepads.splice(+i, 1);
  52613. break;
  52614. }
  52615. }
  52616. // If no gamepads are left, stop the polling loop.
  52617. if (this.babylonGamepads.length == 0) {
  52618. this._stopMonitoringGamepads();
  52619. }
  52620. };
  52621. Gamepads.prototype._startMonitoringGamepads = function () {
  52622. if (!this.isMonitoring) {
  52623. this.isMonitoring = true;
  52624. this._checkGamepadsStatus();
  52625. }
  52626. };
  52627. Gamepads.prototype._stopMonitoringGamepads = function () {
  52628. this.isMonitoring = false;
  52629. };
  52630. Gamepads.prototype._checkGamepadsStatus = function () {
  52631. var _this = this;
  52632. // updating gamepad objects
  52633. this._updateGamepadObjects();
  52634. for (var i in this.babylonGamepads) {
  52635. this.babylonGamepads[i].update();
  52636. }
  52637. if (this.isMonitoring) {
  52638. if (window.requestAnimationFrame) {
  52639. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52640. }
  52641. else if (window.mozRequestAnimationFrame) {
  52642. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52643. }
  52644. else if (window.webkitRequestAnimationFrame) {
  52645. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52646. }
  52647. }
  52648. };
  52649. // This function is called only on Chrome, which does not yet support
  52650. // connection/disconnection events, but requires you to monitor
  52651. // an array for changes.
  52652. Gamepads.prototype._updateGamepadObjects = function () {
  52653. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52654. for (var i = 0; i < gamepads.length; i++) {
  52655. if (gamepads[i]) {
  52656. if (!(gamepads[i].index in this.babylonGamepads)) {
  52657. var newGamepad = this._addNewGamepad(gamepads[i]);
  52658. if (this._callbackGamepadConnected) {
  52659. this._callbackGamepadConnected(newGamepad);
  52660. }
  52661. }
  52662. else {
  52663. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52664. }
  52665. }
  52666. }
  52667. };
  52668. return Gamepads;
  52669. }());
  52670. BABYLON.Gamepads = Gamepads;
  52671. var StickValues = (function () {
  52672. function StickValues(x, y) {
  52673. this.x = x;
  52674. this.y = y;
  52675. }
  52676. return StickValues;
  52677. }());
  52678. BABYLON.StickValues = StickValues;
  52679. var Gamepad = (function () {
  52680. function Gamepad(id, index, browserGamepad) {
  52681. this.id = id;
  52682. this.index = index;
  52683. this.browserGamepad = browserGamepad;
  52684. if (this.browserGamepad.axes.length >= 2) {
  52685. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52686. }
  52687. if (this.browserGamepad.axes.length >= 4) {
  52688. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52689. }
  52690. }
  52691. Gamepad.prototype.onleftstickchanged = function (callback) {
  52692. this._onleftstickchanged = callback;
  52693. };
  52694. Gamepad.prototype.onrightstickchanged = function (callback) {
  52695. this._onrightstickchanged = callback;
  52696. };
  52697. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52698. get: function () {
  52699. return this._leftStick;
  52700. },
  52701. set: function (newValues) {
  52702. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52703. this._onleftstickchanged(newValues);
  52704. }
  52705. this._leftStick = newValues;
  52706. },
  52707. enumerable: true,
  52708. configurable: true
  52709. });
  52710. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52711. get: function () {
  52712. return this._rightStick;
  52713. },
  52714. set: function (newValues) {
  52715. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52716. this._onrightstickchanged(newValues);
  52717. }
  52718. this._rightStick = newValues;
  52719. },
  52720. enumerable: true,
  52721. configurable: true
  52722. });
  52723. Gamepad.prototype.update = function () {
  52724. if (this._leftStick) {
  52725. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52726. }
  52727. if (this._rightStick) {
  52728. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52729. }
  52730. };
  52731. return Gamepad;
  52732. }());
  52733. BABYLON.Gamepad = Gamepad;
  52734. var GenericPad = (function (_super) {
  52735. __extends(GenericPad, _super);
  52736. function GenericPad(id, index, gamepad) {
  52737. _super.call(this, id, index, gamepad);
  52738. this.id = id;
  52739. this.index = index;
  52740. this.gamepad = gamepad;
  52741. this._buttons = new Array(gamepad.buttons.length);
  52742. }
  52743. GenericPad.prototype.onbuttondown = function (callback) {
  52744. this._onbuttondown = callback;
  52745. };
  52746. GenericPad.prototype.onbuttonup = function (callback) {
  52747. this._onbuttonup = callback;
  52748. };
  52749. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52750. if (newValue !== currentValue) {
  52751. if (this._onbuttondown && newValue === 1) {
  52752. this._onbuttondown(buttonIndex);
  52753. }
  52754. if (this._onbuttonup && newValue === 0) {
  52755. this._onbuttonup(buttonIndex);
  52756. }
  52757. }
  52758. return newValue;
  52759. };
  52760. GenericPad.prototype.update = function () {
  52761. _super.prototype.update.call(this);
  52762. for (var index = 0; index < this._buttons.length; index++) {
  52763. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52764. }
  52765. };
  52766. return GenericPad;
  52767. }(Gamepad));
  52768. BABYLON.GenericPad = GenericPad;
  52769. (function (Xbox360Button) {
  52770. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52771. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52772. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52773. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52774. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52775. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52776. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52777. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52778. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52779. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52780. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52781. var Xbox360Button = BABYLON.Xbox360Button;
  52782. (function (Xbox360Dpad) {
  52783. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52784. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52785. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52786. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52787. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52788. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  52789. var Xbox360Pad = (function (_super) {
  52790. __extends(Xbox360Pad, _super);
  52791. function Xbox360Pad() {
  52792. _super.apply(this, arguments);
  52793. this._leftTrigger = 0;
  52794. this._rightTrigger = 0;
  52795. this._buttonA = 0;
  52796. this._buttonB = 0;
  52797. this._buttonX = 0;
  52798. this._buttonY = 0;
  52799. this._buttonBack = 0;
  52800. this._buttonStart = 0;
  52801. this._buttonLB = 0;
  52802. this._buttonRB = 0;
  52803. this._buttonLeftStick = 0;
  52804. this._buttonRightStick = 0;
  52805. this._dPadUp = 0;
  52806. this._dPadDown = 0;
  52807. this._dPadLeft = 0;
  52808. this._dPadRight = 0;
  52809. }
  52810. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52811. this._onlefttriggerchanged = callback;
  52812. };
  52813. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52814. this._onrighttriggerchanged = callback;
  52815. };
  52816. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52817. get: function () {
  52818. return this._leftTrigger;
  52819. },
  52820. set: function (newValue) {
  52821. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52822. this._onlefttriggerchanged(newValue);
  52823. }
  52824. this._leftTrigger = newValue;
  52825. },
  52826. enumerable: true,
  52827. configurable: true
  52828. });
  52829. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52830. get: function () {
  52831. return this._rightTrigger;
  52832. },
  52833. set: function (newValue) {
  52834. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52835. this._onrighttriggerchanged(newValue);
  52836. }
  52837. this._rightTrigger = newValue;
  52838. },
  52839. enumerable: true,
  52840. configurable: true
  52841. });
  52842. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52843. this._onbuttondown = callback;
  52844. };
  52845. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52846. this._onbuttonup = callback;
  52847. };
  52848. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52849. this._ondpaddown = callback;
  52850. };
  52851. Xbox360Pad.prototype.ondpadup = function (callback) {
  52852. this._ondpadup = callback;
  52853. };
  52854. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52855. if (newValue !== currentValue) {
  52856. if (this._onbuttondown && newValue === 1) {
  52857. this._onbuttondown(buttonType);
  52858. }
  52859. if (this._onbuttonup && newValue === 0) {
  52860. this._onbuttonup(buttonType);
  52861. }
  52862. }
  52863. return newValue;
  52864. };
  52865. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52866. if (newValue !== currentValue) {
  52867. if (this._ondpaddown && newValue === 1) {
  52868. this._ondpaddown(buttonType);
  52869. }
  52870. if (this._ondpadup && newValue === 0) {
  52871. this._ondpadup(buttonType);
  52872. }
  52873. }
  52874. return newValue;
  52875. };
  52876. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52877. get: function () {
  52878. return this._buttonA;
  52879. },
  52880. set: function (value) {
  52881. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52882. },
  52883. enumerable: true,
  52884. configurable: true
  52885. });
  52886. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52887. get: function () {
  52888. return this._buttonB;
  52889. },
  52890. set: function (value) {
  52891. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52892. },
  52893. enumerable: true,
  52894. configurable: true
  52895. });
  52896. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52897. get: function () {
  52898. return this._buttonX;
  52899. },
  52900. set: function (value) {
  52901. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52902. },
  52903. enumerable: true,
  52904. configurable: true
  52905. });
  52906. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52907. get: function () {
  52908. return this._buttonY;
  52909. },
  52910. set: function (value) {
  52911. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52912. },
  52913. enumerable: true,
  52914. configurable: true
  52915. });
  52916. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52917. get: function () {
  52918. return this._buttonStart;
  52919. },
  52920. set: function (value) {
  52921. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52927. get: function () {
  52928. return this._buttonBack;
  52929. },
  52930. set: function (value) {
  52931. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52932. },
  52933. enumerable: true,
  52934. configurable: true
  52935. });
  52936. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52937. get: function () {
  52938. return this._buttonLB;
  52939. },
  52940. set: function (value) {
  52941. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52942. },
  52943. enumerable: true,
  52944. configurable: true
  52945. });
  52946. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52947. get: function () {
  52948. return this._buttonRB;
  52949. },
  52950. set: function (value) {
  52951. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52952. },
  52953. enumerable: true,
  52954. configurable: true
  52955. });
  52956. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52957. get: function () {
  52958. return this._buttonLeftStick;
  52959. },
  52960. set: function (value) {
  52961. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52962. },
  52963. enumerable: true,
  52964. configurable: true
  52965. });
  52966. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52967. get: function () {
  52968. return this._buttonRightStick;
  52969. },
  52970. set: function (value) {
  52971. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52972. },
  52973. enumerable: true,
  52974. configurable: true
  52975. });
  52976. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52977. get: function () {
  52978. return this._dPadUp;
  52979. },
  52980. set: function (value) {
  52981. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52982. },
  52983. enumerable: true,
  52984. configurable: true
  52985. });
  52986. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52987. get: function () {
  52988. return this._dPadDown;
  52989. },
  52990. set: function (value) {
  52991. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52992. },
  52993. enumerable: true,
  52994. configurable: true
  52995. });
  52996. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52997. get: function () {
  52998. return this._dPadLeft;
  52999. },
  53000. set: function (value) {
  53001. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53002. },
  53003. enumerable: true,
  53004. configurable: true
  53005. });
  53006. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53007. get: function () {
  53008. return this._dPadRight;
  53009. },
  53010. set: function (value) {
  53011. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53012. },
  53013. enumerable: true,
  53014. configurable: true
  53015. });
  53016. Xbox360Pad.prototype.update = function () {
  53017. _super.prototype.update.call(this);
  53018. this.buttonA = this.browserGamepad.buttons[0].value;
  53019. this.buttonB = this.browserGamepad.buttons[1].value;
  53020. this.buttonX = this.browserGamepad.buttons[2].value;
  53021. this.buttonY = this.browserGamepad.buttons[3].value;
  53022. this.buttonLB = this.browserGamepad.buttons[4].value;
  53023. this.buttonRB = this.browserGamepad.buttons[5].value;
  53024. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53025. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53026. this.buttonBack = this.browserGamepad.buttons[8].value;
  53027. this.buttonStart = this.browserGamepad.buttons[9].value;
  53028. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53029. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53030. this.dPadUp = this.browserGamepad.buttons[12].value;
  53031. this.dPadDown = this.browserGamepad.buttons[13].value;
  53032. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53033. this.dPadRight = this.browserGamepad.buttons[15].value;
  53034. };
  53035. return Xbox360Pad;
  53036. }(Gamepad));
  53037. BABYLON.Xbox360Pad = Xbox360Pad;
  53038. })(BABYLON || (BABYLON = {}));
  53039. var BABYLON;
  53040. (function (BABYLON) {
  53041. // We're mainly based on the logic defined into the FreeCamera code
  53042. var GamepadCamera = (function (_super) {
  53043. __extends(GamepadCamera, _super);
  53044. //-- end properties for backward compatibility for inputs
  53045. function GamepadCamera(name, position, scene) {
  53046. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  53047. _super.call(this, name, position, scene);
  53048. }
  53049. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53050. //-- Begin properties for backward compatibility for inputs
  53051. get: function () {
  53052. var gamepad = this.inputs.attached["gamepad"];
  53053. if (gamepad)
  53054. return gamepad.gamepadAngularSensibility;
  53055. },
  53056. set: function (value) {
  53057. var gamepad = this.inputs.attached["gamepad"];
  53058. if (gamepad)
  53059. gamepad.gamepadAngularSensibility = value;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53065. get: function () {
  53066. var gamepad = this.inputs.attached["gamepad"];
  53067. if (gamepad)
  53068. return gamepad.gamepadMoveSensibility;
  53069. },
  53070. set: function (value) {
  53071. var gamepad = this.inputs.attached["gamepad"];
  53072. if (gamepad)
  53073. gamepad.gamepadMoveSensibility = value;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. GamepadCamera.prototype.getTypeName = function () {
  53079. return "GamepadCamera";
  53080. };
  53081. return GamepadCamera;
  53082. }(BABYLON.UniversalCamera));
  53083. BABYLON.GamepadCamera = GamepadCamera;
  53084. })(BABYLON || (BABYLON = {}));
  53085. var BABYLON;
  53086. (function (BABYLON) {
  53087. var Analyser = (function () {
  53088. function Analyser(scene) {
  53089. this.SMOOTHING = 0.75;
  53090. this.FFT_SIZE = 512;
  53091. this.BARGRAPHAMPLITUDE = 256;
  53092. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53093. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53094. this._scene = scene;
  53095. this._audioEngine = BABYLON.Engine.audioEngine;
  53096. if (this._audioEngine.canUseWebAudio) {
  53097. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53098. this._webAudioAnalyser.minDecibels = -140;
  53099. this._webAudioAnalyser.maxDecibels = 0;
  53100. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53101. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53102. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53103. }
  53104. }
  53105. Analyser.prototype.getFrequencyBinCount = function () {
  53106. if (this._audioEngine.canUseWebAudio) {
  53107. return this._webAudioAnalyser.frequencyBinCount;
  53108. }
  53109. else {
  53110. return 0;
  53111. }
  53112. };
  53113. Analyser.prototype.getByteFrequencyData = function () {
  53114. if (this._audioEngine.canUseWebAudio) {
  53115. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53116. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53117. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53118. }
  53119. return this._byteFreqs;
  53120. };
  53121. Analyser.prototype.getByteTimeDomainData = function () {
  53122. if (this._audioEngine.canUseWebAudio) {
  53123. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53124. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53125. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53126. }
  53127. return this._byteTime;
  53128. };
  53129. Analyser.prototype.getFloatFrequencyData = function () {
  53130. if (this._audioEngine.canUseWebAudio) {
  53131. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53132. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53133. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53134. }
  53135. return this._floatFreqs;
  53136. };
  53137. Analyser.prototype.drawDebugCanvas = function () {
  53138. var _this = this;
  53139. if (this._audioEngine.canUseWebAudio) {
  53140. if (!this._debugCanvas) {
  53141. this._debugCanvas = document.createElement("canvas");
  53142. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53143. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53144. this._debugCanvas.style.position = "absolute";
  53145. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53146. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53147. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53148. document.body.appendChild(this._debugCanvas);
  53149. this._registerFunc = function () {
  53150. _this.drawDebugCanvas();
  53151. };
  53152. this._scene.registerBeforeRender(this._registerFunc);
  53153. }
  53154. if (this._registerFunc) {
  53155. var workingArray = this.getByteFrequencyData();
  53156. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53157. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53158. // Draw the frequency domain chart.
  53159. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53160. var value = workingArray[i];
  53161. var percent = value / this.BARGRAPHAMPLITUDE;
  53162. var height = this.DEBUGCANVASSIZE.height * percent;
  53163. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53164. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53165. var hue = i / this.getFrequencyBinCount() * 360;
  53166. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53167. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53168. }
  53169. }
  53170. }
  53171. };
  53172. Analyser.prototype.stopDebugCanvas = function () {
  53173. if (this._debugCanvas) {
  53174. this._scene.unregisterBeforeRender(this._registerFunc);
  53175. this._registerFunc = null;
  53176. document.body.removeChild(this._debugCanvas);
  53177. this._debugCanvas = null;
  53178. this._debugCanvasContext = null;
  53179. }
  53180. };
  53181. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53182. if (this._audioEngine.canUseWebAudio) {
  53183. inputAudioNode.connect(this._webAudioAnalyser);
  53184. this._webAudioAnalyser.connect(outputAudioNode);
  53185. }
  53186. };
  53187. Analyser.prototype.dispose = function () {
  53188. if (this._audioEngine.canUseWebAudio) {
  53189. this._webAudioAnalyser.disconnect();
  53190. }
  53191. };
  53192. return Analyser;
  53193. }());
  53194. BABYLON.Analyser = Analyser;
  53195. })(BABYLON || (BABYLON = {}));
  53196. var BABYLON;
  53197. (function (BABYLON) {
  53198. var DepthRenderer = (function () {
  53199. function DepthRenderer(scene, type) {
  53200. var _this = this;
  53201. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53202. this._viewMatrix = BABYLON.Matrix.Zero();
  53203. this._projectionMatrix = BABYLON.Matrix.Zero();
  53204. this._transformMatrix = BABYLON.Matrix.Zero();
  53205. this._worldViewProjection = BABYLON.Matrix.Zero();
  53206. this._scene = scene;
  53207. var engine = scene.getEngine();
  53208. // Render target
  53209. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53210. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53211. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53212. this._depthMap.refreshRate = 1;
  53213. this._depthMap.renderParticles = false;
  53214. this._depthMap.renderList = null;
  53215. // set default depth value to 1.0 (far away)
  53216. this._depthMap.onClearObservable.add(function (engine) {
  53217. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  53218. });
  53219. // Custom render function
  53220. var renderSubMesh = function (subMesh) {
  53221. var mesh = subMesh.getRenderingMesh();
  53222. var scene = _this._scene;
  53223. var engine = scene.getEngine();
  53224. // Culling
  53225. engine.setState(subMesh.getMaterial().backFaceCulling);
  53226. // Managing instances
  53227. var batch = mesh._getInstancesRenderList(subMesh._id);
  53228. if (batch.mustReturn) {
  53229. return;
  53230. }
  53231. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53232. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53233. engine.enableEffect(_this._effect);
  53234. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53235. var material = subMesh.getMaterial();
  53236. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53237. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53238. // Alpha test
  53239. if (material && material.needAlphaTesting()) {
  53240. var alphaTexture = material.getAlphaTestTexture();
  53241. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53242. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53243. }
  53244. // Bones
  53245. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53246. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53247. }
  53248. // Draw
  53249. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53250. }
  53251. };
  53252. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53253. var index;
  53254. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53255. renderSubMesh(opaqueSubMeshes.data[index]);
  53256. }
  53257. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53258. renderSubMesh(alphaTestSubMeshes.data[index]);
  53259. }
  53260. };
  53261. }
  53262. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53263. var material = subMesh.getMaterial();
  53264. if (material.disableDepthWrite) {
  53265. return false;
  53266. }
  53267. var defines = [];
  53268. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53269. var mesh = subMesh.getMesh();
  53270. var scene = mesh.getScene();
  53271. // Alpha test
  53272. if (material && material.needAlphaTesting()) {
  53273. defines.push("#define ALPHATEST");
  53274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53275. attribs.push(BABYLON.VertexBuffer.UVKind);
  53276. defines.push("#define UV1");
  53277. }
  53278. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53279. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53280. defines.push("#define UV2");
  53281. }
  53282. }
  53283. // Bones
  53284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53287. if (mesh.numBoneInfluencers > 4) {
  53288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53290. }
  53291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53292. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53293. }
  53294. else {
  53295. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53296. }
  53297. // Instances
  53298. if (useInstances) {
  53299. defines.push("#define INSTANCES");
  53300. attribs.push("world0");
  53301. attribs.push("world1");
  53302. attribs.push("world2");
  53303. attribs.push("world3");
  53304. }
  53305. // Get correct effect
  53306. var join = defines.join("\n");
  53307. if (this._cachedDefines !== join) {
  53308. this._cachedDefines = join;
  53309. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53310. }
  53311. return this._effect.isReady();
  53312. };
  53313. DepthRenderer.prototype.getDepthMap = function () {
  53314. return this._depthMap;
  53315. };
  53316. // Methods
  53317. DepthRenderer.prototype.dispose = function () {
  53318. this._depthMap.dispose();
  53319. };
  53320. return DepthRenderer;
  53321. }());
  53322. BABYLON.DepthRenderer = DepthRenderer;
  53323. })(BABYLON || (BABYLON = {}));
  53324. var BABYLON;
  53325. (function (BABYLON) {
  53326. var SSAORenderingPipeline = (function (_super) {
  53327. __extends(SSAORenderingPipeline, _super);
  53328. /**
  53329. * @constructor
  53330. * @param {string} name - The rendering pipeline name
  53331. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53332. * @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 }
  53333. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53334. */
  53335. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53336. var _this = this;
  53337. _super.call(this, scene.getEngine(), name);
  53338. // Members
  53339. /**
  53340. * The PassPostProcess id in the pipeline that contains the original scene color
  53341. * @type {string}
  53342. */
  53343. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53344. /**
  53345. * The SSAO PostProcess id in the pipeline
  53346. * @type {string}
  53347. */
  53348. this.SSAORenderEffect = "SSAORenderEffect";
  53349. /**
  53350. * The horizontal blur PostProcess id in the pipeline
  53351. * @type {string}
  53352. */
  53353. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53354. /**
  53355. * The vertical blur PostProcess id in the pipeline
  53356. * @type {string}
  53357. */
  53358. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53359. /**
  53360. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53361. * @type {string}
  53362. */
  53363. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53364. /**
  53365. * The output strength of the SSAO post-process. Default value is 1.0.
  53366. * @type {number}
  53367. */
  53368. this.totalStrength = 1.0;
  53369. /**
  53370. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53371. * @type {number}
  53372. */
  53373. this.radius = 0.0001;
  53374. /**
  53375. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53376. * Must not be equal to fallOff and superior to fallOff.
  53377. * Default value is 0.975
  53378. * @type {number}
  53379. */
  53380. this.area = 0.0075;
  53381. /**
  53382. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53383. * Must not be equal to area and inferior to area.
  53384. * Default value is 0.0
  53385. * @type {number}
  53386. */
  53387. this.fallOff = 0.000001;
  53388. /**
  53389. * The base color of the SSAO post-process
  53390. * The final result is "base + ssao" between [0, 1]
  53391. * @type {number}
  53392. */
  53393. this.base = 0.5;
  53394. this._firstUpdate = true;
  53395. this._scene = scene;
  53396. // Set up assets
  53397. this._createRandomTexture();
  53398. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53399. var ssaoRatio = ratio.ssaoRatio || ratio;
  53400. var combineRatio = ratio.combineRatio || ratio;
  53401. this._ratio = {
  53402. ssaoRatio: ssaoRatio,
  53403. combineRatio: combineRatio
  53404. };
  53405. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53406. this._createSSAOPostProcess(ssaoRatio);
  53407. this._createBlurPostProcess(ssaoRatio);
  53408. this._createSSAOCombinePostProcess(combineRatio);
  53409. // Set up pipeline
  53410. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53413. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53415. // Finish
  53416. scene.postProcessRenderPipelineManager.addPipeline(this);
  53417. if (cameras)
  53418. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53419. }
  53420. // Public Methods
  53421. /**
  53422. * Returns the horizontal blur PostProcess
  53423. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  53424. */
  53425. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  53426. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  53427. return null;
  53428. };
  53429. /**
  53430. * Returns the vertical blur PostProcess
  53431. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  53432. */
  53433. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  53434. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  53435. return null;
  53436. };
  53437. /**
  53438. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53439. */
  53440. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53441. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53442. for (var i = 0; i < this._scene.cameras.length; i++) {
  53443. var camera = this._scene.cameras[i];
  53444. this._originalColorPostProcess.dispose(camera);
  53445. this._ssaoPostProcess.dispose(camera);
  53446. this._blurHPostProcess.dispose(camera);
  53447. this._blurVPostProcess.dispose(camera);
  53448. this._ssaoCombinePostProcess.dispose(camera);
  53449. }
  53450. this._randomTexture.dispose();
  53451. if (disableDepthRender)
  53452. this._scene.disableDepthRenderer();
  53453. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53454. };
  53455. // Private Methods
  53456. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53457. var _this = this;
  53458. /*
  53459. var samplerOffsets = [
  53460. -8.0, -6.0, -4.0, -2.0,
  53461. 0.0,
  53462. 2.0, 4.0, 6.0, 8.0
  53463. ];
  53464. */
  53465. var samples = 16;
  53466. var samplerOffsets = [];
  53467. for (var i = -8; i < 8; i++) {
  53468. samplerOffsets.push(i * 2);
  53469. }
  53470. 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");
  53471. this._blurHPostProcess.onApply = function (effect) {
  53472. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53473. effect.setTexture("depthSampler", _this._depthTexture);
  53474. if (_this._firstUpdate) {
  53475. effect.setArray("samplerOffsets", samplerOffsets);
  53476. }
  53477. };
  53478. 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");
  53479. this._blurVPostProcess.onApply = function (effect) {
  53480. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53481. effect.setTexture("depthSampler", _this._depthTexture);
  53482. if (_this._firstUpdate) {
  53483. effect.setArray("samplerOffsets", samplerOffsets);
  53484. _this._firstUpdate = false;
  53485. }
  53486. };
  53487. };
  53488. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53489. var _this = this;
  53490. var numSamples = 16;
  53491. var sampleSphere = [
  53492. 0.5381, 0.1856, -0.4319,
  53493. 0.1379, 0.2486, 0.4430,
  53494. 0.3371, 0.5679, -0.0057,
  53495. -0.6999, -0.0451, -0.0019,
  53496. 0.0689, -0.1598, -0.8547,
  53497. 0.0560, 0.0069, -0.1843,
  53498. -0.0146, 0.1402, 0.0762,
  53499. 0.0100, -0.1924, -0.0344,
  53500. -0.3577, -0.5301, -0.4358,
  53501. -0.3169, 0.1063, 0.0158,
  53502. 0.0103, -0.5869, 0.0046,
  53503. -0.0897, -0.4940, 0.3287,
  53504. 0.7119, -0.0154, -0.0918,
  53505. -0.0533, 0.0596, -0.5411,
  53506. 0.0352, -0.0631, 0.5460,
  53507. -0.4776, 0.2847, -0.0271
  53508. ];
  53509. var samplesFactor = 1.0 / numSamples;
  53510. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53511. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53512. "area", "fallOff", "base", "range", "viewport"
  53513. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53514. var viewport = new BABYLON.Vector2(0, 0);
  53515. this._ssaoPostProcess.onApply = function (effect) {
  53516. if (_this._firstUpdate) {
  53517. effect.setArray3("sampleSphere", sampleSphere);
  53518. effect.setFloat("samplesFactor", samplesFactor);
  53519. effect.setFloat("randTextureTiles", 4.0);
  53520. }
  53521. effect.setFloat("totalStrength", _this.totalStrength);
  53522. effect.setFloat("radius", _this.radius);
  53523. effect.setFloat("area", _this.area);
  53524. effect.setFloat("fallOff", _this.fallOff);
  53525. effect.setFloat("base", _this.base);
  53526. effect.setTexture("textureSampler", _this._depthTexture);
  53527. effect.setTexture("randomSampler", _this._randomTexture);
  53528. };
  53529. };
  53530. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53531. var _this = this;
  53532. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53533. this._ssaoCombinePostProcess.onApply = function (effect) {
  53534. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53535. };
  53536. };
  53537. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53538. var size = 512;
  53539. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53540. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53541. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53542. var context = this._randomTexture.getContext();
  53543. var rand = function (min, max) {
  53544. return Math.random() * (max - min) + min;
  53545. };
  53546. var randVector = BABYLON.Vector3.Zero();
  53547. for (var x = 0; x < size; x++) {
  53548. for (var y = 0; y < size; y++) {
  53549. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53550. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53551. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53552. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53553. context.fillRect(x, y, 1, 1);
  53554. }
  53555. }
  53556. this._randomTexture.update(false);
  53557. };
  53558. __decorate([
  53559. BABYLON.serialize()
  53560. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53561. __decorate([
  53562. BABYLON.serialize()
  53563. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53564. __decorate([
  53565. BABYLON.serialize()
  53566. ], SSAORenderingPipeline.prototype, "area", void 0);
  53567. __decorate([
  53568. BABYLON.serialize()
  53569. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53570. __decorate([
  53571. BABYLON.serialize()
  53572. ], SSAORenderingPipeline.prototype, "base", void 0);
  53573. __decorate([
  53574. BABYLON.serialize()
  53575. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53576. return SSAORenderingPipeline;
  53577. }(BABYLON.PostProcessRenderPipeline));
  53578. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53579. })(BABYLON || (BABYLON = {}));
  53580. var BABYLON;
  53581. (function (BABYLON) {
  53582. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53583. var VolumetricLightScatteringPostProcess = (function (_super) {
  53584. __extends(VolumetricLightScatteringPostProcess, _super);
  53585. /**
  53586. * @constructor
  53587. * @param {string} name - The post-process name
  53588. * @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)
  53589. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53590. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53591. * @param {number} samples - The post-process quality, default 100
  53592. * @param {number} samplingMode - The post-process filtering mode
  53593. * @param {BABYLON.Engine} engine - The babylon engine
  53594. * @param {boolean} reusable - If the post-process is reusable
  53595. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53596. */
  53597. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53598. var _this = this;
  53599. if (samples === void 0) { samples = 100; }
  53600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53601. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  53602. this._screenCoordinates = BABYLON.Vector2.Zero();
  53603. /**
  53604. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53605. * @type {Vector3}
  53606. */
  53607. this.customMeshPosition = BABYLON.Vector3.Zero();
  53608. /**
  53609. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53610. * @type {boolean}
  53611. */
  53612. this.useCustomMeshPosition = false;
  53613. /**
  53614. * If the post-process should inverse the light scattering direction
  53615. * @type {boolean}
  53616. */
  53617. this.invert = true;
  53618. /**
  53619. * Array containing the excluded meshes not rendered in the internal pass
  53620. */
  53621. this.excludedMeshes = new Array();
  53622. /**
  53623. * Controls the overall intensity of the post-process
  53624. * @type {number}
  53625. */
  53626. this.exposure = 0.3;
  53627. /**
  53628. * Dissipates each sample's contribution in range [0, 1]
  53629. * @type {number}
  53630. */
  53631. this.decay = 0.96815;
  53632. /**
  53633. * Controls the overall intensity of each sample
  53634. * @type {number}
  53635. */
  53636. this.weight = 0.58767;
  53637. /**
  53638. * Controls the density of each sample
  53639. * @type {number}
  53640. */
  53641. this.density = 0.926;
  53642. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53643. var engine = scene.getEngine();
  53644. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53645. // Configure mesh
  53646. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53647. // Configure
  53648. this._createPass(scene, ratio.passRatio || ratio);
  53649. this.onActivate = function (camera) {
  53650. if (!_this.isSupported) {
  53651. _this.dispose(camera);
  53652. }
  53653. _this.onActivate = null;
  53654. };
  53655. this.onApplyObservable.add(function (effect) {
  53656. _this._updateMeshScreenCoordinates(scene);
  53657. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53658. effect.setFloat("exposure", _this.exposure);
  53659. effect.setFloat("decay", _this.decay);
  53660. effect.setFloat("weight", _this.weight);
  53661. effect.setFloat("density", _this.density);
  53662. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53663. });
  53664. }
  53665. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53666. get: function () {
  53667. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53668. return false;
  53669. },
  53670. set: function (useDiffuseColor) {
  53671. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53672. },
  53673. enumerable: true,
  53674. configurable: true
  53675. });
  53676. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53677. var mesh = subMesh.getMesh();
  53678. // Render this.mesh as default
  53679. if (mesh === this.mesh) {
  53680. return mesh.material.isReady(mesh);
  53681. }
  53682. var defines = [];
  53683. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53684. var material = subMesh.getMaterial();
  53685. var needUV = false;
  53686. // Alpha test
  53687. if (material) {
  53688. if (material.needAlphaTesting()) {
  53689. defines.push("#define ALPHATEST");
  53690. }
  53691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53692. attribs.push(BABYLON.VertexBuffer.UVKind);
  53693. defines.push("#define UV1");
  53694. }
  53695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53696. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53697. defines.push("#define UV2");
  53698. }
  53699. }
  53700. // Bones
  53701. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53704. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53705. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53706. }
  53707. else {
  53708. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53709. }
  53710. // Instances
  53711. if (useInstances) {
  53712. defines.push("#define INSTANCES");
  53713. attribs.push("world0");
  53714. attribs.push("world1");
  53715. attribs.push("world2");
  53716. attribs.push("world3");
  53717. }
  53718. // Get correct effect
  53719. var join = defines.join("\n");
  53720. if (this._cachedDefines !== join) {
  53721. this._cachedDefines = join;
  53722. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53723. }
  53724. return this._volumetricLightScatteringPass.isReady();
  53725. };
  53726. /**
  53727. * Sets the new light position for light scattering effect
  53728. * @param {BABYLON.Vector3} The new custom light position
  53729. */
  53730. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53731. this.customMeshPosition = position;
  53732. };
  53733. /**
  53734. * Returns the light position for light scattering effect
  53735. * @return {BABYLON.Vector3} The custom light position
  53736. */
  53737. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53738. return this.customMeshPosition;
  53739. };
  53740. /**
  53741. * Disposes the internal assets and detaches the post-process from the camera
  53742. */
  53743. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53744. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53745. if (rttIndex !== -1) {
  53746. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53747. }
  53748. this._volumetricLightScatteringRTT.dispose();
  53749. _super.prototype.dispose.call(this, camera);
  53750. };
  53751. /**
  53752. * Returns the render target texture used by the post-process
  53753. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53754. */
  53755. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53756. return this._volumetricLightScatteringRTT;
  53757. };
  53758. // Private methods
  53759. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53760. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53761. return true;
  53762. }
  53763. return false;
  53764. };
  53765. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53766. var _this = this;
  53767. var engine = scene.getEngine();
  53768. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53769. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53770. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53771. this._volumetricLightScatteringRTT.renderList = null;
  53772. this._volumetricLightScatteringRTT.renderParticles = false;
  53773. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53774. // Custom render function for submeshes
  53775. var renderSubMesh = function (subMesh) {
  53776. var mesh = subMesh.getRenderingMesh();
  53777. if (_this._meshExcluded(mesh)) {
  53778. return;
  53779. }
  53780. var scene = mesh.getScene();
  53781. var engine = scene.getEngine();
  53782. // Culling
  53783. engine.setState(subMesh.getMaterial().backFaceCulling);
  53784. // Managing instances
  53785. var batch = mesh._getInstancesRenderList(subMesh._id);
  53786. if (batch.mustReturn) {
  53787. return;
  53788. }
  53789. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53790. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53791. var effect = _this._volumetricLightScatteringPass;
  53792. if (mesh === _this.mesh) {
  53793. effect = subMesh.getMaterial().getEffect();
  53794. }
  53795. engine.enableEffect(effect);
  53796. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53797. if (mesh === _this.mesh) {
  53798. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53799. }
  53800. else {
  53801. var material = subMesh.getMaterial();
  53802. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53803. // Alpha test
  53804. if (material && material.needAlphaTesting()) {
  53805. var alphaTexture = material.getAlphaTestTexture();
  53806. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53807. if (alphaTexture) {
  53808. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53809. }
  53810. }
  53811. // Bones
  53812. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53813. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53814. }
  53815. }
  53816. // Draw
  53817. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53818. }
  53819. };
  53820. // Render target texture callbacks
  53821. var savedSceneClearColor;
  53822. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53823. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53824. savedSceneClearColor = scene.clearColor;
  53825. scene.clearColor = sceneClearColor;
  53826. });
  53827. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53828. scene.clearColor = savedSceneClearColor;
  53829. });
  53830. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53831. var engine = scene.getEngine();
  53832. var index;
  53833. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53834. renderSubMesh(opaqueSubMeshes.data[index]);
  53835. }
  53836. engine.setAlphaTesting(true);
  53837. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53838. renderSubMesh(alphaTestSubMeshes.data[index]);
  53839. }
  53840. engine.setAlphaTesting(false);
  53841. if (transparentSubMeshes.length) {
  53842. // Sort sub meshes
  53843. for (index = 0; index < transparentSubMeshes.length; index++) {
  53844. var submesh = transparentSubMeshes.data[index];
  53845. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53846. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53847. }
  53848. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53849. sortedArray.sort(function (a, b) {
  53850. // Alpha index first
  53851. if (a._alphaIndex > b._alphaIndex) {
  53852. return 1;
  53853. }
  53854. if (a._alphaIndex < b._alphaIndex) {
  53855. return -1;
  53856. }
  53857. // Then distance to camera
  53858. if (a._distanceToCamera < b._distanceToCamera) {
  53859. return 1;
  53860. }
  53861. if (a._distanceToCamera > b._distanceToCamera) {
  53862. return -1;
  53863. }
  53864. return 0;
  53865. });
  53866. // Render sub meshes
  53867. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53868. for (index = 0; index < sortedArray.length; index++) {
  53869. renderSubMesh(sortedArray[index]);
  53870. }
  53871. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53872. }
  53873. };
  53874. };
  53875. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53876. var transform = scene.getTransformMatrix();
  53877. var meshPosition;
  53878. if (this.useCustomMeshPosition) {
  53879. meshPosition = this.customMeshPosition;
  53880. }
  53881. else if (this.attachedNode) {
  53882. meshPosition = this.attachedNode.position;
  53883. }
  53884. else {
  53885. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53886. }
  53887. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53888. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53889. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53890. if (this.invert)
  53891. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53892. };
  53893. // Static methods
  53894. /**
  53895. * Creates a default mesh for the Volumeric Light Scattering post-process
  53896. * @param {string} The mesh name
  53897. * @param {BABYLON.Scene} The scene where to create the mesh
  53898. * @return {BABYLON.Mesh} the default mesh
  53899. */
  53900. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53901. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53902. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53903. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53904. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53905. mesh.material = material;
  53906. return mesh;
  53907. };
  53908. __decorate([
  53909. BABYLON.serializeAsVector3()
  53910. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53911. __decorate([
  53912. BABYLON.serialize()
  53913. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53914. __decorate([
  53915. BABYLON.serialize()
  53916. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53917. __decorate([
  53918. BABYLON.serializeAsMeshReference()
  53919. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53920. __decorate([
  53921. BABYLON.serialize()
  53922. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53923. __decorate([
  53924. BABYLON.serialize()
  53925. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53926. __decorate([
  53927. BABYLON.serialize()
  53928. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53929. __decorate([
  53930. BABYLON.serialize()
  53931. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53932. __decorate([
  53933. BABYLON.serialize()
  53934. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53935. return VolumetricLightScatteringPostProcess;
  53936. }(BABYLON.PostProcess));
  53937. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53938. })(BABYLON || (BABYLON = {}));
  53939. // BABYLON.JS Chromatic Aberration GLSL Shader
  53940. // Author: Olivier Guyot
  53941. // Separates very slightly R, G and B colors on the edges of the screen
  53942. // Inspired by Francois Tarlier & Martins Upitis
  53943. var BABYLON;
  53944. (function (BABYLON) {
  53945. var LensRenderingPipeline = (function (_super) {
  53946. __extends(LensRenderingPipeline, _super);
  53947. /**
  53948. * @constructor
  53949. *
  53950. * Effect parameters are as follow:
  53951. * {
  53952. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53953. * edge_blur: number; // from 0 to x (1 for realism)
  53954. * distortion: number; // from 0 to x (1 for realism)
  53955. * grain_amount: number; // from 0 to 1
  53956. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53957. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53958. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53959. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53960. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53961. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53962. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53963. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53964. * }
  53965. * Note: if an effect parameter is unset, effect is disabled
  53966. *
  53967. * @param {string} name - The rendering pipeline name
  53968. * @param {object} parameters - An object containing all parameters (see above)
  53969. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53970. * @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)
  53971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53972. */
  53973. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53974. var _this = this;
  53975. if (ratio === void 0) { ratio = 1.0; }
  53976. _super.call(this, scene.getEngine(), name);
  53977. // Lens effects can be of the following:
  53978. // - chromatic aberration (slight shift of RGB colors)
  53979. // - blur on the edge of the lens
  53980. // - lens distortion
  53981. // - depth-of-field blur & highlights enhancing
  53982. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53983. // - grain effect (noise or custom texture)
  53984. // Two additional texture samplers are needed:
  53985. // - depth map (for depth-of-field)
  53986. // - grain texture
  53987. /**
  53988. * The chromatic aberration PostProcess id in the pipeline
  53989. * @type {string}
  53990. */
  53991. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53992. /**
  53993. * The highlights enhancing PostProcess id in the pipeline
  53994. * @type {string}
  53995. */
  53996. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53997. /**
  53998. * The depth-of-field PostProcess id in the pipeline
  53999. * @type {string}
  54000. */
  54001. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54002. this._scene = scene;
  54003. // Fetch texture samplers
  54004. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54005. if (parameters.grain_texture) {
  54006. this._grainTexture = parameters.grain_texture;
  54007. }
  54008. else {
  54009. this._createGrainTexture();
  54010. }
  54011. // save parameters
  54012. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54013. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54014. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54015. this._distortion = parameters.distortion ? parameters.distortion : 0;
  54016. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54017. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54018. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54019. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54020. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54021. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54022. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54023. // Create effects
  54024. this._createChromaticAberrationPostProcess(ratio);
  54025. this._createHighlightsPostProcess(ratio);
  54026. this._createDepthOfFieldPostProcess(ratio / 4);
  54027. // Set up pipeline
  54028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54031. if (this._highlightsGain === -1) {
  54032. this._disableEffect(this.HighlightsEnhancingEffect, null);
  54033. }
  54034. // Finish
  54035. scene.postProcessRenderPipelineManager.addPipeline(this);
  54036. if (cameras) {
  54037. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54038. }
  54039. }
  54040. // public methods (self explanatory)
  54041. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54042. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54043. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54044. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54045. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54046. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54047. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54048. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54049. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54050. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54051. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54052. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54053. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54054. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54055. };
  54056. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54057. this._highlightsPostProcess.updateEffect();
  54058. };
  54059. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54060. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54061. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54062. this._highlightsGain = amount;
  54063. };
  54064. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54065. if (this._highlightsGain === -1) {
  54066. this._highlightsGain = 1.0;
  54067. }
  54068. this._highlightsThreshold = amount;
  54069. };
  54070. LensRenderingPipeline.prototype.disableHighlights = function () {
  54071. this._highlightsGain = -1;
  54072. };
  54073. /**
  54074. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54075. */
  54076. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54077. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54078. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54079. this._chromaticAberrationPostProcess = undefined;
  54080. this._highlightsPostProcess = undefined;
  54081. this._depthOfFieldPostProcess = undefined;
  54082. this._grainTexture.dispose();
  54083. if (disableDepthRender)
  54084. this._scene.disableDepthRenderer();
  54085. };
  54086. // colors shifting and distortion
  54087. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54088. var _this = this;
  54089. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54090. [], // samplers
  54091. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54092. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54093. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54094. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54095. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54096. };
  54097. };
  54098. // highlights enhancing
  54099. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54100. var _this = this;
  54101. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54102. [], // samplers
  54103. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54104. this._highlightsPostProcess.onApply = function (effect) {
  54105. effect.setFloat('gain', _this._highlightsGain);
  54106. effect.setFloat('threshold', _this._highlightsThreshold);
  54107. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54108. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54109. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54110. };
  54111. };
  54112. // colors shifting and distortion
  54113. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54114. var _this = this;
  54115. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54116. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54117. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54118. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54119. this._depthOfFieldPostProcess.onApply = function (effect) {
  54120. effect.setTexture("depthSampler", _this._depthTexture);
  54121. effect.setTexture("grainSampler", _this._grainTexture);
  54122. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54123. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54124. effect.setFloat('grain_amount', _this._grainAmount);
  54125. effect.setBool('blur_noise', _this._blurNoise);
  54126. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54127. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54128. effect.setFloat('distortion', _this._distortion);
  54129. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54130. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54131. effect.setFloat('aperture', _this._dofAperture);
  54132. effect.setFloat('darken', _this._dofDarken);
  54133. effect.setFloat('edge_blur', _this._edgeBlur);
  54134. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54135. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54136. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54137. };
  54138. };
  54139. // creates a black and white random noise texture, 512x512
  54140. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54141. var size = 512;
  54142. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54143. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54144. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54145. var context = this._grainTexture.getContext();
  54146. var rand = function (min, max) {
  54147. return Math.random() * (max - min) + min;
  54148. };
  54149. var value;
  54150. for (var x = 0; x < size; x++) {
  54151. for (var y = 0; y < size; y++) {
  54152. value = Math.floor(rand(0.42, 0.58) * 255);
  54153. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54154. context.fillRect(x, y, 1, 1);
  54155. }
  54156. }
  54157. this._grainTexture.update(false);
  54158. };
  54159. return LensRenderingPipeline;
  54160. }(BABYLON.PostProcessRenderPipeline));
  54161. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54162. })(BABYLON || (BABYLON = {}));
  54163. //
  54164. // This post-process allows the modification of rendered colors by using
  54165. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54166. //
  54167. // The object needs to be provided an url to a texture containing the color
  54168. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54169. // Use an image editing software to tweak the LUT to match your needs.
  54170. //
  54171. // For an example of a color LUT, see here:
  54172. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54173. // For explanations on color grading, see here:
  54174. // http://udn.epicgames.com/Three/ColorGrading.html
  54175. //
  54176. var BABYLON;
  54177. (function (BABYLON) {
  54178. var ColorCorrectionPostProcess = (function (_super) {
  54179. __extends(ColorCorrectionPostProcess, _super);
  54180. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54181. var _this = this;
  54182. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  54183. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54184. this._colorTableTexture.anisotropicFilteringLevel = 1;
  54185. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54186. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54187. this.onApply = function (effect) {
  54188. effect.setTexture("colorTable", _this._colorTableTexture);
  54189. };
  54190. }
  54191. return ColorCorrectionPostProcess;
  54192. }(BABYLON.PostProcess));
  54193. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54194. })(BABYLON || (BABYLON = {}));
  54195. var BABYLON;
  54196. (function (BABYLON) {
  54197. var AnaglyphFreeCamera = (function (_super) {
  54198. __extends(AnaglyphFreeCamera, _super);
  54199. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54200. _super.call(this, name, position, scene);
  54201. this.interaxialDistance = interaxialDistance;
  54202. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54203. }
  54204. AnaglyphFreeCamera.prototype.getTypeName = function () {
  54205. return "AnaglyphFreeCamera";
  54206. };
  54207. return AnaglyphFreeCamera;
  54208. }(BABYLON.FreeCamera));
  54209. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54210. var AnaglyphArcRotateCamera = (function (_super) {
  54211. __extends(AnaglyphArcRotateCamera, _super);
  54212. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54213. _super.call(this, name, alpha, beta, radius, target, scene);
  54214. this.interaxialDistance = interaxialDistance;
  54215. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54216. }
  54217. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  54218. return "AnaglyphArcRotateCamera";
  54219. };
  54220. return AnaglyphArcRotateCamera;
  54221. }(BABYLON.ArcRotateCamera));
  54222. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54223. var AnaglyphGamepadCamera = (function (_super) {
  54224. __extends(AnaglyphGamepadCamera, _super);
  54225. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54226. _super.call(this, name, position, scene);
  54227. this.interaxialDistance = interaxialDistance;
  54228. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54229. }
  54230. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  54231. return "AnaglyphGamepadCamera";
  54232. };
  54233. return AnaglyphGamepadCamera;
  54234. }(BABYLON.GamepadCamera));
  54235. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54236. var AnaglyphUniversalCamera = (function (_super) {
  54237. __extends(AnaglyphUniversalCamera, _super);
  54238. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54239. _super.call(this, name, position, scene);
  54240. this.interaxialDistance = interaxialDistance;
  54241. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54242. }
  54243. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  54244. return "AnaglyphUniversalCamera";
  54245. };
  54246. return AnaglyphUniversalCamera;
  54247. }(BABYLON.UniversalCamera));
  54248. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54249. var StereoscopicFreeCamera = (function (_super) {
  54250. __extends(StereoscopicFreeCamera, _super);
  54251. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54252. _super.call(this, name, position, scene);
  54253. this.interaxialDistance = interaxialDistance;
  54254. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54255. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54256. }
  54257. StereoscopicFreeCamera.prototype.getTypeName = function () {
  54258. return "StereoscopicFreeCamera";
  54259. };
  54260. return StereoscopicFreeCamera;
  54261. }(BABYLON.FreeCamera));
  54262. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54263. var StereoscopicArcRotateCamera = (function (_super) {
  54264. __extends(StereoscopicArcRotateCamera, _super);
  54265. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54266. _super.call(this, name, alpha, beta, radius, target, scene);
  54267. this.interaxialDistance = interaxialDistance;
  54268. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54269. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54270. }
  54271. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  54272. return "StereoscopicArcRotateCamera";
  54273. };
  54274. return StereoscopicArcRotateCamera;
  54275. }(BABYLON.ArcRotateCamera));
  54276. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54277. var StereoscopicGamepadCamera = (function (_super) {
  54278. __extends(StereoscopicGamepadCamera, _super);
  54279. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54280. _super.call(this, name, position, scene);
  54281. this.interaxialDistance = interaxialDistance;
  54282. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54283. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54284. }
  54285. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  54286. return "StereoscopicGamepadCamera";
  54287. };
  54288. return StereoscopicGamepadCamera;
  54289. }(BABYLON.GamepadCamera));
  54290. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54291. var StereoscopicUniversalCamera = (function (_super) {
  54292. __extends(StereoscopicUniversalCamera, _super);
  54293. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54294. _super.call(this, name, position, scene);
  54295. this.interaxialDistance = interaxialDistance;
  54296. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54297. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54298. }
  54299. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  54300. return "StereoscopicUniversalCamera";
  54301. };
  54302. return StereoscopicUniversalCamera;
  54303. }(BABYLON.UniversalCamera));
  54304. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54305. })(BABYLON || (BABYLON = {}));
  54306. var BABYLON;
  54307. (function (BABYLON) {
  54308. var HDRRenderingPipeline = (function (_super) {
  54309. __extends(HDRRenderingPipeline, _super);
  54310. /**
  54311. * @constructor
  54312. * @param {string} name - The rendering pipeline name
  54313. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54314. * @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)
  54315. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54316. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54317. */
  54318. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54319. var _this = this;
  54320. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54321. _super.call(this, scene.getEngine(), name);
  54322. /**
  54323. * Public members
  54324. */
  54325. // Gaussian Blur
  54326. /**
  54327. * Gaussian blur coefficient
  54328. * @type {number}
  54329. */
  54330. this.gaussCoeff = 0.3;
  54331. /**
  54332. * Gaussian blur mean
  54333. * @type {number}
  54334. */
  54335. this.gaussMean = 1.0;
  54336. /**
  54337. * Gaussian blur standard deviation
  54338. * @type {number}
  54339. */
  54340. this.gaussStandDev = 0.8;
  54341. /**
  54342. * Gaussian blur multiplier. Multiplies the blur effect
  54343. * @type {number}
  54344. */
  54345. this.gaussMultiplier = 4.0;
  54346. // HDR
  54347. /**
  54348. * Exposure, controls the overall intensity of the pipeline
  54349. * @type {number}
  54350. */
  54351. this.exposure = 1.0;
  54352. /**
  54353. * Minimum luminance that the post-process can output. Luminance is >= 0
  54354. * @type {number}
  54355. */
  54356. this.minimumLuminance = 1.0;
  54357. /**
  54358. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54359. * @type {number}
  54360. */
  54361. this.maximumLuminance = 1e20;
  54362. /**
  54363. * Increase rate for luminance: eye adaptation speed to dark
  54364. * @type {number}
  54365. */
  54366. this.luminanceIncreaserate = 0.5;
  54367. /**
  54368. * Decrease rate for luminance: eye adaptation speed to bright
  54369. * @type {number}
  54370. */
  54371. this.luminanceDecreaseRate = 0.5;
  54372. // Bright pass
  54373. /**
  54374. * Minimum luminance needed to compute HDR
  54375. * @type {number}
  54376. */
  54377. this.brightThreshold = 0.8;
  54378. this._needUpdate = true;
  54379. this._scene = scene;
  54380. // Bright pass
  54381. this._createBrightPassPostProcess(scene, ratio);
  54382. // Down sample X4
  54383. this._createDownSampleX4PostProcess(scene, ratio);
  54384. // Create gaussian blur post-processes
  54385. this._createGaussianBlurPostProcess(scene, ratio);
  54386. // Texture adder
  54387. this._createTextureAdderPostProcess(scene, ratio);
  54388. // Luminance generator
  54389. this._createLuminanceGeneratorPostProcess(scene);
  54390. // HDR
  54391. this._createHDRPostProcess(scene, ratio);
  54392. // Pass postprocess
  54393. if (originalPostProcess === null) {
  54394. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54395. }
  54396. else {
  54397. this._originalPostProcess = originalPostProcess;
  54398. }
  54399. // Configure pipeline
  54400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54404. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54406. var addDownSamplerPostProcess = function (id) {
  54407. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54408. };
  54409. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54410. addDownSamplerPostProcess(i);
  54411. }
  54412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54413. // Finish
  54414. scene.postProcessRenderPipelineManager.addPipeline(this);
  54415. if (cameras !== null) {
  54416. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54417. }
  54418. this.update();
  54419. }
  54420. /**
  54421. * Tells the pipeline to update its post-processes
  54422. */
  54423. HDRRenderingPipeline.prototype.update = function () {
  54424. this._needUpdate = true;
  54425. };
  54426. /**
  54427. * Returns the current calculated luminance
  54428. */
  54429. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54430. return this._hdrCurrentLuminance;
  54431. };
  54432. /**
  54433. * Returns the currently drawn luminance
  54434. */
  54435. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54436. return this._hdrOutputLuminance;
  54437. };
  54438. /**
  54439. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54440. */
  54441. HDRRenderingPipeline.prototype.dispose = function () {
  54442. this._originalPostProcess = undefined;
  54443. this._brightPassPostProcess = undefined;
  54444. this._downSampleX4PostProcess = undefined;
  54445. this._guassianBlurHPostProcess = undefined;
  54446. this._guassianBlurVPostProcess = undefined;
  54447. this._textureAdderPostProcess = undefined;
  54448. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54449. this._downSamplePostProcesses[i] = undefined;
  54450. }
  54451. this._hdrPostProcess = undefined;
  54452. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54453. };
  54454. /**
  54455. * Creates the HDR post-process and computes the luminance adaptation
  54456. */
  54457. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54458. var _this = this;
  54459. var hdrLastLuminance = 0.0;
  54460. this._hdrOutputLuminance = -1.0;
  54461. this._hdrCurrentLuminance = 1.0;
  54462. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54463. this._hdrPostProcess.onApply = function (effect) {
  54464. if (_this._hdrOutputLuminance < 0.0) {
  54465. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54466. }
  54467. else {
  54468. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54469. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54470. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54471. }
  54472. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54473. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54474. }
  54475. else {
  54476. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54477. }
  54478. }
  54479. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54480. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54481. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54482. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54483. effect.setFloat("exposure", _this.exposure);
  54484. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54485. _this._needUpdate = false;
  54486. };
  54487. };
  54488. /**
  54489. * Texture Adder post-process
  54490. */
  54491. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54492. var _this = this;
  54493. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54494. this._textureAdderPostProcess.onApply = function (effect) {
  54495. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54496. };
  54497. };
  54498. /**
  54499. * Down sample X4 post-process
  54500. */
  54501. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54502. var _this = this;
  54503. var downSampleX4Offsets = new Array(32);
  54504. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54505. this._downSampleX4PostProcess.onApply = function (effect) {
  54506. if (_this._needUpdate) {
  54507. var id = 0;
  54508. for (var i = -2; i < 2; i++) {
  54509. for (var j = -2; j < 2; j++) {
  54510. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54511. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54512. id += 2;
  54513. }
  54514. }
  54515. }
  54516. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54517. };
  54518. };
  54519. /**
  54520. * Bright pass post-process
  54521. */
  54522. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54523. var _this = this;
  54524. var brightOffsets = new Array(8);
  54525. var brightPassCallback = function (effect) {
  54526. if (_this._needUpdate) {
  54527. var sU = (1.0 / _this._brightPassPostProcess.width);
  54528. var sV = (1.0 / _this._brightPassPostProcess.height);
  54529. brightOffsets[0] = -0.5 * sU;
  54530. brightOffsets[1] = 0.5 * sV;
  54531. brightOffsets[2] = 0.5 * sU;
  54532. brightOffsets[3] = 0.5 * sV;
  54533. brightOffsets[4] = -0.5 * sU;
  54534. brightOffsets[5] = -0.5 * sV;
  54535. brightOffsets[6] = 0.5 * sU;
  54536. brightOffsets[7] = -0.5 * sV;
  54537. }
  54538. effect.setArray2("dsOffsets", brightOffsets);
  54539. effect.setFloat("brightThreshold", _this.brightThreshold);
  54540. };
  54541. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54542. this._brightPassPostProcess.onApply = brightPassCallback;
  54543. };
  54544. /**
  54545. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54546. */
  54547. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54548. var _this = this;
  54549. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54550. var luminanceOffsets = new Array(8);
  54551. var downSampleOffsets = new Array(18);
  54552. var halfDestPixelSize;
  54553. this._downSamplePostProcesses = new Array(lumSteps);
  54554. // Utils for luminance
  54555. var luminanceUpdateSourceOffsets = function (width, height) {
  54556. var sU = (1.0 / width);
  54557. var sV = (1.0 / height);
  54558. luminanceOffsets[0] = -0.5 * sU;
  54559. luminanceOffsets[1] = 0.5 * sV;
  54560. luminanceOffsets[2] = 0.5 * sU;
  54561. luminanceOffsets[3] = 0.5 * sV;
  54562. luminanceOffsets[4] = -0.5 * sU;
  54563. luminanceOffsets[5] = -0.5 * sV;
  54564. luminanceOffsets[6] = 0.5 * sU;
  54565. luminanceOffsets[7] = -0.5 * sV;
  54566. };
  54567. var luminanceUpdateDestOffsets = function (width, height) {
  54568. var id = 0;
  54569. for (var x = -1; x < 2; x++) {
  54570. for (var y = -1; y < 2; y++) {
  54571. downSampleOffsets[id] = (x) / width;
  54572. downSampleOffsets[id + 1] = (y) / height;
  54573. id += 2;
  54574. }
  54575. }
  54576. };
  54577. // Luminance callback
  54578. var luminanceCallback = function (effect) {
  54579. if (_this._needUpdate) {
  54580. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54581. }
  54582. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54583. effect.setArray2("lumOffsets", luminanceOffsets);
  54584. };
  54585. // Down sample callbacks
  54586. var downSampleCallback = function (indice) {
  54587. var i = indice;
  54588. return function (effect) {
  54589. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54590. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54591. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54592. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54593. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54594. effect.setArray2("dsOffsets", downSampleOffsets);
  54595. };
  54596. };
  54597. var downSampleAfterRenderCallback = function (effect) {
  54598. // Unpack result
  54599. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54600. 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);
  54601. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54602. };
  54603. // Create luminance post-process
  54604. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54605. 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);
  54606. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54607. // Create down sample post-processes
  54608. for (var i = lumSteps - 2; i >= 0; i--) {
  54609. var length = Math.pow(3, i);
  54610. ratio = { width: length, height: length };
  54611. var defines = "#define DOWN_SAMPLE\n";
  54612. if (i === 0) {
  54613. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54614. }
  54615. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54616. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54617. if (i === 0) {
  54618. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54619. }
  54620. }
  54621. };
  54622. /**
  54623. * Gaussian blur post-processes. Horizontal and Vertical
  54624. */
  54625. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54626. var _this = this;
  54627. var blurOffsetsW = new Array(9);
  54628. var blurOffsetsH = new Array(9);
  54629. var blurWeights = new Array(9);
  54630. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54631. // Utils for gaussian blur
  54632. var calculateBlurOffsets = function (height) {
  54633. var lastOutputDimensions = {
  54634. width: scene.getEngine().getRenderWidth(),
  54635. height: scene.getEngine().getRenderHeight()
  54636. };
  54637. for (var i = 0; i < 9; i++) {
  54638. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54639. if (height) {
  54640. blurOffsetsH[i] = value;
  54641. }
  54642. else {
  54643. blurOffsetsW[i] = value;
  54644. }
  54645. }
  54646. };
  54647. var calculateWeights = function () {
  54648. var x = 0.0;
  54649. for (var i = 0; i < 9; i++) {
  54650. x = (i - 4.0) / 4.0;
  54651. 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));
  54652. }
  54653. };
  54654. // Callback
  54655. var gaussianBlurCallback = function (height) {
  54656. return function (effect) {
  54657. if (_this._needUpdate) {
  54658. calculateWeights();
  54659. calculateBlurOffsets(height);
  54660. }
  54661. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54662. effect.setArray("blurWeights", blurWeights);
  54663. effect.setFloat("multiplier", _this.gaussMultiplier);
  54664. };
  54665. };
  54666. // Create horizontal gaussian blur post-processes
  54667. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54668. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54669. // Create vertical gaussian blur post-process
  54670. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54671. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54672. };
  54673. // Luminance generator
  54674. HDRRenderingPipeline.LUM_STEPS = 6;
  54675. return HDRRenderingPipeline;
  54676. }(BABYLON.PostProcessRenderPipeline));
  54677. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54678. })(BABYLON || (BABYLON = {}));
  54679. var BABYLON;
  54680. (function (BABYLON) {
  54681. var FaceAdjacencies = (function () {
  54682. function FaceAdjacencies() {
  54683. this.edges = new Array();
  54684. this.edgesConnectedCount = 0;
  54685. }
  54686. return FaceAdjacencies;
  54687. }());
  54688. var EdgesRenderer = (function () {
  54689. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54690. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54691. if (epsilon === void 0) { epsilon = 0.95; }
  54692. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54693. this.edgesWidthScalerForOrthographic = 1000.0;
  54694. this.edgesWidthScalerForPerspective = 50.0;
  54695. this._linesPositions = new Array();
  54696. this._linesNormals = new Array();
  54697. this._linesIndices = new Array();
  54698. this._buffers = {};
  54699. this._checkVerticesInsteadOfIndices = false;
  54700. this._source = source;
  54701. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54702. this._epsilon = epsilon;
  54703. this._prepareRessources();
  54704. this._generateEdgesLines();
  54705. }
  54706. EdgesRenderer.prototype._prepareRessources = function () {
  54707. if (this._lineShader) {
  54708. return;
  54709. }
  54710. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54711. attributes: ["position", "normal"],
  54712. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54713. });
  54714. this._lineShader.disableDepthWrite = true;
  54715. this._lineShader.backFaceCulling = false;
  54716. };
  54717. EdgesRenderer.prototype.dispose = function () {
  54718. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54719. if (buffer) {
  54720. buffer.dispose();
  54721. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54722. }
  54723. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54724. if (buffer) {
  54725. buffer.dispose();
  54726. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54727. }
  54728. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54729. this._lineShader.dispose();
  54730. };
  54731. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54732. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54733. return 0;
  54734. }
  54735. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54736. return 1;
  54737. }
  54738. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54739. return 2;
  54740. }
  54741. return -1;
  54742. };
  54743. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54744. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54745. return 0;
  54746. }
  54747. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54748. return 1;
  54749. }
  54750. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54751. return 2;
  54752. }
  54753. return -1;
  54754. };
  54755. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54756. var needToCreateLine;
  54757. if (edge === undefined) {
  54758. needToCreateLine = true;
  54759. }
  54760. else {
  54761. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54762. needToCreateLine = dotProduct < this._epsilon;
  54763. }
  54764. if (needToCreateLine) {
  54765. var offset = this._linesPositions.length / 3;
  54766. var normal = p0.subtract(p1);
  54767. normal.normalize();
  54768. // Positions
  54769. this._linesPositions.push(p0.x);
  54770. this._linesPositions.push(p0.y);
  54771. this._linesPositions.push(p0.z);
  54772. this._linesPositions.push(p0.x);
  54773. this._linesPositions.push(p0.y);
  54774. this._linesPositions.push(p0.z);
  54775. this._linesPositions.push(p1.x);
  54776. this._linesPositions.push(p1.y);
  54777. this._linesPositions.push(p1.z);
  54778. this._linesPositions.push(p1.x);
  54779. this._linesPositions.push(p1.y);
  54780. this._linesPositions.push(p1.z);
  54781. // Normals
  54782. this._linesNormals.push(p1.x);
  54783. this._linesNormals.push(p1.y);
  54784. this._linesNormals.push(p1.z);
  54785. this._linesNormals.push(-1);
  54786. this._linesNormals.push(p1.x);
  54787. this._linesNormals.push(p1.y);
  54788. this._linesNormals.push(p1.z);
  54789. this._linesNormals.push(1);
  54790. this._linesNormals.push(p0.x);
  54791. this._linesNormals.push(p0.y);
  54792. this._linesNormals.push(p0.z);
  54793. this._linesNormals.push(-1);
  54794. this._linesNormals.push(p0.x);
  54795. this._linesNormals.push(p0.y);
  54796. this._linesNormals.push(p0.z);
  54797. this._linesNormals.push(1);
  54798. // Indices
  54799. this._linesIndices.push(offset);
  54800. this._linesIndices.push(offset + 1);
  54801. this._linesIndices.push(offset + 2);
  54802. this._linesIndices.push(offset);
  54803. this._linesIndices.push(offset + 2);
  54804. this._linesIndices.push(offset + 3);
  54805. }
  54806. };
  54807. EdgesRenderer.prototype._generateEdgesLines = function () {
  54808. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54809. var indices = this._source.getIndices();
  54810. // First let's find adjacencies
  54811. var adjacencies = new Array();
  54812. var faceNormals = new Array();
  54813. var index;
  54814. var faceAdjacencies;
  54815. // Prepare faces
  54816. for (index = 0; index < indices.length; index += 3) {
  54817. faceAdjacencies = new FaceAdjacencies();
  54818. var p0Index = indices[index];
  54819. var p1Index = indices[index + 1];
  54820. var p2Index = indices[index + 2];
  54821. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54822. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54823. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54824. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54825. faceNormal.normalize();
  54826. faceNormals.push(faceNormal);
  54827. adjacencies.push(faceAdjacencies);
  54828. }
  54829. // Scan
  54830. for (index = 0; index < adjacencies.length; index++) {
  54831. faceAdjacencies = adjacencies[index];
  54832. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54833. var otherFaceAdjacencies = adjacencies[otherIndex];
  54834. if (faceAdjacencies.edgesConnectedCount === 3) {
  54835. break;
  54836. }
  54837. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54838. continue;
  54839. }
  54840. var otherP0 = indices[otherIndex * 3];
  54841. var otherP1 = indices[otherIndex * 3 + 1];
  54842. var otherP2 = indices[otherIndex * 3 + 2];
  54843. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  54844. var otherEdgeIndex;
  54845. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  54846. continue;
  54847. }
  54848. switch (edgeIndex) {
  54849. case 0:
  54850. if (this._checkVerticesInsteadOfIndices) {
  54851. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54852. }
  54853. else {
  54854. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  54855. }
  54856. break;
  54857. case 1:
  54858. if (this._checkVerticesInsteadOfIndices) {
  54859. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54860. }
  54861. else {
  54862. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  54863. }
  54864. break;
  54865. case 2:
  54866. if (this._checkVerticesInsteadOfIndices) {
  54867. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54868. }
  54869. else {
  54870. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  54871. }
  54872. break;
  54873. }
  54874. if (otherEdgeIndex === -1) {
  54875. continue;
  54876. }
  54877. faceAdjacencies.edges[edgeIndex] = otherIndex;
  54878. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  54879. faceAdjacencies.edgesConnectedCount++;
  54880. otherFaceAdjacencies.edgesConnectedCount++;
  54881. if (faceAdjacencies.edgesConnectedCount === 3) {
  54882. break;
  54883. }
  54884. }
  54885. }
  54886. }
  54887. // Create lines
  54888. for (index = 0; index < adjacencies.length; index++) {
  54889. // 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
  54890. var current = adjacencies[index];
  54891. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  54892. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  54893. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  54894. }
  54895. // Merge into a single mesh
  54896. var engine = this._source.getScene().getEngine();
  54897. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  54898. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  54899. this._ib = engine.createIndexBuffer(this._linesIndices);
  54900. this._indicesCount = this._linesIndices.length;
  54901. };
  54902. EdgesRenderer.prototype.render = function () {
  54903. if (!this._lineShader.isReady()) {
  54904. return;
  54905. }
  54906. var scene = this._source.getScene();
  54907. var engine = scene.getEngine();
  54908. this._lineShader._preBind();
  54909. // VBOs
  54910. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  54911. scene.resetCachedMaterial();
  54912. this._lineShader.setColor4("color", this._source.edgesColor);
  54913. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  54914. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  54915. }
  54916. else {
  54917. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  54918. }
  54919. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  54920. this._lineShader.bind(this._source.getWorldMatrix());
  54921. // Draw order
  54922. engine.draw(true, 0, this._indicesCount);
  54923. this._lineShader.unbind();
  54924. engine.setDepthWrite(true);
  54925. };
  54926. return EdgesRenderer;
  54927. }());
  54928. BABYLON.EdgesRenderer = EdgesRenderer;
  54929. })(BABYLON || (BABYLON = {}));
  54930. var BABYLON;
  54931. (function (BABYLON) {
  54932. (function (TonemappingOperator) {
  54933. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54934. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54935. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54936. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54937. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54938. var TonemappingOperator = BABYLON.TonemappingOperator;
  54939. ;
  54940. var TonemapPostProcess = (function (_super) {
  54941. __extends(TonemapPostProcess, _super);
  54942. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54943. var _this = this;
  54944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54945. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54946. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  54947. this._operator = _operator;
  54948. this.exposureAdjustment = exposureAdjustment;
  54949. var defines = "#define ";
  54950. if (this._operator === TonemappingOperator.Hable)
  54951. defines += "HABLE_TONEMAPPING";
  54952. else if (this._operator === TonemappingOperator.Reinhard)
  54953. defines += "REINHARD_TONEMAPPING";
  54954. else if (this._operator === TonemappingOperator.HejiDawson)
  54955. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54956. else if (this._operator === TonemappingOperator.Photographic)
  54957. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54958. //sadly a second call to create the effect.
  54959. this.updateEffect(defines);
  54960. this.onApply = function (effect) {
  54961. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54962. };
  54963. }
  54964. return TonemapPostProcess;
  54965. }(BABYLON.PostProcess));
  54966. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54967. })(BABYLON || (BABYLON = {}));
  54968. var BABYLON;
  54969. (function (BABYLON) {
  54970. var ReflectionProbe = (function () {
  54971. function ReflectionProbe(name, size, scene, generateMipMaps) {
  54972. var _this = this;
  54973. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54974. this.name = name;
  54975. this._viewMatrix = BABYLON.Matrix.Identity();
  54976. this._target = BABYLON.Vector3.Zero();
  54977. this._add = BABYLON.Vector3.Zero();
  54978. this.invertYAxis = false;
  54979. this.position = BABYLON.Vector3.Zero();
  54980. this._scene = scene;
  54981. this._scene.reflectionProbes.push(this);
  54982. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  54983. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  54984. switch (faceIndex) {
  54985. case 0:
  54986. _this._add.copyFromFloats(1, 0, 0);
  54987. break;
  54988. case 1:
  54989. _this._add.copyFromFloats(-1, 0, 0);
  54990. break;
  54991. case 2:
  54992. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  54993. break;
  54994. case 3:
  54995. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  54996. break;
  54997. case 4:
  54998. _this._add.copyFromFloats(0, 0, 1);
  54999. break;
  55000. case 5:
  55001. _this._add.copyFromFloats(0, 0, -1);
  55002. break;
  55003. }
  55004. if (_this._attachedMesh) {
  55005. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55006. }
  55007. _this.position.addToRef(_this._add, _this._target);
  55008. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55009. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55010. });
  55011. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55012. scene.updateTransformMatrix(true);
  55013. });
  55014. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55015. }
  55016. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55017. get: function () {
  55018. return this._renderTargetTexture.refreshRate;
  55019. },
  55020. set: function (value) {
  55021. this._renderTargetTexture.refreshRate = value;
  55022. },
  55023. enumerable: true,
  55024. configurable: true
  55025. });
  55026. ReflectionProbe.prototype.getScene = function () {
  55027. return this._scene;
  55028. };
  55029. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55030. get: function () {
  55031. return this._renderTargetTexture;
  55032. },
  55033. enumerable: true,
  55034. configurable: true
  55035. });
  55036. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55037. get: function () {
  55038. return this._renderTargetTexture.renderList;
  55039. },
  55040. enumerable: true,
  55041. configurable: true
  55042. });
  55043. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55044. this._attachedMesh = mesh;
  55045. };
  55046. ReflectionProbe.prototype.dispose = function () {
  55047. var index = this._scene.reflectionProbes.indexOf(this);
  55048. if (index !== -1) {
  55049. // Remove from the scene if found
  55050. this._scene.reflectionProbes.splice(index, 1);
  55051. }
  55052. if (this._renderTargetTexture) {
  55053. this._renderTargetTexture.dispose();
  55054. this._renderTargetTexture = null;
  55055. }
  55056. };
  55057. return ReflectionProbe;
  55058. }());
  55059. BABYLON.ReflectionProbe = ReflectionProbe;
  55060. })(BABYLON || (BABYLON = {}));
  55061. var BABYLON;
  55062. (function (BABYLON) {
  55063. var SolidParticle = (function () {
  55064. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  55065. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  55066. this.position = BABYLON.Vector3.Zero(); // position
  55067. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55068. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  55069. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  55070. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55071. this.alive = true; // alive
  55072. this.isVisible = true; // visibility
  55073. this.idx = particleIndex;
  55074. this._pos = positionIndex;
  55075. this._model = model;
  55076. this.shapeId = shapeId;
  55077. this.idxInShape = idxInShape;
  55078. }
  55079. Object.defineProperty(SolidParticle.prototype, "scale", {
  55080. //legacy support, changed scale to scaling
  55081. get: function () {
  55082. return this.scaling;
  55083. },
  55084. set: function (scale) {
  55085. this.scaling = scale;
  55086. },
  55087. enumerable: true,
  55088. configurable: true
  55089. });
  55090. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55091. //legacy support, changed quaternion to rotationQuaternion
  55092. get: function () {
  55093. return this.rotationQuaternion;
  55094. },
  55095. set: function (q) {
  55096. this.rotationQuaternion = q;
  55097. },
  55098. enumerable: true,
  55099. configurable: true
  55100. });
  55101. return SolidParticle;
  55102. }());
  55103. BABYLON.SolidParticle = SolidParticle;
  55104. var ModelShape = (function () {
  55105. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55106. this.shapeID = id;
  55107. this._shape = shape;
  55108. this._shapeUV = shapeUV;
  55109. this._positionFunction = posFunction;
  55110. this._vertexFunction = vtxFunction;
  55111. }
  55112. return ModelShape;
  55113. }());
  55114. BABYLON.ModelShape = ModelShape;
  55115. })(BABYLON || (BABYLON = {}));
  55116. var BABYLON;
  55117. (function (BABYLON) {
  55118. /**
  55119. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55120. */
  55121. var SolidParticleSystem = (function () {
  55122. /**
  55123. * Creates a SPS (Solid Particle System) object.
  55124. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55125. * `scene` (Scene) is the scene in which the SPS is added.
  55126. * `updatable` (default true) : if the SPS must be updatable or immutable.
  55127. * `isPickable` (default false) : if the solid particles must be pickable.
  55128. */
  55129. function SolidParticleSystem(name, scene, options) {
  55130. // public members
  55131. /**
  55132. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55133. * Example : var p = SPS.particles[i];
  55134. */
  55135. this.particles = new Array();
  55136. /**
  55137. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55138. */
  55139. this.nbParticles = 0;
  55140. /**
  55141. * If the particles must ever face the camera (default false). Useful for planar particles.
  55142. */
  55143. this.billboard = false;
  55144. /**
  55145. * This a counter ofr your own usage. It's not set by any SPS functions.
  55146. */
  55147. this.counter = 0;
  55148. /**
  55149. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55150. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55151. */
  55152. this.vars = {};
  55153. this._positions = new Array();
  55154. this._indices = new Array();
  55155. this._normals = new Array();
  55156. this._colors = new Array();
  55157. this._uvs = new Array();
  55158. this._index = 0; // indices index
  55159. this._updatable = true;
  55160. this._pickable = false;
  55161. this._isVisibilityBoxLocked = false;
  55162. this._alwaysVisible = false;
  55163. this._shapeCounter = 0;
  55164. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  55165. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55166. this._computeParticleColor = true;
  55167. this._computeParticleTexture = true;
  55168. this._computeParticleRotation = true;
  55169. this._computeParticleVertex = false;
  55170. this._computeBoundingBox = false;
  55171. this._cam_axisZ = BABYLON.Vector3.Zero();
  55172. this._cam_axisY = BABYLON.Vector3.Zero();
  55173. this._cam_axisX = BABYLON.Vector3.Zero();
  55174. this._axisX = BABYLON.Axis.X;
  55175. this._axisY = BABYLON.Axis.Y;
  55176. this._axisZ = BABYLON.Axis.Z;
  55177. this._fakeCamPos = BABYLON.Vector3.Zero();
  55178. this._rotMatrix = new BABYLON.Matrix();
  55179. this._invertMatrix = new BABYLON.Matrix();
  55180. this._rotated = BABYLON.Vector3.Zero();
  55181. this._quaternion = new BABYLON.Quaternion();
  55182. this._vertex = BABYLON.Vector3.Zero();
  55183. this._normal = BABYLON.Vector3.Zero();
  55184. this._yaw = 0.0;
  55185. this._pitch = 0.0;
  55186. this._roll = 0.0;
  55187. this._halfroll = 0.0;
  55188. this._halfpitch = 0.0;
  55189. this._halfyaw = 0.0;
  55190. this._sinRoll = 0.0;
  55191. this._cosRoll = 0.0;
  55192. this._sinPitch = 0.0;
  55193. this._cosPitch = 0.0;
  55194. this._sinYaw = 0.0;
  55195. this._cosYaw = 0.0;
  55196. this._w = 0.0;
  55197. this._minimum = BABYLON.Tmp.Vector3[0];
  55198. this._maximum = BABYLON.Tmp.Vector3[1];
  55199. this.name = name;
  55200. this._scene = scene;
  55201. this._camera = scene.activeCamera;
  55202. this._pickable = options ? options.isPickable : false;
  55203. if (options && options.updatable) {
  55204. this._updatable = options.updatable;
  55205. }
  55206. else {
  55207. this._updatable = true;
  55208. }
  55209. if (this._pickable) {
  55210. this.pickedParticles = [];
  55211. }
  55212. }
  55213. /**
  55214. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55215. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55216. */
  55217. SolidParticleSystem.prototype.buildMesh = function () {
  55218. if (this.nbParticles === 0) {
  55219. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55220. this.addShape(triangle, 1);
  55221. triangle.dispose();
  55222. }
  55223. this._positions32 = new Float32Array(this._positions);
  55224. this._uvs32 = new Float32Array(this._uvs);
  55225. this._colors32 = new Float32Array(this._colors);
  55226. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55227. this._normals32 = new Float32Array(this._normals);
  55228. this._fixedNormal32 = new Float32Array(this._normals);
  55229. var vertexData = new BABYLON.VertexData();
  55230. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55231. vertexData.indices = this._indices;
  55232. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55233. if (this._uvs32) {
  55234. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55235. ;
  55236. }
  55237. if (this._colors32) {
  55238. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55239. }
  55240. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55241. vertexData.applyToMesh(mesh, this._updatable);
  55242. this.mesh = mesh;
  55243. this.mesh.isPickable = this._pickable;
  55244. // free memory
  55245. this._positions = null;
  55246. this._normals = null;
  55247. this._uvs = null;
  55248. this._colors = null;
  55249. if (!this._updatable) {
  55250. this.particles.length = 0;
  55251. }
  55252. return mesh;
  55253. };
  55254. /**
  55255. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55256. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55257. * Thus the particles generated from `digest()` have their property `position` set yet.
  55258. * `mesh` ( Mesh ) is the mesh to be digested
  55259. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55260. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55261. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55262. */
  55263. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55264. var size = (options && options.facetNb) || 1;
  55265. var number = (options && options.number);
  55266. var delta = (options && options.delta) || 0;
  55267. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55268. var meshInd = mesh.getIndices();
  55269. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55270. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55271. var f = 0; // facet counter
  55272. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55273. // compute size from number
  55274. if (number) {
  55275. number = (number > totalFacets) ? totalFacets : number;
  55276. size = Math.round(totalFacets / number);
  55277. delta = 0;
  55278. }
  55279. else {
  55280. size = (size > totalFacets) ? totalFacets : size;
  55281. }
  55282. var facetPos = []; // submesh positions
  55283. var facetInd = []; // submesh indices
  55284. var facetUV = []; // submesh UV
  55285. var facetCol = []; // submesh colors
  55286. var barycenter = BABYLON.Tmp.Vector3[0];
  55287. var rand;
  55288. var sizeO = size;
  55289. while (f < totalFacets) {
  55290. size = sizeO + Math.floor((1 + delta) * Math.random());
  55291. if (f > totalFacets - size) {
  55292. size = totalFacets - f;
  55293. }
  55294. // reset temp arrays
  55295. facetPos.length = 0;
  55296. facetInd.length = 0;
  55297. facetUV.length = 0;
  55298. facetCol.length = 0;
  55299. // iterate over "size" facets
  55300. var fi = 0;
  55301. for (var j = f * 3; j < (f + size) * 3; j++) {
  55302. facetInd.push(fi);
  55303. var i = meshInd[j];
  55304. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55305. if (meshUV) {
  55306. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55307. }
  55308. if (meshCol) {
  55309. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55310. }
  55311. fi++;
  55312. }
  55313. // create a model shape for each single particle
  55314. var idx = this.nbParticles;
  55315. var shape = this._posToShape(facetPos);
  55316. var shapeUV = this._uvsToShapeUV(facetUV);
  55317. // compute the barycenter of the shape
  55318. var v;
  55319. for (v = 0; v < shape.length; v++) {
  55320. barycenter.addInPlace(shape[v]);
  55321. }
  55322. barycenter.scaleInPlace(1 / shape.length);
  55323. // shift the shape from its barycenter to the origin
  55324. for (v = 0; v < shape.length; v++) {
  55325. shape[v].subtractInPlace(barycenter);
  55326. }
  55327. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55328. // add the particle in the SPS
  55329. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  55330. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  55331. // initialize the particle position
  55332. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55333. this._index += shape.length;
  55334. idx++;
  55335. this.nbParticles++;
  55336. this._shapeCounter++;
  55337. f += size;
  55338. }
  55339. return this;
  55340. };
  55341. //reset copy
  55342. SolidParticleSystem.prototype._resetCopy = function () {
  55343. this._copy.position.x = 0;
  55344. this._copy.position.y = 0;
  55345. this._copy.position.z = 0;
  55346. this._copy.rotation.x = 0;
  55347. this._copy.rotation.y = 0;
  55348. this._copy.rotation.z = 0;
  55349. this._copy.rotationQuaternion = null;
  55350. this._copy.scaling.x = 1;
  55351. this._copy.scaling.y = 1;
  55352. this._copy.scaling.z = 1;
  55353. this._copy.uvs.x = 0;
  55354. this._copy.uvs.y = 0;
  55355. this._copy.uvs.z = 1;
  55356. this._copy.uvs.w = 1;
  55357. this._copy.color = null;
  55358. };
  55359. // _meshBuilder : inserts the shape model in the global SPS mesh
  55360. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  55361. var i;
  55362. var u = 0;
  55363. var c = 0;
  55364. this._resetCopy();
  55365. if (options && options.positionFunction) {
  55366. options.positionFunction(this._copy, idx, idxInShape);
  55367. }
  55368. if (this._copy.rotationQuaternion) {
  55369. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55370. }
  55371. else {
  55372. this._yaw = this._copy.rotation.y;
  55373. this._pitch = this._copy.rotation.x;
  55374. this._roll = this._copy.rotation.z;
  55375. this._quaternionRotationYPR();
  55376. }
  55377. this._quaternionToRotationMatrix();
  55378. for (i = 0; i < shape.length; i++) {
  55379. this._vertex.x = shape[i].x;
  55380. this._vertex.y = shape[i].y;
  55381. this._vertex.z = shape[i].z;
  55382. if (options && options.vertexFunction) {
  55383. options.vertexFunction(this._copy, this._vertex, i);
  55384. }
  55385. this._vertex.x *= this._copy.scaling.x;
  55386. this._vertex.y *= this._copy.scaling.y;
  55387. this._vertex.z *= this._copy.scaling.z;
  55388. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55389. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55390. if (meshUV) {
  55391. 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);
  55392. u += 2;
  55393. }
  55394. if (this._copy.color) {
  55395. this._color = this._copy.color;
  55396. }
  55397. else if (meshCol && meshCol[c] !== undefined) {
  55398. this._color.r = meshCol[c];
  55399. this._color.g = meshCol[c + 1];
  55400. this._color.b = meshCol[c + 2];
  55401. this._color.a = meshCol[c + 3];
  55402. }
  55403. else {
  55404. this._color.r = 1;
  55405. this._color.g = 1;
  55406. this._color.b = 1;
  55407. this._color.a = 1;
  55408. }
  55409. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55410. c += 4;
  55411. }
  55412. for (i = 0; i < meshInd.length; i++) {
  55413. indices.push(p + meshInd[i]);
  55414. }
  55415. if (this._pickable) {
  55416. var nbfaces = meshInd.length / 3;
  55417. for (i = 0; i < nbfaces; i++) {
  55418. this.pickedParticles.push({ idx: idx, faceId: i });
  55419. }
  55420. }
  55421. };
  55422. // returns a shape array from positions array
  55423. SolidParticleSystem.prototype._posToShape = function (positions) {
  55424. var shape = [];
  55425. for (var i = 0; i < positions.length; i += 3) {
  55426. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55427. }
  55428. return shape;
  55429. };
  55430. // returns a shapeUV array from a Vector4 uvs
  55431. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55432. var shapeUV = [];
  55433. if (uvs) {
  55434. for (var i = 0; i < uvs.length; i++)
  55435. shapeUV.push(uvs[i]);
  55436. }
  55437. return shapeUV;
  55438. };
  55439. // adds a new particle object in the particles array
  55440. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  55441. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  55442. };
  55443. /**
  55444. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55445. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55446. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55447. * `nb` (positive integer) the number of particles to be created from this model
  55448. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55449. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55450. */
  55451. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55452. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55453. var meshInd = mesh.getIndices();
  55454. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55455. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55456. var shape = this._posToShape(meshPos);
  55457. var shapeUV = this._uvsToShapeUV(meshUV);
  55458. var posfunc = options ? options.positionFunction : null;
  55459. var vtxfunc = options ? options.vertexFunction : null;
  55460. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55461. // particles
  55462. var idx = this.nbParticles;
  55463. for (var i = 0; i < nb; i++) {
  55464. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  55465. if (this._updatable) {
  55466. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  55467. }
  55468. this._index += shape.length;
  55469. idx++;
  55470. }
  55471. this.nbParticles += nb;
  55472. this._shapeCounter++;
  55473. return this._shapeCounter - 1;
  55474. };
  55475. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55476. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55477. this._resetCopy();
  55478. if (particle._model._positionFunction) {
  55479. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55480. }
  55481. if (this._copy.rotationQuaternion) {
  55482. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55483. }
  55484. else {
  55485. this._yaw = this._copy.rotation.y;
  55486. this._pitch = this._copy.rotation.x;
  55487. this._roll = this._copy.rotation.z;
  55488. this._quaternionRotationYPR();
  55489. }
  55490. this._quaternionToRotationMatrix();
  55491. this._shape = particle._model._shape;
  55492. for (var pt = 0; pt < this._shape.length; pt++) {
  55493. this._vertex.x = this._shape[pt].x;
  55494. this._vertex.y = this._shape[pt].y;
  55495. this._vertex.z = this._shape[pt].z;
  55496. if (particle._model._vertexFunction) {
  55497. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55498. }
  55499. this._vertex.x *= this._copy.scaling.x;
  55500. this._vertex.y *= this._copy.scaling.y;
  55501. this._vertex.z *= this._copy.scaling.z;
  55502. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55503. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55504. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55505. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55506. }
  55507. particle.position.x = 0;
  55508. particle.position.y = 0;
  55509. particle.position.z = 0;
  55510. particle.rotation.x = 0;
  55511. particle.rotation.y = 0;
  55512. particle.rotation.z = 0;
  55513. particle.rotationQuaternion = null;
  55514. particle.scaling.x = 1;
  55515. particle.scaling.y = 1;
  55516. particle.scaling.z = 1;
  55517. };
  55518. /**
  55519. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55520. */
  55521. SolidParticleSystem.prototype.rebuildMesh = function () {
  55522. for (var p = 0; p < this.particles.length; p++) {
  55523. this._rebuildParticle(this.particles[p]);
  55524. }
  55525. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55526. };
  55527. /**
  55528. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55529. * This method calls `updateParticle()` for each particle of the SPS.
  55530. * For an animated SPS, it is usually called within the render loop.
  55531. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55532. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55533. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55534. */
  55535. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55536. if (start === void 0) { start = 0; }
  55537. if (end === void 0) { end = this.nbParticles - 1; }
  55538. if (update === void 0) { update = true; }
  55539. if (!this._updatable) {
  55540. return;
  55541. }
  55542. // custom beforeUpdate
  55543. this.beforeUpdateParticles(start, end, update);
  55544. this._cam_axisX.x = 1;
  55545. this._cam_axisX.y = 0;
  55546. this._cam_axisX.z = 0;
  55547. this._cam_axisY.x = 0;
  55548. this._cam_axisY.y = 1;
  55549. this._cam_axisY.z = 0;
  55550. this._cam_axisZ.x = 0;
  55551. this._cam_axisZ.y = 0;
  55552. this._cam_axisZ.z = 1;
  55553. // if the particles will always face the camera
  55554. if (this.billboard) {
  55555. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  55556. this._yaw = this.mesh.rotation.y;
  55557. this._pitch = this.mesh.rotation.x;
  55558. this._roll = this.mesh.rotation.z;
  55559. this._quaternionRotationYPR();
  55560. this._quaternionToRotationMatrix();
  55561. this._rotMatrix.invertToRef(this._invertMatrix);
  55562. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  55563. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  55564. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  55565. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  55566. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  55567. this._cam_axisY.normalize();
  55568. this._cam_axisX.normalize();
  55569. this._cam_axisZ.normalize();
  55570. }
  55571. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55572. var idx = 0;
  55573. var index = 0;
  55574. var colidx = 0;
  55575. var colorIndex = 0;
  55576. var uvidx = 0;
  55577. var uvIndex = 0;
  55578. var pt = 0;
  55579. if (this._computeBoundingBox) {
  55580. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55581. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55582. }
  55583. // particle loop
  55584. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  55585. for (var p = start; p <= end; p++) {
  55586. this._particle = this.particles[p];
  55587. this._shape = this._particle._model._shape;
  55588. this._shapeUV = this._particle._model._shapeUV;
  55589. // call to custom user function to update the particle properties
  55590. this.updateParticle(this._particle);
  55591. if (this._particle.isVisible) {
  55592. // particle rotation matrix
  55593. if (this.billboard) {
  55594. this._particle.rotation.x = 0.0;
  55595. this._particle.rotation.y = 0.0;
  55596. }
  55597. if (this._computeParticleRotation) {
  55598. if (this._particle.rotationQuaternion) {
  55599. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55600. }
  55601. else {
  55602. this._yaw = this._particle.rotation.y;
  55603. this._pitch = this._particle.rotation.x;
  55604. this._roll = this._particle.rotation.z;
  55605. this._quaternionRotationYPR();
  55606. }
  55607. this._quaternionToRotationMatrix();
  55608. }
  55609. // particle vertex loop
  55610. for (pt = 0; pt < this._shape.length; pt++) {
  55611. idx = index + pt * 3;
  55612. colidx = colorIndex + pt * 4;
  55613. uvidx = uvIndex + pt * 2;
  55614. this._vertex.x = this._shape[pt].x;
  55615. this._vertex.y = this._shape[pt].y;
  55616. this._vertex.z = this._shape[pt].z;
  55617. if (this._computeParticleVertex) {
  55618. this.updateParticleVertex(this._particle, this._vertex, pt);
  55619. }
  55620. // positions
  55621. this._vertex.x *= this._particle.scaling.x;
  55622. this._vertex.y *= this._particle.scaling.y;
  55623. this._vertex.z *= this._particle.scaling.z;
  55624. 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];
  55625. 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;
  55626. 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;
  55627. 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;
  55628. 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;
  55629. 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;
  55630. 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;
  55631. if (this._computeBoundingBox) {
  55632. if (this._positions32[idx] < this._minimum.x) {
  55633. this._minimum.x = this._positions32[idx];
  55634. }
  55635. if (this._positions32[idx] > this._maximum.x) {
  55636. this._maximum.x = this._positions32[idx];
  55637. }
  55638. if (this._positions32[idx + 1] < this._minimum.y) {
  55639. this._minimum.y = this._positions32[idx + 1];
  55640. }
  55641. if (this._positions32[idx + 1] > this._maximum.y) {
  55642. this._maximum.y = this._positions32[idx + 1];
  55643. }
  55644. if (this._positions32[idx + 2] < this._minimum.z) {
  55645. this._minimum.z = this._positions32[idx + 2];
  55646. }
  55647. if (this._positions32[idx + 2] > this._maximum.z) {
  55648. this._maximum.z = this._positions32[idx + 2];
  55649. }
  55650. }
  55651. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  55652. if (!this._computeParticleVertex && !this.billboard) {
  55653. this._normal.x = this._fixedNormal32[idx];
  55654. this._normal.y = this._fixedNormal32[idx + 1];
  55655. this._normal.z = this._fixedNormal32[idx + 2];
  55656. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  55657. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  55658. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  55659. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  55660. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55661. 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;
  55662. 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;
  55663. }
  55664. if (this._computeParticleColor) {
  55665. this._colors32[colidx] = this._particle.color.r;
  55666. this._colors32[colidx + 1] = this._particle.color.g;
  55667. this._colors32[colidx + 2] = this._particle.color.b;
  55668. this._colors32[colidx + 3] = this._particle.color.a;
  55669. }
  55670. if (this._computeParticleTexture) {
  55671. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55672. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55673. }
  55674. }
  55675. }
  55676. else {
  55677. for (pt = 0; pt < this._shape.length; pt++) {
  55678. idx = index + pt * 3;
  55679. colidx = colorIndex + pt * 4;
  55680. uvidx = uvIndex + pt * 2;
  55681. this._positions32[idx] = this._camera.position.x;
  55682. this._positions32[idx + 1] = this._camera.position.y;
  55683. this._positions32[idx + 2] = this._camera.position.z;
  55684. this._normals32[idx] = 0.0;
  55685. this._normals32[idx + 1] = 0.0;
  55686. this._normals32[idx + 2] = 0.0;
  55687. if (this._computeParticleColor) {
  55688. this._colors32[colidx] = this._particle.color.r;
  55689. this._colors32[colidx + 1] = this._particle.color.g;
  55690. this._colors32[colidx + 2] = this._particle.color.b;
  55691. this._colors32[colidx + 3] = this._particle.color.a;
  55692. }
  55693. if (this._computeParticleTexture) {
  55694. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55695. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55696. }
  55697. }
  55698. }
  55699. // increment indexes for the next particle
  55700. index = idx + 3;
  55701. colorIndex = colidx + 4;
  55702. uvIndex = uvidx + 2;
  55703. }
  55704. // if the VBO must be updated
  55705. if (update) {
  55706. if (this._computeParticleColor) {
  55707. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55708. }
  55709. if (this._computeParticleTexture) {
  55710. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55711. }
  55712. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55713. if (!this.mesh.areNormalsFrozen) {
  55714. if (this._computeParticleVertex || this.billboard) {
  55715. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55716. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  55717. for (var i = 0; i < this._normals32.length; i++) {
  55718. this._fixedNormal32[i] = this._normals32[i];
  55719. }
  55720. }
  55721. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55722. }
  55723. }
  55724. if (this._computeBoundingBox) {
  55725. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55726. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55727. }
  55728. this.afterUpdateParticles(start, end, update);
  55729. };
  55730. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55731. this._halfroll = this._roll * 0.5;
  55732. this._halfpitch = this._pitch * 0.5;
  55733. this._halfyaw = this._yaw * 0.5;
  55734. this._sinRoll = Math.sin(this._halfroll);
  55735. this._cosRoll = Math.cos(this._halfroll);
  55736. this._sinPitch = Math.sin(this._halfpitch);
  55737. this._cosPitch = Math.cos(this._halfpitch);
  55738. this._sinYaw = Math.sin(this._halfyaw);
  55739. this._cosYaw = Math.cos(this._halfyaw);
  55740. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  55741. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  55742. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  55743. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  55744. };
  55745. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55746. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55747. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55748. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55749. this._rotMatrix.m[3] = 0;
  55750. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55751. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55752. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55753. this._rotMatrix.m[7] = 0;
  55754. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55755. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55756. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55757. this._rotMatrix.m[11] = 0;
  55758. this._rotMatrix.m[12] = 0;
  55759. this._rotMatrix.m[13] = 0;
  55760. this._rotMatrix.m[14] = 0;
  55761. this._rotMatrix.m[15] = 1.0;
  55762. };
  55763. /**
  55764. * Disposes the SPS
  55765. */
  55766. SolidParticleSystem.prototype.dispose = function () {
  55767. this.mesh.dispose();
  55768. this.vars = null;
  55769. // drop references to internal big arrays for the GC
  55770. this._positions = null;
  55771. this._indices = null;
  55772. this._normals = null;
  55773. this._uvs = null;
  55774. this._colors = null;
  55775. this._positions32 = null;
  55776. this._normals32 = null;
  55777. this._fixedNormal32 = null;
  55778. this._uvs32 = null;
  55779. this._colors32 = null;
  55780. this.pickedParticles = null;
  55781. };
  55782. /**
  55783. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55784. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55785. */
  55786. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55787. if (!this._isVisibilityBoxLocked) {
  55788. this.mesh.refreshBoundingInfo();
  55789. }
  55790. };
  55791. /**
  55792. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55793. * @param size the size (float) of the visibility box
  55794. * note : this doesn't lock the SPS mesh bounding box.
  55795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55796. */
  55797. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55798. var vis = size / 2;
  55799. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55800. };
  55801. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55802. // getter and setter
  55803. get: function () {
  55804. return this._alwaysVisible;
  55805. },
  55806. /**
  55807. * Sets the SPS as always visible or not
  55808. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55809. */
  55810. set: function (val) {
  55811. this._alwaysVisible = val;
  55812. this.mesh.alwaysSelectAsActiveMesh = val;
  55813. },
  55814. enumerable: true,
  55815. configurable: true
  55816. });
  55817. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55818. get: function () {
  55819. return this._isVisibilityBoxLocked;
  55820. },
  55821. /**
  55822. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55823. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55824. */
  55825. set: function (val) {
  55826. this._isVisibilityBoxLocked = val;
  55827. this.mesh.getBoundingInfo().isLocked = val;
  55828. },
  55829. enumerable: true,
  55830. configurable: true
  55831. });
  55832. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55833. // getters
  55834. get: function () {
  55835. return this._computeParticleRotation;
  55836. },
  55837. // Optimizer setters
  55838. /**
  55839. * Tells to `setParticles()` to compute the particle rotations or not.
  55840. * Default value : true. The SPS is faster when it's set to false.
  55841. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55842. */
  55843. set: function (val) {
  55844. this._computeParticleRotation = val;
  55845. },
  55846. enumerable: true,
  55847. configurable: true
  55848. });
  55849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55850. get: function () {
  55851. return this._computeParticleColor;
  55852. },
  55853. /**
  55854. * Tells to `setParticles()` to compute the particle colors or not.
  55855. * Default value : true. The SPS is faster when it's set to false.
  55856. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55857. */
  55858. set: function (val) {
  55859. this._computeParticleColor = val;
  55860. },
  55861. enumerable: true,
  55862. configurable: true
  55863. });
  55864. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55865. get: function () {
  55866. return this._computeParticleTexture;
  55867. },
  55868. /**
  55869. * Tells to `setParticles()` to compute the particle textures or not.
  55870. * Default value : true. The SPS is faster when it's set to false.
  55871. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55872. */
  55873. set: function (val) {
  55874. this._computeParticleTexture = val;
  55875. },
  55876. enumerable: true,
  55877. configurable: true
  55878. });
  55879. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55880. get: function () {
  55881. return this._computeParticleVertex;
  55882. },
  55883. /**
  55884. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55885. * Default value : false. The SPS is faster when it's set to false.
  55886. * Note : the particle custom vertex positions aren't stored values.
  55887. */
  55888. set: function (val) {
  55889. this._computeParticleVertex = val;
  55890. },
  55891. enumerable: true,
  55892. configurable: true
  55893. });
  55894. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55895. get: function () {
  55896. return this._computeBoundingBox;
  55897. },
  55898. /**
  55899. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55900. */
  55901. set: function (val) {
  55902. this._computeBoundingBox = val;
  55903. },
  55904. enumerable: true,
  55905. configurable: true
  55906. });
  55907. // =======================================================================
  55908. // Particle behavior logic
  55909. // these following methods may be overwritten by the user to fit his needs
  55910. /**
  55911. * This function does nothing. It may be overwritten to set all the particle first values.
  55912. * The SPS doesn't call this function, you may have to call it by your own.
  55913. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55914. */
  55915. SolidParticleSystem.prototype.initParticles = function () {
  55916. };
  55917. /**
  55918. * This function does nothing. It may be overwritten to recycle a particle.
  55919. * The SPS doesn't call this function, you may have to call it by your own.
  55920. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55921. */
  55922. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55923. return particle;
  55924. };
  55925. /**
  55926. * Updates a particle : this function should be overwritten by the user.
  55927. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55928. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55929. * ex : just set a particle position or velocity and recycle conditions
  55930. */
  55931. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55932. return particle;
  55933. };
  55934. /**
  55935. * Updates a vertex of a particle : it can be overwritten by the user.
  55936. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55937. * @param particle the current particle
  55938. * @param vertex the current index of the current particle
  55939. * @param pt the index of the current vertex in the particle shape
  55940. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55941. * ex : just set a vertex particle position
  55942. */
  55943. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55944. return vertex;
  55945. };
  55946. /**
  55947. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55948. * This does nothing and may be overwritten by the user.
  55949. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55950. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55951. * @param update the boolean update value actually passed to setParticles()
  55952. */
  55953. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55954. };
  55955. /**
  55956. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55957. * This will be passed three parameters.
  55958. * This does nothing and may be overwritten by the user.
  55959. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55960. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55961. * @param update the boolean update value actually passed to setParticles()
  55962. */
  55963. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55964. };
  55965. return SolidParticleSystem;
  55966. }());
  55967. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55968. })(BABYLON || (BABYLON = {}));
  55969. var BABYLON;
  55970. (function (BABYLON) {
  55971. var Internals;
  55972. (function (Internals) {
  55973. var FileFaceOrientation = (function () {
  55974. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  55975. this.name = name;
  55976. this.worldAxisForNormal = worldAxisForNormal;
  55977. this.worldAxisForFileX = worldAxisForFileX;
  55978. this.worldAxisForFileY = worldAxisForFileY;
  55979. }
  55980. return FileFaceOrientation;
  55981. }());
  55982. ;
  55983. /**
  55984. * Helper class dealing with the extraction of spherical polynomial dataArray
  55985. * from a cube map.
  55986. */
  55987. var CubeMapToSphericalPolynomialTools = (function () {
  55988. function CubeMapToSphericalPolynomialTools() {
  55989. }
  55990. /**
  55991. * Converts a cubemap to the according Spherical Polynomial data.
  55992. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55993. *
  55994. * @param cubeInfo The Cube map to extract the information from.
  55995. * @return The Spherical Polynomial data.
  55996. */
  55997. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  55998. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  55999. var totalSolidAngle = 0.0;
  56000. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56001. var du = 2.0 / cubeInfo.size;
  56002. var dv = du;
  56003. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56004. var minUV = du * 0.5 - 1.0;
  56005. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56006. var fileFace = this.FileFaces[faceIndex];
  56007. var dataArray = cubeInfo[fileFace.name];
  56008. var v = minUV;
  56009. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56010. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56011. // Because SP is still linear, so summation is fine in that basis.
  56012. for (var y = 0; y < cubeInfo.size; y++) {
  56013. var u = minUV;
  56014. for (var x = 0; x < cubeInfo.size; x++) {
  56015. // World direction (not normalised)
  56016. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56017. worldDirection.normalize();
  56018. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56019. if (1) {
  56020. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56021. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56022. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56023. var color = new BABYLON.Color3(r, g, b);
  56024. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56025. }
  56026. else {
  56027. if (faceIndex == 0) {
  56028. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56029. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56030. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56031. }
  56032. else if (faceIndex == 1) {
  56033. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56034. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56036. }
  56037. else if (faceIndex == 2) {
  56038. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56039. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56040. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56041. }
  56042. else if (faceIndex == 3) {
  56043. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56044. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56045. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56046. }
  56047. else if (faceIndex == 4) {
  56048. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56049. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56050. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56051. }
  56052. else if (faceIndex == 5) {
  56053. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56054. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56055. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56056. }
  56057. 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]);
  56058. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56059. }
  56060. totalSolidAngle += deltaSolidAngle;
  56061. u += du;
  56062. }
  56063. v += dv;
  56064. }
  56065. }
  56066. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56067. var correction = correctSolidAngle / totalSolidAngle;
  56068. sphericalHarmonics.scale(correction);
  56069. // Additionally scale by pi -- audit needed
  56070. sphericalHarmonics.scale(1.0 / Math.PI);
  56071. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56072. };
  56073. CubeMapToSphericalPolynomialTools.FileFaces = [
  56074. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56075. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56076. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56077. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56078. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56079. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56080. ];
  56081. return CubeMapToSphericalPolynomialTools;
  56082. }());
  56083. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56084. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56085. })(BABYLON || (BABYLON = {}));
  56086. var BABYLON;
  56087. (function (BABYLON) {
  56088. var Internals;
  56089. (function (Internals) {
  56090. /**
  56091. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56092. */
  56093. var PanoramaToCubeMapTools = (function () {
  56094. function PanoramaToCubeMapTools() {
  56095. }
  56096. /**
  56097. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56098. *
  56099. * @param float32Array The source data.
  56100. * @param inputWidth The width of the input panorama.
  56101. * @param inputhHeight The height of the input panorama.
  56102. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56103. * @return The cubemap data
  56104. */
  56105. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56106. if (!float32Array) {
  56107. throw "ConvertPanoramaToCubemap: input cannot be null";
  56108. }
  56109. if (float32Array.length != inputWidth * inputHeight * 3) {
  56110. throw "ConvertPanoramaToCubemap: input size is wrong";
  56111. }
  56112. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56113. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56114. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56115. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56116. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56117. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56118. return {
  56119. front: textureFront,
  56120. back: textureBack,
  56121. left: textureLeft,
  56122. right: textureRight,
  56123. up: textureUp,
  56124. down: textureDown,
  56125. size: size
  56126. };
  56127. };
  56128. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56129. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56130. var textureArray = new Float32Array(buffer);
  56131. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56132. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56133. var dy = 1 / texSize;
  56134. var fy = 0;
  56135. for (var y = 0; y < texSize; y++) {
  56136. var xv1 = faceData[0];
  56137. var xv2 = faceData[2];
  56138. for (var x = 0; x < texSize; x++) {
  56139. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56140. v.normalize();
  56141. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56142. // 3 channels per pixels
  56143. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56144. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56145. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56146. xv1 = xv1.add(rotDX1);
  56147. xv2 = xv2.add(rotDX2);
  56148. }
  56149. fy += dy;
  56150. }
  56151. return textureArray;
  56152. };
  56153. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56154. var theta = Math.atan2(vDir.z, vDir.x);
  56155. var phi = Math.acos(vDir.y);
  56156. while (theta < -Math.PI)
  56157. theta += 2 * Math.PI;
  56158. while (theta > Math.PI)
  56159. theta -= 2 * Math.PI;
  56160. var dx = theta / Math.PI;
  56161. var dy = phi / Math.PI;
  56162. // recenter.
  56163. dx = dx * 0.5 + 0.5;
  56164. var px = Math.round(dx * inputWidth);
  56165. if (px < 0)
  56166. px = 0;
  56167. else if (px >= inputWidth)
  56168. px = inputWidth - 1;
  56169. var py = Math.round(dy * inputHeight);
  56170. if (py < 0)
  56171. py = 0;
  56172. else if (py >= inputHeight)
  56173. py = inputHeight - 1;
  56174. var inputY = (inputHeight - py - 1);
  56175. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56176. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56177. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56178. return {
  56179. r: r,
  56180. g: g,
  56181. b: b
  56182. };
  56183. };
  56184. PanoramaToCubeMapTools.FACE_FRONT = [
  56185. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56186. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56187. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56188. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56189. ];
  56190. PanoramaToCubeMapTools.FACE_BACK = [
  56191. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56192. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56193. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56194. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56195. ];
  56196. PanoramaToCubeMapTools.FACE_RIGHT = [
  56197. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56198. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56199. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56200. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56201. ];
  56202. PanoramaToCubeMapTools.FACE_LEFT = [
  56203. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56204. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56205. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56206. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56207. ];
  56208. PanoramaToCubeMapTools.FACE_DOWN = [
  56209. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56210. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56211. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56212. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56213. ];
  56214. PanoramaToCubeMapTools.FACE_UP = [
  56215. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56216. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56217. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56218. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56219. ];
  56220. return PanoramaToCubeMapTools;
  56221. }());
  56222. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56223. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56224. })(BABYLON || (BABYLON = {}));
  56225. var BABYLON;
  56226. (function (BABYLON) {
  56227. var Internals;
  56228. (function (Internals) {
  56229. ;
  56230. /**
  56231. * This groups tools to convert HDR texture to native colors array.
  56232. */
  56233. var HDRTools = (function () {
  56234. function HDRTools() {
  56235. }
  56236. HDRTools.Ldexp = function (mantissa, exponent) {
  56237. if (exponent > 1023) {
  56238. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56239. }
  56240. if (exponent < -1074) {
  56241. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56242. }
  56243. return mantissa * Math.pow(2, exponent);
  56244. };
  56245. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56246. if (exponent > 0) {
  56247. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56248. float32array[index + 0] = red * exponent;
  56249. float32array[index + 1] = green * exponent;
  56250. float32array[index + 2] = blue * exponent;
  56251. }
  56252. else {
  56253. float32array[index + 0] = 0;
  56254. float32array[index + 1] = 0;
  56255. float32array[index + 2] = 0;
  56256. }
  56257. };
  56258. HDRTools.readStringLine = function (uint8array, startIndex) {
  56259. var line = "";
  56260. var character = "";
  56261. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56262. character = String.fromCharCode(uint8array[i]);
  56263. if (character == "\n") {
  56264. break;
  56265. }
  56266. line += character;
  56267. }
  56268. return line;
  56269. };
  56270. /**
  56271. * Reads header information from an RGBE texture stored in a native array.
  56272. * More information on this format are available here:
  56273. * https://en.wikipedia.org/wiki/RGBE_image_format
  56274. *
  56275. * @param uint8array The binary file stored in native array.
  56276. * @return The header information.
  56277. */
  56278. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56279. var height = 0;
  56280. var width = 0;
  56281. var line = this.readStringLine(uint8array, 0);
  56282. if (line[0] != '#' || line[1] != '?') {
  56283. throw "Bad HDR Format.";
  56284. }
  56285. var endOfHeader = false;
  56286. var findFormat = false;
  56287. var lineIndex = 0;
  56288. do {
  56289. lineIndex += (line.length + 1);
  56290. line = this.readStringLine(uint8array, lineIndex);
  56291. if (line == "FORMAT=32-bit_rle_rgbe") {
  56292. findFormat = true;
  56293. }
  56294. else if (line.length == 0) {
  56295. endOfHeader = true;
  56296. }
  56297. } while (!endOfHeader);
  56298. if (!findFormat) {
  56299. throw "HDR Bad header format, unsupported FORMAT";
  56300. }
  56301. lineIndex += (line.length + 1);
  56302. line = this.readStringLine(uint8array, lineIndex);
  56303. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56304. var match = sizeRegexp.exec(line);
  56305. // TODO. Support +Y and -X if needed.
  56306. if (match.length < 3) {
  56307. throw "HDR Bad header format, no size";
  56308. }
  56309. width = parseInt(match[2]);
  56310. height = parseInt(match[1]);
  56311. if (width < 8 || width > 0x7fff) {
  56312. throw "HDR Bad header format, unsupported size";
  56313. }
  56314. lineIndex += (line.length + 1);
  56315. return {
  56316. height: height,
  56317. width: width,
  56318. dataPosition: lineIndex
  56319. };
  56320. };
  56321. /**
  56322. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56323. * This RGBE texture needs to store the information as a panorama.
  56324. *
  56325. * More information on this format are available here:
  56326. * https://en.wikipedia.org/wiki/RGBE_image_format
  56327. *
  56328. * @param buffer The binary file stored in an array buffer.
  56329. * @param size The expected size of the extracted cubemap.
  56330. * @return The Cube Map information.
  56331. */
  56332. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56333. var uint8array = new Uint8Array(buffer);
  56334. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56335. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56336. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56337. return cubeMapData;
  56338. };
  56339. /**
  56340. * Returns the pixels data extracted from an RGBE texture.
  56341. * This pixels will be stored left to right up to down in the R G B order in one array.
  56342. *
  56343. * More information on this format are available here:
  56344. * https://en.wikipedia.org/wiki/RGBE_image_format
  56345. *
  56346. * @param uint8array The binary file stored in an array buffer.
  56347. * @param hdrInfo The header information of the file.
  56348. * @return The pixels data in RGB right to left up to down order.
  56349. */
  56350. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56351. // Keep for multi format supports.
  56352. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56353. };
  56354. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56355. var num_scanlines = hdrInfo.height;
  56356. var scanline_width = hdrInfo.width;
  56357. var a, b, c, d, count;
  56358. var dataIndex = hdrInfo.dataPosition;
  56359. var index = 0, endIndex = 0, i = 0;
  56360. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56361. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56362. // 3 channels of 4 bytes per pixel in float.
  56363. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56364. var resultArray = new Float32Array(resultBuffer);
  56365. // read in each successive scanline
  56366. while (num_scanlines > 0) {
  56367. a = uint8array[dataIndex++];
  56368. b = uint8array[dataIndex++];
  56369. c = uint8array[dataIndex++];
  56370. d = uint8array[dataIndex++];
  56371. if (a != 2 || b != 2 || (c & 0x80)) {
  56372. // this file is not run length encoded
  56373. throw "HDR Bad header format, not RLE";
  56374. }
  56375. if (((c << 8) | d) != scanline_width) {
  56376. throw "HDR Bad header format, wrong scan line width";
  56377. }
  56378. index = 0;
  56379. // read each of the four channels for the scanline into the buffer
  56380. for (i = 0; i < 4; i++) {
  56381. endIndex = (i + 1) * scanline_width;
  56382. while (index < endIndex) {
  56383. a = uint8array[dataIndex++];
  56384. b = uint8array[dataIndex++];
  56385. if (a > 128) {
  56386. // a run of the same value
  56387. count = a - 128;
  56388. if ((count == 0) || (count > endIndex - index)) {
  56389. throw "HDR Bad Format, bad scanline data (run)";
  56390. }
  56391. while (count-- > 0) {
  56392. scanLineArray[index++] = b;
  56393. }
  56394. }
  56395. else {
  56396. // a non-run
  56397. count = a;
  56398. if ((count == 0) || (count > endIndex - index)) {
  56399. throw "HDR Bad Format, bad scanline data (non-run)";
  56400. }
  56401. scanLineArray[index++] = b;
  56402. if (--count > 0) {
  56403. for (var j = 0; j < count; j++) {
  56404. scanLineArray[index++] = uint8array[dataIndex++];
  56405. }
  56406. }
  56407. }
  56408. }
  56409. }
  56410. // now convert data from buffer into floats
  56411. for (i = 0; i < scanline_width; i++) {
  56412. a = scanLineArray[i];
  56413. b = scanLineArray[i + scanline_width];
  56414. c = scanLineArray[i + 2 * scanline_width];
  56415. d = scanLineArray[i + 3 * scanline_width];
  56416. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56417. }
  56418. num_scanlines--;
  56419. }
  56420. return resultArray;
  56421. };
  56422. return HDRTools;
  56423. }());
  56424. Internals.HDRTools = HDRTools;
  56425. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56426. })(BABYLON || (BABYLON = {}));
  56427. //_______________________________________________________________
  56428. // Extracted from CubeMapGen:
  56429. // https://code.google.com/archive/p/cubemapgen/
  56430. //
  56431. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56432. //_______________________________________________________________
  56433. var BABYLON;
  56434. (function (BABYLON) {
  56435. var Internals;
  56436. (function (Internals) {
  56437. /**
  56438. * The bounding box information used during the conversion process.
  56439. */
  56440. var CMGBoundinBox = (function () {
  56441. function CMGBoundinBox() {
  56442. this.min = new BABYLON.Vector3(0, 0, 0);
  56443. this.max = new BABYLON.Vector3(0, 0, 0);
  56444. this.clear();
  56445. }
  56446. CMGBoundinBox.prototype.clear = function () {
  56447. this.min.x = CMGBoundinBox.MAX;
  56448. this.min.y = CMGBoundinBox.MAX;
  56449. this.min.z = CMGBoundinBox.MAX;
  56450. this.max.x = CMGBoundinBox.MIN;
  56451. this.max.y = CMGBoundinBox.MIN;
  56452. this.max.z = CMGBoundinBox.MIN;
  56453. };
  56454. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56455. this.min.x = Math.min(this.min.x, x);
  56456. this.min.y = Math.min(this.min.y, y);
  56457. this.min.z = Math.min(this.min.z, z);
  56458. this.max.x = Math.max(this.max.x, x);
  56459. this.max.y = Math.max(this.max.y, y);
  56460. this.max.z = Math.max(this.max.z, z);
  56461. };
  56462. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56463. this.min.x = Math.max(this.min.x, x);
  56464. this.min.y = Math.max(this.min.y, y);
  56465. this.min.z = Math.max(this.min.z, z);
  56466. };
  56467. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56468. this.max.x = Math.min(this.max.x, x);
  56469. this.max.y = Math.min(this.max.y, y);
  56470. this.max.z = Math.min(this.max.z, z);
  56471. };
  56472. CMGBoundinBox.prototype.empty = function () {
  56473. if ((this.min.x > this.max.y) ||
  56474. (this.min.y > this.max.y) ||
  56475. (this.min.z > this.max.y)) {
  56476. return true;
  56477. }
  56478. else {
  56479. return false;
  56480. }
  56481. };
  56482. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56483. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56484. return CMGBoundinBox;
  56485. }());
  56486. /**
  56487. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56488. * required by the glossinees of a material.
  56489. *
  56490. * This only supports the cosine drop power as well as Warp fixup generation method.
  56491. *
  56492. * This is using the process from CubeMapGen described here:
  56493. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56494. */
  56495. var PMREMGenerator = (function () {
  56496. /**
  56497. * Constructor of the generator.
  56498. *
  56499. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56500. * @param inputSize The size of the cubemap faces
  56501. * @param outputSize The size of the output cubemap faces
  56502. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56503. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56504. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56505. * @param specularPower The max specular level of the desired cubemap
  56506. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56507. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56508. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56509. */
  56510. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56511. this.input = input;
  56512. this.inputSize = inputSize;
  56513. this.outputSize = outputSize;
  56514. this.maxNumMipLevels = maxNumMipLevels;
  56515. this.numChannels = numChannels;
  56516. this.isFloat = isFloat;
  56517. this.specularPower = specularPower;
  56518. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56519. this.excludeBase = excludeBase;
  56520. this.fixup = fixup;
  56521. this._outputSurface = [];
  56522. this._numMipLevels = 0;
  56523. }
  56524. /**
  56525. * Launches the filter process and return the result.
  56526. *
  56527. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56528. */
  56529. PMREMGenerator.prototype.filterCubeMap = function () {
  56530. // Init cubemap processor
  56531. this.init();
  56532. // Filters the cubemap
  56533. this.filterCubeMapMipChain();
  56534. // Returns the filtered mips.
  56535. return this._outputSurface;
  56536. };
  56537. PMREMGenerator.prototype.init = function () {
  56538. var i;
  56539. var j;
  56540. var mipLevelSize;
  56541. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56542. if (this.maxNumMipLevels == 0) {
  56543. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56544. }
  56545. //first miplevel size
  56546. mipLevelSize = this.outputSize;
  56547. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56548. for (j = 0; j < this.maxNumMipLevels; j++) {
  56549. this._outputSurface.length++;
  56550. this._outputSurface[j] = [];
  56551. //Iterate over faces for output images
  56552. for (i = 0; i < 6; i++) {
  56553. this._outputSurface[j].length++;
  56554. // Initializes a new array for the output.
  56555. if (this.isFloat) {
  56556. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56557. }
  56558. else {
  56559. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56560. }
  56561. }
  56562. //next mip level is half size
  56563. mipLevelSize >>= 1;
  56564. this._numMipLevels++;
  56565. //terminate if mip chain becomes too small
  56566. if (mipLevelSize == 0) {
  56567. this.maxNumMipLevels = j;
  56568. return;
  56569. }
  56570. }
  56571. };
  56572. //--------------------------------------------------------------------------------------
  56573. //Cube map filtering and mip chain generation.
  56574. // the cube map filtereing is specified using a number of parameters:
  56575. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56576. // indicates the region of the hemisphere to filter over for each tap.
  56577. //
  56578. // Note that the top mip level is also a filtered version of the original input images
  56579. // as well in order to create mip chains for diffuse environment illumination.
  56580. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56581. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56582. //
  56583. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56584. // is a_InitialMipAngle
  56585. //
  56586. // The angle for the subsequent levels of the mip chain are specified by their parents
  56587. // filtering angle and a per-level scale and bias
  56588. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56589. //
  56590. //--------------------------------------------------------------------------------------
  56591. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56592. // First, take count of the lighting model to modify SpecularPower
  56593. // 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;
  56594. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56595. //Cone angle start (for generating subsequent mip levels)
  56596. var currentSpecularPower = this.specularPower;
  56597. //Build filter lookup tables based on the source miplevel size
  56598. this.precomputeFilterLookupTables(this.inputSize);
  56599. // Note that we need to filter the first level before generating mipmap
  56600. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56601. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56602. // TODO : Write a function to copy and scale the base mipmap in output
  56603. // I am just lazy here and just put a high specular power value, and do some if.
  56604. if (this.excludeBase && (levelIndex == 0)) {
  56605. // 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).
  56606. currentSpecularPower = 100000.0;
  56607. }
  56608. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56609. var srcCubeImage = this.input;
  56610. var dstCubeImage = this._outputSurface[levelIndex];
  56611. var dstSize = this.outputSize >> levelIndex;
  56612. // Compute required angle.
  56613. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56614. // filter cube surfaces
  56615. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56616. // fix seams
  56617. if (this.fixup) {
  56618. this.fixupCubeEdges(dstCubeImage, dstSize);
  56619. }
  56620. // Decrease the specular power to generate the mipmap chain
  56621. // TODO : Use another method for Exclude (see first comment at start of the function
  56622. if (this.excludeBase && (levelIndex == 0)) {
  56623. currentSpecularPower = this.specularPower;
  56624. }
  56625. currentSpecularPower *= this.cosinePowerDropPerMip;
  56626. }
  56627. };
  56628. //--------------------------------------------------------------------------------------
  56629. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56630. // It allow to optimize the texel to access base on the specular power.
  56631. //--------------------------------------------------------------------------------------
  56632. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56633. // We want to find the alpha such that:
  56634. // cos(alpha)^cosinePower = epsilon
  56635. // That's: acos(epsilon^(1/cosinePower))
  56636. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  56637. var angle = 180.0;
  56638. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  56639. angle *= 180.0 / Math.PI; // Convert to degree
  56640. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  56641. return angle;
  56642. };
  56643. //--------------------------------------------------------------------------------------
  56644. //Builds the following lookup tables prior to filtering:
  56645. // -normalizer cube map
  56646. // -tap weight lookup table
  56647. //
  56648. //--------------------------------------------------------------------------------------
  56649. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  56650. var srcTexelAngle;
  56651. var iCubeFace;
  56652. //clear pre-existing normalizer cube map
  56653. this._normCubeMap = [];
  56654. //Normalized vectors per cubeface and per-texel solid angle
  56655. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  56656. };
  56657. //--------------------------------------------------------------------------------------
  56658. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  56659. //
  56660. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  56661. //
  56662. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  56663. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  56664. // below
  56665. //--------------------------------------------------------------------------------------
  56666. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  56667. var iCubeFace;
  56668. var u;
  56669. var v;
  56670. //iterate over cube faces
  56671. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56672. //First three channels for norm cube, and last channel for solid angle
  56673. this._normCubeMap.push(new Float32Array(size * size * 4));
  56674. //fast texture walk, build normalizer cube map
  56675. var facesData = this.input[iCubeFace];
  56676. for (v = 0; v < size; v++) {
  56677. for (u = 0; u < size; u++) {
  56678. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  56679. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  56680. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  56681. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  56682. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  56683. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  56684. }
  56685. }
  56686. }
  56687. };
  56688. //--------------------------------------------------------------------------------------
  56689. // Convert cubemap face texel coordinates and face idx to 3D vector
  56690. // note the U and V coords are integer coords and range from 0 to size-1
  56691. // this routine can be used to generate a normalizer cube map
  56692. //--------------------------------------------------------------------------------------
  56693. // SL BEGIN
  56694. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  56695. var nvcU;
  56696. var nvcV;
  56697. var tempVec;
  56698. // Change from original AMD code
  56699. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56700. // + 0.5f is for texel center addressing
  56701. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  56702. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  56703. // warp fixup
  56704. if (fixup && size > 1) {
  56705. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  56706. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  56707. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  56708. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  56709. }
  56710. // Get current vector
  56711. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  56712. // U contribution
  56713. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56714. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  56715. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  56716. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  56717. // V contribution and Sum
  56718. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56719. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  56720. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  56721. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  56722. //add face axis
  56723. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  56724. PMREMGenerator._vectorTemp.x += faceAxis[0];
  56725. PMREMGenerator._vectorTemp.y += faceAxis[1];
  56726. PMREMGenerator._vectorTemp.z += faceAxis[2];
  56727. //normalize vector
  56728. PMREMGenerator._vectorTemp.normalize();
  56729. return PMREMGenerator._vectorTemp;
  56730. };
  56731. //--------------------------------------------------------------------------------------
  56732. // Convert 3D vector to cubemap face texel coordinates and face idx
  56733. // note the U and V coords are integer coords and range from 0 to size-1
  56734. // this routine can be used to generate a normalizer cube map
  56735. //
  56736. // returns face IDX and texel coords
  56737. //--------------------------------------------------------------------------------------
  56738. // SL BEGIN
  56739. /*
  56740. Mapping Texture Coordinates to Cube Map Faces
  56741. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  56742. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  56743. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  56744. map arrangement in Pixar's RenderMan package.
  56745. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  56746. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  56747. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  56748. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  56749. the major axis direction). The target column in the table below explains how the major axis direction
  56750. maps to the 2D image of a particular cube map target.
  56751. major axis
  56752. direction target sc tc ma
  56753. ---------- --------------------------------- --- --- ---
  56754. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  56755. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  56756. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  56757. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  56758. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  56759. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  56760. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  56761. an updated (s,t) is calculated as follows
  56762. s = ( sc/|ma| + 1 ) / 2
  56763. t = ( tc/|ma| + 1 ) / 2
  56764. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  56765. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  56766. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  56767. */
  56768. // Note this method return U and V in range from 0 to size-1
  56769. // SL END
  56770. // Store the information in vector3 for convenience (faceindex, u, v)
  56771. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  56772. var maxCoord;
  56773. var faceIdx;
  56774. //absolute value 3
  56775. var absX = Math.abs(x);
  56776. var absY = Math.abs(y);
  56777. var absZ = Math.abs(z);
  56778. if (absX >= absY && absX >= absZ) {
  56779. maxCoord = absX;
  56780. if (x >= 0) {
  56781. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  56782. }
  56783. else {
  56784. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56785. }
  56786. }
  56787. else if (absY >= absX && absY >= absZ) {
  56788. maxCoord = absY;
  56789. if (y >= 0) {
  56790. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56791. }
  56792. else {
  56793. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56794. }
  56795. }
  56796. else {
  56797. maxCoord = absZ;
  56798. if (z >= 0) {
  56799. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56800. }
  56801. else {
  56802. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56803. }
  56804. }
  56805. //divide through by max coord so face vector lies on cube face
  56806. var scale = 1 / maxCoord;
  56807. x *= scale;
  56808. y *= scale;
  56809. z *= scale;
  56810. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56811. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  56812. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56813. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  56814. // Modify original AMD code to return value from 0 to Size - 1
  56815. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  56816. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  56817. PMREMGenerator._vectorTemp.x = faceIdx;
  56818. PMREMGenerator._vectorTemp.y = u;
  56819. PMREMGenerator._vectorTemp.z = v;
  56820. return PMREMGenerator._vectorTemp;
  56821. };
  56822. //--------------------------------------------------------------------------------------
  56823. //Original code from Ignacio CastaÒo
  56824. // This formula is from Manne ÷hrstrˆm's thesis.
  56825. // Take two coordiantes in the range [-1, 1] that define a portion of a
  56826. // cube face and return the area of the projection of that portion on the
  56827. // surface of the sphere.
  56828. //--------------------------------------------------------------------------------------
  56829. PMREMGenerator.prototype.areaElement = function (x, y) {
  56830. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  56831. };
  56832. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  56833. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56834. // (+ 0.5f is for texel center addressing)
  56835. u = (2.0 * (u + 0.5) / size) - 1.0;
  56836. v = (2.0 * (v + 0.5) / size) - 1.0;
  56837. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  56838. var invResolution = 1.0 / size;
  56839. // U and V are the -1..1 texture coordinate on the current face.
  56840. // Get projected area for this texel
  56841. var x0 = u - invResolution;
  56842. var y0 = v - invResolution;
  56843. var x1 = u + invResolution;
  56844. var y1 = v + invResolution;
  56845. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  56846. return solidAngle;
  56847. };
  56848. //--------------------------------------------------------------------------------------
  56849. //The key to the speed of these filtering routines is to quickly define a per-face
  56850. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  56851. // Later these pixels are selectively processed based on their dot products to see if
  56852. // they reside within the filtering cone.
  56853. //
  56854. //This is done by computing the smallest per-texel angle to get a conservative estimate
  56855. // of the number of texels needed to be covered in width and height order to filter the
  56856. // region. the bounding box for the center taps face is defined first, and if the
  56857. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  56858. // defined next
  56859. //--------------------------------------------------------------------------------------
  56860. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  56861. // note that pixels within these regions may be rejected
  56862. // based on the anlge
  56863. var iCubeFace;
  56864. var u;
  56865. var v;
  56866. // bounding box per face to specify region to process
  56867. var filterExtents = [];
  56868. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56869. filterExtents.push(new CMGBoundinBox());
  56870. }
  56871. // min angle a src texel can cover (in degrees)
  56872. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  56873. // angle about center tap to define filter cone
  56874. // filter angle is 1/2 the cone angle
  56875. var filterAngle = filterConeAngle / 2.0;
  56876. //ensure filter angle is larger than a texel
  56877. if (filterAngle < srcTexelAngle) {
  56878. filterAngle = srcTexelAngle;
  56879. }
  56880. //ensure filter cone is always smaller than the hemisphere
  56881. if (filterAngle > 90.0) {
  56882. filterAngle = 90.0;
  56883. }
  56884. // the maximum number of texels in 1D the filter cone angle will cover
  56885. // used to determine bounding box size for filter extents
  56886. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  56887. // ensure conservative region always covers at least one texel
  56888. if (filterSize < 1) {
  56889. filterSize = 1;
  56890. }
  56891. // dotProdThresh threshold based on cone angle to determine whether or not taps
  56892. // reside within the cone angle
  56893. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  56894. // process required faces
  56895. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56896. //iterate over dst cube map face texel
  56897. for (v = 0; v < dstSize; v++) {
  56898. for (u = 0; u < dstSize; u++) {
  56899. //get center tap direction
  56900. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  56901. //clear old per-face filter extents
  56902. this.clearFilterExtents(filterExtents);
  56903. //define per-face filter extents
  56904. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  56905. //perform filtering of src faces using filter extents
  56906. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  56907. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  56908. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  56909. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  56910. }
  56911. }
  56912. }
  56913. };
  56914. //--------------------------------------------------------------------------------------
  56915. //Clear filter extents for the 6 cube map faces
  56916. //--------------------------------------------------------------------------------------
  56917. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  56918. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  56919. filterExtents[iCubeFaces].clear();
  56920. }
  56921. };
  56922. //--------------------------------------------------------------------------------------
  56923. //Define per-face bounding box filter extents
  56924. //
  56925. // These define conservative texel regions in each of the faces the filter can possibly
  56926. // process. When the pixels in the regions are actually processed, the dot product
  56927. // between the tap vector and the center tap vector is used to determine the weight of
  56928. // the tap and whether or not the tap is within the cone.
  56929. //
  56930. //--------------------------------------------------------------------------------------
  56931. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  56932. //neighboring face and bleed over amount, and width of BBOX for
  56933. // left, right, top, and bottom edges of this face
  56934. var bleedOverAmount = [0, 0, 0, 0];
  56935. var bleedOverBBoxMin = [0, 0, 0, 0];
  56936. var bleedOverBBoxMax = [0, 0, 0, 0];
  56937. var neighborFace;
  56938. var neighborEdge;
  56939. var oppositeFaceIdx;
  56940. //get face idx, and u, v info from center tap dir
  56941. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  56942. var faceIdx = result.x;
  56943. var u = result.y;
  56944. var v = result.z;
  56945. //define bbox size within face
  56946. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  56947. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  56948. filterExtents[faceIdx].clampMin(0, 0, 0);
  56949. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  56950. //u and v extent in face corresponding to center tap
  56951. var minU = filterExtents[faceIdx].min.x;
  56952. var minV = filterExtents[faceIdx].min.y;
  56953. var maxU = filterExtents[faceIdx].max.x;
  56954. var maxV = filterExtents[faceIdx].max.y;
  56955. //bleed over amounts for face across u=0 edge (left)
  56956. bleedOverAmount[0] = (bboxSize - u);
  56957. bleedOverBBoxMin[0] = minV;
  56958. bleedOverBBoxMax[0] = maxV;
  56959. //bleed over amounts for face across u=1 edge (right)
  56960. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  56961. bleedOverBBoxMin[1] = minV;
  56962. bleedOverBBoxMax[1] = maxV;
  56963. //bleed over to face across v=0 edge (up)
  56964. bleedOverAmount[2] = (bboxSize - v);
  56965. bleedOverBBoxMin[2] = minU;
  56966. bleedOverBBoxMax[2] = maxU;
  56967. //bleed over to face across v=1 edge (down)
  56968. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  56969. bleedOverBBoxMin[3] = minU;
  56970. bleedOverBBoxMax[3] = maxU;
  56971. //compute bleed over regions in neighboring faces
  56972. for (var i = 0; i < 4; i++) {
  56973. if (bleedOverAmount[i] > 0) {
  56974. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  56975. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  56976. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  56977. // be flipped: the cases are
  56978. // if a left edge mates with a left or bottom edge on the neighbor
  56979. // if a top edge mates with a top or right edge on the neighbor
  56980. // if a right edge mates with a right or top edge on the neighbor
  56981. // if a bottom edge mates with a bottom or left edge on the neighbor
  56982. //Seeing as the edges are enumerated as follows
  56983. // left =0
  56984. // right =1
  56985. // top =2
  56986. // bottom =3
  56987. //
  56988. // so if the edge enums are the same, or the sum of the enums == 3,
  56989. // the bbox needs to be flipped
  56990. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  56991. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  56992. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  56993. }
  56994. //The way the bounding box is extended onto the neighboring face
  56995. // depends on which edge of neighboring face abuts with this one
  56996. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  56997. case PMREMGenerator.CP_EDGE_LEFT:
  56998. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  56999. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57000. break;
  57001. case PMREMGenerator.CP_EDGE_RIGHT:
  57002. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57003. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57004. break;
  57005. case PMREMGenerator.CP_EDGE_TOP:
  57006. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57007. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57008. break;
  57009. case PMREMGenerator.CP_EDGE_BOTTOM:
  57010. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57011. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57012. break;
  57013. }
  57014. //clamp filter extents in non-center tap faces to remain within surface
  57015. filterExtents[neighborFace].clampMin(0, 0, 0);
  57016. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57017. }
  57018. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57019. // from the center tap face, then process the opposite face entirely for now.
  57020. //Note that the cases in which this happens, what usually happens is that
  57021. // more than one edge bleeds onto the opposite face, and the bounding box
  57022. // encompasses the entire cube map face.
  57023. if (bleedOverAmount[i] > srcSize) {
  57024. //determine opposite face
  57025. switch (faceIdx) {
  57026. case PMREMGenerator.CP_FACE_X_POS:
  57027. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57028. break;
  57029. case PMREMGenerator.CP_FACE_X_NEG:
  57030. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57031. break;
  57032. case PMREMGenerator.CP_FACE_Y_POS:
  57033. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57034. break;
  57035. case PMREMGenerator.CP_FACE_Y_NEG:
  57036. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57037. break;
  57038. case PMREMGenerator.CP_FACE_Z_POS:
  57039. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57040. break;
  57041. case PMREMGenerator.CP_FACE_Z_NEG:
  57042. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57043. break;
  57044. default:
  57045. break;
  57046. }
  57047. //just encompass entire face for now
  57048. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57049. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57050. }
  57051. }
  57052. };
  57053. //--------------------------------------------------------------------------------------
  57054. //ProcessFilterExtents
  57055. // Process bounding box in each cube face
  57056. //
  57057. //--------------------------------------------------------------------------------------
  57058. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57059. //accumulators are 64-bit floats in order to have the precision needed
  57060. // over a summation of a large number of pixels
  57061. var dstAccum = [0, 0, 0, 0];
  57062. var weightAccum = 0;
  57063. var k = 0;
  57064. var nSrcChannels = this.numChannels;
  57065. // norm cube map and srcCubeMap have same face width
  57066. var faceWidth = srcSize;
  57067. //amount to add to pointer to move to next scanline in images
  57068. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57069. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57070. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57071. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57072. // iterate over cubefaces
  57073. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57074. //if bbox is non empty
  57075. if (!filterExtents[iFaceIdx].empty()) {
  57076. var uStart = filterExtents[iFaceIdx].min.x;
  57077. var vStart = filterExtents[iFaceIdx].min.y;
  57078. var uEnd = filterExtents[iFaceIdx].max.x;
  57079. var vEnd = filterExtents[iFaceIdx].max.y;
  57080. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57081. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57082. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57083. for (var v = vStart; v <= vEnd; v++) {
  57084. var normCubeRowWalk = 0;
  57085. var srcCubeRowWalk = 0;
  57086. for (var u = uStart; u <= uEnd; u++) {
  57087. //pointer to direction in cube map associated with texel
  57088. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57089. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57090. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57091. //check dot product to see if texel is within cone
  57092. var tapDotProd = texelVectX * centerTapDir.x +
  57093. texelVectY * centerTapDir.y +
  57094. texelVectZ * centerTapDir.z;
  57095. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57096. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57097. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57098. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57099. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57100. // so just adding one to specularpower do the trick.
  57101. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57102. //iterate over channels
  57103. for (k = 0; k < nSrcChannels; k++) {
  57104. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57105. srcCubeRowWalk++;
  57106. }
  57107. weightAccum += weight; //accumulate weight
  57108. }
  57109. else {
  57110. //step across source pixel
  57111. srcCubeRowWalk += nSrcChannels;
  57112. }
  57113. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57114. }
  57115. startIndexNormCubeMap += normCubePitch;
  57116. startIndexSrcCubeMap += srcCubePitch;
  57117. }
  57118. }
  57119. }
  57120. //divide through by weights if weight is non zero
  57121. if (weightAccum != 0.0) {
  57122. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57123. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57124. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57125. if (this.numChannels > 3) {
  57126. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57127. }
  57128. }
  57129. else {
  57130. // otherwise sample nearest
  57131. // get face idx and u, v texel coordinate in face
  57132. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57133. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57134. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57135. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57136. if (this.numChannels > 3) {
  57137. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57138. }
  57139. }
  57140. return PMREMGenerator._vectorTemp;
  57141. };
  57142. //--------------------------------------------------------------------------------------
  57143. // Fixup cube edges
  57144. //
  57145. // average texels on cube map faces across the edges
  57146. // WARP/BENT Method Only.
  57147. //--------------------------------------------------------------------------------------
  57148. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57149. var k;
  57150. var j;
  57151. var i;
  57152. var iFace;
  57153. var iCorner = 0;
  57154. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57155. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57156. // note that if functionality to filter across the three texels for each corner, then
  57157. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57158. var cornerPtr = [
  57159. [[], [], []],
  57160. [[], [], []],
  57161. [[], [], []],
  57162. [[], [], []],
  57163. [[], [], []],
  57164. [[], [], []],
  57165. [[], [], []],
  57166. [[], [], []]
  57167. ];
  57168. //if there is no fixup, or fixup width = 0, do nothing
  57169. if (cubeMapSize < 1) {
  57170. return;
  57171. }
  57172. //special case 1x1 cubemap, average face colors
  57173. if (cubeMapSize == 1) {
  57174. //iterate over channels
  57175. for (k = 0; k < this.numChannels; k++) {
  57176. var accum = 0.0;
  57177. //iterate over faces to accumulate face colors
  57178. for (iFace = 0; iFace < 6; iFace++) {
  57179. accum += cubeMap[iFace][k];
  57180. }
  57181. //compute average over 6 face colors
  57182. accum /= 6.0;
  57183. //iterate over faces to distribute face colors
  57184. for (iFace = 0; iFace < 6; iFace++) {
  57185. cubeMap[iFace][k] = accum;
  57186. }
  57187. }
  57188. return;
  57189. }
  57190. //iterate over faces to collect list of corner texel pointers
  57191. for (iFace = 0; iFace < 6; iFace++) {
  57192. //the 4 corner pointers for this face
  57193. faceCornerStartIndicies[0] = [iFace, 0];
  57194. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57195. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57196. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57197. //iterate over face corners to collect cube corner pointers
  57198. for (iCorner = 0; iCorner < 4; iCorner++) {
  57199. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57200. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57201. cornerNumPtrs[corner]++;
  57202. }
  57203. }
  57204. //iterate over corners to average across corner tap values
  57205. for (iCorner = 0; iCorner < 8; iCorner++) {
  57206. for (k = 0; k < this.numChannels; k++) {
  57207. var cornerTapAccum = 0.0;
  57208. //iterate over corner texels and average results
  57209. for (i = 0; i < 3; i++) {
  57210. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57211. }
  57212. //divide by 3 to compute average of corner tap values
  57213. cornerTapAccum *= (1.0 / 3.0);
  57214. //iterate over corner texels and average results
  57215. for (i = 0; i < 3; i++) {
  57216. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57217. }
  57218. }
  57219. }
  57220. //iterate over the twelve edges of the cube to average across edges
  57221. for (i = 0; i < 12; i++) {
  57222. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57223. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57224. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57225. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57226. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57227. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57228. var edgeWalk = 0;
  57229. var neighborEdgeWalk = 0;
  57230. //Determine walking pointers based on edge type
  57231. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57232. switch (edge) {
  57233. case PMREMGenerator.CP_EDGE_LEFT:
  57234. // no change to faceEdgeStartPtr
  57235. edgeWalk = this.numChannels * cubeMapSize;
  57236. break;
  57237. case PMREMGenerator.CP_EDGE_RIGHT:
  57238. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57239. edgeWalk = this.numChannels * cubeMapSize;
  57240. break;
  57241. case PMREMGenerator.CP_EDGE_TOP:
  57242. // no change to faceEdgeStartPtr
  57243. edgeWalk = this.numChannels;
  57244. break;
  57245. case PMREMGenerator.CP_EDGE_BOTTOM:
  57246. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57247. edgeWalk = this.numChannels;
  57248. break;
  57249. }
  57250. //For certain types of edge abutments, the neighbor edge walk needs to
  57251. // be flipped: the cases are
  57252. // if a left edge mates with a left or bottom edge on the neighbor
  57253. // if a top edge mates with a top or right edge on the neighbor
  57254. // if a right edge mates with a right or top edge on the neighbor
  57255. // if a bottom edge mates with a bottom or left edge on the neighbor
  57256. //Seeing as the edges are enumerated as follows
  57257. // left =0
  57258. // right =1
  57259. // top =2
  57260. // bottom =3
  57261. //
  57262. //If the edge enums are the same, or the sum of the enums == 3,
  57263. // the neighbor edge walk needs to be flipped
  57264. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57265. switch (neighborEdge) {
  57266. case PMREMGenerator.CP_EDGE_LEFT:
  57267. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57268. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57269. break;
  57270. case PMREMGenerator.CP_EDGE_RIGHT:
  57271. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57272. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57273. break;
  57274. case PMREMGenerator.CP_EDGE_TOP:
  57275. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57276. neighborEdgeWalk = -this.numChannels;
  57277. break;
  57278. case PMREMGenerator.CP_EDGE_BOTTOM:
  57279. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57280. neighborEdgeWalk = -this.numChannels;
  57281. break;
  57282. }
  57283. }
  57284. else {
  57285. //swapped direction neighbor edge walk
  57286. switch (neighborEdge) {
  57287. case PMREMGenerator.CP_EDGE_LEFT:
  57288. //no change to neighborEdgeStartPtr for this case since it points
  57289. // to the upper left corner already
  57290. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57291. break;
  57292. case PMREMGenerator.CP_EDGE_RIGHT:
  57293. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57294. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57295. break;
  57296. case PMREMGenerator.CP_EDGE_TOP:
  57297. //no change to neighborEdgeStartPtr for this case since it points
  57298. // to the upper left corner already
  57299. neighborEdgeWalk = this.numChannels;
  57300. break;
  57301. case PMREMGenerator.CP_EDGE_BOTTOM:
  57302. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57303. neighborEdgeWalk = this.numChannels;
  57304. break;
  57305. }
  57306. }
  57307. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57308. //nearby neighborhood
  57309. //step ahead one texel on edge
  57310. edgeStartIndex += edgeWalk;
  57311. neighborEdgeStartIndex += neighborEdgeWalk;
  57312. // note that this loop does not process the corner texels, since they have already been
  57313. // averaged across faces across earlier
  57314. for (j = 1; j < (cubeMapSize - 1); j++) {
  57315. //for each set of taps along edge, average them
  57316. // and rewrite the results into the edges
  57317. for (k = 0; k < this.numChannels; k++) {
  57318. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57319. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57320. //compute average of tap intensity values
  57321. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57322. //propagate average of taps to edge taps
  57323. cubeMap[face][edgeStartIndex + k] = avgTap;
  57324. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57325. }
  57326. edgeStartIndex += edgeWalk;
  57327. neighborEdgeStartIndex += neighborEdgeWalk;
  57328. }
  57329. }
  57330. };
  57331. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57332. PMREMGenerator.CP_UDIR = 0;
  57333. PMREMGenerator.CP_VDIR = 1;
  57334. PMREMGenerator.CP_FACEAXIS = 2;
  57335. //used to index cube faces
  57336. PMREMGenerator.CP_FACE_X_POS = 0;
  57337. PMREMGenerator.CP_FACE_X_NEG = 1;
  57338. PMREMGenerator.CP_FACE_Y_POS = 2;
  57339. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57340. PMREMGenerator.CP_FACE_Z_POS = 4;
  57341. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57342. //used to index image edges
  57343. // NOTE.. the actual number corresponding to the edge is important
  57344. // do not change these, or the code will break
  57345. //
  57346. // CP_EDGE_LEFT is u = 0
  57347. // CP_EDGE_RIGHT is u = width-1
  57348. // CP_EDGE_TOP is v = 0
  57349. // CP_EDGE_BOTTOM is v = height-1
  57350. PMREMGenerator.CP_EDGE_LEFT = 0;
  57351. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57352. PMREMGenerator.CP_EDGE_TOP = 2;
  57353. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57354. //corners of CUBE map (P or N specifys if it corresponds to the
  57355. // positive or negative direction each of X, Y, and Z
  57356. PMREMGenerator.CP_CORNER_NNN = 0;
  57357. PMREMGenerator.CP_CORNER_NNP = 1;
  57358. PMREMGenerator.CP_CORNER_NPN = 2;
  57359. PMREMGenerator.CP_CORNER_NPP = 3;
  57360. PMREMGenerator.CP_CORNER_PNN = 4;
  57361. PMREMGenerator.CP_CORNER_PNP = 5;
  57362. PMREMGenerator.CP_CORNER_PPN = 6;
  57363. PMREMGenerator.CP_CORNER_PPP = 7;
  57364. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57365. //3x2 matrices that map cube map indexing vectors in 3d
  57366. // (after face selection and divide through by the
  57367. // _ABSOLUTE VALUE_ of the max coord)
  57368. // into NVC space
  57369. //Note this currently assumes the D3D cube face ordering and orientation
  57370. PMREMGenerator._sgFace2DMapping = [
  57371. //XPOS face
  57372. [[0, 0, -1],
  57373. [0, -1, 0],
  57374. [1, 0, 0]],
  57375. //XNEG face
  57376. [[0, 0, 1],
  57377. [0, -1, 0],
  57378. [-1, 0, 0]],
  57379. //YPOS face
  57380. [[1, 0, 0],
  57381. [0, 0, 1],
  57382. [0, 1, 0]],
  57383. //YNEG face
  57384. [[1, 0, 0],
  57385. [0, 0, -1],
  57386. [0, -1, 0]],
  57387. //ZPOS face
  57388. [[1, 0, 0],
  57389. [0, -1, 0],
  57390. [0, 0, 1]],
  57391. //ZNEG face
  57392. [[-1, 0, 0],
  57393. [0, -1, 0],
  57394. [0, 0, -1]],
  57395. ];
  57396. //------------------------------------------------------------------------------
  57397. // D3D cube map face specification
  57398. // mapping from 3D x,y,z cube map lookup coordinates
  57399. // to 2D within face u,v coordinates
  57400. //
  57401. // --------------------> U direction
  57402. // | (within-face texture space)
  57403. // | _____
  57404. // | | |
  57405. // | | +Y |
  57406. // | _____|_____|_____ _____
  57407. // | | | | | |
  57408. // | | -X | +Z | +X | -Z |
  57409. // | |_____|_____|_____|_____|
  57410. // | | |
  57411. // | | -Y |
  57412. // | |_____|
  57413. // |
  57414. // v V direction
  57415. // (within-face texture space)
  57416. //------------------------------------------------------------------------------
  57417. //Information about neighbors and how texture coorrdinates change across faces
  57418. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57419. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57420. //Note this currently assumes the D3D cube face ordering and orientation
  57421. PMREMGenerator._sgCubeNgh = [
  57422. //XPOS face
  57423. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57424. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57425. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57426. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57427. //XNEG face
  57428. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57429. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57430. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57431. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57432. //YPOS face
  57433. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57434. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57435. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57436. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57437. //YNEG face
  57438. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57439. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57440. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57441. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57442. //ZPOS face
  57443. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57444. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57445. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57446. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57447. //ZNEG face
  57448. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57449. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57450. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57451. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57452. ];
  57453. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57454. // this table is used to average over the edges.
  57455. PMREMGenerator._sgCubeEdgeList = [
  57456. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57457. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57458. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57459. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57460. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57461. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57462. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57463. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57464. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57465. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57466. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57467. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57468. ];
  57469. //Information about which of the 8 cube corners are correspond to the
  57470. // the 4 corners in each cube face
  57471. // the order is upper left, upper right, lower left, lower right
  57472. PMREMGenerator._sgCubeCornerList = [
  57473. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57474. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57475. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57476. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57477. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57478. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57479. ];
  57480. return PMREMGenerator;
  57481. }());
  57482. Internals.PMREMGenerator = PMREMGenerator;
  57483. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57484. })(BABYLON || (BABYLON = {}));
  57485. var BABYLON;
  57486. (function (BABYLON) {
  57487. /**
  57488. * This represents a texture coming from an HDR input.
  57489. *
  57490. * The only supported format is currently panorama picture stored in RGBE format.
  57491. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57492. */
  57493. var HDRCubeTexture = (function (_super) {
  57494. __extends(HDRCubeTexture, _super);
  57495. /**
  57496. * Instantiates an HDRTexture from the following parameters.
  57497. *
  57498. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57499. * @param scene The scene the texture will be used in
  57500. * @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.
  57501. * @param noMipmap Forces to not generate the mipmap if true
  57502. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57503. * @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)
  57504. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57505. */
  57506. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  57507. if (noMipmap === void 0) { noMipmap = false; }
  57508. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57509. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57510. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57511. _super.call(this, scene);
  57512. this._useInGammaSpace = false;
  57513. this._generateHarmonics = true;
  57514. this._isBABYLONPreprocessed = false;
  57515. /**
  57516. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57517. */
  57518. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57519. /**
  57520. * The spherical polynomial data extracted from the texture.
  57521. */
  57522. this.sphericalPolynomial = null;
  57523. /**
  57524. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57525. * This is usefull at run time to apply the good shader.
  57526. */
  57527. this.isPMREM = false;
  57528. if (!url) {
  57529. return;
  57530. }
  57531. this.name = url;
  57532. this.url = url;
  57533. this.hasAlpha = false;
  57534. this.isCube = true;
  57535. this._textureMatrix = BABYLON.Matrix.Identity();
  57536. if (size) {
  57537. this._isBABYLONPreprocessed = false;
  57538. this._noMipmap = noMipmap;
  57539. this._size = size;
  57540. this._useInGammaSpace = useInGammaSpace;
  57541. this._usePMREMGenerator = usePMREMGenerator &&
  57542. scene.getEngine().getCaps().textureLOD &&
  57543. this.getScene().getEngine().getCaps().textureFloat &&
  57544. !this._useInGammaSpace;
  57545. }
  57546. else {
  57547. this._isBABYLONPreprocessed = true;
  57548. this._noMipmap = false;
  57549. this._useInGammaSpace = false;
  57550. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57551. this.getScene().getEngine().getCaps().textureFloat &&
  57552. !this._useInGammaSpace;
  57553. }
  57554. this.isPMREM = this._usePMREMGenerator;
  57555. this._texture = this._getFromCache(url, this._noMipmap);
  57556. if (!this._texture) {
  57557. if (!scene.useDelayedTextureLoading) {
  57558. this.loadTexture();
  57559. }
  57560. else {
  57561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57562. }
  57563. }
  57564. }
  57565. /**
  57566. * Occurs when the file is a preprocessed .babylon.hdr file.
  57567. */
  57568. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57569. var _this = this;
  57570. var mipLevels = 0;
  57571. var floatArrayView = null;
  57572. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57573. var mips = [];
  57574. var startIndex = 30;
  57575. for (var level = 0; level < mipLevels; level++) {
  57576. mips.push([]);
  57577. // Fill each pixel of the mip level.
  57578. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57579. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57580. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57581. mips[level].push(faceData);
  57582. startIndex += faceSize;
  57583. }
  57584. }
  57585. return mips;
  57586. } : null;
  57587. var callback = function (buffer) {
  57588. // Create Native Array Views
  57589. var intArrayView = new Int32Array(buffer);
  57590. floatArrayView = new Float32Array(buffer);
  57591. // Fill header.
  57592. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57593. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57594. // Update Texture Information.
  57595. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57596. // Fill polynomial information.
  57597. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57598. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57599. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57600. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57601. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57602. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57603. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57604. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57605. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57606. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57607. // Fill pixel data.
  57608. mipLevels = intArrayView[29]; // Number of mip levels.
  57609. var startIndex = 30;
  57610. var data = [];
  57611. var faceSize = Math.pow(_this._size, 2) * 3;
  57612. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57613. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57614. startIndex += faceSize;
  57615. }
  57616. var results = [];
  57617. var byteArray = null;
  57618. // Push each faces.
  57619. for (var k = 0; k < 6; k++) {
  57620. var dataFace = null;
  57621. // If special cases.
  57622. if (!mipmapGenerator) {
  57623. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57624. dataFace = data[j];
  57625. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57626. // 3 channels of 1 bytes per pixel in bytes.
  57627. var byteBuffer = new ArrayBuffer(faceSize);
  57628. byteArray = new Uint8Array(byteBuffer);
  57629. }
  57630. for (var i = 0; i < _this._size * _this._size; i++) {
  57631. // Put in gamma space if requested.
  57632. if (_this._useInGammaSpace) {
  57633. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57634. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57635. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57636. }
  57637. // Convert to int texture for fallback.
  57638. if (byteArray) {
  57639. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57640. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57641. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57642. // May use luminance instead if the result is not accurate.
  57643. var max = Math.max(Math.max(r, g), b);
  57644. if (max > 255) {
  57645. var scale = 255 / max;
  57646. r *= scale;
  57647. g *= scale;
  57648. b *= scale;
  57649. }
  57650. byteArray[(i * 3) + 0] = r;
  57651. byteArray[(i * 3) + 1] = g;
  57652. byteArray[(i * 3) + 2] = b;
  57653. }
  57654. }
  57655. }
  57656. else {
  57657. dataFace = data[k];
  57658. }
  57659. // Fill the array accordingly.
  57660. if (byteArray) {
  57661. results.push(byteArray);
  57662. }
  57663. else {
  57664. results.push(dataFace);
  57665. }
  57666. }
  57667. return results;
  57668. };
  57669. 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);
  57670. };
  57671. /**
  57672. * Occurs when the file is raw .hdr file.
  57673. */
  57674. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57675. var _this = this;
  57676. var callback = function (buffer) {
  57677. // Extract the raw linear data.
  57678. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57679. // Generate harmonics if needed.
  57680. if (_this._generateHarmonics) {
  57681. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57682. }
  57683. var results = [];
  57684. var byteArray = null;
  57685. // Push each faces.
  57686. for (var j = 0; j < 6; j++) {
  57687. // Create uintarray fallback.
  57688. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57689. // 3 channels of 1 bytes per pixel in bytes.
  57690. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57691. byteArray = new Uint8Array(byteBuffer);
  57692. }
  57693. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57694. // If special cases.
  57695. if (_this._useInGammaSpace || byteArray) {
  57696. for (var i = 0; i < _this._size * _this._size; i++) {
  57697. // Put in gamma space if requested.
  57698. if (_this._useInGammaSpace) {
  57699. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57700. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57701. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57702. }
  57703. // Convert to int texture for fallback.
  57704. if (byteArray) {
  57705. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57706. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57707. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57708. // May use luminance instead if the result is not accurate.
  57709. var max = Math.max(Math.max(r, g), b);
  57710. if (max > 255) {
  57711. var scale = 255 / max;
  57712. r *= scale;
  57713. g *= scale;
  57714. b *= scale;
  57715. }
  57716. byteArray[(i * 3) + 0] = r;
  57717. byteArray[(i * 3) + 1] = g;
  57718. byteArray[(i * 3) + 2] = b;
  57719. }
  57720. }
  57721. }
  57722. if (byteArray) {
  57723. results.push(byteArray);
  57724. }
  57725. else {
  57726. results.push(dataFace);
  57727. }
  57728. }
  57729. return results;
  57730. };
  57731. var mipmapGenerator = null;
  57732. if (!this._noMipmap &&
  57733. this._usePMREMGenerator) {
  57734. mipmapGenerator = function (data) {
  57735. // Custom setup of the generator matching with the PBR shader values.
  57736. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  57737. return generator.filterCubeMap();
  57738. };
  57739. }
  57740. 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);
  57741. };
  57742. /**
  57743. * Starts the loading process of the texture.
  57744. */
  57745. HDRCubeTexture.prototype.loadTexture = function () {
  57746. if (this._isBABYLONPreprocessed) {
  57747. this.loadBabylonTexture();
  57748. }
  57749. else {
  57750. this.loadHDRTexture();
  57751. }
  57752. };
  57753. HDRCubeTexture.prototype.clone = function () {
  57754. var size = this._isBABYLONPreprocessed ? null : this._size;
  57755. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57756. // Base texture
  57757. newTexture.level = this.level;
  57758. newTexture.wrapU = this.wrapU;
  57759. newTexture.wrapV = this.wrapV;
  57760. newTexture.coordinatesIndex = this.coordinatesIndex;
  57761. newTexture.coordinatesMode = this.coordinatesMode;
  57762. return newTexture;
  57763. };
  57764. // Methods
  57765. HDRCubeTexture.prototype.delayLoad = function () {
  57766. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57767. return;
  57768. }
  57769. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57770. this._texture = this._getFromCache(this.url, this._noMipmap);
  57771. if (!this._texture) {
  57772. this.loadTexture();
  57773. }
  57774. };
  57775. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57776. return this._textureMatrix;
  57777. };
  57778. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57779. var texture = null;
  57780. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57781. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57782. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  57783. texture.name = parsedTexture.name;
  57784. texture.hasAlpha = parsedTexture.hasAlpha;
  57785. texture.level = parsedTexture.level;
  57786. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57787. }
  57788. return texture;
  57789. };
  57790. HDRCubeTexture.prototype.serialize = function () {
  57791. if (!this.name) {
  57792. return null;
  57793. }
  57794. var serializationObject = {};
  57795. serializationObject.name = this.name;
  57796. serializationObject.hasAlpha = this.hasAlpha;
  57797. serializationObject.isCube = true;
  57798. serializationObject.level = this.level;
  57799. serializationObject.size = this._size;
  57800. serializationObject.coordinatesMode = this.coordinatesMode;
  57801. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57802. serializationObject.generateHarmonics = this._generateHarmonics;
  57803. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57804. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57805. return serializationObject;
  57806. };
  57807. /**
  57808. * Saves as a file the data contained in the texture in a binary format.
  57809. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57810. * as the spherical used in the lighting.
  57811. * @param url The HDR file url.
  57812. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57813. * @param onError Method called if any error happens during download.
  57814. * @return The packed binary data.
  57815. */
  57816. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57817. if (onError === void 0) { onError = null; }
  57818. var callback = function (buffer) {
  57819. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57820. // Returns a URL you can use as a href.
  57821. var objUrl = window.URL.createObjectURL(data);
  57822. // Simulates a link to it and click to dowload.
  57823. var a = document.createElement("a");
  57824. document.body.appendChild(a);
  57825. a.style.display = "none";
  57826. a.href = objUrl;
  57827. a.download = "envmap.babylon.hdr";
  57828. a.click();
  57829. };
  57830. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57831. };
  57832. /**
  57833. * Serializes the data contained in the texture in a binary format.
  57834. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57835. * as the spherical used in the lighting.
  57836. * @param url The HDR file url.
  57837. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57838. * @param onError Method called if any error happens during download.
  57839. * @return The packed binary data.
  57840. */
  57841. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57842. if (onError === void 0) { onError = null; }
  57843. // Needs the url tho create the texture.
  57844. if (!url) {
  57845. return null;
  57846. }
  57847. // Check Power of two size.
  57848. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57849. return null;
  57850. }
  57851. var getDataCallback = function (dataBuffer) {
  57852. // Extract the raw linear data.
  57853. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  57854. // Generate harmonics if needed.
  57855. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  57856. // Generate seamless faces
  57857. var mipGeneratorArray = [];
  57858. // Data are known to be in +X +Y +Z -X -Y -Z
  57859. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  57860. mipGeneratorArray.push(cubeData.right); // +X
  57861. mipGeneratorArray.push(cubeData.left); // -X
  57862. mipGeneratorArray.push(cubeData.up); // +Y
  57863. mipGeneratorArray.push(cubeData.down); // -Y
  57864. mipGeneratorArray.push(cubeData.front); // +Z
  57865. mipGeneratorArray.push(cubeData.back); // -Z
  57866. // Custom setup of the generator matching with the PBR shader values.
  57867. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  57868. var mippedData = generator.filterCubeMap();
  57869. // Compute required byte length.
  57870. var byteLength = 1 * 4; // Raw Data Version int32.
  57871. byteLength += 4; // CubeMap max mip face size int32.
  57872. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  57873. // Add data size.
  57874. byteLength += 4; // Number of mip levels int32.
  57875. for (var level = 0; level < mippedData.length; level++) {
  57876. var mipSize = size >> level;
  57877. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  57878. }
  57879. // Prepare binary structure.
  57880. var buffer = new ArrayBuffer(byteLength);
  57881. var intArrayView = new Int32Array(buffer);
  57882. var floatArrayView = new Float32Array(buffer);
  57883. // Fill header.
  57884. intArrayView[0] = 1; // Version 1.
  57885. intArrayView[1] = size; // CubeMap max mip face size.
  57886. // Fill polynomial information.
  57887. sphericalPolynomial.x.toArray(floatArrayView, 2);
  57888. sphericalPolynomial.y.toArray(floatArrayView, 5);
  57889. sphericalPolynomial.z.toArray(floatArrayView, 8);
  57890. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  57891. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  57892. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  57893. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  57894. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  57895. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  57896. // Fill pixel data.
  57897. intArrayView[29] = mippedData.length; // Number of mip levels.
  57898. var startIndex = 30;
  57899. for (var level = 0; level < mippedData.length; level++) {
  57900. // Fill each pixel of the mip level.
  57901. var faceSize = Math.pow(size >> level, 2) * 3;
  57902. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57903. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  57904. startIndex += faceSize;
  57905. }
  57906. }
  57907. // Callback.
  57908. callback(buffer);
  57909. };
  57910. // Download and process.
  57911. BABYLON.Tools.LoadFile(url, function (data) {
  57912. getDataCallback(data);
  57913. }, null, null, true, onError);
  57914. };
  57915. HDRCubeTexture._facesMapping = [
  57916. "right",
  57917. "up",
  57918. "front",
  57919. "left",
  57920. "down",
  57921. "back"
  57922. ];
  57923. return HDRCubeTexture;
  57924. }(BABYLON.BaseTexture));
  57925. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57926. })(BABYLON || (BABYLON = {}));
  57927. var BABYLON;
  57928. (function (BABYLON) {
  57929. var Debug;
  57930. (function (Debug) {
  57931. /**
  57932. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  57933. */
  57934. var SkeletonViewer = (function () {
  57935. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  57936. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  57937. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  57938. this.skeleton = skeleton;
  57939. this.mesh = mesh;
  57940. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  57941. this.renderingGroupId = renderingGroupId;
  57942. this.color = BABYLON.Color3.White();
  57943. this._debugLines = [];
  57944. this._isEnabled = false;
  57945. this._scene = scene;
  57946. this.update();
  57947. this._renderFunction = this.update.bind(this);
  57948. }
  57949. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  57950. get: function () {
  57951. return this._isEnabled;
  57952. },
  57953. set: function (value) {
  57954. if (this._isEnabled === value) {
  57955. return;
  57956. }
  57957. this._isEnabled = value;
  57958. if (value) {
  57959. this._scene.registerBeforeRender(this._renderFunction);
  57960. }
  57961. else {
  57962. this._scene.unregisterBeforeRender(this._renderFunction);
  57963. }
  57964. },
  57965. enumerable: true,
  57966. configurable: true
  57967. });
  57968. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  57969. if (x === void 0) { x = 0; }
  57970. if (y === void 0) { y = 0; }
  57971. if (z === void 0) { z = 0; }
  57972. var tmat = BABYLON.Tmp.Matrix[0];
  57973. var parentBone = bone.getParent();
  57974. tmat.copyFrom(bone.getLocalMatrix());
  57975. if (x !== 0 || y !== 0 || z !== 0) {
  57976. var tmat2 = BABYLON.Tmp.Matrix[1];
  57977. BABYLON.Matrix.IdentityToRef(tmat2);
  57978. tmat2.m[12] = x;
  57979. tmat2.m[13] = y;
  57980. tmat2.m[14] = z;
  57981. tmat2.multiplyToRef(tmat, tmat);
  57982. }
  57983. if (parentBone) {
  57984. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  57985. }
  57986. tmat.multiplyToRef(meshMat, tmat);
  57987. position.x = tmat.m[12];
  57988. position.y = tmat.m[13];
  57989. position.z = tmat.m[14];
  57990. };
  57991. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  57992. var len = bones.length;
  57993. for (var i = 0; i < len; i++) {
  57994. var bone = bones[i];
  57995. var points = this._debugLines[i];
  57996. if (!points) {
  57997. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57998. this._debugLines[i] = points;
  57999. }
  58000. this._getBonePosition(points[0], bone, meshMat);
  58001. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58002. }
  58003. };
  58004. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58005. var len = bones.length;
  58006. var boneNum = 0;
  58007. for (var i = len - 1; i >= 0; i--) {
  58008. var childBone = bones[i];
  58009. var parentBone = childBone.getParent();
  58010. if (!parentBone) {
  58011. continue;
  58012. }
  58013. var points = this._debugLines[boneNum];
  58014. if (!points) {
  58015. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58016. this._debugLines[boneNum] = points;
  58017. }
  58018. this._getBonePosition(points[0], childBone, meshMat);
  58019. this._getBonePosition(points[1], parentBone, meshMat);
  58020. boneNum++;
  58021. }
  58022. };
  58023. SkeletonViewer.prototype.update = function () {
  58024. if (this.autoUpdateBonesMatrices) {
  58025. this._updateBoneMatrix(this.skeleton.bones[0]);
  58026. }
  58027. if (this.skeleton.bones[0].length === undefined) {
  58028. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58029. }
  58030. else {
  58031. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58032. }
  58033. if (!this._debugMesh) {
  58034. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58035. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58036. }
  58037. else {
  58038. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58039. }
  58040. this._debugMesh.color = this.color;
  58041. };
  58042. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  58043. if (bone.getParent()) {
  58044. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  58045. }
  58046. var children = bone.children;
  58047. var len = children.length;
  58048. for (var i = 0; i < len; i++) {
  58049. this._updateBoneMatrix(children[i]);
  58050. }
  58051. };
  58052. SkeletonViewer.prototype.dispose = function () {
  58053. if (this._debugMesh) {
  58054. this.isEnabled = false;
  58055. this._debugMesh.dispose();
  58056. this._debugMesh = null;
  58057. }
  58058. };
  58059. return SkeletonViewer;
  58060. }());
  58061. Debug.SkeletonViewer = SkeletonViewer;
  58062. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58063. })(BABYLON || (BABYLON = {}));
  58064. var BABYLON;
  58065. (function (BABYLON) {
  58066. /**
  58067. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58068. * It can help converting any input color in a desired output one. This can then be used to create effects
  58069. * from sepia, black and white to sixties or futuristic rendering...
  58070. *
  58071. * The only supported format is currently 3dl.
  58072. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58073. */
  58074. var ColorGradingTexture = (function (_super) {
  58075. __extends(ColorGradingTexture, _super);
  58076. /**
  58077. * Instantiates a ColorGradingTexture from the following parameters.
  58078. *
  58079. * @param url The location of the color gradind data (currently only supporting 3dl)
  58080. * @param scene The scene the texture will be used in
  58081. */
  58082. function ColorGradingTexture(url, scene) {
  58083. _super.call(this, scene);
  58084. if (!url) {
  58085. return;
  58086. }
  58087. this._textureMatrix = BABYLON.Matrix.Identity();
  58088. this.name = url;
  58089. this.url = url;
  58090. this.hasAlpha = false;
  58091. this.isCube = false;
  58092. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58093. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58094. this.anisotropicFilteringLevel = 1;
  58095. this._texture = this._getFromCache(url, true);
  58096. if (!this._texture) {
  58097. if (!scene.useDelayedTextureLoading) {
  58098. this.loadTexture();
  58099. }
  58100. else {
  58101. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58102. }
  58103. }
  58104. }
  58105. /**
  58106. * Returns the texture matrix used in most of the material.
  58107. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58108. */
  58109. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58110. return this._textureMatrix;
  58111. };
  58112. /**
  58113. * Occurs when the file being loaded is a .3dl LUT file.
  58114. */
  58115. ColorGradingTexture.prototype.load3dlTexture = function () {
  58116. var _this = this;
  58117. var mipLevels = 0;
  58118. var floatArrayView = null;
  58119. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58120. this._texture = texture;
  58121. var callback = function (text) {
  58122. var data;
  58123. var tempData;
  58124. var line;
  58125. var lines = text.split('\n');
  58126. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58127. var maxColor = 0;
  58128. for (var i = 0; i < lines.length; i++) {
  58129. line = lines[i];
  58130. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58131. continue;
  58132. if (line.indexOf('#') === 0)
  58133. continue;
  58134. var words = line.split(" ");
  58135. if (size === 0) {
  58136. // Number of space + one
  58137. size = words.length;
  58138. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58139. tempData = new Float32Array(size * size * size * 4);
  58140. continue;
  58141. }
  58142. if (size != 0) {
  58143. var r = Math.max(parseInt(words[0]), 0);
  58144. var g = Math.max(parseInt(words[1]), 0);
  58145. var b = Math.max(parseInt(words[2]), 0);
  58146. maxColor = Math.max(r, maxColor);
  58147. maxColor = Math.max(g, maxColor);
  58148. maxColor = Math.max(b, maxColor);
  58149. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58150. tempData[pixelStorageIndex + 0] = r;
  58151. tempData[pixelStorageIndex + 1] = g;
  58152. tempData[pixelStorageIndex + 2] = b;
  58153. tempData[pixelStorageIndex + 3] = 0;
  58154. pixelIndexSlice++;
  58155. if (pixelIndexSlice % size == 0) {
  58156. pixelIndexH++;
  58157. pixelIndexSlice = 0;
  58158. if (pixelIndexH % size == 0) {
  58159. pixelIndexW++;
  58160. pixelIndexH = 0;
  58161. }
  58162. }
  58163. }
  58164. }
  58165. for (var i = 0; i < tempData.length; i++) {
  58166. var value = tempData[i];
  58167. data[i] = (value / maxColor * 255);
  58168. }
  58169. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58170. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58171. };
  58172. BABYLON.Tools.LoadFile(this.url, callback);
  58173. return this._texture;
  58174. };
  58175. /**
  58176. * Starts the loading process of the texture.
  58177. */
  58178. ColorGradingTexture.prototype.loadTexture = function () {
  58179. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58180. this.load3dlTexture();
  58181. }
  58182. };
  58183. /**
  58184. * Clones the color gradind texture.
  58185. */
  58186. ColorGradingTexture.prototype.clone = function () {
  58187. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58188. // Base texture
  58189. newTexture.level = this.level;
  58190. return newTexture;
  58191. };
  58192. /**
  58193. * Called during delayed load for textures.
  58194. */
  58195. ColorGradingTexture.prototype.delayLoad = function () {
  58196. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58197. return;
  58198. }
  58199. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58200. this._texture = this._getFromCache(this.url, true);
  58201. if (!this._texture) {
  58202. this.loadTexture();
  58203. }
  58204. };
  58205. /**
  58206. * Binds the color grading to the shader.
  58207. * @param colorGrading The texture to bind
  58208. * @param effect The effect to bind to
  58209. */
  58210. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58211. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58212. var x = colorGrading.level; // Texture Level
  58213. var y = colorGrading.getSize().height; // Texture Size example with 8
  58214. var z = y - 1.0; // SizeMinusOne 8 - 1
  58215. var w = 1 / y; // Space of 1 slice 1 / 8
  58216. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58217. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58218. 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
  58219. 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
  58220. 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
  58221. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58222. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58223. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58224. };
  58225. /**
  58226. * Prepare the list of uniforms associated with the ColorGrading effects.
  58227. * @param uniformsList The list of uniforms used in the effect
  58228. * @param samplersList The list of samplers used in the effect
  58229. */
  58230. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58231. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58232. samplersList.push("cameraColorGrading2DSampler");
  58233. };
  58234. /**
  58235. * Parses a color grading texture serialized by Babylon.
  58236. * @param parsedTexture The texture information being parsedTexture
  58237. * @param scene The scene to load the texture in
  58238. * @param rootUrl The root url of the data assets to load
  58239. * @return A color gradind texture
  58240. */
  58241. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58242. var texture = null;
  58243. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58244. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58245. texture.name = parsedTexture.name;
  58246. texture.level = parsedTexture.level;
  58247. }
  58248. return texture;
  58249. };
  58250. /**
  58251. * Serializes the LUT texture to json format.
  58252. */
  58253. ColorGradingTexture.prototype.serialize = function () {
  58254. if (!this.name) {
  58255. return null;
  58256. }
  58257. var serializationObject = {};
  58258. serializationObject.name = this.name;
  58259. serializationObject.level = this.level;
  58260. return serializationObject;
  58261. };
  58262. /**
  58263. * Empty line regex stored for GC.
  58264. */
  58265. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58266. return ColorGradingTexture;
  58267. }(BABYLON.BaseTexture));
  58268. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58269. })(BABYLON || (BABYLON = {}));
  58270. var BABYLON;
  58271. (function (BABYLON) {
  58272. /**
  58273. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58274. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58275. * 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;
  58276. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58277. */
  58278. var ColorCurves = (function () {
  58279. function ColorCurves() {
  58280. this._dirty = true;
  58281. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58282. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58283. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58284. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58285. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58286. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58287. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58288. this._globalHue = 30;
  58289. this._globalDensity = 0;
  58290. this._globalSaturation = 0;
  58291. this._globalExposure = 0;
  58292. this._highlightsHue = 30;
  58293. this._highlightsDensity = 0;
  58294. this._highlightsSaturation = 0;
  58295. this._highlightsExposure = 0;
  58296. this._midtonesHue = 30;
  58297. this._midtonesDensity = 0;
  58298. this._midtonesSaturation = 0;
  58299. this._midtonesExposure = 0;
  58300. this._shadowsHue = 30;
  58301. this._shadowsDensity = 0;
  58302. this._shadowsSaturation = 0;
  58303. this._shadowsExposure = 0;
  58304. }
  58305. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58306. /**
  58307. * Gets the global Hue value.
  58308. * 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).
  58309. */
  58310. get: function () {
  58311. return this._globalHue;
  58312. },
  58313. /**
  58314. * Sets the global Hue value.
  58315. * 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).
  58316. */
  58317. set: function (value) {
  58318. this._globalHue = value;
  58319. this._dirty = true;
  58320. },
  58321. enumerable: true,
  58322. configurable: true
  58323. });
  58324. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58325. /**
  58326. * Gets the global Density value.
  58327. * 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.
  58328. * Values less than zero provide a filter of opposite hue.
  58329. */
  58330. get: function () {
  58331. return this._globalDensity;
  58332. },
  58333. /**
  58334. * Sets the global Density value.
  58335. * 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.
  58336. * Values less than zero provide a filter of opposite hue.
  58337. */
  58338. set: function (value) {
  58339. this._globalDensity = value;
  58340. this._dirty = true;
  58341. },
  58342. enumerable: true,
  58343. configurable: true
  58344. });
  58345. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58346. /**
  58347. * Gets the global Saturation value.
  58348. * 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.
  58349. */
  58350. get: function () {
  58351. return this._globalSaturation;
  58352. },
  58353. /**
  58354. * Sets the global Saturation value.
  58355. * 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.
  58356. */
  58357. set: function (value) {
  58358. this._globalSaturation = value;
  58359. this._dirty = true;
  58360. },
  58361. enumerable: true,
  58362. configurable: true
  58363. });
  58364. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58365. /**
  58366. * Gets the highlights Hue value.
  58367. * 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).
  58368. */
  58369. get: function () {
  58370. return this._highlightsHue;
  58371. },
  58372. /**
  58373. * Sets the highlights Hue value.
  58374. * 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).
  58375. */
  58376. set: function (value) {
  58377. this._highlightsHue = value;
  58378. this._dirty = true;
  58379. },
  58380. enumerable: true,
  58381. configurable: true
  58382. });
  58383. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58384. /**
  58385. * Gets the highlights Density value.
  58386. * 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.
  58387. * Values less than zero provide a filter of opposite hue.
  58388. */
  58389. get: function () {
  58390. return this._highlightsDensity;
  58391. },
  58392. /**
  58393. * Sets the highlights Density value.
  58394. * 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.
  58395. * Values less than zero provide a filter of opposite hue.
  58396. */
  58397. set: function (value) {
  58398. this._highlightsDensity = value;
  58399. this._dirty = true;
  58400. },
  58401. enumerable: true,
  58402. configurable: true
  58403. });
  58404. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58405. /**
  58406. * Gets the highlights Saturation value.
  58407. * 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.
  58408. */
  58409. get: function () {
  58410. return this._highlightsSaturation;
  58411. },
  58412. /**
  58413. * Sets the highlights Saturation value.
  58414. * 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.
  58415. */
  58416. set: function (value) {
  58417. this._highlightsSaturation = value;
  58418. this._dirty = true;
  58419. },
  58420. enumerable: true,
  58421. configurable: true
  58422. });
  58423. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58424. /**
  58425. * Gets the highlights Exposure value.
  58426. * 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.
  58427. */
  58428. get: function () {
  58429. return this._highlightsExposure;
  58430. },
  58431. /**
  58432. * Sets the highlights Exposure value.
  58433. * 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.
  58434. */
  58435. set: function (value) {
  58436. this._highlightsExposure = value;
  58437. this._dirty = true;
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58443. /**
  58444. * Gets the midtones Hue value.
  58445. * 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).
  58446. */
  58447. get: function () {
  58448. return this._midtonesHue;
  58449. },
  58450. /**
  58451. * Sets the midtones Hue value.
  58452. * 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).
  58453. */
  58454. set: function (value) {
  58455. this._midtonesHue = value;
  58456. this._dirty = true;
  58457. },
  58458. enumerable: true,
  58459. configurable: true
  58460. });
  58461. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58462. /**
  58463. * Gets the midtones Density value.
  58464. * 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.
  58465. * Values less than zero provide a filter of opposite hue.
  58466. */
  58467. get: function () {
  58468. return this._midtonesDensity;
  58469. },
  58470. /**
  58471. * Sets the midtones Density value.
  58472. * 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.
  58473. * Values less than zero provide a filter of opposite hue.
  58474. */
  58475. set: function (value) {
  58476. this._midtonesDensity = value;
  58477. this._dirty = true;
  58478. },
  58479. enumerable: true,
  58480. configurable: true
  58481. });
  58482. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58483. /**
  58484. * Gets the midtones Saturation value.
  58485. * 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.
  58486. */
  58487. get: function () {
  58488. return this._midtonesSaturation;
  58489. },
  58490. /**
  58491. * Sets the midtones Saturation value.
  58492. * 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.
  58493. */
  58494. set: function (value) {
  58495. this._midtonesSaturation = value;
  58496. this._dirty = true;
  58497. },
  58498. enumerable: true,
  58499. configurable: true
  58500. });
  58501. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58502. /**
  58503. * Gets the midtones Exposure value.
  58504. * 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.
  58505. */
  58506. get: function () {
  58507. return this._midtonesExposure;
  58508. },
  58509. /**
  58510. * Sets the midtones Exposure value.
  58511. * 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.
  58512. */
  58513. set: function (value) {
  58514. this._midtonesExposure = value;
  58515. this._dirty = true;
  58516. },
  58517. enumerable: true,
  58518. configurable: true
  58519. });
  58520. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58521. /**
  58522. * Gets the shadows Hue value.
  58523. * 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).
  58524. */
  58525. get: function () {
  58526. return this._shadowsHue;
  58527. },
  58528. /**
  58529. * Sets the shadows Hue value.
  58530. * 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).
  58531. */
  58532. set: function (value) {
  58533. this._shadowsHue = value;
  58534. this._dirty = true;
  58535. },
  58536. enumerable: true,
  58537. configurable: true
  58538. });
  58539. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58540. /**
  58541. * Gets the shadows Density value.
  58542. * 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.
  58543. * Values less than zero provide a filter of opposite hue.
  58544. */
  58545. get: function () {
  58546. return this._shadowsDensity;
  58547. },
  58548. /**
  58549. * Sets the shadows Density value.
  58550. * 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.
  58551. * Values less than zero provide a filter of opposite hue.
  58552. */
  58553. set: function (value) {
  58554. this._shadowsDensity = value;
  58555. this._dirty = true;
  58556. },
  58557. enumerable: true,
  58558. configurable: true
  58559. });
  58560. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58561. /**
  58562. * Gets the shadows Saturation value.
  58563. * 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.
  58564. */
  58565. get: function () {
  58566. return this._shadowsSaturation;
  58567. },
  58568. /**
  58569. * Sets the shadows Saturation value.
  58570. * 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.
  58571. */
  58572. set: function (value) {
  58573. this._shadowsSaturation = value;
  58574. this._dirty = true;
  58575. },
  58576. enumerable: true,
  58577. configurable: true
  58578. });
  58579. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58580. /**
  58581. * Gets the shadows Exposure value.
  58582. * 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.
  58583. */
  58584. get: function () {
  58585. return this._shadowsExposure;
  58586. },
  58587. /**
  58588. * Sets the shadows Exposure value.
  58589. * 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.
  58590. */
  58591. set: function (value) {
  58592. this._shadowsExposure = value;
  58593. this._dirty = true;
  58594. },
  58595. enumerable: true,
  58596. configurable: true
  58597. });
  58598. /**
  58599. * Binds the color curves to the shader.
  58600. * @param colorCurves The color curve to bind
  58601. * @param effect The effect to bind to
  58602. */
  58603. ColorCurves.Bind = function (colorCurves, effect) {
  58604. if (colorCurves._dirty) {
  58605. colorCurves._dirty = false;
  58606. // Fill in global info.
  58607. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58608. // Compute highlights info.
  58609. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58610. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58611. // Compute midtones info.
  58612. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58613. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58614. // Compute shadows info.
  58615. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58616. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58617. // Compute deltas (neutral is midtones).
  58618. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58619. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58620. }
  58621. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58622. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58623. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58624. };
  58625. /**
  58626. * Prepare the list of uniforms associated with the ColorCurves effects.
  58627. * @param uniformsList The list of uniforms used in the effect
  58628. */
  58629. ColorCurves.PrepareUniforms = function (uniformsList) {
  58630. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58631. };
  58632. /**
  58633. * Returns color grading data based on a hue, density, saturation and exposure value.
  58634. * @param filterHue The hue of the color filter.
  58635. * @param filterDensity The density of the color filter.
  58636. * @param saturation The saturation.
  58637. * @param exposure The exposure.
  58638. * @param result The result data container.
  58639. */
  58640. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58641. if (hue == null) {
  58642. return;
  58643. }
  58644. hue = ColorCurves.clamp(hue, 0, 360);
  58645. density = ColorCurves.clamp(density, -100, 100);
  58646. saturation = ColorCurves.clamp(saturation, -100, 100);
  58647. exposure = ColorCurves.clamp(exposure, -100, 100);
  58648. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58649. // so that the maximum filter density is only 50% control. This provides fine control
  58650. // for small values and reasonable range.
  58651. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58652. density *= 0.5;
  58653. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58654. if (density < 0) {
  58655. density *= -1;
  58656. hue = (hue + 180) % 360;
  58657. }
  58658. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58659. result.scaleToRef(2, result);
  58660. result.a = 1 + 0.01 * saturation;
  58661. };
  58662. /**
  58663. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58664. * @param value The input slider value in range [-100,100].
  58665. * @returns Adjusted value.
  58666. */
  58667. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58668. value /= 100;
  58669. var x = Math.abs(value);
  58670. x = Math.pow(x, 2);
  58671. if (value < 0) {
  58672. x *= -1;
  58673. }
  58674. x *= 100;
  58675. return x;
  58676. };
  58677. /**
  58678. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58679. * @param hue The hue (H) input.
  58680. * @param saturation The saturation (S) input.
  58681. * @param brightness The brightness (B) input.
  58682. * @result An RGBA color represented as Vector4.
  58683. */
  58684. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58685. var h = ColorCurves.clamp(hue, 0, 360);
  58686. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58687. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58688. if (s === 0) {
  58689. result.r = v;
  58690. result.g = v;
  58691. result.b = v;
  58692. }
  58693. else {
  58694. // sector 0 to 5
  58695. h /= 60;
  58696. var i = Math.floor(h);
  58697. // fractional part of h
  58698. var f = h - i;
  58699. var p = v * (1 - s);
  58700. var q = v * (1 - s * f);
  58701. var t = v * (1 - s * (1 - f));
  58702. switch (i) {
  58703. case 0:
  58704. result.r = v;
  58705. result.g = t;
  58706. result.b = p;
  58707. break;
  58708. case 1:
  58709. result.r = q;
  58710. result.g = v;
  58711. result.b = p;
  58712. break;
  58713. case 2:
  58714. result.r = p;
  58715. result.g = v;
  58716. result.b = t;
  58717. break;
  58718. case 3:
  58719. result.r = p;
  58720. result.g = q;
  58721. result.b = v;
  58722. break;
  58723. case 4:
  58724. result.r = t;
  58725. result.g = p;
  58726. result.b = v;
  58727. break;
  58728. default:
  58729. result.r = v;
  58730. result.g = p;
  58731. result.b = q;
  58732. break;
  58733. }
  58734. }
  58735. result.a = 1;
  58736. };
  58737. /**
  58738. * Returns a value clamped between min and max
  58739. * @param value The value to clamp
  58740. * @param min The minimum of value
  58741. * @param max The maximum of value
  58742. * @returns The clamped value.
  58743. */
  58744. ColorCurves.clamp = function (value, min, max) {
  58745. return Math.min(Math.max(value, min), max);
  58746. };
  58747. /**
  58748. * Clones the current color curve instance.
  58749. * @return The cloned curves
  58750. */
  58751. ColorCurves.prototype.clone = function () {
  58752. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58753. };
  58754. /**
  58755. * Serializes the current color curve instance to a json representation.
  58756. * @return a JSON representation
  58757. */
  58758. ColorCurves.prototype.serialize = function () {
  58759. return BABYLON.SerializationHelper.Serialize(this);
  58760. };
  58761. /**
  58762. * Parses the color curve from a json representation.
  58763. * @param source the JSON source to parse
  58764. * @return The parsed curves
  58765. */
  58766. ColorCurves.Parse = function (source) {
  58767. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58768. };
  58769. __decorate([
  58770. BABYLON.serialize()
  58771. ], ColorCurves.prototype, "_globalHue", void 0);
  58772. __decorate([
  58773. BABYLON.serialize()
  58774. ], ColorCurves.prototype, "_globalDensity", void 0);
  58775. __decorate([
  58776. BABYLON.serialize()
  58777. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58778. __decorate([
  58779. BABYLON.serialize()
  58780. ], ColorCurves.prototype, "_globalExposure", void 0);
  58781. __decorate([
  58782. BABYLON.serialize()
  58783. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58784. __decorate([
  58785. BABYLON.serialize()
  58786. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58787. __decorate([
  58788. BABYLON.serialize()
  58789. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58790. __decorate([
  58791. BABYLON.serialize()
  58792. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58793. __decorate([
  58794. BABYLON.serialize()
  58795. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58796. __decorate([
  58797. BABYLON.serialize()
  58798. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58799. __decorate([
  58800. BABYLON.serialize()
  58801. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58802. __decorate([
  58803. BABYLON.serialize()
  58804. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58805. return ColorCurves;
  58806. }());
  58807. BABYLON.ColorCurves = ColorCurves;
  58808. })(BABYLON || (BABYLON = {}));
  58809. var BABYLON;
  58810. (function (BABYLON) {
  58811. var PBRMaterialDefines = (function (_super) {
  58812. __extends(PBRMaterialDefines, _super);
  58813. function PBRMaterialDefines() {
  58814. _super.call(this);
  58815. this.ALBEDO = false;
  58816. this.AMBIENT = false;
  58817. this.OPACITY = false;
  58818. this.OPACITYRGB = false;
  58819. this.REFLECTION = false;
  58820. this.EMISSIVE = false;
  58821. this.REFLECTIVITY = false;
  58822. this.BUMP = false;
  58823. this.PARALLAX = false;
  58824. this.PARALLAXOCCLUSION = false;
  58825. this.SPECULAROVERALPHA = false;
  58826. this.CLIPPLANE = false;
  58827. this.ALPHATEST = false;
  58828. this.ALPHAFROMALBEDO = false;
  58829. this.POINTSIZE = false;
  58830. this.FOG = false;
  58831. this.SPECULARTERM = false;
  58832. this.OPACITYFRESNEL = false;
  58833. this.EMISSIVEFRESNEL = false;
  58834. this.FRESNEL = false;
  58835. this.NORMAL = false;
  58836. this.UV1 = false;
  58837. this.UV2 = false;
  58838. this.VERTEXCOLOR = false;
  58839. this.VERTEXALPHA = false;
  58840. this.NUM_BONE_INFLUENCERS = 0;
  58841. this.BonesPerMesh = 0;
  58842. this.INSTANCES = false;
  58843. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58844. this.MICROSURFACEAUTOMATIC = false;
  58845. this.EMISSIVEASILLUMINATION = false;
  58846. this.LINKEMISSIVEWITHALBEDO = false;
  58847. this.LIGHTMAP = false;
  58848. this.USELIGHTMAPASSHADOWMAP = false;
  58849. this.REFLECTIONMAP_3D = false;
  58850. this.REFLECTIONMAP_SPHERICAL = false;
  58851. this.REFLECTIONMAP_PLANAR = false;
  58852. this.REFLECTIONMAP_CUBIC = false;
  58853. this.REFLECTIONMAP_PROJECTION = false;
  58854. this.REFLECTIONMAP_SKYBOX = false;
  58855. this.REFLECTIONMAP_EXPLICIT = false;
  58856. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58857. this.INVERTCUBICMAP = false;
  58858. this.LOGARITHMICDEPTH = false;
  58859. this.CAMERATONEMAP = false;
  58860. this.CAMERACONTRAST = false;
  58861. this.CAMERACOLORGRADING = false;
  58862. this.CAMERACOLORCURVES = false;
  58863. this.OVERLOADEDVALUES = false;
  58864. this.OVERLOADEDSHADOWVALUES = false;
  58865. this.USESPHERICALFROMREFLECTIONMAP = false;
  58866. this.REFRACTION = false;
  58867. this.REFRACTIONMAP_3D = false;
  58868. this.LINKREFRACTIONTOTRANSPARENCY = false;
  58869. this.REFRACTIONMAPINLINEARSPACE = false;
  58870. this.LODBASEDMICROSFURACE = false;
  58871. this.USEPHYSICALLIGHTFALLOFF = false;
  58872. this.RADIANCEOVERALPHA = false;
  58873. this.USEPMREMREFLECTION = false;
  58874. this.USEPMREMREFRACTION = false;
  58875. this.OPENGLNORMALMAP = false;
  58876. this.INVERTNORMALMAPX = false;
  58877. this.INVERTNORMALMAPY = false;
  58878. this.SHADOWFULLFLOAT = false;
  58879. this.rebuild();
  58880. }
  58881. return PBRMaterialDefines;
  58882. }(BABYLON.MaterialDefines));
  58883. /**
  58884. * The Physically based material of BJS.
  58885. *
  58886. * This offers the main features of a standard PBR material.
  58887. * For more information, please refer to the documentation :
  58888. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58889. */
  58890. var PBRMaterial = (function (_super) {
  58891. __extends(PBRMaterial, _super);
  58892. /**
  58893. * Instantiates a new PBRMaterial instance.
  58894. *
  58895. * @param name The material name
  58896. * @param scene The scene the material will be use in.
  58897. */
  58898. function PBRMaterial(name, scene) {
  58899. var _this = this;
  58900. _super.call(this, name, scene);
  58901. /**
  58902. * Intensity of the direct lights e.g. the four lights available in your scene.
  58903. * This impacts both the direct diffuse and specular highlights.
  58904. */
  58905. this.directIntensity = 1.0;
  58906. /**
  58907. * Intensity of the emissive part of the material.
  58908. * This helps controlling the emissive effect without modifying the emissive color.
  58909. */
  58910. this.emissiveIntensity = 1.0;
  58911. /**
  58912. * Intensity of the environment e.g. how much the environment will light the object
  58913. * either through harmonics for rough material or through the refelction for shiny ones.
  58914. */
  58915. this.environmentIntensity = 1.0;
  58916. /**
  58917. * This is a special control allowing the reduction of the specular highlights coming from the
  58918. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58919. */
  58920. this.specularIntensity = 1.0;
  58921. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  58922. /**
  58923. * Debug Control allowing disabling the bump map on this material.
  58924. */
  58925. this.disableBumpMap = false;
  58926. /**
  58927. * Debug Control helping enforcing or dropping the darkness of shadows.
  58928. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58929. */
  58930. this.overloadedShadowIntensity = 1.0;
  58931. /**
  58932. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58933. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58934. */
  58935. this.overloadedShadeIntensity = 1.0;
  58936. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  58937. /**
  58938. * The camera exposure used on this material.
  58939. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58940. * This corresponds to a photographic exposure.
  58941. */
  58942. this.cameraExposure = 1.0;
  58943. /**
  58944. * The camera contrast used on this material.
  58945. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58946. */
  58947. this.cameraContrast = 1.0;
  58948. /**
  58949. * Color Grading 2D Lookup Texture.
  58950. * This allows special effects like sepia, black and white to sixties rendering style.
  58951. */
  58952. this.cameraColorGradingTexture = null;
  58953. /**
  58954. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58955. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58956. * 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;
  58957. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58958. */
  58959. this.cameraColorCurves = null;
  58960. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58961. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58962. /**
  58963. * Debug Control allowing to overload the ambient color.
  58964. * This as to be use with the overloadedAmbientIntensity parameter.
  58965. */
  58966. this.overloadedAmbient = BABYLON.Color3.White();
  58967. /**
  58968. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58969. */
  58970. this.overloadedAmbientIntensity = 0.0;
  58971. /**
  58972. * Debug Control allowing to overload the albedo color.
  58973. * This as to be use with the overloadedAlbedoIntensity parameter.
  58974. */
  58975. this.overloadedAlbedo = BABYLON.Color3.White();
  58976. /**
  58977. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58978. */
  58979. this.overloadedAlbedoIntensity = 0.0;
  58980. /**
  58981. * Debug Control allowing to overload the reflectivity color.
  58982. * This as to be use with the overloadedReflectivityIntensity parameter.
  58983. */
  58984. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58985. /**
  58986. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58987. */
  58988. this.overloadedReflectivityIntensity = 0.0;
  58989. /**
  58990. * Debug Control allowing to overload the emissive color.
  58991. * This as to be use with the overloadedEmissiveIntensity parameter.
  58992. */
  58993. this.overloadedEmissive = BABYLON.Color3.White();
  58994. /**
  58995. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58996. */
  58997. this.overloadedEmissiveIntensity = 0.0;
  58998. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  58999. /**
  59000. * Debug Control allowing to overload the reflection color.
  59001. * This as to be use with the overloadedReflectionIntensity parameter.
  59002. */
  59003. this.overloadedReflection = BABYLON.Color3.White();
  59004. /**
  59005. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59006. */
  59007. this.overloadedReflectionIntensity = 0.0;
  59008. /**
  59009. * Debug Control allowing to overload the microsurface.
  59010. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59011. */
  59012. this.overloadedMicroSurface = 0.0;
  59013. /**
  59014. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59015. */
  59016. this.overloadedMicroSurfaceIntensity = 0.0;
  59017. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  59018. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59019. /**
  59020. * AKA Diffuse Color in other nomenclature.
  59021. */
  59022. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59023. /**
  59024. * AKA Specular Color in other nomenclature.
  59025. */
  59026. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59027. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59028. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59029. /**
  59030. * AKA Glossiness in other nomenclature.
  59031. */
  59032. this.microSurface = 0.9;
  59033. /**
  59034. * source material index of refraction (IOR)' / 'destination material IOR.
  59035. */
  59036. this.indexOfRefraction = 0.66;
  59037. /**
  59038. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59039. */
  59040. this.invertRefractionY = false;
  59041. /**
  59042. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59043. * Materials half opaque for instance using refraction could benefit from this control.
  59044. */
  59045. this.linkRefractionWithTransparency = false;
  59046. /**
  59047. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59048. */
  59049. this.linkEmissiveWithAlbedo = false;
  59050. this.useLightmapAsShadowmap = false;
  59051. /**
  59052. * In this mode, the emissive informtaion will always be added to the lighting once.
  59053. * A light for instance can be thought as emissive.
  59054. */
  59055. this.useEmissiveAsIllumination = false;
  59056. /**
  59057. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59058. */
  59059. this.useAlphaFromAlbedoTexture = false;
  59060. /**
  59061. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59062. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59063. */
  59064. this.useSpecularOverAlpha = true;
  59065. /**
  59066. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59067. */
  59068. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59069. /**
  59070. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59071. * The material will try to infer what glossiness each pixel should be.
  59072. */
  59073. this.useAutoMicroSurfaceFromReflectivityMap = false;
  59074. /**
  59075. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59076. * the creation of the material.
  59077. */
  59078. this.useScalarInLinearSpace = false;
  59079. /**
  59080. * BJS is using an harcoded light falloff based on a manually sets up range.
  59081. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59082. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59083. */
  59084. this.usePhysicalLightFalloff = true;
  59085. /**
  59086. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59087. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59088. */
  59089. this.useRadianceOverAlpha = true;
  59090. /**
  59091. * Allows using the bump map in parallax mode.
  59092. */
  59093. this.useParallax = false;
  59094. /**
  59095. * Allows using the bump map in parallax occlusion mode.
  59096. */
  59097. this.useParallaxOcclusion = false;
  59098. /**
  59099. * Controls the scale bias of the parallax mode.
  59100. */
  59101. this.parallaxScaleBias = 0.05;
  59102. /**
  59103. * If sets to true, disables all the lights affecting the material.
  59104. */
  59105. this.disableLighting = false;
  59106. /**
  59107. * Number of Simultaneous lights allowed on the material.
  59108. */
  59109. this.maxSimultaneousLights = 4;
  59110. /**
  59111. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59112. */
  59113. this.invertNormalMapX = false;
  59114. /**
  59115. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59116. */
  59117. this.invertNormalMapY = false;
  59118. this._renderTargets = new BABYLON.SmartArray(16);
  59119. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59120. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59121. this._tempColor = new BABYLON.Color3();
  59122. this._defines = new PBRMaterialDefines();
  59123. this._cachedDefines = new PBRMaterialDefines();
  59124. this._myScene = null;
  59125. this._myShadowGenerator = null;
  59126. this._cachedDefines.BonesPerMesh = -1;
  59127. this.getRenderTargetTextures = function () {
  59128. _this._renderTargets.reset();
  59129. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59130. _this._renderTargets.push(_this.reflectionTexture);
  59131. }
  59132. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59133. _this._renderTargets.push(_this.refractionTexture);
  59134. }
  59135. return _this._renderTargets;
  59136. };
  59137. }
  59138. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59139. get: function () {
  59140. return this._useLogarithmicDepth;
  59141. },
  59142. set: function (value) {
  59143. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59144. },
  59145. enumerable: true,
  59146. configurable: true
  59147. });
  59148. PBRMaterial.prototype.needAlphaBlending = function () {
  59149. if (this.linkRefractionWithTransparency) {
  59150. return false;
  59151. }
  59152. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59153. };
  59154. PBRMaterial.prototype.needAlphaTesting = function () {
  59155. if (this.linkRefractionWithTransparency) {
  59156. return false;
  59157. }
  59158. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59159. };
  59160. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59161. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59162. };
  59163. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59164. return this.albedoTexture;
  59165. };
  59166. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59167. if (!mesh) {
  59168. return true;
  59169. }
  59170. if (this._defines.INSTANCES !== useInstances) {
  59171. return false;
  59172. }
  59173. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  59174. return true;
  59175. }
  59176. return false;
  59177. };
  59178. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59179. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59180. };
  59181. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59182. if (!useScalarInLinear) {
  59183. color.toLinearSpaceToRef(ref);
  59184. }
  59185. else {
  59186. ref.r = color.r;
  59187. ref.g = color.g;
  59188. ref.b = color.b;
  59189. }
  59190. };
  59191. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59192. var lightIndex = 0;
  59193. var depthValuesAlreadySet = false;
  59194. for (var index = 0; index < scene.lights.length; index++) {
  59195. var light = scene.lights[index];
  59196. if (!light.isEnabled()) {
  59197. continue;
  59198. }
  59199. if (!light.canAffectMesh(mesh)) {
  59200. continue;
  59201. }
  59202. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59203. // GAMMA CORRECTION.
  59204. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59205. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59206. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59207. if (defines["SPECULARTERM"]) {
  59208. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59209. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59210. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59211. }
  59212. // Shadows
  59213. if (scene.shadowsEnabled) {
  59214. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59215. }
  59216. lightIndex++;
  59217. if (lightIndex === maxSimultaneousLights)
  59218. break;
  59219. }
  59220. };
  59221. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59222. if (this.checkReadyOnlyOnce) {
  59223. if (this._wasPreviouslyReady) {
  59224. return true;
  59225. }
  59226. }
  59227. var scene = this.getScene();
  59228. if (!this.checkReadyOnEveryCall) {
  59229. if (this._renderId === scene.getRenderId()) {
  59230. if (this._checkCache(scene, mesh, useInstances)) {
  59231. return true;
  59232. }
  59233. }
  59234. }
  59235. var engine = scene.getEngine();
  59236. var needNormals = false;
  59237. var needUVs = false;
  59238. this._defines.reset();
  59239. if (scene.texturesEnabled) {
  59240. // Textures
  59241. if (scene.texturesEnabled) {
  59242. if (scene.getEngine().getCaps().textureLOD) {
  59243. this._defines.LODBASEDMICROSFURACE = true;
  59244. }
  59245. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59246. if (!this.albedoTexture.isReady()) {
  59247. return false;
  59248. }
  59249. else {
  59250. needUVs = true;
  59251. this._defines.ALBEDO = true;
  59252. }
  59253. }
  59254. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59255. if (!this.ambientTexture.isReady()) {
  59256. return false;
  59257. }
  59258. else {
  59259. needUVs = true;
  59260. this._defines.AMBIENT = true;
  59261. }
  59262. }
  59263. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59264. if (!this.opacityTexture.isReady()) {
  59265. return false;
  59266. }
  59267. else {
  59268. needUVs = true;
  59269. this._defines.OPACITY = true;
  59270. if (this.opacityTexture.getAlphaFromRGB) {
  59271. this._defines.OPACITYRGB = true;
  59272. }
  59273. }
  59274. }
  59275. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59276. if (!this.reflectionTexture.isReady()) {
  59277. return false;
  59278. }
  59279. else {
  59280. needNormals = true;
  59281. this._defines.REFLECTION = true;
  59282. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59283. this._defines.INVERTCUBICMAP = true;
  59284. }
  59285. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59286. switch (this.reflectionTexture.coordinatesMode) {
  59287. case BABYLON.Texture.CUBIC_MODE:
  59288. case BABYLON.Texture.INVCUBIC_MODE:
  59289. this._defines.REFLECTIONMAP_CUBIC = true;
  59290. break;
  59291. case BABYLON.Texture.EXPLICIT_MODE:
  59292. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59293. break;
  59294. case BABYLON.Texture.PLANAR_MODE:
  59295. this._defines.REFLECTIONMAP_PLANAR = true;
  59296. break;
  59297. case BABYLON.Texture.PROJECTION_MODE:
  59298. this._defines.REFLECTIONMAP_PROJECTION = true;
  59299. break;
  59300. case BABYLON.Texture.SKYBOX_MODE:
  59301. this._defines.REFLECTIONMAP_SKYBOX = true;
  59302. break;
  59303. case BABYLON.Texture.SPHERICAL_MODE:
  59304. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59305. break;
  59306. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59307. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59308. break;
  59309. }
  59310. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59311. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59312. needNormals = true;
  59313. if (this.reflectionTexture.isPMREM) {
  59314. this._defines.USEPMREMREFLECTION = true;
  59315. }
  59316. }
  59317. }
  59318. }
  59319. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59320. if (!this.lightmapTexture.isReady()) {
  59321. return false;
  59322. }
  59323. else {
  59324. needUVs = true;
  59325. this._defines.LIGHTMAP = true;
  59326. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59327. }
  59328. }
  59329. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59330. if (!this.emissiveTexture.isReady()) {
  59331. return false;
  59332. }
  59333. else {
  59334. needUVs = true;
  59335. this._defines.EMISSIVE = true;
  59336. }
  59337. }
  59338. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59339. if (!this.reflectivityTexture.isReady()) {
  59340. return false;
  59341. }
  59342. else {
  59343. needUVs = true;
  59344. this._defines.REFLECTIVITY = true;
  59345. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59346. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59347. }
  59348. }
  59349. }
  59350. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59351. if (!this.bumpTexture.isReady()) {
  59352. return false;
  59353. }
  59354. else {
  59355. needUVs = true;
  59356. this._defines.BUMP = true;
  59357. if (this.useParallax) {
  59358. this._defines.PARALLAX = true;
  59359. if (this.useParallaxOcclusion) {
  59360. this._defines.PARALLAXOCCLUSION = true;
  59361. }
  59362. }
  59363. if (this.invertNormalMapX) {
  59364. this._defines.INVERTNORMALMAPX = true;
  59365. }
  59366. if (this.invertNormalMapY) {
  59367. this._defines.INVERTNORMALMAPY = true;
  59368. }
  59369. }
  59370. }
  59371. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59372. if (!this.refractionTexture.isReady()) {
  59373. return false;
  59374. }
  59375. else {
  59376. needUVs = true;
  59377. this._defines.REFRACTION = true;
  59378. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59379. if (this.linkRefractionWithTransparency) {
  59380. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59381. }
  59382. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59383. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59384. if (this.refractionTexture.isPMREM) {
  59385. this._defines.USEPMREMREFRACTION = true;
  59386. }
  59387. }
  59388. }
  59389. }
  59390. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59391. if (!this.cameraColorGradingTexture.isReady()) {
  59392. return false;
  59393. }
  59394. else {
  59395. this._defines.CAMERACOLORGRADING = true;
  59396. }
  59397. }
  59398. }
  59399. // Effect
  59400. if (scene.clipPlane) {
  59401. this._defines.CLIPPLANE = true;
  59402. }
  59403. if (engine.getAlphaTesting()) {
  59404. this._defines.ALPHATEST = true;
  59405. }
  59406. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59407. this._defines.ALPHAFROMALBEDO = true;
  59408. }
  59409. if (this.useEmissiveAsIllumination) {
  59410. this._defines.EMISSIVEASILLUMINATION = true;
  59411. }
  59412. if (this.linkEmissiveWithAlbedo) {
  59413. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59414. }
  59415. if (this.useLogarithmicDepth) {
  59416. this._defines.LOGARITHMICDEPTH = true;
  59417. }
  59418. if (this.cameraContrast != 1) {
  59419. this._defines.CAMERACONTRAST = true;
  59420. }
  59421. if (this.cameraExposure != 1) {
  59422. this._defines.CAMERATONEMAP = true;
  59423. }
  59424. if (this.cameraColorCurves) {
  59425. this._defines.CAMERACOLORCURVES = true;
  59426. }
  59427. if (this.overloadedShadeIntensity != 1 ||
  59428. this.overloadedShadowIntensity != 1) {
  59429. this._defines.OVERLOADEDSHADOWVALUES = true;
  59430. }
  59431. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59432. this.overloadedEmissiveIntensity > 0 ||
  59433. this.overloadedReflectivityIntensity > 0 ||
  59434. this.overloadedAlbedoIntensity > 0 ||
  59435. this.overloadedAmbientIntensity > 0 ||
  59436. this.overloadedReflectionIntensity > 0) {
  59437. this._defines.OVERLOADEDVALUES = true;
  59438. }
  59439. // Point size
  59440. if (this.pointsCloud || scene.forcePointsCloud) {
  59441. this._defines.POINTSIZE = true;
  59442. }
  59443. // Fog
  59444. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59445. this._defines.FOG = true;
  59446. }
  59447. if (scene.lightsEnabled && !this.disableLighting) {
  59448. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59449. }
  59450. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59451. // Fresnel
  59452. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59453. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59454. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59455. this._defines.OPACITYFRESNEL = true;
  59456. }
  59457. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59458. this._defines.EMISSIVEFRESNEL = true;
  59459. }
  59460. needNormals = true;
  59461. this._defines.FRESNEL = true;
  59462. }
  59463. }
  59464. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  59465. this._defines.SPECULAROVERALPHA = true;
  59466. }
  59467. if (this.usePhysicalLightFalloff) {
  59468. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  59469. }
  59470. if (this.useRadianceOverAlpha) {
  59471. this._defines.RADIANCEOVERALPHA = true;
  59472. }
  59473. // Attribs
  59474. if (mesh) {
  59475. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59476. this._defines.NORMAL = true;
  59477. }
  59478. if (needUVs) {
  59479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59480. this._defines.UV1 = true;
  59481. }
  59482. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59483. this._defines.UV2 = true;
  59484. }
  59485. }
  59486. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59487. this._defines.VERTEXCOLOR = true;
  59488. if (mesh.hasVertexAlpha) {
  59489. this._defines.VERTEXALPHA = true;
  59490. }
  59491. }
  59492. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59493. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  59494. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  59495. }
  59496. // Instances
  59497. if (useInstances) {
  59498. this._defines.INSTANCES = true;
  59499. }
  59500. }
  59501. // Get correct effect
  59502. if (!this._defines.isEqual(this._cachedDefines)) {
  59503. this._defines.cloneTo(this._cachedDefines);
  59504. scene.resetCachedMaterial();
  59505. // Fallbacks
  59506. var fallbacks = new BABYLON.EffectFallbacks();
  59507. if (this._defines.REFLECTION) {
  59508. fallbacks.addFallback(0, "REFLECTION");
  59509. }
  59510. if (this._defines.REFRACTION) {
  59511. fallbacks.addFallback(0, "REFRACTION");
  59512. }
  59513. if (this._defines.REFLECTIVITY) {
  59514. fallbacks.addFallback(0, "REFLECTIVITY");
  59515. }
  59516. if (this._defines.BUMP) {
  59517. fallbacks.addFallback(0, "BUMP");
  59518. }
  59519. if (this._defines.PARALLAX) {
  59520. fallbacks.addFallback(1, "PARALLAX");
  59521. }
  59522. if (this._defines.PARALLAXOCCLUSION) {
  59523. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  59524. }
  59525. if (this._defines.SPECULAROVERALPHA) {
  59526. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  59527. }
  59528. if (this._defines.FOG) {
  59529. fallbacks.addFallback(1, "FOG");
  59530. }
  59531. if (this._defines.POINTSIZE) {
  59532. fallbacks.addFallback(0, "POINTSIZE");
  59533. }
  59534. if (this._defines.LOGARITHMICDEPTH) {
  59535. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  59536. }
  59537. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  59538. if (this._defines.SPECULARTERM) {
  59539. fallbacks.addFallback(0, "SPECULARTERM");
  59540. }
  59541. if (this._defines.OPACITYFRESNEL) {
  59542. fallbacks.addFallback(1, "OPACITYFRESNEL");
  59543. }
  59544. if (this._defines.EMISSIVEFRESNEL) {
  59545. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  59546. }
  59547. if (this._defines.FRESNEL) {
  59548. fallbacks.addFallback(3, "FRESNEL");
  59549. }
  59550. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  59551. fallbacks.addCPUSkinningFallback(0, mesh);
  59552. }
  59553. //Attributes
  59554. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59555. if (this._defines.NORMAL) {
  59556. attribs.push(BABYLON.VertexBuffer.NormalKind);
  59557. }
  59558. if (this._defines.UV1) {
  59559. attribs.push(BABYLON.VertexBuffer.UVKind);
  59560. }
  59561. if (this._defines.UV2) {
  59562. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59563. }
  59564. if (this._defines.VERTEXCOLOR) {
  59565. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59566. }
  59567. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  59568. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  59569. // Legacy browser patch
  59570. var shaderName = "pbr";
  59571. if (!scene.getEngine().getCaps().standardDerivatives) {
  59572. shaderName = "legacypbr";
  59573. }
  59574. var join = this._defines.toString();
  59575. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  59576. "vFogInfos", "vFogColor", "pointSize",
  59577. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  59578. "mBones",
  59579. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  59580. "depthValues",
  59581. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  59582. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  59583. "logarithmicDepthConstant",
  59584. "vSphericalX", "vSphericalY", "vSphericalZ",
  59585. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  59586. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  59587. "vMicrosurfaceTextureLods",
  59588. "vCameraInfos"
  59589. ];
  59590. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  59591. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  59592. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  59593. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  59594. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  59595. }
  59596. if (!this._effect.isReady()) {
  59597. return false;
  59598. }
  59599. this._renderId = scene.getRenderId();
  59600. this._wasPreviouslyReady = true;
  59601. if (mesh) {
  59602. if (!mesh._materialDefines) {
  59603. mesh._materialDefines = new PBRMaterialDefines();
  59604. }
  59605. this._defines.cloneTo(mesh._materialDefines);
  59606. }
  59607. return true;
  59608. };
  59609. PBRMaterial.prototype.unbind = function () {
  59610. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  59611. this._effect.setTexture("reflection2DSampler", null);
  59612. }
  59613. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  59614. this._effect.setTexture("refraction2DSampler", null);
  59615. }
  59616. _super.prototype.unbind.call(this);
  59617. };
  59618. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59619. this._effect.setMatrix("world", world);
  59620. };
  59621. PBRMaterial.prototype.bind = function (world, mesh) {
  59622. this._myScene = this.getScene();
  59623. // Matrices
  59624. this.bindOnlyWorldMatrix(world);
  59625. // Bones
  59626. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59627. if (this._myScene.getCachedMaterial() !== this) {
  59628. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  59629. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59630. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59631. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  59632. }
  59633. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59634. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  59635. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  59636. }
  59637. }
  59638. // Textures
  59639. if (this._myScene.texturesEnabled) {
  59640. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59641. this._effect.setTexture("albedoSampler", this.albedoTexture);
  59642. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  59643. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  59644. }
  59645. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59646. this._effect.setTexture("ambientSampler", this.ambientTexture);
  59647. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  59648. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  59649. }
  59650. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59651. this._effect.setTexture("opacitySampler", this.opacityTexture);
  59652. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  59653. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  59654. }
  59655. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59656. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  59657. if (this.reflectionTexture.isCube) {
  59658. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  59659. }
  59660. else {
  59661. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  59662. }
  59663. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  59664. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  59665. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  59666. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  59667. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  59668. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  59669. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  59670. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  59671. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  59672. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  59673. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  59674. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  59675. }
  59676. }
  59677. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59678. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  59679. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  59680. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  59681. }
  59682. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59683. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  59684. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  59685. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  59686. }
  59687. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59688. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  59689. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  59690. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  59691. }
  59692. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59693. this._effect.setTexture("bumpSampler", this.bumpTexture);
  59694. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  59695. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  59696. }
  59697. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59698. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  59699. var depth = 1.0;
  59700. if (this.refractionTexture.isCube) {
  59701. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  59702. }
  59703. else {
  59704. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  59705. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  59706. if (this.refractionTexture.depth) {
  59707. depth = this.refractionTexture.depth;
  59708. }
  59709. }
  59710. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59711. }
  59712. if ((this.reflectionTexture || this.refractionTexture)) {
  59713. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59714. }
  59715. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59716. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  59717. }
  59718. }
  59719. // Clip plane
  59720. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59721. // Point size
  59722. if (this.pointsCloud) {
  59723. this._effect.setFloat("pointSize", this.pointSize);
  59724. }
  59725. // Colors
  59726. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  59727. // GAMMA CORRECTION.
  59728. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  59729. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  59730. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  59731. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  59732. // GAMMA CORRECTION.
  59733. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  59734. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  59735. // GAMMA CORRECTION.
  59736. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  59737. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  59738. }
  59739. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59740. // GAMMA CORRECTION.
  59741. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59742. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59743. // Lights
  59744. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59745. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59746. }
  59747. // View
  59748. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59749. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59750. }
  59751. // Fog
  59752. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59753. this._lightingInfos.x = this.directIntensity;
  59754. this._lightingInfos.y = this.emissiveIntensity;
  59755. this._lightingInfos.z = this.environmentIntensity;
  59756. this._lightingInfos.w = this.specularIntensity;
  59757. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59758. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59759. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59760. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59761. this._cameraInfos.x = this.cameraExposure;
  59762. this._cameraInfos.y = this.cameraContrast;
  59763. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59764. if (this.cameraColorCurves) {
  59765. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59766. }
  59767. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59768. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59769. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59770. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59771. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59772. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  59773. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  59774. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59775. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59776. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59777. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59778. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59779. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59780. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59781. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59782. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59783. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59784. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59785. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59786. // Log. depth
  59787. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59788. }
  59789. _super.prototype.bind.call(this, world, mesh);
  59790. this._myScene = null;
  59791. };
  59792. PBRMaterial.prototype.getAnimatables = function () {
  59793. var results = [];
  59794. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59795. results.push(this.albedoTexture);
  59796. }
  59797. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59798. results.push(this.ambientTexture);
  59799. }
  59800. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59801. results.push(this.opacityTexture);
  59802. }
  59803. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59804. results.push(this.reflectionTexture);
  59805. }
  59806. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59807. results.push(this.emissiveTexture);
  59808. }
  59809. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59810. results.push(this.reflectivityTexture);
  59811. }
  59812. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59813. results.push(this.bumpTexture);
  59814. }
  59815. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59816. results.push(this.lightmapTexture);
  59817. }
  59818. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59819. results.push(this.refractionTexture);
  59820. }
  59821. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59822. results.push(this.cameraColorGradingTexture);
  59823. }
  59824. return results;
  59825. };
  59826. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59827. if (forceDisposeTextures) {
  59828. if (this.albedoTexture) {
  59829. this.albedoTexture.dispose();
  59830. }
  59831. if (this.ambientTexture) {
  59832. this.ambientTexture.dispose();
  59833. }
  59834. if (this.opacityTexture) {
  59835. this.opacityTexture.dispose();
  59836. }
  59837. if (this.reflectionTexture) {
  59838. this.reflectionTexture.dispose();
  59839. }
  59840. if (this.emissiveTexture) {
  59841. this.emissiveTexture.dispose();
  59842. }
  59843. if (this.reflectivityTexture) {
  59844. this.reflectivityTexture.dispose();
  59845. }
  59846. if (this.bumpTexture) {
  59847. this.bumpTexture.dispose();
  59848. }
  59849. if (this.lightmapTexture) {
  59850. this.lightmapTexture.dispose();
  59851. }
  59852. if (this.refractionTexture) {
  59853. this.refractionTexture.dispose();
  59854. }
  59855. if (this.cameraColorGradingTexture) {
  59856. this.cameraColorGradingTexture.dispose();
  59857. }
  59858. }
  59859. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59860. };
  59861. PBRMaterial.prototype.clone = function (name) {
  59862. var _this = this;
  59863. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59864. };
  59865. PBRMaterial.prototype.serialize = function () {
  59866. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59867. serializationObject.customType = "BABYLON.PBRMaterial";
  59868. return serializationObject;
  59869. };
  59870. // Statics
  59871. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59872. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59873. };
  59874. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59875. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59876. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59877. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59878. __decorate([
  59879. BABYLON.serialize()
  59880. ], PBRMaterial.prototype, "directIntensity", void 0);
  59881. __decorate([
  59882. BABYLON.serialize()
  59883. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59884. __decorate([
  59885. BABYLON.serialize()
  59886. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59887. __decorate([
  59888. BABYLON.serialize()
  59889. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59890. __decorate([
  59891. BABYLON.serialize()
  59892. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59893. __decorate([
  59894. BABYLON.serialize()
  59895. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59896. __decorate([
  59897. BABYLON.serialize()
  59898. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59899. __decorate([
  59900. BABYLON.serialize()
  59901. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59902. __decorate([
  59903. BABYLON.serialize()
  59904. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59905. __decorate([
  59906. BABYLON.serializeAsTexture()
  59907. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59908. __decorate([
  59909. BABYLON.serializeAsColorCurves()
  59910. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59911. __decorate([
  59912. BABYLON.serializeAsColor3()
  59913. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59914. __decorate([
  59915. BABYLON.serialize()
  59916. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59917. __decorate([
  59918. BABYLON.serializeAsColor3()
  59919. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59920. __decorate([
  59921. BABYLON.serialize()
  59922. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59923. __decorate([
  59924. BABYLON.serializeAsColor3()
  59925. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59926. __decorate([
  59927. BABYLON.serialize()
  59928. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59929. __decorate([
  59930. BABYLON.serializeAsColor3()
  59931. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59932. __decorate([
  59933. BABYLON.serialize()
  59934. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59935. __decorate([
  59936. BABYLON.serializeAsColor3()
  59937. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59938. __decorate([
  59939. BABYLON.serialize()
  59940. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59941. __decorate([
  59942. BABYLON.serialize()
  59943. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59944. __decorate([
  59945. BABYLON.serialize()
  59946. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59947. __decorate([
  59948. BABYLON.serializeAsTexture()
  59949. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59950. __decorate([
  59951. BABYLON.serializeAsTexture()
  59952. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59953. __decorate([
  59954. BABYLON.serializeAsTexture()
  59955. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59956. __decorate([
  59957. BABYLON.serializeAsTexture()
  59958. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59959. __decorate([
  59960. BABYLON.serializeAsTexture()
  59961. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59962. __decorate([
  59963. BABYLON.serializeAsTexture()
  59964. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59965. __decorate([
  59966. BABYLON.serializeAsTexture()
  59967. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59968. __decorate([
  59969. BABYLON.serializeAsTexture()
  59970. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59971. __decorate([
  59972. BABYLON.serializeAsTexture()
  59973. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59974. __decorate([
  59975. BABYLON.serializeAsColor3("ambient")
  59976. ], PBRMaterial.prototype, "ambientColor", void 0);
  59977. __decorate([
  59978. BABYLON.serializeAsColor3("albedo")
  59979. ], PBRMaterial.prototype, "albedoColor", void 0);
  59980. __decorate([
  59981. BABYLON.serializeAsColor3("reflectivity")
  59982. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59983. __decorate([
  59984. BABYLON.serializeAsColor3("reflection")
  59985. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59986. __decorate([
  59987. BABYLON.serializeAsColor3("emissive")
  59988. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59989. __decorate([
  59990. BABYLON.serialize()
  59991. ], PBRMaterial.prototype, "microSurface", void 0);
  59992. __decorate([
  59993. BABYLON.serialize()
  59994. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59995. __decorate([
  59996. BABYLON.serialize()
  59997. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59998. __decorate([
  59999. BABYLON.serializeAsFresnelParameters()
  60000. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60001. __decorate([
  60002. BABYLON.serializeAsFresnelParameters()
  60003. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60004. __decorate([
  60005. BABYLON.serialize()
  60006. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60007. __decorate([
  60008. BABYLON.serialize()
  60009. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60010. __decorate([
  60011. BABYLON.serialize()
  60012. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60013. __decorate([
  60014. BABYLON.serialize()
  60015. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60016. __decorate([
  60017. BABYLON.serialize()
  60018. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60019. __decorate([
  60020. BABYLON.serialize()
  60021. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60022. __decorate([
  60023. BABYLON.serialize()
  60024. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60025. __decorate([
  60026. BABYLON.serialize()
  60027. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60028. __decorate([
  60029. BABYLON.serialize()
  60030. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60031. __decorate([
  60032. BABYLON.serialize()
  60033. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60034. __decorate([
  60035. BABYLON.serialize()
  60036. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60037. __decorate([
  60038. BABYLON.serialize()
  60039. ], PBRMaterial.prototype, "useParallax", void 0);
  60040. __decorate([
  60041. BABYLON.serialize()
  60042. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60043. __decorate([
  60044. BABYLON.serialize()
  60045. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60046. __decorate([
  60047. BABYLON.serialize()
  60048. ], PBRMaterial.prototype, "disableLighting", void 0);
  60049. __decorate([
  60050. BABYLON.serialize()
  60051. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60052. __decorate([
  60053. BABYLON.serialize()
  60054. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60055. __decorate([
  60056. BABYLON.serialize()
  60057. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60058. __decorate([
  60059. BABYLON.serialize()
  60060. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60061. return PBRMaterial;
  60062. }(BABYLON.Material));
  60063. BABYLON.PBRMaterial = PBRMaterial;
  60064. })(BABYLON || (BABYLON = {}));
  60065. var BABYLON;
  60066. (function (BABYLON) {
  60067. var DebugLayer = (function () {
  60068. function DebugLayer(scene) {
  60069. var _this = this;
  60070. this._transformationMatrix = BABYLON.Matrix.Identity();
  60071. this._enabled = false;
  60072. this._labelsEnabled = false;
  60073. this._displayStatistics = true;
  60074. this._displayTree = false;
  60075. this._displayLogs = false;
  60076. this._skeletonViewers = new Array();
  60077. this._identityMatrix = BABYLON.Matrix.Identity();
  60078. this.axisRatio = 0.02;
  60079. this.accentColor = "orange";
  60080. this._scene = scene;
  60081. this._syncPositions = function () {
  60082. var engine = _this._scene.getEngine();
  60083. var canvasRect = engine.getRenderingCanvasClientRect();
  60084. if (_this._showUI) {
  60085. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  60086. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  60087. _this._statsDiv.style.width = "400px";
  60088. _this._statsDiv.style.height = "auto";
  60089. _this._statsSubsetDiv.style.maxHeight = "240px";
  60090. _this._optionsDiv.style.left = "0px";
  60091. _this._optionsDiv.style.top = "10px";
  60092. _this._optionsDiv.style.width = "200px";
  60093. _this._optionsDiv.style.height = "auto";
  60094. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  60095. _this._logDiv.style.left = "0px";
  60096. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  60097. _this._logDiv.style.width = "600px";
  60098. _this._logDiv.style.height = "160px";
  60099. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  60100. _this._treeDiv.style.top = "10px";
  60101. _this._treeDiv.style.width = "300px";
  60102. _this._treeDiv.style.height = "auto";
  60103. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  60104. }
  60105. _this._globalDiv.style.left = canvasRect.left + "px";
  60106. _this._globalDiv.style.top = canvasRect.top + "px";
  60107. _this._drawingCanvas.style.left = "0px";
  60108. _this._drawingCanvas.style.top = "0px";
  60109. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  60110. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  60111. var devicePixelRatio = window.devicePixelRatio || 1;
  60112. var context = _this._drawingContext;
  60113. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  60114. context.mozBackingStorePixelRatio ||
  60115. context.msBackingStorePixelRatio ||
  60116. context.oBackingStorePixelRatio ||
  60117. context.backingStorePixelRatio || 1;
  60118. _this._ratio = devicePixelRatio / backingStoreRatio;
  60119. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  60120. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  60121. };
  60122. this._onCanvasClick = function (evt) {
  60123. _this._clickPosition = {
  60124. x: evt.clientX * _this._ratio,
  60125. y: evt.clientY * _this._ratio
  60126. };
  60127. };
  60128. this._syncUI = function () {
  60129. if (_this._showUI) {
  60130. if (_this._displayStatistics) {
  60131. _this._displayStats();
  60132. _this._statsDiv.style.display = "";
  60133. }
  60134. else {
  60135. _this._statsDiv.style.display = "none";
  60136. }
  60137. if (_this._displayLogs) {
  60138. _this._logDiv.style.display = "";
  60139. }
  60140. else {
  60141. _this._logDiv.style.display = "none";
  60142. }
  60143. if (_this._displayTree) {
  60144. _this._treeDiv.style.display = "";
  60145. if (_this._needToRefreshMeshesTree) {
  60146. _this._needToRefreshMeshesTree = false;
  60147. _this._refreshMeshesTreeContent();
  60148. }
  60149. }
  60150. else {
  60151. _this._treeDiv.style.display = "none";
  60152. }
  60153. }
  60154. };
  60155. this._syncData = function () {
  60156. if (_this._labelsEnabled || !_this._showUI) {
  60157. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  60158. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  60159. var engine = _this._scene.getEngine();
  60160. var viewport = _this._camera.viewport;
  60161. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60162. // Meshes
  60163. var meshes = _this._camera.getActiveMeshes();
  60164. var index;
  60165. var projectedPosition;
  60166. for (index = 0; index < meshes.length; index++) {
  60167. var mesh = meshes.data[index];
  60168. var position = mesh.getBoundingInfo().boundingSphere.center;
  60169. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60170. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  60171. _this._renderAxis(projectedPosition, mesh, globalViewport);
  60172. }
  60173. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  60174. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  60175. }
  60176. }
  60177. // Cameras
  60178. var cameras = _this._scene.cameras;
  60179. for (index = 0; index < cameras.length; index++) {
  60180. var camera = cameras[index];
  60181. if (camera === _this._camera) {
  60182. continue;
  60183. }
  60184. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60185. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  60186. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  60187. _this._camera.detachControl(engine.getRenderingCanvas());
  60188. _this._camera = camera;
  60189. _this._camera.attachControl(engine.getRenderingCanvas());
  60190. }, function () { return "purple"; });
  60191. }
  60192. }
  60193. // Lights
  60194. var lights = _this._scene.lights;
  60195. for (index = 0; index < lights.length; index++) {
  60196. var light = lights[index];
  60197. if (light.position) {
  60198. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  60199. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  60200. _this._renderLabel(light.name, projectedPosition, -20, function () {
  60201. light.setEnabled(!light.isEnabled());
  60202. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  60203. }
  60204. }
  60205. }
  60206. }
  60207. _this._clickPosition = undefined;
  60208. };
  60209. }
  60210. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  60211. while (this._treeSubsetDiv.hasChildNodes()) {
  60212. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  60213. }
  60214. // Add meshes
  60215. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  60216. sortedArray.sort(function (a, b) {
  60217. if (a.name === b.name) {
  60218. return 0;
  60219. }
  60220. return (a.name > b.name) ? 1 : -1;
  60221. });
  60222. for (var index = 0; index < sortedArray.length; index++) {
  60223. var mesh = sortedArray[index];
  60224. if (!mesh.isEnabled()) {
  60225. continue;
  60226. }
  60227. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  60228. m.isVisible = element.checked;
  60229. }, mesh);
  60230. }
  60231. };
  60232. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  60233. this._drawingContext.beginPath();
  60234. this._drawingContext.moveTo(zero.x, zero.y);
  60235. this._drawingContext.lineTo(unit.x, unit.y);
  60236. this._drawingContext.strokeStyle = color;
  60237. this._drawingContext.lineWidth = 4;
  60238. this._drawingContext.stroke();
  60239. this._drawingContext.font = "normal 14px Segoe UI";
  60240. this._drawingContext.fillStyle = color;
  60241. this._drawingContext.fillText(label, unitText.x, unitText.y);
  60242. };
  60243. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  60244. var position = mesh.getBoundingInfo().boundingSphere.center;
  60245. var worldMatrix = mesh.getWorldMatrix();
  60246. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  60247. var unit = (unprojectedVector.subtract(position)).length();
  60248. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60249. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60250. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  60251. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60252. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60253. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  60254. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  60255. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  60256. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  60257. };
  60258. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  60259. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  60260. this._drawingContext.font = "normal 12px Segoe UI";
  60261. var textMetrics = this._drawingContext.measureText(text);
  60262. var centerX = projectedPosition.x - textMetrics.width / 2;
  60263. var centerY = projectedPosition.y;
  60264. var clientRect = this._drawingCanvas.getBoundingClientRect();
  60265. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  60266. onClick();
  60267. }
  60268. this._drawingContext.beginPath();
  60269. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  60270. this._drawingContext.fillStyle = getFillStyle();
  60271. this._drawingContext.globalAlpha = 0.5;
  60272. this._drawingContext.fill();
  60273. this._drawingContext.globalAlpha = 1.0;
  60274. this._drawingContext.strokeStyle = '#FFFFFF';
  60275. this._drawingContext.lineWidth = 1;
  60276. this._drawingContext.stroke();
  60277. this._drawingContext.fillStyle = "#FFFFFF";
  60278. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  60279. this._drawingContext.beginPath();
  60280. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  60281. this._drawingContext.fill();
  60282. }
  60283. };
  60284. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  60285. if (!this._clickPosition) {
  60286. return false;
  60287. }
  60288. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  60289. return false;
  60290. }
  60291. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  60292. return false;
  60293. }
  60294. return true;
  60295. };
  60296. DebugLayer.prototype.isVisible = function () {
  60297. return this._enabled;
  60298. };
  60299. DebugLayer.prototype.hide = function () {
  60300. if (!this._enabled) {
  60301. return;
  60302. }
  60303. this._enabled = false;
  60304. var engine = this._scene.getEngine();
  60305. this._scene.unregisterBeforeRender(this._syncData);
  60306. this._scene.unregisterAfterRender(this._syncUI);
  60307. this._rootElement.removeChild(this._globalDiv);
  60308. this._scene.forceShowBoundingBoxes = false;
  60309. this._scene.forceWireframe = false;
  60310. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  60311. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  60312. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  60313. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  60314. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  60315. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  60316. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  60317. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  60318. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  60319. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  60320. this._scene.shadowsEnabled = true;
  60321. this._scene.particlesEnabled = true;
  60322. this._scene.postProcessesEnabled = true;
  60323. this._scene.collisionsEnabled = true;
  60324. this._scene.lightsEnabled = true;
  60325. this._scene.texturesEnabled = true;
  60326. this._scene.lensFlaresEnabled = true;
  60327. this._scene.proceduralTexturesEnabled = true;
  60328. this._scene.renderTargetsEnabled = true;
  60329. this._scene.probesEnabled = true;
  60330. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  60331. this._clearSkeletonViewers();
  60332. };
  60333. DebugLayer.prototype._clearSkeletonViewers = function () {
  60334. for (var index = 0; index < this._skeletonViewers.length; index++) {
  60335. this._skeletonViewers[index].dispose();
  60336. }
  60337. this._skeletonViewers = [];
  60338. };
  60339. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  60340. if (showUI === void 0) { showUI = true; }
  60341. if (camera === void 0) { camera = null; }
  60342. if (rootElement === void 0) { rootElement = null; }
  60343. if (this._enabled) {
  60344. return;
  60345. }
  60346. this._enabled = true;
  60347. if (camera) {
  60348. this._camera = camera;
  60349. }
  60350. else {
  60351. this._camera = this._scene.activeCamera;
  60352. }
  60353. this._showUI = showUI;
  60354. var engine = this._scene.getEngine();
  60355. this._globalDiv = document.createElement("div");
  60356. this._rootElement = rootElement || document.body;
  60357. this._rootElement.appendChild(this._globalDiv);
  60358. this._generateDOMelements();
  60359. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  60360. this._syncPositions();
  60361. this._scene.registerBeforeRender(this._syncData);
  60362. this._scene.registerAfterRender(this._syncUI);
  60363. };
  60364. DebugLayer.prototype._clearLabels = function () {
  60365. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  60366. for (var index = 0; index < this._scene.meshes.length; index++) {
  60367. var mesh = this._scene.meshes[index];
  60368. mesh.renderOverlay = false;
  60369. }
  60370. };
  60371. DebugLayer.prototype._generateheader = function (root, text) {
  60372. var header = document.createElement("div");
  60373. header.innerHTML = text + "&nbsp;";
  60374. header.style.textAlign = "right";
  60375. header.style.width = "100%";
  60376. header.style.color = "white";
  60377. header.style.backgroundColor = "Black";
  60378. header.style.padding = "5px 5px 4px 0px";
  60379. header.style.marginLeft = "-5px";
  60380. header.style.fontWeight = "bold";
  60381. root.appendChild(header);
  60382. };
  60383. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  60384. var label = document.createElement("label");
  60385. label.style.display = "inline";
  60386. label.innerHTML = title;
  60387. label.style.color = color;
  60388. root.appendChild(label);
  60389. root.appendChild(document.createElement("br"));
  60390. };
  60391. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  60392. if (tag === void 0) { tag = null; }
  60393. var label = document.createElement("label");
  60394. label.style.display = "inline";
  60395. var boundingBoxesCheckbox = document.createElement("input");
  60396. boundingBoxesCheckbox.type = "checkbox";
  60397. boundingBoxesCheckbox.checked = initialState;
  60398. boundingBoxesCheckbox.style.display = "inline";
  60399. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  60400. boundingBoxesCheckbox.style.verticalAlign = "sub";
  60401. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  60402. task(evt.target, tag);
  60403. });
  60404. label.appendChild(boundingBoxesCheckbox);
  60405. var container = document.createElement("span");
  60406. var leftPart = document.createElement("span");
  60407. var rightPart = document.createElement("span");
  60408. rightPart.style.cssFloat = "right";
  60409. leftPart.innerHTML = leftTitle;
  60410. rightPart.innerHTML = rightTitle;
  60411. rightPart.style.fontSize = "12px";
  60412. rightPart.style.maxWidth = "200px";
  60413. container.appendChild(leftPart);
  60414. container.appendChild(rightPart);
  60415. label.appendChild(container);
  60416. root.appendChild(label);
  60417. root.appendChild(document.createElement("br"));
  60418. };
  60419. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  60420. if (tag === void 0) { tag = null; }
  60421. var label = document.createElement("label");
  60422. label.style.display = "inline";
  60423. var checkBox = document.createElement("input");
  60424. checkBox.type = "checkbox";
  60425. checkBox.checked = initialState;
  60426. checkBox.style.display = "inline";
  60427. checkBox.style.margin = "0px 5px 0px 0px";
  60428. checkBox.style.verticalAlign = "sub";
  60429. checkBox.addEventListener("change", function (evt) {
  60430. task(evt.target, tag);
  60431. });
  60432. label.appendChild(checkBox);
  60433. label.appendChild(document.createTextNode(title));
  60434. root.appendChild(label);
  60435. root.appendChild(document.createElement("br"));
  60436. };
  60437. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  60438. if (tag === void 0) { tag = null; }
  60439. var button = document.createElement("button");
  60440. button.innerHTML = title;
  60441. button.style.height = "24px";
  60442. button.style.width = "150px";
  60443. button.style.marginBottom = "5px";
  60444. button.style.color = "#444444";
  60445. button.style.border = "1px solid white";
  60446. button.className = "debugLayerButton";
  60447. button.addEventListener("click", function (evt) {
  60448. task(evt.target, tag);
  60449. });
  60450. root.appendChild(button);
  60451. root.appendChild(document.createElement("br"));
  60452. };
  60453. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  60454. if (tag === void 0) { tag = null; }
  60455. var label = document.createElement("label");
  60456. label.style.display = "inline";
  60457. var boundingBoxesRadio = document.createElement("input");
  60458. boundingBoxesRadio.type = "radio";
  60459. boundingBoxesRadio.name = name;
  60460. boundingBoxesRadio.checked = initialState;
  60461. boundingBoxesRadio.style.display = "inline";
  60462. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  60463. boundingBoxesRadio.style.verticalAlign = "sub";
  60464. boundingBoxesRadio.addEventListener("change", function (evt) {
  60465. task(evt.target, tag);
  60466. });
  60467. label.appendChild(boundingBoxesRadio);
  60468. label.appendChild(document.createTextNode(title));
  60469. root.appendChild(label);
  60470. root.appendChild(document.createElement("br"));
  60471. };
  60472. DebugLayer.prototype._generateDOMelements = function () {
  60473. var _this = this;
  60474. this._globalDiv.id = "DebugLayer";
  60475. this._globalDiv.style.position = "absolute";
  60476. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  60477. this._globalDiv.style.fontSize = "14px";
  60478. this._globalDiv.style.color = "white";
  60479. // Drawing canvas
  60480. this._drawingCanvas = document.createElement("canvas");
  60481. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  60482. this._drawingCanvas.style.position = "absolute";
  60483. this._drawingCanvas.style.pointerEvents = "none";
  60484. this._drawingCanvas.style.backgroundColor = "transparent";
  60485. this._drawingContext = this._drawingCanvas.getContext("2d");
  60486. this._globalDiv.appendChild(this._drawingCanvas);
  60487. if (this._showUI) {
  60488. var background = "rgba(128, 128, 128, 0.4)";
  60489. var border = "rgb(180, 180, 180) solid 1px";
  60490. // Stats
  60491. this._statsDiv = document.createElement("div");
  60492. this._statsDiv.id = "DebugLayerStats";
  60493. this._statsDiv.style.border = border;
  60494. this._statsDiv.style.position = "absolute";
  60495. this._statsDiv.style.background = background;
  60496. this._statsDiv.style.padding = "0px 0px 0px 5px";
  60497. this._generateheader(this._statsDiv, "STATISTICS");
  60498. this._statsSubsetDiv = document.createElement("div");
  60499. this._statsSubsetDiv.style.paddingTop = "5px";
  60500. this._statsSubsetDiv.style.paddingBottom = "5px";
  60501. this._statsSubsetDiv.style.overflowY = "auto";
  60502. this._statsDiv.appendChild(this._statsSubsetDiv);
  60503. // Tree
  60504. this._treeDiv = document.createElement("div");
  60505. this._treeDiv.id = "DebugLayerTree";
  60506. this._treeDiv.style.border = border;
  60507. this._treeDiv.style.position = "absolute";
  60508. this._treeDiv.style.background = background;
  60509. this._treeDiv.style.padding = "0px 0px 0px 5px";
  60510. this._treeDiv.style.display = "none";
  60511. this._generateheader(this._treeDiv, "MESHES TREE");
  60512. this._treeSubsetDiv = document.createElement("div");
  60513. this._treeSubsetDiv.style.paddingTop = "5px";
  60514. this._treeSubsetDiv.style.paddingRight = "5px";
  60515. this._treeSubsetDiv.style.overflowY = "auto";
  60516. this._treeSubsetDiv.style.maxHeight = "300px";
  60517. this._treeDiv.appendChild(this._treeSubsetDiv);
  60518. this._needToRefreshMeshesTree = true;
  60519. // Logs
  60520. this._logDiv = document.createElement("div");
  60521. this._logDiv.style.border = border;
  60522. this._logDiv.id = "DebugLayerLogs";
  60523. this._logDiv.style.position = "absolute";
  60524. this._logDiv.style.background = background;
  60525. this._logDiv.style.padding = "0px 0px 0px 5px";
  60526. this._logDiv.style.display = "none";
  60527. this._generateheader(this._logDiv, "LOGS");
  60528. this._logSubsetDiv = document.createElement("div");
  60529. this._logSubsetDiv.style.height = "127px";
  60530. this._logSubsetDiv.style.paddingTop = "5px";
  60531. this._logSubsetDiv.style.overflowY = "auto";
  60532. this._logSubsetDiv.style.fontSize = "12px";
  60533. this._logSubsetDiv.style.fontFamily = "consolas";
  60534. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  60535. this._logDiv.appendChild(this._logSubsetDiv);
  60536. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  60537. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  60538. };
  60539. // Options
  60540. this._optionsDiv = document.createElement("div");
  60541. this._optionsDiv.id = "DebugLayerOptions";
  60542. this._optionsDiv.style.border = border;
  60543. this._optionsDiv.style.position = "absolute";
  60544. this._optionsDiv.style.background = background;
  60545. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  60546. this._optionsDiv.style.overflowY = "auto";
  60547. this._generateheader(this._optionsDiv, "OPTIONS");
  60548. this._optionsSubsetDiv = document.createElement("div");
  60549. this._optionsSubsetDiv.style.paddingTop = "5px";
  60550. this._optionsSubsetDiv.style.paddingBottom = "5px";
  60551. this._optionsSubsetDiv.style.overflowY = "auto";
  60552. this._optionsSubsetDiv.style.maxHeight = "200px";
  60553. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  60554. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  60555. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  60556. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  60557. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  60558. _this._displayTree = element.checked;
  60559. _this._needToRefreshMeshesTree = true;
  60560. });
  60561. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60562. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  60563. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  60564. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  60565. _this._labelsEnabled = element.checked;
  60566. if (!_this._labelsEnabled) {
  60567. _this._clearLabels();
  60568. }
  60569. });
  60570. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  60571. if (element.checked) {
  60572. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  60573. }
  60574. else {
  60575. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  60576. }
  60577. });
  60578. ;
  60579. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60580. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  60581. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  60582. if (element.checked) {
  60583. _this._scene.forceWireframe = false;
  60584. _this._scene.forcePointsCloud = false;
  60585. }
  60586. });
  60587. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  60588. if (element.checked) {
  60589. _this._scene.forceWireframe = true;
  60590. _this._scene.forcePointsCloud = false;
  60591. }
  60592. });
  60593. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  60594. if (element.checked) {
  60595. _this._scene.forceWireframe = false;
  60596. _this._scene.forcePointsCloud = true;
  60597. }
  60598. });
  60599. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60600. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  60601. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  60602. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  60603. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  60604. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  60605. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  60606. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  60607. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  60608. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  60609. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  60610. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  60611. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  60612. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60613. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  60614. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  60615. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  60616. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  60617. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  60618. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  60619. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  60620. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  60621. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  60622. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  60623. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  60624. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  60625. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  60626. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  60627. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  60628. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60629. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60630. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  60631. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  60632. if (element.checked) {
  60633. _this._scene.headphone = true;
  60634. }
  60635. });
  60636. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  60637. if (element.checked) {
  60638. _this._scene.headphone = false;
  60639. }
  60640. });
  60641. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  60642. _this._scene.audioEnabled = !element.checked;
  60643. });
  60644. }
  60645. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60646. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  60647. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  60648. if (!element.checked) {
  60649. _this._clearSkeletonViewers();
  60650. return;
  60651. }
  60652. for (var index = 0; index < _this._scene.meshes.length; index++) {
  60653. var mesh = _this._scene.meshes[index];
  60654. if (mesh.skeleton) {
  60655. var found = false;
  60656. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  60657. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  60658. found = true;
  60659. break;
  60660. }
  60661. }
  60662. if (found) {
  60663. continue;
  60664. }
  60665. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  60666. viewer.isEnabled = true;
  60667. _this._skeletonViewers.push(viewer);
  60668. }
  60669. }
  60670. });
  60671. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60672. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  60673. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  60674. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  60675. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  60676. if (_this._camera) {
  60677. console.log(_this._camera);
  60678. }
  60679. else {
  60680. console.warn("No camera defined, or debug layer created before camera creation!");
  60681. }
  60682. });
  60683. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60684. this._globalDiv.appendChild(this._statsDiv);
  60685. this._globalDiv.appendChild(this._logDiv);
  60686. this._globalDiv.appendChild(this._optionsDiv);
  60687. this._globalDiv.appendChild(this._treeDiv);
  60688. }
  60689. };
  60690. DebugLayer.prototype._displayStats = function () {
  60691. var scene = this._scene;
  60692. var engine = scene.getEngine();
  60693. var glInfo = engine.getGlInfo();
  60694. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  60695. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60696. + "<b>Count</b><br>"
  60697. + "Total meshes: " + scene.meshes.length + "<br>"
  60698. + "Total lights: " + scene.lights.length + "<br>"
  60699. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  60700. + "Total materials: " + scene.materials.length + "<br>"
  60701. + "Total textures: " + scene.textures.length + "<br>"
  60702. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  60703. + "Active indices: " + scene.getActiveIndices() + "<br>"
  60704. + "Active bones: " + scene.getActiveBones() + "<br>"
  60705. + "Active particles: " + scene.getActiveParticles() + "<br>"
  60706. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  60707. + "<b>Duration</b><br>"
  60708. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  60709. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  60710. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  60711. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  60712. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  60713. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  60714. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  60715. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  60716. + "</div>"
  60717. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60718. + "<b>Extensions</b><br>"
  60719. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  60720. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  60721. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  60722. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  60723. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  60724. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  60725. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  60726. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  60727. + "</div><br>"
  60728. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60729. + "<b>Caps.</b><br>"
  60730. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  60731. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  60732. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  60733. + "<b>Info</b><br>"
  60734. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  60735. + glInfo.version + "<br>"
  60736. + "</div><br>"
  60737. + glInfo.renderer + "<br>";
  60738. if (this.customStatsFunction) {
  60739. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  60740. }
  60741. };
  60742. return DebugLayer;
  60743. }());
  60744. BABYLON.DebugLayer = DebugLayer;
  60745. })(BABYLON || (BABYLON = {}));
  60746. 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#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..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);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\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\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..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 vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\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 vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#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<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\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);\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).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#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 vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[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)\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}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\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}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\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","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}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a<0.05)\ndiscard;\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  60747. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\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 float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,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-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,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#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#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\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"};
  60748. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},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(0>r)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&&s>c?(t.root=c,t.found=!0,t):h>0&&s>h?(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()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var 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=2*g*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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=2*g*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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=2*g*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&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return n>=-r&&r>=n},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,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}();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.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=0>o?-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&&2*o*e>s+h},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.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){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},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.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){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},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=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},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,1,0,h+e/2,s/2+a,0,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),t.z),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(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),r.CrossToRef(h,R,g),g.normalize(),r.Dot(a,g)<0&&(v=1),T=r.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,r.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),r.CrossToRef(_,R,b),b.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(R,g)<0&&(v=1),T=r.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,r.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,R,g),g.normalize(),r.Dot(g,m)<0&&(v=1),T=r.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},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){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},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){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},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.substract=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 t(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 t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.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)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.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},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),-.499>u&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=r,t.z=n,t.x=o,this},t.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},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.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)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.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},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.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},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.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)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.w,a=!1;if(0>h&&(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}return new t(e*i.x+o*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],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)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;16>r;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],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],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+r*_+n*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*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*T)*F,t.m[13]=(i*v-r*g+n*T)*F,t.m[2]=(r*A-n*L+o*C)*F,t.m[6]=-(i*A-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*q+o*H)*F,t.m[7]=(i*I-n*N+o*V)*F,t.m[11]=-(i*q-r*N+o*D)*F,t.m[15]=(i*H-r*V+n*D)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;16>r;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.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],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=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];\n\nreturn i[r]=n*v+o*R+e*F+s*P,i[r+1]=n*d+o*_+e*A+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*T+o*b+e*C+s*I,i[r+4]=h*v+a*R+u*F+m*P,i[r+5]=h*d+a*_+u*A+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*T+a*b+u*C+m*I,i[r+8]=y*v+c*R+p*F+f*P,i[r+9]=y*d+c*_+p*A+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*T+c*b+p*C+f*I,i[r+12]=l*v+x*R+z*F+w*P,i[r+13]=l*d+x*_+z*A+w*Z,i[r+14]=l*g+x*M+z*L+w*S,i[r+15]=l*T+x*b+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(r,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;if(r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=t.FromValues(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,n),!0},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;16>n;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;16>o;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=r,x.m[3]=n,x.m[4]=o,x.m[5]=e,x.m[6]=s,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||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])},t.prototype.setRow=function(t,i){if(0>t||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},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=r,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]=l,z.m[15]=x,z},t.Compose=function(i,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.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},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.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},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.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},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.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},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.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},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);o.m[0]=e?s/i:s,o.m[1]=o.m[2]=o.m[3]=0,o.m[5]=e?s:s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-n/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.GetFinalMatrix=function(i,r,n,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.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},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();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 i>=r},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}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;6>n;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;5>u;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=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=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=x;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>c;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(0>t||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&&u>=i){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(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;if(void 0===o||null===o){var h;i.WithinEpsilon(n.y,1,t.Epsilon)?i.WithinEpsilon(n.x,1,t.Epsilon)?i.WithinEpsilon(n.z,1,t.Epsilon)||(h=new e(0,0,1)):h=new e(1,0,0):h=new e(0,-1,0),s=e.Cross(n,h)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;o>=a;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;s>=u;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;s>=u;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var 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=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var 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 R=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=R;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[r.Black(),r.Black(),r.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  60749. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60750. module.exports = BABYLON;
  60751. };