babylon.max.js 3.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416
  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.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = 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.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. 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);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. }());
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. }());
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. }());
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. 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));
  1745. };
  1746. return Quaternion;
  1747. }());
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. 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]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. 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);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. 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);
  2272. };
  2273. Matrix.LookAtRH = function (eye, target, up) {
  2274. var result = Matrix.Zero();
  2275. Matrix.LookAtRHToRef(eye, target, up, result);
  2276. return result;
  2277. };
  2278. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2279. // Z axis
  2280. eye.subtractToRef(target, this._zAxis);
  2281. this._zAxis.normalize();
  2282. // X axis
  2283. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2284. if (this._xAxis.lengthSquared() === 0) {
  2285. this._xAxis.x = 1.0;
  2286. }
  2287. else {
  2288. this._xAxis.normalize();
  2289. }
  2290. // Y axis
  2291. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2292. this._yAxis.normalize();
  2293. // Eye angles
  2294. var ex = -Vector3.Dot(this._xAxis, eye);
  2295. var ey = -Vector3.Dot(this._yAxis, eye);
  2296. var ez = -Vector3.Dot(this._zAxis, eye);
  2297. 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);
  2298. };
  2299. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2300. var matrix = Matrix.Zero();
  2301. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2302. return matrix;
  2303. };
  2304. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2305. var hw = 2.0 / width;
  2306. var hh = 2.0 / height;
  2307. var id = 1.0 / (zfar - znear);
  2308. var nid = znear / (znear - zfar);
  2309. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2310. };
  2311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2312. var matrix = Matrix.Zero();
  2313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2314. return matrix;
  2315. };
  2316. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2317. result.m[0] = 2.0 / (right - left);
  2318. result.m[1] = result.m[2] = result.m[3] = 0;
  2319. result.m[5] = 2.0 / (top - bottom);
  2320. result.m[4] = result.m[6] = result.m[7] = 0;
  2321. result.m[10] = 1.0 / (zfar - znear);
  2322. result.m[8] = result.m[9] = result.m[11] = 0;
  2323. result.m[12] = (left + right) / (left - right);
  2324. result.m[13] = (top + bottom) / (bottom - top);
  2325. result.m[14] = -znear / (zfar - znear);
  2326. result.m[15] = 1.0;
  2327. };
  2328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2334. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2335. result.m[10] *= -1.0;
  2336. };
  2337. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2338. var matrix = Matrix.Zero();
  2339. matrix.m[0] = (2.0 * znear) / width;
  2340. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2341. matrix.m[5] = (2.0 * znear) / height;
  2342. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2343. matrix.m[10] = -zfar / (znear - zfar);
  2344. matrix.m[8] = matrix.m[9] = 0.0;
  2345. matrix.m[11] = 1.0;
  2346. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2347. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2348. return matrix;
  2349. };
  2350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2351. var matrix = Matrix.Zero();
  2352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2353. return matrix;
  2354. };
  2355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2357. var tan = 1.0 / (Math.tan(fov * 0.5));
  2358. if (isVerticalFovFixed) {
  2359. result.m[0] = tan / aspect;
  2360. }
  2361. else {
  2362. result.m[0] = tan;
  2363. }
  2364. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2365. if (isVerticalFovFixed) {
  2366. result.m[5] = tan;
  2367. }
  2368. else {
  2369. result.m[5] = tan * aspect;
  2370. }
  2371. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2372. result.m[8] = result.m[9] = 0.0;
  2373. result.m[10] = zfar / (zfar - znear);
  2374. result.m[11] = 1.0;
  2375. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2376. result.m[14] = -(znear * zfar) / (zfar - znear);
  2377. };
  2378. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2379. var matrix = Matrix.Zero();
  2380. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2384. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2385. var tan = 1.0 / (Math.tan(fov * 0.5));
  2386. if (isVerticalFovFixed) {
  2387. result.m[0] = tan / aspect;
  2388. }
  2389. else {
  2390. result.m[0] = tan;
  2391. }
  2392. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2393. if (isVerticalFovFixed) {
  2394. result.m[5] = tan;
  2395. }
  2396. else {
  2397. result.m[5] = tan * aspect;
  2398. }
  2399. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2400. result.m[8] = result.m[9] = 0.0;
  2401. result.m[10] = zfar / (znear - zfar);
  2402. result.m[11] = -1.0;
  2403. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2404. result.m[14] = (znear * zfar) / (znear - zfar);
  2405. };
  2406. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2408. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2409. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2410. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2411. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2412. var xScale = 2.0 / (leftTan + rightTan);
  2413. var yScale = 2.0 / (upTan + downTan);
  2414. result.m[0] = xScale;
  2415. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2416. result.m[5] = yScale;
  2417. result.m[6] = result.m[7] = 0.0;
  2418. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2419. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2420. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2421. result.m[10] = -zfar / (znear - zfar);
  2422. result.m[11] = 1.0;
  2423. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2424. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2425. result.m[14] = (znear * zfar) / (znear - zfar);
  2426. };
  2427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2428. var cw = viewport.width;
  2429. var ch = viewport.height;
  2430. var cx = viewport.x;
  2431. var cy = viewport.y;
  2432. 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);
  2433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2434. };
  2435. Matrix.GetAsMatrix2x2 = function (matrix) {
  2436. return new Float32Array([
  2437. matrix.m[0], matrix.m[1],
  2438. matrix.m[4], matrix.m[5]
  2439. ]);
  2440. };
  2441. Matrix.GetAsMatrix3x3 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1], matrix.m[2],
  2444. matrix.m[4], matrix.m[5], matrix.m[6],
  2445. matrix.m[8], matrix.m[9], matrix.m[10]
  2446. ]);
  2447. };
  2448. Matrix.Transpose = function (matrix) {
  2449. var result = new Matrix();
  2450. result.m[0] = matrix.m[0];
  2451. result.m[1] = matrix.m[4];
  2452. result.m[2] = matrix.m[8];
  2453. result.m[3] = matrix.m[12];
  2454. result.m[4] = matrix.m[1];
  2455. result.m[5] = matrix.m[5];
  2456. result.m[6] = matrix.m[9];
  2457. result.m[7] = matrix.m[13];
  2458. result.m[8] = matrix.m[2];
  2459. result.m[9] = matrix.m[6];
  2460. result.m[10] = matrix.m[10];
  2461. result.m[11] = matrix.m[14];
  2462. result.m[12] = matrix.m[3];
  2463. result.m[13] = matrix.m[7];
  2464. result.m[14] = matrix.m[11];
  2465. result.m[15] = matrix.m[15];
  2466. return result;
  2467. };
  2468. Matrix.Reflection = function (plane) {
  2469. var matrix = new Matrix();
  2470. Matrix.ReflectionToRef(plane, matrix);
  2471. return matrix;
  2472. };
  2473. Matrix.ReflectionToRef = function (plane, result) {
  2474. plane.normalize();
  2475. var x = plane.normal.x;
  2476. var y = plane.normal.y;
  2477. var z = plane.normal.z;
  2478. var temp = -2 * x;
  2479. var temp2 = -2 * y;
  2480. var temp3 = -2 * z;
  2481. result.m[0] = (temp * x) + 1;
  2482. result.m[1] = temp2 * x;
  2483. result.m[2] = temp3 * x;
  2484. result.m[3] = 0.0;
  2485. result.m[4] = temp * y;
  2486. result.m[5] = (temp2 * y) + 1;
  2487. result.m[6] = temp3 * y;
  2488. result.m[7] = 0.0;
  2489. result.m[8] = temp * z;
  2490. result.m[9] = temp2 * z;
  2491. result.m[10] = (temp3 * z) + 1;
  2492. result.m[11] = 0.0;
  2493. result.m[12] = temp * plane.d;
  2494. result.m[13] = temp2 * plane.d;
  2495. result.m[14] = temp3 * plane.d;
  2496. result.m[15] = 1.0;
  2497. };
  2498. Matrix._tempQuaternion = new Quaternion();
  2499. Matrix._xAxis = Vector3.Zero();
  2500. Matrix._yAxis = Vector3.Zero();
  2501. Matrix._zAxis = Vector3.Zero();
  2502. return Matrix;
  2503. }());
  2504. BABYLON.Matrix = Matrix;
  2505. var Plane = (function () {
  2506. function Plane(a, b, c, d) {
  2507. this.normal = new Vector3(a, b, c);
  2508. this.d = d;
  2509. }
  2510. Plane.prototype.asArray = function () {
  2511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2512. };
  2513. // Methods
  2514. Plane.prototype.clone = function () {
  2515. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2516. };
  2517. Plane.prototype.getClassName = function () {
  2518. return "Plane";
  2519. };
  2520. Plane.prototype.getHashCode = function () {
  2521. var hash = this.normal.getHashCode();
  2522. hash = (hash * 397) ^ (this.d || 0);
  2523. return hash;
  2524. };
  2525. Plane.prototype.normalize = function () {
  2526. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2527. var magnitude = 0;
  2528. if (norm !== 0) {
  2529. magnitude = 1.0 / norm;
  2530. }
  2531. this.normal.x *= magnitude;
  2532. this.normal.y *= magnitude;
  2533. this.normal.z *= magnitude;
  2534. this.d *= magnitude;
  2535. return this;
  2536. };
  2537. Plane.prototype.transform = function (transformation) {
  2538. var transposedMatrix = Matrix.Transpose(transformation);
  2539. var x = this.normal.x;
  2540. var y = this.normal.y;
  2541. var z = this.normal.z;
  2542. var d = this.d;
  2543. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2544. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2545. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2546. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2547. return new Plane(normalX, normalY, normalZ, finalD);
  2548. };
  2549. Plane.prototype.dotCoordinate = function (point) {
  2550. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2551. };
  2552. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2553. var x1 = point2.x - point1.x;
  2554. var y1 = point2.y - point1.y;
  2555. var z1 = point2.z - point1.z;
  2556. var x2 = point3.x - point1.x;
  2557. var y2 = point3.y - point1.y;
  2558. var z2 = point3.z - point1.z;
  2559. var yz = (y1 * z2) - (z1 * y2);
  2560. var xz = (z1 * x2) - (x1 * z2);
  2561. var xy = (x1 * y2) - (y1 * x2);
  2562. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2563. var invPyth;
  2564. if (pyth !== 0) {
  2565. invPyth = 1.0 / pyth;
  2566. }
  2567. else {
  2568. invPyth = 0;
  2569. }
  2570. this.normal.x = yz * invPyth;
  2571. this.normal.y = xz * invPyth;
  2572. this.normal.z = xy * invPyth;
  2573. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2574. return this;
  2575. };
  2576. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2577. var dot = Vector3.Dot(this.normal, direction);
  2578. return (dot <= epsilon);
  2579. };
  2580. Plane.prototype.signedDistanceTo = function (point) {
  2581. return Vector3.Dot(point, this.normal) + this.d;
  2582. };
  2583. // Statics
  2584. Plane.FromArray = function (array) {
  2585. return new Plane(array[0], array[1], array[2], array[3]);
  2586. };
  2587. Plane.FromPoints = function (point1, point2, point3) {
  2588. var result = new Plane(0, 0, 0, 0);
  2589. result.copyFromPoints(point1, point2, point3);
  2590. return result;
  2591. };
  2592. Plane.FromPositionAndNormal = function (origin, normal) {
  2593. var result = new Plane(0, 0, 0, 0);
  2594. normal.normalize();
  2595. result.normal = normal;
  2596. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2597. return result;
  2598. };
  2599. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2600. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2601. return Vector3.Dot(point, normal) + d;
  2602. };
  2603. return Plane;
  2604. }());
  2605. BABYLON.Plane = Plane;
  2606. var Viewport = (function () {
  2607. function Viewport(x, y, width, height) {
  2608. this.x = x;
  2609. this.y = y;
  2610. this.width = width;
  2611. this.height = height;
  2612. }
  2613. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2614. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2615. };
  2616. return Viewport;
  2617. }());
  2618. BABYLON.Viewport = Viewport;
  2619. var Frustum = (function () {
  2620. function Frustum() {
  2621. }
  2622. Frustum.GetPlanes = function (transform) {
  2623. var frustumPlanes = [];
  2624. for (var index = 0; index < 6; index++) {
  2625. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2626. }
  2627. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2628. return frustumPlanes;
  2629. };
  2630. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2631. // Near
  2632. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2633. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2634. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2635. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2636. frustumPlanes[0].normalize();
  2637. // Far
  2638. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2639. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2640. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2641. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2642. frustumPlanes[1].normalize();
  2643. // Left
  2644. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2645. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2646. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2647. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2648. frustumPlanes[2].normalize();
  2649. // Right
  2650. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2651. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2652. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2653. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2654. frustumPlanes[3].normalize();
  2655. // Top
  2656. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2657. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2658. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2659. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2660. frustumPlanes[4].normalize();
  2661. // Bottom
  2662. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2663. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2664. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2665. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2666. frustumPlanes[5].normalize();
  2667. };
  2668. return Frustum;
  2669. }());
  2670. BABYLON.Frustum = Frustum;
  2671. (function (Space) {
  2672. Space[Space["LOCAL"] = 0] = "LOCAL";
  2673. Space[Space["WORLD"] = 1] = "WORLD";
  2674. })(BABYLON.Space || (BABYLON.Space = {}));
  2675. var Space = BABYLON.Space;
  2676. var Axis = (function () {
  2677. function Axis() {
  2678. }
  2679. Axis.X = new Vector3(1, 0, 0);
  2680. Axis.Y = new Vector3(0, 1, 0);
  2681. Axis.Z = new Vector3(0, 0, 1);
  2682. return Axis;
  2683. }());
  2684. BABYLON.Axis = Axis;
  2685. ;
  2686. var BezierCurve = (function () {
  2687. function BezierCurve() {
  2688. }
  2689. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2690. // Extract X (which is equal to time here)
  2691. var f0 = 1 - 3 * x2 + 3 * x1;
  2692. var f1 = 3 * x2 - 6 * x1;
  2693. var f2 = 3 * x1;
  2694. var refinedT = t;
  2695. for (var i = 0; i < 5; i++) {
  2696. var refinedT2 = refinedT * refinedT;
  2697. var refinedT3 = refinedT2 * refinedT;
  2698. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2699. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2700. refinedT -= (x - t) * slope;
  2701. refinedT = Math.min(1, Math.max(0, refinedT));
  2702. }
  2703. // Resolve cubic bezier for the given x
  2704. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2705. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2706. Math.pow(refinedT, 3);
  2707. };
  2708. return BezierCurve;
  2709. }());
  2710. BABYLON.BezierCurve = BezierCurve;
  2711. (function (Orientation) {
  2712. Orientation[Orientation["CW"] = 0] = "CW";
  2713. Orientation[Orientation["CCW"] = 1] = "CCW";
  2714. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2715. var Orientation = BABYLON.Orientation;
  2716. var Angle = (function () {
  2717. function Angle(radians) {
  2718. var _this = this;
  2719. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2720. this.radians = function () { return _this._radians; };
  2721. this._radians = radians;
  2722. if (this._radians < 0)
  2723. this._radians += (2 * Math.PI);
  2724. }
  2725. Angle.BetweenTwoPoints = function (a, b) {
  2726. var delta = b.subtract(a);
  2727. var theta = Math.atan2(delta.y, delta.x);
  2728. return new Angle(theta);
  2729. };
  2730. Angle.FromRadians = function (radians) {
  2731. return new Angle(radians);
  2732. };
  2733. Angle.FromDegrees = function (degrees) {
  2734. return new Angle(degrees * Math.PI / 180);
  2735. };
  2736. return Angle;
  2737. }());
  2738. BABYLON.Angle = Angle;
  2739. var Arc2 = (function () {
  2740. function Arc2(startPoint, midPoint, endPoint) {
  2741. this.startPoint = startPoint;
  2742. this.midPoint = midPoint;
  2743. this.endPoint = endPoint;
  2744. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2745. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2746. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2747. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2748. 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);
  2749. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2750. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2751. var a1 = this.startAngle.degrees();
  2752. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2753. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2754. // angles correction
  2755. if (a2 - a1 > +180.0)
  2756. a2 -= 360.0;
  2757. if (a2 - a1 < -180.0)
  2758. a2 += 360.0;
  2759. if (a3 - a2 > +180.0)
  2760. a3 -= 360.0;
  2761. if (a3 - a2 < -180.0)
  2762. a3 += 360.0;
  2763. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2764. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2765. }
  2766. return Arc2;
  2767. }());
  2768. BABYLON.Arc2 = Arc2;
  2769. var Path2 = (function () {
  2770. function Path2(x, y) {
  2771. this._points = new Array();
  2772. this._length = 0;
  2773. this.closed = false;
  2774. this._points.push(new Vector2(x, y));
  2775. }
  2776. Path2.prototype.addLineTo = function (x, y) {
  2777. if (closed) {
  2778. //Tools.Error("cannot add lines to closed paths");
  2779. return this;
  2780. }
  2781. var newPoint = new Vector2(x, y);
  2782. var previousPoint = this._points[this._points.length - 1];
  2783. this._points.push(newPoint);
  2784. this._length += newPoint.subtract(previousPoint).length();
  2785. return this;
  2786. };
  2787. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2788. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2789. if (closed) {
  2790. //Tools.Error("cannot add arcs to closed paths");
  2791. return this;
  2792. }
  2793. var startPoint = this._points[this._points.length - 1];
  2794. var midPoint = new Vector2(midX, midY);
  2795. var endPoint = new Vector2(endX, endY);
  2796. var arc = new Arc2(startPoint, midPoint, endPoint);
  2797. var increment = arc.angle.radians() / numberOfSegments;
  2798. if (arc.orientation === Orientation.CW)
  2799. increment *= -1;
  2800. var currentAngle = arc.startAngle.radians() + increment;
  2801. for (var i = 0; i < numberOfSegments; i++) {
  2802. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2803. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2804. this.addLineTo(x, y);
  2805. currentAngle += increment;
  2806. }
  2807. return this;
  2808. };
  2809. Path2.prototype.close = function () {
  2810. this.closed = true;
  2811. return this;
  2812. };
  2813. Path2.prototype.length = function () {
  2814. var result = this._length;
  2815. if (!this.closed) {
  2816. var lastPoint = this._points[this._points.length - 1];
  2817. var firstPoint = this._points[0];
  2818. result += (firstPoint.subtract(lastPoint).length());
  2819. }
  2820. return result;
  2821. };
  2822. Path2.prototype.getPoints = function () {
  2823. return this._points;
  2824. };
  2825. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2826. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2827. //Tools.Error("normalized length position should be between 0 and 1.");
  2828. return Vector2.Zero();
  2829. }
  2830. var lengthPosition = normalizedLengthPosition * this.length();
  2831. var previousOffset = 0;
  2832. for (var i = 0; i < this._points.length; i++) {
  2833. var j = (i + 1) % this._points.length;
  2834. var a = this._points[i];
  2835. var b = this._points[j];
  2836. var bToA = b.subtract(a);
  2837. var nextOffset = (bToA.length() + previousOffset);
  2838. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2839. var dir = bToA.normalize();
  2840. var localOffset = lengthPosition - previousOffset;
  2841. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2842. }
  2843. previousOffset = nextOffset;
  2844. }
  2845. //Tools.Error("internal error");
  2846. return Vector2.Zero();
  2847. };
  2848. Path2.StartingAt = function (x, y) {
  2849. return new Path2(x, y);
  2850. };
  2851. return Path2;
  2852. }());
  2853. BABYLON.Path2 = Path2;
  2854. var Path3D = (function () {
  2855. /**
  2856. * new Path3D(path, normal, raw)
  2857. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2858. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2859. * path : an array of Vector3, the curve axis of the Path3D
  2860. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2861. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2862. */
  2863. function Path3D(path, firstNormal, raw) {
  2864. this.path = path;
  2865. this._curve = new Array();
  2866. this._distances = new Array();
  2867. this._tangents = new Array();
  2868. this._normals = new Array();
  2869. this._binormals = new Array();
  2870. for (var p = 0; p < path.length; p++) {
  2871. this._curve[p] = path[p].clone(); // hard copy
  2872. }
  2873. this._raw = raw || false;
  2874. this._compute(firstNormal);
  2875. }
  2876. /**
  2877. * Returns the Path3D array of successive Vector3 designing its curve.
  2878. */
  2879. Path3D.prototype.getCurve = function () {
  2880. return this._curve;
  2881. };
  2882. /**
  2883. * Returns an array populated with tangent vectors on each Path3D curve point.
  2884. */
  2885. Path3D.prototype.getTangents = function () {
  2886. return this._tangents;
  2887. };
  2888. /**
  2889. * Returns an array populated with normal vectors on each Path3D curve point.
  2890. */
  2891. Path3D.prototype.getNormals = function () {
  2892. return this._normals;
  2893. };
  2894. /**
  2895. * Returns an array populated with binormal vectors on each Path3D curve point.
  2896. */
  2897. Path3D.prototype.getBinormals = function () {
  2898. return this._binormals;
  2899. };
  2900. /**
  2901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2902. */
  2903. Path3D.prototype.getDistances = function () {
  2904. return this._distances;
  2905. };
  2906. /**
  2907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2908. * Returns the same object updated.
  2909. */
  2910. Path3D.prototype.update = function (path, firstNormal) {
  2911. for (var p = 0; p < path.length; p++) {
  2912. this._curve[p].x = path[p].x;
  2913. this._curve[p].y = path[p].y;
  2914. this._curve[p].z = path[p].z;
  2915. }
  2916. this._compute(firstNormal);
  2917. return this;
  2918. };
  2919. // private function compute() : computes tangents, normals and binormals
  2920. Path3D.prototype._compute = function (firstNormal) {
  2921. var l = this._curve.length;
  2922. // first and last tangents
  2923. this._tangents[0] = this._getFirstNonNullVector(0);
  2924. if (!this._raw) {
  2925. this._tangents[0].normalize();
  2926. }
  2927. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2928. if (!this._raw) {
  2929. this._tangents[l - 1].normalize();
  2930. }
  2931. // normals and binormals at first point : arbitrary vector with _normalVector()
  2932. var tg0 = this._tangents[0];
  2933. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2934. this._normals[0] = pp0;
  2935. if (!this._raw) {
  2936. this._normals[0].normalize();
  2937. }
  2938. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2939. if (!this._raw) {
  2940. this._binormals[0].normalize();
  2941. }
  2942. this._distances[0] = 0.0;
  2943. // normals and binormals : next points
  2944. var prev; // previous vector (segment)
  2945. var cur; // current vector (segment)
  2946. var curTang; // current tangent
  2947. // previous normal
  2948. var prevBinor; // previous binormal
  2949. for (var i = 1; i < l; i++) {
  2950. // tangents
  2951. prev = this._getLastNonNullVector(i);
  2952. if (i < l - 1) {
  2953. cur = this._getFirstNonNullVector(i);
  2954. this._tangents[i] = prev.add(cur);
  2955. this._tangents[i].normalize();
  2956. }
  2957. this._distances[i] = this._distances[i - 1] + prev.length();
  2958. // normals and binormals
  2959. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2960. curTang = this._tangents[i];
  2961. prevBinor = this._binormals[i - 1];
  2962. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2963. if (!this._raw) {
  2964. this._normals[i].normalize();
  2965. }
  2966. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2967. if (!this._raw) {
  2968. this._binormals[i].normalize();
  2969. }
  2970. }
  2971. };
  2972. // private function getFirstNonNullVector(index)
  2973. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2974. Path3D.prototype._getFirstNonNullVector = function (index) {
  2975. var i = 1;
  2976. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2978. i++;
  2979. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2980. }
  2981. return nNVector;
  2982. };
  2983. // private function getLastNonNullVector(index)
  2984. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2985. Path3D.prototype._getLastNonNullVector = function (index) {
  2986. var i = 1;
  2987. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. while (nLVector.length() === 0 && index > i + 1) {
  2989. i++;
  2990. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2991. }
  2992. return nLVector;
  2993. };
  2994. // private function normalVector(v0, vt, va) :
  2995. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2996. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2997. Path3D.prototype._normalVector = function (v0, vt, va) {
  2998. var normal0;
  2999. var tgl = vt.length();
  3000. if (tgl === 0.0) {
  3001. tgl = 1.0;
  3002. }
  3003. if (va === undefined || va === null) {
  3004. var point;
  3005. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(0.0, -1.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(1.0, 0.0, 0.0);
  3010. }
  3011. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3012. point = new Vector3(0.0, 0.0, 1.0);
  3013. }
  3014. normal0 = Vector3.Cross(vt, point);
  3015. }
  3016. else {
  3017. normal0 = Vector3.Cross(vt, va);
  3018. Vector3.CrossToRef(normal0, vt, normal0);
  3019. }
  3020. normal0.normalize();
  3021. return normal0;
  3022. };
  3023. return Path3D;
  3024. }());
  3025. BABYLON.Path3D = Path3D;
  3026. var Curve3 = (function () {
  3027. /**
  3028. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3029. * A Curve3 is designed from a series of successive Vector3.
  3030. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3031. */
  3032. function Curve3(points) {
  3033. this._length = 0.0;
  3034. this._points = points;
  3035. this._length = this._computeLength(points);
  3036. }
  3037. /**
  3038. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3039. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3040. * @param v1 (Vector3) the control point
  3041. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3042. * @param nbPoints (integer) the wanted number of points in the curve
  3043. */
  3044. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3045. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3046. var bez = new Array();
  3047. var equation = function (t, val0, val1, val2) {
  3048. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3049. return res;
  3050. };
  3051. for (var i = 0; i <= nbPoints; i++) {
  3052. 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)));
  3053. }
  3054. return new Curve3(bez);
  3055. };
  3056. /**
  3057. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3058. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3059. * @param v1 (Vector3) the first control point
  3060. * @param v2 (Vector3) the second control point
  3061. * @param v3 (Vector3) the end point of the Cubic Bezier
  3062. * @param nbPoints (integer) the wanted number of points in the curve
  3063. */
  3064. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3065. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3066. var bez = new Array();
  3067. var equation = function (t, val0, val1, val2, val3) {
  3068. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3069. return res;
  3070. };
  3071. for (var i = 0; i <= nbPoints; i++) {
  3072. 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)));
  3073. }
  3074. return new Curve3(bez);
  3075. };
  3076. /**
  3077. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3078. * @param p1 (Vector3) the origin point of the Hermite Spline
  3079. * @param t1 (Vector3) the tangent vector at the origin point
  3080. * @param p2 (Vector3) the end point of the Hermite Spline
  3081. * @param t2 (Vector3) the tangent vector at the end point
  3082. * @param nbPoints (integer) the wanted number of points in the curve
  3083. */
  3084. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3085. var hermite = new Array();
  3086. var step = 1.0 / nbPoints;
  3087. for (var i = 0; i <= nbPoints; i++) {
  3088. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3089. }
  3090. return new Curve3(hermite);
  3091. };
  3092. /**
  3093. * Returns the Curve3 stored array of successive Vector3
  3094. */
  3095. Curve3.prototype.getPoints = function () {
  3096. return this._points;
  3097. };
  3098. /**
  3099. * Returns the computed length (float) of the curve.
  3100. */
  3101. Curve3.prototype.length = function () {
  3102. return this._length;
  3103. };
  3104. /**
  3105. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3106. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3107. * curveA and curveB keep unchanged.
  3108. */
  3109. Curve3.prototype.continue = function (curve) {
  3110. var lastPoint = this._points[this._points.length - 1];
  3111. var continuedPoints = this._points.slice();
  3112. var curvePoints = curve.getPoints();
  3113. for (var i = 1; i < curvePoints.length; i++) {
  3114. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3115. }
  3116. var continuedCurve = new Curve3(continuedPoints);
  3117. return continuedCurve;
  3118. };
  3119. Curve3.prototype._computeLength = function (path) {
  3120. var l = 0;
  3121. for (var i = 1; i < path.length; i++) {
  3122. l += (path[i].subtract(path[i - 1])).length();
  3123. }
  3124. return l;
  3125. };
  3126. return Curve3;
  3127. }());
  3128. BABYLON.Curve3 = Curve3;
  3129. // SphericalHarmonics
  3130. var SphericalHarmonics = (function () {
  3131. function SphericalHarmonics() {
  3132. this.L00 = Vector3.Zero();
  3133. this.L1_1 = Vector3.Zero();
  3134. this.L10 = Vector3.Zero();
  3135. this.L11 = Vector3.Zero();
  3136. this.L2_2 = Vector3.Zero();
  3137. this.L2_1 = Vector3.Zero();
  3138. this.L20 = Vector3.Zero();
  3139. this.L21 = Vector3.Zero();
  3140. this.L22 = Vector3.Zero();
  3141. }
  3142. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3143. var colorVector = new Vector3(color.r, color.g, color.b);
  3144. var c = colorVector.scale(deltaSolidAngle);
  3145. this.L00 = this.L00.add(c.scale(0.282095));
  3146. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3147. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3148. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3149. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3150. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3151. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3152. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3153. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3154. };
  3155. SphericalHarmonics.prototype.scale = function (scale) {
  3156. this.L00 = this.L00.scale(scale);
  3157. this.L1_1 = this.L1_1.scale(scale);
  3158. this.L10 = this.L10.scale(scale);
  3159. this.L11 = this.L11.scale(scale);
  3160. this.L2_2 = this.L2_2.scale(scale);
  3161. this.L2_1 = this.L2_1.scale(scale);
  3162. this.L20 = this.L20.scale(scale);
  3163. this.L21 = this.L21.scale(scale);
  3164. this.L22 = this.L22.scale(scale);
  3165. };
  3166. return SphericalHarmonics;
  3167. }());
  3168. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3169. // SphericalPolynomial
  3170. var SphericalPolynomial = (function () {
  3171. function SphericalPolynomial() {
  3172. this.x = Vector3.Zero();
  3173. this.y = Vector3.Zero();
  3174. this.z = Vector3.Zero();
  3175. this.xx = Vector3.Zero();
  3176. this.yy = Vector3.Zero();
  3177. this.zz = Vector3.Zero();
  3178. this.xy = Vector3.Zero();
  3179. this.yz = Vector3.Zero();
  3180. this.zx = Vector3.Zero();
  3181. }
  3182. SphericalPolynomial.prototype.addAmbient = function (color) {
  3183. var colorVector = new Vector3(color.r, color.g, color.b);
  3184. this.xx = this.xx.add(colorVector);
  3185. this.yy = this.yy.add(colorVector);
  3186. this.zz = this.zz.add(colorVector);
  3187. };
  3188. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3189. var result = new SphericalPolynomial();
  3190. result.x = harmonics.L11.scale(1.02333);
  3191. result.y = harmonics.L1_1.scale(1.02333);
  3192. result.z = harmonics.L10.scale(1.02333);
  3193. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3194. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3195. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3196. result.yz = harmonics.L2_1.scale(0.858086);
  3197. result.zx = harmonics.L21.scale(0.858086);
  3198. result.xy = harmonics.L2_2.scale(0.858086);
  3199. return result;
  3200. };
  3201. return SphericalPolynomial;
  3202. }());
  3203. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3204. // Vertex formats
  3205. var PositionNormalVertex = (function () {
  3206. function PositionNormalVertex(position, normal) {
  3207. if (position === void 0) { position = Vector3.Zero(); }
  3208. if (normal === void 0) { normal = Vector3.Up(); }
  3209. this.position = position;
  3210. this.normal = normal;
  3211. }
  3212. PositionNormalVertex.prototype.clone = function () {
  3213. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3214. };
  3215. return PositionNormalVertex;
  3216. }());
  3217. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3218. var PositionNormalTextureVertex = (function () {
  3219. function PositionNormalTextureVertex(position, normal, uv) {
  3220. if (position === void 0) { position = Vector3.Zero(); }
  3221. if (normal === void 0) { normal = Vector3.Up(); }
  3222. if (uv === void 0) { uv = Vector2.Zero(); }
  3223. this.position = position;
  3224. this.normal = normal;
  3225. this.uv = uv;
  3226. }
  3227. PositionNormalTextureVertex.prototype.clone = function () {
  3228. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3229. };
  3230. return PositionNormalTextureVertex;
  3231. }());
  3232. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3233. // Temporary pre-allocated objects for engine internal use
  3234. // usage in any internal function :
  3235. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3236. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3237. var Tmp = (function () {
  3238. function Tmp() {
  3239. }
  3240. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3241. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3242. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3243. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3244. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3245. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3246. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3247. Matrix.Zero(), Matrix.Zero(),
  3248. Matrix.Zero(), Matrix.Zero(),
  3249. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3250. return Tmp;
  3251. }());
  3252. BABYLON.Tmp = Tmp;
  3253. })(BABYLON || (BABYLON = {}));
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. function generateSerializableMember(type, sourceName) {
  3257. return function (target, propertyKey) {
  3258. if (!target.__serializableMembers) {
  3259. target.__serializableMembers = {};
  3260. }
  3261. if (!target.__serializableMembers[propertyKey]) {
  3262. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3263. }
  3264. };
  3265. }
  3266. function serialize(sourceName) {
  3267. return generateSerializableMember(0, sourceName); // value member
  3268. }
  3269. BABYLON.serialize = serialize;
  3270. function serializeAsTexture(sourceName) {
  3271. return generateSerializableMember(1, sourceName); // texture member
  3272. }
  3273. BABYLON.serializeAsTexture = serializeAsTexture;
  3274. function serializeAsColor3(sourceName) {
  3275. return generateSerializableMember(2, sourceName); // color3 member
  3276. }
  3277. BABYLON.serializeAsColor3 = serializeAsColor3;
  3278. function serializeAsFresnelParameters(sourceName) {
  3279. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3280. }
  3281. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3282. function serializeAsVector2(sourceName) {
  3283. return generateSerializableMember(4, sourceName); // vector2 member
  3284. }
  3285. BABYLON.serializeAsVector2 = serializeAsVector2;
  3286. function serializeAsVector3(sourceName) {
  3287. return generateSerializableMember(5, sourceName); // vector3 member
  3288. }
  3289. BABYLON.serializeAsVector3 = serializeAsVector3;
  3290. function serializeAsMeshReference(sourceName) {
  3291. return generateSerializableMember(6, sourceName); // mesh reference member
  3292. }
  3293. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3294. function serializeAsColorCurves(sourceName) {
  3295. return generateSerializableMember(7, sourceName); // color curves
  3296. }
  3297. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3298. var SerializationHelper = (function () {
  3299. function SerializationHelper() {
  3300. }
  3301. SerializationHelper.Serialize = function (entity, serializationObject) {
  3302. if (!serializationObject) {
  3303. serializationObject = {};
  3304. }
  3305. // Tags
  3306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3307. // Properties
  3308. for (var property in entity.__serializableMembers) {
  3309. var propertyDescriptor = entity.__serializableMembers[property];
  3310. var targetPropertyName = propertyDescriptor.sourceName || property;
  3311. var propertyType = propertyDescriptor.type;
  3312. var sourceProperty = entity[property];
  3313. if (sourceProperty !== undefined && sourceProperty !== null) {
  3314. switch (propertyType) {
  3315. case 0:
  3316. serializationObject[targetPropertyName] = sourceProperty;
  3317. break;
  3318. case 1:
  3319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3320. break;
  3321. case 2:
  3322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3323. break;
  3324. case 3:
  3325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3326. break;
  3327. case 4:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 5:
  3331. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3332. break;
  3333. case 6:
  3334. serializationObject[targetPropertyName] = sourceProperty.id;
  3335. break;
  3336. case 7:
  3337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return serializationObject;
  3343. };
  3344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3345. var destination = creationFunction();
  3346. // Tags
  3347. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3348. // Properties
  3349. for (var property in destination.__serializableMembers) {
  3350. var propertyDescriptor = destination.__serializableMembers[property];
  3351. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3352. var propertyType = propertyDescriptor.type;
  3353. if (sourceProperty !== undefined && sourceProperty !== null) {
  3354. switch (propertyType) {
  3355. case 0:
  3356. destination[property] = sourceProperty;
  3357. break;
  3358. case 1:
  3359. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3360. break;
  3361. case 2:
  3362. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3363. break;
  3364. case 3:
  3365. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3366. break;
  3367. case 4:
  3368. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3369. break;
  3370. case 5:
  3371. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3372. break;
  3373. case 6:
  3374. destination[property] = scene.getLastMeshByID(sourceProperty);
  3375. break;
  3376. case 7:
  3377. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. return destination;
  3383. };
  3384. SerializationHelper.Clone = function (creationFunction, source) {
  3385. var destination = creationFunction();
  3386. // Tags
  3387. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3388. // Properties
  3389. for (var property in destination.__serializableMembers) {
  3390. var propertyDescriptor = destination.__serializableMembers[property];
  3391. var sourceProperty = source[property];
  3392. var propertyType = propertyDescriptor.type;
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0: // Value
  3396. case 6:
  3397. destination[property] = sourceProperty;
  3398. break;
  3399. case 1: // Texture
  3400. case 2: // Color3
  3401. case 3: // FresnelParameters
  3402. case 4: // Vector2
  3403. case 5: // Vector3
  3404. case 7:
  3405. destination[property] = sourceProperty.clone();
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. return destination;
  3411. };
  3412. return SerializationHelper;
  3413. }());
  3414. BABYLON.SerializationHelper = SerializationHelper;
  3415. })(BABYLON || (BABYLON = {}));
  3416. var BABYLON;
  3417. (function (BABYLON) {
  3418. /**
  3419. * A class serves as a medium between the observable and its observers
  3420. */
  3421. var EventState = (function () {
  3422. /**
  3423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3424. */
  3425. function EventState(mask, skipNextObservers) {
  3426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3427. this.initalize(mask, skipNextObservers);
  3428. }
  3429. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3431. this.mask = mask;
  3432. this.skipNextObservers = skipNextObservers;
  3433. return this;
  3434. };
  3435. return EventState;
  3436. }());
  3437. BABYLON.EventState = EventState;
  3438. /**
  3439. * Represent an Observer registered to a given Observable object.
  3440. */
  3441. var Observer = (function () {
  3442. function Observer(callback, mask) {
  3443. this.callback = callback;
  3444. this.mask = mask;
  3445. }
  3446. return Observer;
  3447. }());
  3448. BABYLON.Observer = Observer;
  3449. /**
  3450. * The Observable class is a simple implementation of the Observable pattern.
  3451. * 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.
  3452. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3453. * 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).
  3454. * 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.
  3455. */
  3456. var Observable = (function () {
  3457. function Observable() {
  3458. this._observers = new Array();
  3459. this._eventState = new EventState(0);
  3460. }
  3461. /**
  3462. * Create a new Observer with the specified callback
  3463. * @param callback the callback that will be executed for that Observer
  3464. * @param mask the mask used to filter observers
  3465. * @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.
  3466. */
  3467. Observable.prototype.add = function (callback, mask, insertFirst) {
  3468. if (mask === void 0) { mask = -1; }
  3469. if (insertFirst === void 0) { insertFirst = false; }
  3470. if (!callback) {
  3471. return null;
  3472. }
  3473. var observer = new Observer(callback, mask);
  3474. if (insertFirst) {
  3475. this._observers.unshift(observer);
  3476. }
  3477. else {
  3478. this._observers.push(observer);
  3479. }
  3480. return observer;
  3481. };
  3482. /**
  3483. * Remove an Observer from the Observable object
  3484. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3485. */
  3486. Observable.prototype.remove = function (observer) {
  3487. var index = this._observers.indexOf(observer);
  3488. if (index !== -1) {
  3489. this._observers.splice(index, 1);
  3490. return true;
  3491. }
  3492. return false;
  3493. };
  3494. /**
  3495. * Remove a callback from the Observable object
  3496. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3497. */
  3498. Observable.prototype.removeCallback = function (callback) {
  3499. for (var index = 0; index < this._observers.length; index++) {
  3500. if (this._observers[index].callback === callback) {
  3501. this._observers.splice(index, 1);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. };
  3507. /**
  3508. * Notify all Observers by calling their respective callback with the given data
  3509. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3510. * @param eventData
  3511. * @param mask
  3512. */
  3513. Observable.prototype.notifyObservers = function (eventData, mask) {
  3514. if (mask === void 0) { mask = -1; }
  3515. var state = this._eventState;
  3516. state.mask = mask;
  3517. state.skipNextObservers = false;
  3518. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3519. var obs = _a[_i];
  3520. if (obs.mask & mask) {
  3521. obs.callback(eventData, state);
  3522. }
  3523. if (state.skipNextObservers) {
  3524. return false;
  3525. }
  3526. }
  3527. return true;
  3528. };
  3529. /**
  3530. * return true is the Observable has at least one Observer registered
  3531. */
  3532. Observable.prototype.hasObservers = function () {
  3533. return this._observers.length > 0;
  3534. };
  3535. /**
  3536. * Clear the list of observers
  3537. */
  3538. Observable.prototype.clear = function () {
  3539. this._observers = new Array();
  3540. };
  3541. /**
  3542. * Clone the current observable
  3543. */
  3544. Observable.prototype.clone = function () {
  3545. var result = new Observable();
  3546. result._observers = this._observers.slice(0);
  3547. return result;
  3548. };
  3549. return Observable;
  3550. }());
  3551. BABYLON.Observable = Observable;
  3552. })(BABYLON || (BABYLON = {}));
  3553. var BABYLON;
  3554. (function (BABYLON) {
  3555. var Database = (function () {
  3556. function Database(urlToScene, callbackManifestChecked) {
  3557. // Handling various flavors of prefixed version of IndexedDB
  3558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3559. this.callbackManifestChecked = callbackManifestChecked;
  3560. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3561. this.db = null;
  3562. this.enableSceneOffline = false;
  3563. this.enableTexturesOffline = false;
  3564. this.manifestVersionFound = 0;
  3565. this.mustUpdateRessources = false;
  3566. this.hasReachedQuota = false;
  3567. if (!Database.IDBStorageEnabled) {
  3568. this.callbackManifestChecked(true);
  3569. }
  3570. else {
  3571. this.checkManifestFile();
  3572. }
  3573. }
  3574. Database.prototype.checkManifestFile = function () {
  3575. var _this = this;
  3576. function noManifestFile() {
  3577. that.enableSceneOffline = false;
  3578. that.enableTexturesOffline = false;
  3579. that.callbackManifestChecked(false);
  3580. }
  3581. var that = this;
  3582. var timeStampUsed = false;
  3583. var manifestURL = this.currentSceneUrl + ".manifest";
  3584. var xhr = new XMLHttpRequest();
  3585. if (navigator.onLine) {
  3586. // Adding a timestamp to by-pass browsers' cache
  3587. timeStampUsed = true;
  3588. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3589. }
  3590. xhr.open("GET", manifestURL, true);
  3591. xhr.addEventListener("load", function () {
  3592. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3593. try {
  3594. var manifestFile = JSON.parse(xhr.response);
  3595. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3596. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3597. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3598. _this.manifestVersionFound = manifestFile.version;
  3599. }
  3600. if (_this.callbackManifestChecked) {
  3601. _this.callbackManifestChecked(true);
  3602. }
  3603. }
  3604. catch (ex) {
  3605. noManifestFile();
  3606. }
  3607. }
  3608. else {
  3609. noManifestFile();
  3610. }
  3611. }, false);
  3612. xhr.addEventListener("error", function (event) {
  3613. if (timeStampUsed) {
  3614. timeStampUsed = false;
  3615. // Let's retry without the timeStamp
  3616. // It could fail when coupled with HTML5 Offline API
  3617. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3618. xhr.open("GET", retryManifestURL, true);
  3619. xhr.send();
  3620. }
  3621. else {
  3622. noManifestFile();
  3623. }
  3624. }, false);
  3625. try {
  3626. xhr.send();
  3627. }
  3628. catch (ex) {
  3629. BABYLON.Tools.Error("Error on XHR send request.");
  3630. that.callbackManifestChecked(false);
  3631. }
  3632. };
  3633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3634. var _this = this;
  3635. function handleError() {
  3636. that.isSupported = false;
  3637. if (errorCallback)
  3638. errorCallback();
  3639. }
  3640. var that = this;
  3641. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3642. // Your browser doesn't support IndexedDB
  3643. this.isSupported = false;
  3644. if (errorCallback)
  3645. errorCallback();
  3646. }
  3647. else {
  3648. // If the DB hasn't been opened or created yet
  3649. if (!this.db) {
  3650. this.hasReachedQuota = false;
  3651. this.isSupported = true;
  3652. var request = this.idbFactory.open("babylonjs", 1);
  3653. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3654. request.onerror = function (event) {
  3655. handleError();
  3656. };
  3657. // executes when a version change transaction cannot complete due to other active transactions
  3658. request.onblocked = function (event) {
  3659. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3660. handleError();
  3661. };
  3662. // DB has been opened successfully
  3663. request.onsuccess = function (event) {
  3664. _this.db = request.result;
  3665. successCallback();
  3666. };
  3667. // Initialization of the DB. Creating Scenes & Textures stores
  3668. request.onupgradeneeded = function (event) {
  3669. _this.db = (event.target).result;
  3670. try {
  3671. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3672. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3673. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3674. }
  3675. catch (ex) {
  3676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3677. handleError();
  3678. }
  3679. };
  3680. }
  3681. else {
  3682. if (successCallback)
  3683. successCallback();
  3684. }
  3685. }
  3686. };
  3687. Database.prototype.loadImageFromDB = function (url, image) {
  3688. var _this = this;
  3689. var completeURL = Database.ReturnFullUrlLocation(url);
  3690. var saveAndLoadImage = function () {
  3691. if (!_this.hasReachedQuota && _this.db !== null) {
  3692. // the texture is not yet in the DB, let's try to save it
  3693. _this._saveImageIntoDBAsync(completeURL, image);
  3694. }
  3695. else {
  3696. image.src = url;
  3697. }
  3698. };
  3699. if (!this.mustUpdateRessources) {
  3700. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3701. }
  3702. else {
  3703. saveAndLoadImage();
  3704. }
  3705. };
  3706. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3707. if (this.isSupported && this.db !== null) {
  3708. var texture;
  3709. var transaction = this.db.transaction(["textures"]);
  3710. transaction.onabort = function (event) {
  3711. image.src = url;
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. var blobTextureURL;
  3715. if (texture) {
  3716. var URL = window.URL || window.webkitURL;
  3717. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3718. image.onerror = function () {
  3719. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3720. image.src = url;
  3721. };
  3722. image.src = blobTextureURL;
  3723. }
  3724. else {
  3725. notInDBCallback();
  3726. }
  3727. };
  3728. var getRequest = transaction.objectStore("textures").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. texture = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3734. image.src = url;
  3735. };
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. image.src = url;
  3740. }
  3741. };
  3742. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3743. var _this = this;
  3744. if (this.isSupported) {
  3745. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3746. var generateBlobUrl = function () {
  3747. var blobTextureURL;
  3748. if (blob) {
  3749. var URL = window.URL || window.webkitURL;
  3750. try {
  3751. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3752. }
  3753. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3754. catch (ex) {
  3755. blobTextureURL = URL.createObjectURL(blob);
  3756. }
  3757. }
  3758. image.src = blobTextureURL;
  3759. };
  3760. if (Database.IsUASupportingBlobStorage) {
  3761. var xhr = new XMLHttpRequest(), blob;
  3762. xhr.open("GET", url, true);
  3763. xhr.responseType = "blob";
  3764. xhr.addEventListener("load", function () {
  3765. if (xhr.status === 200) {
  3766. // Blob as response (XHR2)
  3767. blob = xhr.response;
  3768. var transaction = _this.db.transaction(["textures"], "readwrite");
  3769. // the transaction could abort because of a QuotaExceededError error
  3770. transaction.onabort = function (event) {
  3771. try {
  3772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3773. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3774. _this.hasReachedQuota = true;
  3775. }
  3776. }
  3777. catch (ex) { }
  3778. generateBlobUrl();
  3779. };
  3780. transaction.oncomplete = function (event) {
  3781. generateBlobUrl();
  3782. };
  3783. var newTexture = { textureUrl: url, data: blob };
  3784. try {
  3785. // Put the blob into the dabase
  3786. var addRequest = transaction.objectStore("textures").put(newTexture);
  3787. addRequest.onsuccess = function (event) {
  3788. };
  3789. addRequest.onerror = function (event) {
  3790. generateBlobUrl();
  3791. };
  3792. }
  3793. catch (ex) {
  3794. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3795. if (ex.code === 25) {
  3796. Database.IsUASupportingBlobStorage = false;
  3797. }
  3798. image.src = url;
  3799. }
  3800. }
  3801. else {
  3802. image.src = url;
  3803. }
  3804. }, false);
  3805. xhr.addEventListener("error", function (event) {
  3806. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3807. image.src = url;
  3808. }, false);
  3809. xhr.send();
  3810. }
  3811. else {
  3812. image.src = url;
  3813. }
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3821. var _this = this;
  3822. var updateVersion = function (event) {
  3823. // the version is not yet in the DB or we need to update it
  3824. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3825. };
  3826. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3827. };
  3828. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3829. var _this = this;
  3830. if (this.isSupported) {
  3831. var version;
  3832. try {
  3833. var transaction = this.db.transaction(["versions"]);
  3834. transaction.oncomplete = function (event) {
  3835. if (version) {
  3836. // If the version in the JSON file is > than the version in DB
  3837. if (_this.manifestVersionFound > version.data) {
  3838. _this.mustUpdateRessources = true;
  3839. updateInDBCallback();
  3840. }
  3841. else {
  3842. callback(version.data);
  3843. }
  3844. }
  3845. else {
  3846. _this.mustUpdateRessources = true;
  3847. updateInDBCallback();
  3848. }
  3849. };
  3850. transaction.onabort = function (event) {
  3851. callback(-1);
  3852. };
  3853. var getRequest = transaction.objectStore("versions").get(url);
  3854. getRequest.onsuccess = function (event) {
  3855. version = (event.target).result;
  3856. };
  3857. getRequest.onerror = function (event) {
  3858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3859. callback(-1);
  3860. };
  3861. }
  3862. catch (ex) {
  3863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3864. callback(-1);
  3865. }
  3866. }
  3867. else {
  3868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3869. callback(-1);
  3870. }
  3871. };
  3872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3873. var _this = this;
  3874. if (this.isSupported && !this.hasReachedQuota) {
  3875. try {
  3876. // Open a transaction to the database
  3877. var transaction = this.db.transaction(["versions"], "readwrite");
  3878. // the transaction could abort because of a QuotaExceededError error
  3879. transaction.onabort = function (event) {
  3880. try {
  3881. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3882. _this.hasReachedQuota = true;
  3883. }
  3884. }
  3885. catch (ex) { }
  3886. callback(-1);
  3887. };
  3888. transaction.oncomplete = function (event) {
  3889. callback(_this.manifestVersionFound);
  3890. };
  3891. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3892. // Put the scene into the database
  3893. var addRequest = transaction.objectStore("versions").put(newVersion);
  3894. addRequest.onsuccess = function (event) {
  3895. };
  3896. addRequest.onerror = function (event) {
  3897. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3898. };
  3899. }
  3900. catch (ex) {
  3901. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3902. callback(-1);
  3903. }
  3904. }
  3905. else {
  3906. callback(-1);
  3907. }
  3908. };
  3909. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3910. var _this = this;
  3911. var completeUrl = Database.ReturnFullUrlLocation(url);
  3912. var saveAndLoadFile = function (event) {
  3913. // the scene is not yet in the DB, let's try to save it
  3914. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3915. };
  3916. this._checkVersionFromDB(completeUrl, function (version) {
  3917. if (version !== -1) {
  3918. if (!_this.mustUpdateRessources) {
  3919. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3920. }
  3921. else {
  3922. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3923. }
  3924. }
  3925. else {
  3926. errorCallback();
  3927. }
  3928. });
  3929. };
  3930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3931. if (this.isSupported) {
  3932. var targetStore;
  3933. if (url.indexOf(".babylon") !== -1) {
  3934. targetStore = "scenes";
  3935. }
  3936. else {
  3937. targetStore = "textures";
  3938. }
  3939. var file;
  3940. var transaction = this.db.transaction([targetStore]);
  3941. transaction.oncomplete = function (event) {
  3942. if (file) {
  3943. callback(file.data);
  3944. }
  3945. else {
  3946. notInDBCallback();
  3947. }
  3948. };
  3949. transaction.onabort = function (event) {
  3950. notInDBCallback();
  3951. };
  3952. var getRequest = transaction.objectStore(targetStore).get(url);
  3953. getRequest.onsuccess = function (event) {
  3954. file = (event.target).result;
  3955. };
  3956. getRequest.onerror = function (event) {
  3957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3958. notInDBCallback();
  3959. };
  3960. }
  3961. else {
  3962. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3963. callback();
  3964. }
  3965. };
  3966. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3967. var _this = this;
  3968. if (this.isSupported) {
  3969. var targetStore;
  3970. if (url.indexOf(".babylon") !== -1) {
  3971. targetStore = "scenes";
  3972. }
  3973. else {
  3974. targetStore = "textures";
  3975. }
  3976. // Create XHR
  3977. var xhr = new XMLHttpRequest(), fileData;
  3978. xhr.open("GET", url, true);
  3979. if (useArrayBuffer) {
  3980. xhr.responseType = "arraybuffer";
  3981. }
  3982. xhr.onprogress = progressCallback;
  3983. xhr.addEventListener("load", function () {
  3984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3985. // Blob as response (XHR2)
  3986. //fileData = xhr.responseText;
  3987. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3988. if (!_this.hasReachedQuota) {
  3989. // Open a transaction to the database
  3990. var transaction = _this.db.transaction([targetStore], "readwrite");
  3991. // the transaction could abort because of a QuotaExceededError error
  3992. transaction.onabort = function (event) {
  3993. try {
  3994. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3995. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3996. _this.hasReachedQuota = true;
  3997. }
  3998. }
  3999. catch (ex) { }
  4000. callback(fileData);
  4001. };
  4002. transaction.oncomplete = function (event) {
  4003. callback(fileData);
  4004. };
  4005. var newFile;
  4006. if (targetStore === "scenes") {
  4007. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4008. }
  4009. else {
  4010. newFile = { textureUrl: url, data: fileData };
  4011. }
  4012. try {
  4013. // Put the scene into the database
  4014. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4015. addRequest.onsuccess = function (event) {
  4016. };
  4017. addRequest.onerror = function (event) {
  4018. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4019. };
  4020. }
  4021. catch (ex) {
  4022. callback(fileData);
  4023. }
  4024. }
  4025. else {
  4026. callback(fileData);
  4027. }
  4028. }
  4029. else {
  4030. callback();
  4031. }
  4032. }, false);
  4033. xhr.addEventListener("error", function (event) {
  4034. BABYLON.Tools.Error("error on XHR request.");
  4035. callback();
  4036. }, false);
  4037. xhr.send();
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.IsUASupportingBlobStorage = true;
  4045. Database.IDBStorageEnabled = true;
  4046. Database.parseURL = function (url) {
  4047. var a = document.createElement('a');
  4048. a.href = url;
  4049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4052. return absLocation;
  4053. };
  4054. Database.ReturnFullUrlLocation = function (url) {
  4055. if (url.indexOf("http:/") === -1) {
  4056. return (Database.parseURL(window.location.href) + url);
  4057. }
  4058. else {
  4059. return url;
  4060. }
  4061. };
  4062. return Database;
  4063. }());
  4064. BABYLON.Database = Database;
  4065. })(BABYLON || (BABYLON = {}));
  4066. var BABYLON;
  4067. (function (BABYLON) {
  4068. var Internals;
  4069. (function (Internals) {
  4070. /*
  4071. * Based on jsTGALoader - Javascript loader for TGA file
  4072. * By Vincent Thibault
  4073. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4074. */
  4075. var TGATools = (function () {
  4076. function TGATools() {
  4077. }
  4078. TGATools.GetTGAHeader = function (data) {
  4079. var offset = 0;
  4080. var header = {
  4081. id_length: data[offset++],
  4082. colormap_type: data[offset++],
  4083. image_type: data[offset++],
  4084. colormap_index: data[offset++] | data[offset++] << 8,
  4085. colormap_length: data[offset++] | data[offset++] << 8,
  4086. colormap_size: data[offset++],
  4087. origin: [
  4088. data[offset++] | data[offset++] << 8,
  4089. data[offset++] | data[offset++] << 8
  4090. ],
  4091. width: data[offset++] | data[offset++] << 8,
  4092. height: data[offset++] | data[offset++] << 8,
  4093. pixel_size: data[offset++],
  4094. flags: data[offset++]
  4095. };
  4096. return header;
  4097. };
  4098. TGATools.UploadContent = function (gl, data) {
  4099. // Not enough data to contain header ?
  4100. if (data.length < 19) {
  4101. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4102. return;
  4103. }
  4104. // Read Header
  4105. var offset = 18;
  4106. var header = TGATools.GetTGAHeader(data);
  4107. // Assume it's a valid Targa file.
  4108. if (header.id_length + offset > data.length) {
  4109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4110. return;
  4111. }
  4112. // Skip not needed data
  4113. offset += header.id_length;
  4114. var use_rle = false;
  4115. var use_pal = false;
  4116. var use_rgb = false;
  4117. var use_grey = false;
  4118. // Get some informations.
  4119. switch (header.image_type) {
  4120. case TGATools._TYPE_RLE_INDEXED:
  4121. use_rle = true;
  4122. case TGATools._TYPE_INDEXED:
  4123. use_pal = true;
  4124. break;
  4125. case TGATools._TYPE_RLE_RGB:
  4126. use_rle = true;
  4127. case TGATools._TYPE_RGB:
  4128. use_rgb = true;
  4129. break;
  4130. case TGATools._TYPE_RLE_GREY:
  4131. use_rle = true;
  4132. case TGATools._TYPE_GREY:
  4133. use_grey = true;
  4134. break;
  4135. }
  4136. var pixel_data;
  4137. var numAlphaBits = header.flags & 0xf;
  4138. var pixel_size = header.pixel_size >> 3;
  4139. var pixel_total = header.width * header.height * pixel_size;
  4140. // Read palettes
  4141. var palettes;
  4142. if (use_pal) {
  4143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4144. }
  4145. // Read LRE
  4146. if (use_rle) {
  4147. pixel_data = new Uint8Array(pixel_total);
  4148. var c, count, i;
  4149. var localOffset = 0;
  4150. var pixels = new Uint8Array(pixel_size);
  4151. while (offset < pixel_total && localOffset < pixel_total) {
  4152. c = data[offset++];
  4153. count = (c & 0x7f) + 1;
  4154. // RLE pixels
  4155. if (c & 0x80) {
  4156. // Bind pixel tmp array
  4157. for (i = 0; i < pixel_size; ++i) {
  4158. pixels[i] = data[offset++];
  4159. }
  4160. // Copy pixel array
  4161. for (i = 0; i < count; ++i) {
  4162. pixel_data.set(pixels, localOffset + i * pixel_size);
  4163. }
  4164. localOffset += pixel_size * count;
  4165. }
  4166. else {
  4167. count *= pixel_size;
  4168. for (i = 0; i < count; ++i) {
  4169. pixel_data[localOffset + i] = data[offset++];
  4170. }
  4171. localOffset += count;
  4172. }
  4173. }
  4174. }
  4175. else {
  4176. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4177. }
  4178. // Load to texture
  4179. var x_start, y_start, x_step, y_step, y_end, x_end;
  4180. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4181. default:
  4182. case TGATools._ORIGIN_UL:
  4183. x_start = 0;
  4184. x_step = 1;
  4185. x_end = header.width;
  4186. y_start = 0;
  4187. y_step = 1;
  4188. y_end = header.height;
  4189. break;
  4190. case TGATools._ORIGIN_BL:
  4191. x_start = 0;
  4192. x_step = 1;
  4193. x_end = header.width;
  4194. y_start = header.height - 1;
  4195. y_step = -1;
  4196. y_end = -1;
  4197. break;
  4198. case TGATools._ORIGIN_UR:
  4199. x_start = header.width - 1;
  4200. x_step = -1;
  4201. x_end = -1;
  4202. y_start = 0;
  4203. y_step = 1;
  4204. y_end = header.height;
  4205. break;
  4206. case TGATools._ORIGIN_BR:
  4207. x_start = header.width - 1;
  4208. x_step = -1;
  4209. x_end = -1;
  4210. y_start = header.height - 1;
  4211. y_step = -1;
  4212. y_end = -1;
  4213. break;
  4214. }
  4215. // Load the specify method
  4216. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4217. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4219. };
  4220. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4221. var image = pixel_data, colormap = palettes;
  4222. var width = header.width, height = header.height;
  4223. var color, i = 0, x, y;
  4224. var imageData = new Uint8Array(width * height * 4);
  4225. for (y = y_start; y !== y_end; y += y_step) {
  4226. for (x = x_start; x !== x_end; x += x_step, i++) {
  4227. color = image[i];
  4228. imageData[(x + width * y) * 4 + 3] = 255;
  4229. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4230. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4231. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4232. }
  4233. }
  4234. return imageData;
  4235. };
  4236. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4237. var image = pixel_data;
  4238. var width = header.width, height = header.height;
  4239. var color, i = 0, x, y;
  4240. var imageData = new Uint8Array(width * height * 4);
  4241. for (y = y_start; y !== y_end; y += y_step) {
  4242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4243. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4244. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4245. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4246. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4247. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4253. var image = pixel_data;
  4254. var width = header.width, height = header.height;
  4255. var i = 0, x, y;
  4256. var imageData = new Uint8Array(width * height * 4);
  4257. for (y = y_start; y !== y_end; y += y_step) {
  4258. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4259. imageData[(x + width * y) * 4 + 3] = 255;
  4260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4261. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4262. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4274. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4275. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4276. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4277. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var color, i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i++) {
  4289. color = image[i];
  4290. imageData[(x + width * y) * 4 + 0] = color;
  4291. imageData[(x + width * y) * 4 + 1] = color;
  4292. imageData[(x + width * y) * 4 + 2] = color;
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4299. var image = pixel_data;
  4300. var width = header.width, height = header.height;
  4301. var i = 0, x, y;
  4302. var imageData = new Uint8Array(width * height * 4);
  4303. for (y = y_start; y !== y_end; y += y_step) {
  4304. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4305. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4306. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4308. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._TYPE_NO_DATA = 0;
  4314. TGATools._TYPE_INDEXED = 1;
  4315. TGATools._TYPE_RGB = 2;
  4316. TGATools._TYPE_GREY = 3;
  4317. TGATools._TYPE_RLE_INDEXED = 9;
  4318. TGATools._TYPE_RLE_RGB = 10;
  4319. TGATools._TYPE_RLE_GREY = 11;
  4320. TGATools._ORIGIN_MASK = 0x30;
  4321. TGATools._ORIGIN_SHIFT = 0x04;
  4322. TGATools._ORIGIN_BL = 0x00;
  4323. TGATools._ORIGIN_BR = 0x01;
  4324. TGATools._ORIGIN_UL = 0x02;
  4325. TGATools._ORIGIN_UR = 0x03;
  4326. return TGATools;
  4327. }());
  4328. Internals.TGATools = TGATools;
  4329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. var BABYLON;
  4332. (function (BABYLON) {
  4333. var SmartArray = (function () {
  4334. function SmartArray(capacity) {
  4335. this.length = 0;
  4336. this._duplicateId = 0;
  4337. this.data = new Array(capacity);
  4338. this._id = SmartArray._GlobalId++;
  4339. }
  4340. SmartArray.prototype.push = function (value) {
  4341. this.data[this.length++] = value;
  4342. if (this.length > this.data.length) {
  4343. this.data.length *= 2;
  4344. }
  4345. if (!value.__smartArrayFlags) {
  4346. value.__smartArrayFlags = {};
  4347. }
  4348. value.__smartArrayFlags[this._id] = this._duplicateId;
  4349. };
  4350. SmartArray.prototype.pushNoDuplicate = function (value) {
  4351. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4352. return false;
  4353. }
  4354. this.push(value);
  4355. return true;
  4356. };
  4357. SmartArray.prototype.sort = function (compareFn) {
  4358. this.data.sort(compareFn);
  4359. };
  4360. SmartArray.prototype.reset = function () {
  4361. this.length = 0;
  4362. this._duplicateId++;
  4363. };
  4364. SmartArray.prototype.concat = function (array) {
  4365. if (array.length === 0) {
  4366. return;
  4367. }
  4368. if (this.length + array.length > this.data.length) {
  4369. this.data.length = (this.length + array.length) * 2;
  4370. }
  4371. for (var index = 0; index < array.length; index++) {
  4372. this.data[this.length++] = (array.data || array)[index];
  4373. }
  4374. };
  4375. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4376. if (array.length === 0) {
  4377. return;
  4378. }
  4379. if (this.length + array.length > this.data.length) {
  4380. this.data.length = (this.length + array.length) * 2;
  4381. }
  4382. for (var index = 0; index < array.length; index++) {
  4383. var item = (array.data || array)[index];
  4384. this.pushNoDuplicate(item);
  4385. }
  4386. };
  4387. SmartArray.prototype.indexOf = function (value) {
  4388. var position = this.data.indexOf(value);
  4389. if (position >= this.length) {
  4390. return -1;
  4391. }
  4392. return position;
  4393. };
  4394. // Statics
  4395. SmartArray._GlobalId = 0;
  4396. return SmartArray;
  4397. }());
  4398. BABYLON.SmartArray = SmartArray;
  4399. })(BABYLON || (BABYLON = {}));
  4400. var BABYLON;
  4401. (function (BABYLON) {
  4402. /**
  4403. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4404. * The underlying implementation relies on an associative array to ensure the best performances.
  4405. * The value can be anything including 'null' but except 'undefined'
  4406. */
  4407. var StringDictionary = (function () {
  4408. function StringDictionary() {
  4409. this._count = 0;
  4410. this._data = {};
  4411. }
  4412. /**
  4413. * Get a value based from its key
  4414. * @param key the given key to get the matching value from
  4415. * @return the value if found, otherwise undefined is returned
  4416. */
  4417. StringDictionary.prototype.get = function (key) {
  4418. var val = this._data[key];
  4419. if (val !== undefined) {
  4420. return val;
  4421. }
  4422. return undefined;
  4423. };
  4424. /**
  4425. * Get a value from its key or add it if it doesn't exist.
  4426. * This method will ensure you that a given key/data will be present in the dictionary.
  4427. * @param key the given key to get the matching value from
  4428. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4429. * The factory will only be invoked if there's no data for the given key.
  4430. * @return the value corresponding to the key.
  4431. */
  4432. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4433. var val = this.get(key);
  4434. if (val !== undefined) {
  4435. return val;
  4436. }
  4437. val = factory(key);
  4438. if (val) {
  4439. this.add(key, val);
  4440. }
  4441. return val;
  4442. };
  4443. /**
  4444. * Get a value from its key if present in the dictionary otherwise add it
  4445. * @param key the key to get the value from
  4446. * @param val if there's no such key/value pair in the dictionary add it with this value
  4447. * @return the value corresponding to the key
  4448. */
  4449. StringDictionary.prototype.getOrAdd = function (key, val) {
  4450. var curVal = this.get(key);
  4451. if (curVal !== undefined) {
  4452. return curVal;
  4453. }
  4454. this.add(key, val);
  4455. return val;
  4456. };
  4457. /**
  4458. * Check if there's a given key in the dictionary
  4459. * @param key the key to check for
  4460. * @return true if the key is present, false otherwise
  4461. */
  4462. StringDictionary.prototype.contains = function (key) {
  4463. return this._data[key] !== undefined;
  4464. };
  4465. /**
  4466. * Add a new key and its corresponding value
  4467. * @param key the key to add
  4468. * @param value the value corresponding to the key
  4469. * @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
  4470. */
  4471. StringDictionary.prototype.add = function (key, value) {
  4472. if (this._data[key] !== undefined) {
  4473. return false;
  4474. }
  4475. this._data[key] = value;
  4476. ++this._count;
  4477. return true;
  4478. };
  4479. StringDictionary.prototype.set = function (key, value) {
  4480. if (this._data[key] === undefined) {
  4481. return false;
  4482. }
  4483. this._data[key] = value;
  4484. return true;
  4485. };
  4486. /**
  4487. * Remove a key/value from the dictionary.
  4488. * @param key the key to remove
  4489. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4490. */
  4491. StringDictionary.prototype.remove = function (key) {
  4492. if (this.contains(key)) {
  4493. delete this._data[key];
  4494. --this._count;
  4495. return true;
  4496. }
  4497. return false;
  4498. };
  4499. /**
  4500. * Clear the whole content of the dictionary
  4501. */
  4502. StringDictionary.prototype.clear = function () {
  4503. this._data = {};
  4504. this._count = 0;
  4505. };
  4506. Object.defineProperty(StringDictionary.prototype, "count", {
  4507. get: function () {
  4508. return this._count;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. /**
  4514. * Execute a callback on each key/val of the dictionary.
  4515. * Note that you can remove any element in this dictionary in the callback implementation
  4516. * @param callback the callback to execute on a given key/value pair
  4517. */
  4518. StringDictionary.prototype.forEach = function (callback) {
  4519. for (var cur in this._data) {
  4520. var val = this._data[cur];
  4521. callback(cur, val);
  4522. }
  4523. };
  4524. /**
  4525. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4526. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4527. * Note that you can remove any element in this dictionary in the callback implementation
  4528. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4529. */
  4530. StringDictionary.prototype.first = function (callback) {
  4531. for (var cur in this._data) {
  4532. var val = this._data[cur];
  4533. var res = callback(cur, val);
  4534. if (res) {
  4535. return res;
  4536. }
  4537. }
  4538. return null;
  4539. };
  4540. return StringDictionary;
  4541. }());
  4542. BABYLON.StringDictionary = StringDictionary;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var BABYLON;
  4545. (function (BABYLON) {
  4546. // Screenshots
  4547. var screenshotCanvas;
  4548. var cloneValue = function (source, destinationObject) {
  4549. if (!source)
  4550. return null;
  4551. if (source instanceof BABYLON.Mesh) {
  4552. return null;
  4553. }
  4554. if (source instanceof BABYLON.SubMesh) {
  4555. return source.clone(destinationObject);
  4556. }
  4557. else if (source.clone) {
  4558. return source.clone();
  4559. }
  4560. return null;
  4561. };
  4562. var Tools = (function () {
  4563. function Tools() {
  4564. }
  4565. Tools.Instantiate = function (className) {
  4566. var arr = className.split(".");
  4567. var fn = (window || this);
  4568. for (var i = 0, len = arr.length; i < len; i++) {
  4569. fn = fn[arr[i]];
  4570. }
  4571. if (typeof fn !== "function") {
  4572. return null;
  4573. }
  4574. return fn;
  4575. };
  4576. Tools.SetImmediate = function (action) {
  4577. if (window.setImmediate) {
  4578. window.setImmediate(action);
  4579. }
  4580. else {
  4581. setTimeout(action, 1);
  4582. }
  4583. };
  4584. Tools.IsExponentOfTwo = function (value) {
  4585. var count = 1;
  4586. do {
  4587. count *= 2;
  4588. } while (count < value);
  4589. return count === value;
  4590. };
  4591. Tools.GetExponentOfTwo = function (value, max) {
  4592. var count = 1;
  4593. do {
  4594. count *= 2;
  4595. } while (count < value);
  4596. if (count > max)
  4597. count = max;
  4598. return count;
  4599. };
  4600. Tools.GetFilename = function (path) {
  4601. var index = path.lastIndexOf("/");
  4602. if (index < 0)
  4603. return path;
  4604. return path.substring(index + 1);
  4605. };
  4606. Tools.GetDOMTextContent = function (element) {
  4607. var result = "";
  4608. var child = element.firstChild;
  4609. while (child) {
  4610. if (child.nodeType === 3) {
  4611. result += child.textContent;
  4612. }
  4613. child = child.nextSibling;
  4614. }
  4615. return result;
  4616. };
  4617. Tools.ToDegrees = function (angle) {
  4618. return angle * 180 / Math.PI;
  4619. };
  4620. Tools.ToRadians = function (angle) {
  4621. return angle * Math.PI / 180;
  4622. };
  4623. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4624. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4625. var output = "";
  4626. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4627. var i = 0;
  4628. var bytes = new Uint8Array(buffer);
  4629. while (i < bytes.length) {
  4630. chr1 = bytes[i++];
  4631. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4632. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4633. enc1 = chr1 >> 2;
  4634. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4635. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4636. enc4 = chr3 & 63;
  4637. if (isNaN(chr2)) {
  4638. enc3 = enc4 = 64;
  4639. }
  4640. else if (isNaN(chr3)) {
  4641. enc4 = 64;
  4642. }
  4643. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4644. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4645. }
  4646. return "data:image/png;base64," + output;
  4647. };
  4648. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4649. if (bias === void 0) { bias = null; }
  4650. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4651. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4652. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4653. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4654. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4655. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4656. }
  4657. if (bias) {
  4658. minimum.x -= minimum.x * bias.x + bias.y;
  4659. minimum.y -= minimum.y * bias.x + bias.y;
  4660. minimum.z -= minimum.z * bias.x + bias.y;
  4661. maximum.x += maximum.x * bias.x + bias.y;
  4662. maximum.y += maximum.y * bias.x + bias.y;
  4663. maximum.z += maximum.z * bias.x + bias.y;
  4664. }
  4665. return {
  4666. minimum: minimum,
  4667. maximum: maximum
  4668. };
  4669. };
  4670. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4671. if (bias === void 0) { bias = null; }
  4672. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4673. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4674. if (!stride) {
  4675. stride = 3;
  4676. }
  4677. for (var index = start; index < start + count; index++) {
  4678. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4679. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4680. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4681. }
  4682. if (bias) {
  4683. minimum.x -= minimum.x * bias.x + bias.y;
  4684. minimum.y -= minimum.y * bias.x + bias.y;
  4685. minimum.z -= minimum.z * bias.x + bias.y;
  4686. maximum.x += maximum.x * bias.x + bias.y;
  4687. maximum.y += maximum.y * bias.x + bias.y;
  4688. maximum.z += maximum.z * bias.x + bias.y;
  4689. }
  4690. return {
  4691. minimum: minimum,
  4692. maximum: maximum
  4693. };
  4694. };
  4695. Tools.Vector2ArrayFeeder = function (array) {
  4696. return function (index) {
  4697. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4698. var length = isFloatArray ? array.length / 2 : array.length;
  4699. if (index >= length) {
  4700. return null;
  4701. }
  4702. if (isFloatArray) {
  4703. var fa = array;
  4704. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4705. }
  4706. var a = array;
  4707. return a[index];
  4708. };
  4709. };
  4710. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4711. if (bias === void 0) { bias = null; }
  4712. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4713. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4714. var i = 0;
  4715. var cur = feeder(i++);
  4716. while (cur) {
  4717. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4718. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4719. cur = feeder(i++);
  4720. }
  4721. if (bias) {
  4722. minimum.x -= minimum.x * bias.x + bias.y;
  4723. minimum.y -= minimum.y * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. }
  4727. return {
  4728. minimum: minimum,
  4729. maximum: maximum
  4730. };
  4731. };
  4732. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4733. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4734. return undefined;
  4735. return Array.isArray(obj) ? obj : [obj];
  4736. };
  4737. // Misc.
  4738. Tools.GetPointerPrefix = function () {
  4739. var eventPrefix = "pointer";
  4740. // Check if pointer events are supported
  4741. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4742. eventPrefix = "mouse";
  4743. }
  4744. return eventPrefix;
  4745. };
  4746. /**
  4747. * @param func - the function to be called
  4748. * @param requester - the object that will request the next frame. Falls back to window.
  4749. */
  4750. Tools.QueueNewFrame = function (func, requester) {
  4751. if (requester === void 0) { requester = window; }
  4752. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4753. /*if(requester.isPresenting) {
  4754. return;
  4755. } else*/ if (requester.requestAnimationFrame)
  4756. requester.requestAnimationFrame(func);
  4757. else if (requester.msRequestAnimationFrame)
  4758. requester.msRequestAnimationFrame(func);
  4759. else if (requester.webkitRequestAnimationFrame)
  4760. requester.webkitRequestAnimationFrame(func);
  4761. else if (requester.mozRequestAnimationFrame)
  4762. requester.mozRequestAnimationFrame(func);
  4763. else if (requester.oRequestAnimationFrame)
  4764. requester.oRequestAnimationFrame(func);
  4765. else {
  4766. window.setTimeout(func, 16);
  4767. }
  4768. };
  4769. Tools.RequestFullscreen = function (element) {
  4770. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4771. if (!requestFunction)
  4772. return;
  4773. requestFunction.call(element);
  4774. };
  4775. Tools.ExitFullscreen = function () {
  4776. if (document.exitFullscreen) {
  4777. document.exitFullscreen();
  4778. }
  4779. else if (document.mozCancelFullScreen) {
  4780. document.mozCancelFullScreen();
  4781. }
  4782. else if (document.webkitCancelFullScreen) {
  4783. document.webkitCancelFullScreen();
  4784. }
  4785. else if (document.msCancelFullScreen) {
  4786. document.msCancelFullScreen();
  4787. }
  4788. };
  4789. Tools.SetCorsBehavior = function (url, img) {
  4790. if (Tools.CorsBehavior) {
  4791. switch (typeof (Tools.CorsBehavior)) {
  4792. case "function":
  4793. var result = Tools.CorsBehavior(url);
  4794. if (result) {
  4795. return result;
  4796. }
  4797. break;
  4798. case "string":
  4799. default:
  4800. img.crossOrigin = Tools.CorsBehavior;
  4801. break;
  4802. }
  4803. }
  4804. };
  4805. // External files
  4806. Tools.CleanUrl = function (url) {
  4807. url = url.replace(/#/mg, "%23");
  4808. return url;
  4809. };
  4810. Tools.LoadImage = function (url, onload, onerror, database) {
  4811. if (url instanceof ArrayBuffer) {
  4812. url = Tools.EncodeArrayBufferTobase64(url);
  4813. }
  4814. url = Tools.CleanUrl(url);
  4815. var img = new Image();
  4816. if (url.substr(0, 5) !== "data:") {
  4817. Tools.SetCorsBehavior(url, img);
  4818. }
  4819. img.onload = function () {
  4820. onload(img);
  4821. };
  4822. img.onerror = function (err) {
  4823. Tools.Error("Error while trying to load texture: " + url);
  4824. if (Tools.UseFallbackTexture) {
  4825. 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";
  4826. onload(img);
  4827. }
  4828. else {
  4829. onerror();
  4830. }
  4831. };
  4832. var noIndexedDB = function () {
  4833. img.src = url;
  4834. };
  4835. var loadFromIndexedDB = function () {
  4836. database.loadImageFromDB(url, img);
  4837. };
  4838. //ANY database to do!
  4839. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4840. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4841. }
  4842. else {
  4843. if (url.indexOf("file:") === -1) {
  4844. noIndexedDB();
  4845. }
  4846. else {
  4847. try {
  4848. var textureName = url.substring(5).toLowerCase();
  4849. var blobURL;
  4850. try {
  4851. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4852. }
  4853. catch (ex) {
  4854. // Chrome doesn't support oneTimeOnly parameter
  4855. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4856. }
  4857. img.src = blobURL;
  4858. }
  4859. catch (e) {
  4860. img.src = null;
  4861. }
  4862. }
  4863. }
  4864. return img;
  4865. };
  4866. //ANY
  4867. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4868. url = Tools.CleanUrl(url);
  4869. var noIndexedDB = function () {
  4870. var request = new XMLHttpRequest();
  4871. var loadUrl = Tools.BaseUrl + url;
  4872. request.open('GET', loadUrl, true);
  4873. if (useArrayBuffer) {
  4874. request.responseType = "arraybuffer";
  4875. }
  4876. request.onprogress = progressCallBack;
  4877. request.onreadystatechange = function () {
  4878. if (request.readyState === 4) {
  4879. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4880. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4881. callback(!useArrayBuffer ? request.responseText : request.response);
  4882. }
  4883. else {
  4884. if (onError) {
  4885. onError();
  4886. }
  4887. else {
  4888. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4889. }
  4890. }
  4891. }
  4892. };
  4893. request.send(null);
  4894. };
  4895. var loadFromIndexedDB = function () {
  4896. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4897. };
  4898. if (url.indexOf("file:") !== -1) {
  4899. var fileName = url.substring(5).toLowerCase();
  4900. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4901. }
  4902. else {
  4903. // Caching all files
  4904. if (database && database.enableSceneOffline) {
  4905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4906. }
  4907. else {
  4908. noIndexedDB();
  4909. }
  4910. }
  4911. };
  4912. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4913. var reader = new FileReader();
  4914. reader.onload = function (e) {
  4915. //target doesn't have result from ts 1.3
  4916. callback(e.target['result']);
  4917. };
  4918. reader.onprogress = progressCallback;
  4919. reader.readAsDataURL(fileToLoad);
  4920. };
  4921. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4922. var reader = new FileReader();
  4923. reader.onerror = function (e) {
  4924. Tools.Log("Error while reading file: " + fileToLoad.name);
  4925. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4926. };
  4927. reader.onload = function (e) {
  4928. //target doesn't have result from ts 1.3
  4929. callback(e.target['result']);
  4930. };
  4931. reader.onprogress = progressCallBack;
  4932. if (!useArrayBuffer) {
  4933. // Asynchronous read
  4934. reader.readAsText(fileToLoad);
  4935. }
  4936. else {
  4937. reader.readAsArrayBuffer(fileToLoad);
  4938. }
  4939. };
  4940. //returns a downloadable url to a file content.
  4941. Tools.FileAsURL = function (content) {
  4942. var fileBlob = new Blob([content]);
  4943. var url = window.URL || window.webkitURL;
  4944. var link = url.createObjectURL(fileBlob);
  4945. return link;
  4946. };
  4947. // Misc.
  4948. Tools.Format = function (value, decimals) {
  4949. if (decimals === void 0) { decimals = 2; }
  4950. return value.toFixed(decimals);
  4951. };
  4952. Tools.CheckExtends = function (v, min, max) {
  4953. if (v.x < min.x)
  4954. min.x = v.x;
  4955. if (v.y < min.y)
  4956. min.y = v.y;
  4957. if (v.z < min.z)
  4958. min.z = v.z;
  4959. if (v.x > max.x)
  4960. max.x = v.x;
  4961. if (v.y > max.y)
  4962. max.y = v.y;
  4963. if (v.z > max.z)
  4964. max.z = v.z;
  4965. };
  4966. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4967. for (var prop in source) {
  4968. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4969. continue;
  4970. }
  4971. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4972. continue;
  4973. }
  4974. var sourceValue = source[prop];
  4975. var typeOfSourceValue = typeof sourceValue;
  4976. if (typeOfSourceValue === "function") {
  4977. continue;
  4978. }
  4979. if (typeOfSourceValue === "object") {
  4980. if (sourceValue instanceof Array) {
  4981. destination[prop] = [];
  4982. if (sourceValue.length > 0) {
  4983. if (typeof sourceValue[0] == "object") {
  4984. for (var index = 0; index < sourceValue.length; index++) {
  4985. var clonedValue = cloneValue(sourceValue[index], destination);
  4986. if (destination[prop].indexOf(clonedValue) === -1) {
  4987. destination[prop].push(clonedValue);
  4988. }
  4989. }
  4990. }
  4991. else {
  4992. destination[prop] = sourceValue.slice(0);
  4993. }
  4994. }
  4995. }
  4996. else {
  4997. destination[prop] = cloneValue(sourceValue, destination);
  4998. }
  4999. }
  5000. else {
  5001. destination[prop] = sourceValue;
  5002. }
  5003. }
  5004. };
  5005. Tools.IsEmpty = function (obj) {
  5006. for (var i in obj) {
  5007. return false;
  5008. }
  5009. return true;
  5010. };
  5011. Tools.RegisterTopRootEvents = function (events) {
  5012. for (var index = 0; index < events.length; index++) {
  5013. var event = events[index];
  5014. window.addEventListener(event.name, event.handler, false);
  5015. try {
  5016. if (window.parent) {
  5017. window.parent.addEventListener(event.name, event.handler, false);
  5018. }
  5019. }
  5020. catch (e) {
  5021. }
  5022. }
  5023. };
  5024. Tools.UnregisterTopRootEvents = function (events) {
  5025. for (var index = 0; index < events.length; index++) {
  5026. var event = events[index];
  5027. window.removeEventListener(event.name, event.handler);
  5028. try {
  5029. if (window.parent) {
  5030. window.parent.removeEventListener(event.name, event.handler);
  5031. }
  5032. }
  5033. catch (e) {
  5034. }
  5035. }
  5036. };
  5037. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5038. if (mimeType === void 0) { mimeType = "image/png"; }
  5039. // Read the contents of the framebuffer
  5040. var numberOfChannelsByLine = width * 4;
  5041. var halfHeight = height / 2;
  5042. //Reading datas from WebGL
  5043. var data = engine.readPixels(0, 0, width, height);
  5044. //To flip image on Y axis.
  5045. for (var i = 0; i < halfHeight; i++) {
  5046. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5047. var currentCell = j + i * numberOfChannelsByLine;
  5048. var targetLine = height - i - 1;
  5049. var targetCell = j + targetLine * numberOfChannelsByLine;
  5050. var temp = data[currentCell];
  5051. data[currentCell] = data[targetCell];
  5052. data[targetCell] = temp;
  5053. }
  5054. }
  5055. // Create a 2D canvas to store the result
  5056. if (!screenshotCanvas) {
  5057. screenshotCanvas = document.createElement('canvas');
  5058. }
  5059. screenshotCanvas.width = width;
  5060. screenshotCanvas.height = height;
  5061. var context = screenshotCanvas.getContext('2d');
  5062. // Copy the pixels to a 2D canvas
  5063. var imageData = context.createImageData(width, height);
  5064. var castData = (imageData.data);
  5065. castData.set(data);
  5066. context.putImageData(imageData, 0, 0);
  5067. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5068. };
  5069. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5070. if (mimeType === void 0) { mimeType = "image/png"; }
  5071. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5072. if (successCallback) {
  5073. successCallback(base64Image);
  5074. }
  5075. else {
  5076. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5077. if (("download" in document.createElement("a"))) {
  5078. var a = window.document.createElement("a");
  5079. a.href = base64Image;
  5080. var date = new Date();
  5081. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5082. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5083. window.document.body.appendChild(a);
  5084. a.addEventListener("click", function () {
  5085. a.parentElement.removeChild(a);
  5086. });
  5087. a.click();
  5088. }
  5089. else {
  5090. var newWindow = window.open("");
  5091. var img = newWindow.document.createElement("img");
  5092. img.src = base64Image;
  5093. newWindow.document.body.appendChild(img);
  5094. }
  5095. }
  5096. };
  5097. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5098. if (mimeType === void 0) { mimeType = "image/png"; }
  5099. var width;
  5100. var height;
  5101. // If a precision value is specified
  5102. if (size.precision) {
  5103. width = Math.round(engine.getRenderWidth() * size.precision);
  5104. height = Math.round(width / engine.getAspectRatio(camera));
  5105. }
  5106. else if (size.width && size.height) {
  5107. width = size.width;
  5108. height = size.height;
  5109. }
  5110. else if (size.width && !size.height) {
  5111. width = size.width;
  5112. height = Math.round(width / engine.getAspectRatio(camera));
  5113. }
  5114. else if (size.height && !size.width) {
  5115. height = size.height;
  5116. width = Math.round(height * engine.getAspectRatio(camera));
  5117. }
  5118. else if (!isNaN(size)) {
  5119. height = size;
  5120. width = size;
  5121. }
  5122. else {
  5123. Tools.Error("Invalid 'size' parameter !");
  5124. return;
  5125. }
  5126. if (!screenshotCanvas) {
  5127. screenshotCanvas = document.createElement('canvas');
  5128. }
  5129. screenshotCanvas.width = width;
  5130. screenshotCanvas.height = height;
  5131. var renderContext = screenshotCanvas.getContext("2d");
  5132. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5133. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5134. };
  5135. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5136. if (mimeType === void 0) { mimeType = "image/png"; }
  5137. var width;
  5138. var height;
  5139. //If a precision value is specified
  5140. if (size.precision) {
  5141. width = Math.round(engine.getRenderWidth() * size.precision);
  5142. height = Math.round(width / engine.getAspectRatio(camera));
  5143. size = { width: width, height: height };
  5144. }
  5145. else if (size.width && size.height) {
  5146. width = size.width;
  5147. height = size.height;
  5148. }
  5149. else if (size.width && !size.height) {
  5150. width = size.width;
  5151. height = Math.round(width / engine.getAspectRatio(camera));
  5152. size = { width: width, height: height };
  5153. }
  5154. else if (size.height && !size.width) {
  5155. height = size.height;
  5156. width = Math.round(height * engine.getAspectRatio(camera));
  5157. size = { width: width, height: height };
  5158. }
  5159. else if (!isNaN(size)) {
  5160. height = size;
  5161. width = size;
  5162. }
  5163. else {
  5164. Tools.Error("Invalid 'size' parameter !");
  5165. return;
  5166. }
  5167. var scene = camera.getScene();
  5168. var previousCamera = null;
  5169. if (scene.activeCamera !== camera) {
  5170. previousCamera = scene.activeCamera;
  5171. scene.activeCamera = camera;
  5172. }
  5173. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5174. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5175. texture.renderList = scene.meshes;
  5176. texture.onAfterRenderObservable.add(function () {
  5177. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5178. });
  5179. scene.incrementRenderId();
  5180. scene.resetCachedMaterial();
  5181. texture.render(true);
  5182. texture.dispose();
  5183. if (previousCamera) {
  5184. scene.activeCamera = previousCamera;
  5185. }
  5186. camera.getProjectionMatrix(true); // Force cache refresh;
  5187. };
  5188. // XHR response validator for local file scenario
  5189. Tools.ValidateXHRData = function (xhr, dataType) {
  5190. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5191. if (dataType === void 0) { dataType = 7; }
  5192. try {
  5193. if (dataType & 1) {
  5194. if (xhr.responseText && xhr.responseText.length > 0) {
  5195. return true;
  5196. }
  5197. else if (dataType === 1) {
  5198. return false;
  5199. }
  5200. }
  5201. if (dataType & 2) {
  5202. // Check header width and height since there is no "TGA" magic number
  5203. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5204. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5205. return true;
  5206. }
  5207. else if (dataType === 2) {
  5208. return false;
  5209. }
  5210. }
  5211. if (dataType & 4) {
  5212. // Check for the "DDS" magic number
  5213. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5214. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5215. return true;
  5216. }
  5217. else {
  5218. return false;
  5219. }
  5220. }
  5221. }
  5222. catch (e) {
  5223. }
  5224. return false;
  5225. };
  5226. /**
  5227. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5228. * Be aware Math.random() could cause collisions, but:
  5229. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5230. */
  5231. Tools.RandomId = function () {
  5232. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5233. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5234. return v.toString(16);
  5235. });
  5236. };
  5237. Object.defineProperty(Tools, "NoneLogLevel", {
  5238. get: function () {
  5239. return Tools._NoneLogLevel;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(Tools, "MessageLogLevel", {
  5245. get: function () {
  5246. return Tools._MessageLogLevel;
  5247. },
  5248. enumerable: true,
  5249. configurable: true
  5250. });
  5251. Object.defineProperty(Tools, "WarningLogLevel", {
  5252. get: function () {
  5253. return Tools._WarningLogLevel;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. Object.defineProperty(Tools, "ErrorLogLevel", {
  5259. get: function () {
  5260. return Tools._ErrorLogLevel;
  5261. },
  5262. enumerable: true,
  5263. configurable: true
  5264. });
  5265. Object.defineProperty(Tools, "AllLogLevel", {
  5266. get: function () {
  5267. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5268. },
  5269. enumerable: true,
  5270. configurable: true
  5271. });
  5272. Tools._AddLogEntry = function (entry) {
  5273. Tools._LogCache = entry + Tools._LogCache;
  5274. if (Tools.OnNewCacheEntry) {
  5275. Tools.OnNewCacheEntry(entry);
  5276. }
  5277. };
  5278. Tools._FormatMessage = function (message) {
  5279. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5280. var date = new Date();
  5281. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5282. };
  5283. Tools._LogDisabled = function (message) {
  5284. // nothing to do
  5285. };
  5286. Tools._LogEnabled = function (message) {
  5287. var formattedMessage = Tools._FormatMessage(message);
  5288. console.log("BJS - " + formattedMessage);
  5289. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5290. Tools._AddLogEntry(entry);
  5291. };
  5292. Tools._WarnDisabled = function (message) {
  5293. // nothing to do
  5294. };
  5295. Tools._WarnEnabled = function (message) {
  5296. var formattedMessage = Tools._FormatMessage(message);
  5297. console.warn("BJS - " + formattedMessage);
  5298. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5299. Tools._AddLogEntry(entry);
  5300. };
  5301. Tools._ErrorDisabled = function (message) {
  5302. // nothing to do
  5303. };
  5304. Tools._ErrorEnabled = function (message) {
  5305. Tools.errorsCount++;
  5306. var formattedMessage = Tools._FormatMessage(message);
  5307. console.error("BJS - " + formattedMessage);
  5308. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5309. Tools._AddLogEntry(entry);
  5310. };
  5311. Object.defineProperty(Tools, "LogCache", {
  5312. get: function () {
  5313. return Tools._LogCache;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Tools.ClearLogCache = function () {
  5319. Tools._LogCache = "";
  5320. Tools.errorsCount = 0;
  5321. };
  5322. Object.defineProperty(Tools, "LogLevels", {
  5323. set: function (level) {
  5324. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5325. Tools.Log = Tools._LogEnabled;
  5326. }
  5327. else {
  5328. Tools.Log = Tools._LogDisabled;
  5329. }
  5330. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5331. Tools.Warn = Tools._WarnEnabled;
  5332. }
  5333. else {
  5334. Tools.Warn = Tools._WarnDisabled;
  5335. }
  5336. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5337. Tools.Error = Tools._ErrorEnabled;
  5338. }
  5339. else {
  5340. Tools.Error = Tools._ErrorDisabled;
  5341. }
  5342. },
  5343. enumerable: true,
  5344. configurable: true
  5345. });
  5346. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5347. get: function () {
  5348. return Tools._PerformanceNoneLogLevel;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5354. get: function () {
  5355. return Tools._PerformanceUserMarkLogLevel;
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5361. get: function () {
  5362. return Tools._PerformanceConsoleLogLevel;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5368. set: function (level) {
  5369. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5370. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5371. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5372. return;
  5373. }
  5374. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5375. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5376. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5377. return;
  5378. }
  5379. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5380. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5386. };
  5387. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5388. };
  5389. Tools._StartUserMark = function (counterName, condition) {
  5390. if (condition === void 0) { condition = true; }
  5391. if (!condition || !Tools._performance.mark) {
  5392. return;
  5393. }
  5394. Tools._performance.mark(counterName + "-Begin");
  5395. };
  5396. Tools._EndUserMark = function (counterName, condition) {
  5397. if (condition === void 0) { condition = true; }
  5398. if (!condition || !Tools._performance.mark) {
  5399. return;
  5400. }
  5401. Tools._performance.mark(counterName + "-End");
  5402. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5403. };
  5404. Tools._StartPerformanceConsole = function (counterName, condition) {
  5405. if (condition === void 0) { condition = true; }
  5406. if (!condition) {
  5407. return;
  5408. }
  5409. Tools._StartUserMark(counterName, condition);
  5410. if (console.time) {
  5411. console.time(counterName);
  5412. }
  5413. };
  5414. Tools._EndPerformanceConsole = function (counterName, condition) {
  5415. if (condition === void 0) { condition = true; }
  5416. if (!condition) {
  5417. return;
  5418. }
  5419. Tools._EndUserMark(counterName, condition);
  5420. if (console.time) {
  5421. console.timeEnd(counterName);
  5422. }
  5423. };
  5424. Object.defineProperty(Tools, "Now", {
  5425. get: function () {
  5426. if (window.performance && window.performance.now) {
  5427. return window.performance.now();
  5428. }
  5429. return new Date().getTime();
  5430. },
  5431. enumerable: true,
  5432. configurable: true
  5433. });
  5434. /**
  5435. * This method will return the name of the class used to create the instance of the given object.
  5436. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5437. * @param object the object to get the class name from
  5438. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5439. */
  5440. Tools.getClassName = function (object, isType) {
  5441. if (isType === void 0) { isType = false; }
  5442. var name = null;
  5443. if (!isType && object.getClassName) {
  5444. name = object.getClassName();
  5445. }
  5446. else {
  5447. if (object instanceof Object) {
  5448. var classObj = isType ? object : Object.getPrototypeOf(object);
  5449. name = classObj.constructor["__bjsclassName__"];
  5450. }
  5451. if (!name) {
  5452. name = typeof object;
  5453. }
  5454. }
  5455. return name;
  5456. };
  5457. Tools.first = function (array, predicate) {
  5458. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5459. var el = array_1[_i];
  5460. if (predicate(el)) {
  5461. return el;
  5462. }
  5463. }
  5464. };
  5465. /**
  5466. * 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.
  5467. * @param array
  5468. */
  5469. Tools.arrayOrStringFeeder = function (array) {
  5470. return function (index) {
  5471. if (index >= array.length) {
  5472. return null;
  5473. }
  5474. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5475. if (val && val.getHashCode) {
  5476. val = val.getHashCode();
  5477. }
  5478. if (typeof val === "string") {
  5479. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5480. }
  5481. return val;
  5482. };
  5483. };
  5484. /**
  5485. * Compute the hashCode of a stream of number
  5486. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5487. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5488. * @return the hash code computed
  5489. */
  5490. Tools.hashCodeFromStream = function (feeder) {
  5491. // Based from here: http://stackoverflow.com/a/7616484/802124
  5492. var hash = 0;
  5493. var index = 0;
  5494. var chr = feeder(index++);
  5495. while (chr != null) {
  5496. hash = ((hash << 5) - hash) + chr;
  5497. hash |= 0; // Convert to 32bit integer
  5498. chr = feeder(index++);
  5499. }
  5500. return hash;
  5501. };
  5502. Tools.BaseUrl = "";
  5503. Tools.CorsBehavior = "anonymous";
  5504. Tools.UseFallbackTexture = true;
  5505. // Logs
  5506. Tools._NoneLogLevel = 0;
  5507. Tools._MessageLogLevel = 1;
  5508. Tools._WarningLogLevel = 2;
  5509. Tools._ErrorLogLevel = 4;
  5510. Tools._LogCache = "";
  5511. Tools.errorsCount = 0;
  5512. Tools.Log = Tools._LogEnabled;
  5513. Tools.Warn = Tools._WarnEnabled;
  5514. Tools.Error = Tools._ErrorEnabled;
  5515. // Performances
  5516. Tools._PerformanceNoneLogLevel = 0;
  5517. Tools._PerformanceUserMarkLogLevel = 1;
  5518. Tools._PerformanceConsoleLogLevel = 2;
  5519. Tools._performance = window.performance;
  5520. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5521. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5522. return Tools;
  5523. }());
  5524. BABYLON.Tools = Tools;
  5525. /**
  5526. * This class is used to track a performance counter which is number based.
  5527. * The user has access to many properties which give statistics of different nature
  5528. *
  5529. * The implementer can track two kinds of Performance Counter: time and count
  5530. * 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.
  5531. * 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.
  5532. */
  5533. var PerfCounter = (function () {
  5534. function PerfCounter() {
  5535. this._startMonitoringTime = 0;
  5536. this._min = 0;
  5537. this._max = 0;
  5538. this._average = 0;
  5539. this._lastSecAverage = 0;
  5540. this._current = 0;
  5541. this._totalValueCount = 0;
  5542. this._totalAccumulated = 0;
  5543. this._lastSecAccumulated = 0;
  5544. this._lastSecTime = 0;
  5545. this._lastSecValueCount = 0;
  5546. }
  5547. Object.defineProperty(PerfCounter.prototype, "min", {
  5548. /**
  5549. * Returns the smallest value ever
  5550. */
  5551. get: function () {
  5552. return this._min;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(PerfCounter.prototype, "max", {
  5558. /**
  5559. * Returns the biggest value ever
  5560. */
  5561. get: function () {
  5562. return this._max;
  5563. },
  5564. enumerable: true,
  5565. configurable: true
  5566. });
  5567. Object.defineProperty(PerfCounter.prototype, "average", {
  5568. /**
  5569. * Returns the average value since the performance counter is running
  5570. */
  5571. get: function () {
  5572. return this._average;
  5573. },
  5574. enumerable: true,
  5575. configurable: true
  5576. });
  5577. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5578. /**
  5579. * Returns the average value of the last second the counter was monitored
  5580. */
  5581. get: function () {
  5582. return this._lastSecAverage;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(PerfCounter.prototype, "current", {
  5588. /**
  5589. * Returns the current value
  5590. */
  5591. get: function () {
  5592. return this._current;
  5593. },
  5594. enumerable: true,
  5595. configurable: true
  5596. });
  5597. Object.defineProperty(PerfCounter.prototype, "total", {
  5598. get: function () {
  5599. return this._totalAccumulated;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. /**
  5605. * Call this method to start monitoring a new frame.
  5606. * 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.
  5607. */
  5608. PerfCounter.prototype.fetchNewFrame = function () {
  5609. this._totalValueCount++;
  5610. this._current = 0;
  5611. this._lastSecValueCount++;
  5612. };
  5613. /**
  5614. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5615. * @param newCount the count value to add to the monitored count
  5616. * @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.
  5617. */
  5618. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5619. this._current += newCount;
  5620. if (fetchResult) {
  5621. this._fetchResult();
  5622. }
  5623. };
  5624. /**
  5625. * Start monitoring this performance counter
  5626. */
  5627. PerfCounter.prototype.beginMonitoring = function () {
  5628. this._startMonitoringTime = Tools.Now;
  5629. };
  5630. /**
  5631. * Compute the time lapsed since the previous beginMonitoring() call.
  5632. * @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
  5633. */
  5634. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5635. if (newFrame === void 0) { newFrame = true; }
  5636. if (newFrame) {
  5637. this.fetchNewFrame();
  5638. }
  5639. var currentTime = Tools.Now;
  5640. this._current = currentTime - this._startMonitoringTime;
  5641. if (newFrame) {
  5642. this._fetchResult();
  5643. }
  5644. };
  5645. PerfCounter.prototype._fetchResult = function () {
  5646. this._totalAccumulated += this._current;
  5647. this._lastSecAccumulated += this._current;
  5648. // Min/Max update
  5649. this._min = Math.min(this._min, this._current);
  5650. this._max = Math.max(this._max, this._current);
  5651. this._average = this._totalAccumulated / this._totalValueCount;
  5652. // Reset last sec?
  5653. var now = Tools.Now;
  5654. if ((now - this._lastSecTime) > 1000) {
  5655. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5656. this._lastSecTime = now;
  5657. this._lastSecAccumulated = 0;
  5658. this._lastSecValueCount = 0;
  5659. }
  5660. };
  5661. return PerfCounter;
  5662. }());
  5663. BABYLON.PerfCounter = PerfCounter;
  5664. /**
  5665. * Use this className as a decorator on a given class definition to add it a name.
  5666. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5667. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5668. * @param name
  5669. */
  5670. function className(name) {
  5671. return function (target) {
  5672. target["__bjsclassName__"] = name;
  5673. };
  5674. }
  5675. BABYLON.className = className;
  5676. /**
  5677. * An implementation of a loop for asynchronous functions.
  5678. */
  5679. var AsyncLoop = (function () {
  5680. /**
  5681. * Constroctor.
  5682. * @param iterations the number of iterations.
  5683. * @param _fn the function to run each iteration
  5684. * @param _successCallback the callback that will be called upon succesful execution
  5685. * @param offset starting offset.
  5686. */
  5687. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5688. if (offset === void 0) { offset = 0; }
  5689. this.iterations = iterations;
  5690. this._fn = _fn;
  5691. this._successCallback = _successCallback;
  5692. this.index = offset - 1;
  5693. this._done = false;
  5694. }
  5695. /**
  5696. * Execute the next iteration. Must be called after the last iteration was finished.
  5697. */
  5698. AsyncLoop.prototype.executeNext = function () {
  5699. if (!this._done) {
  5700. if (this.index + 1 < this.iterations) {
  5701. ++this.index;
  5702. this._fn(this);
  5703. }
  5704. else {
  5705. this.breakLoop();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * Break the loop and run the success callback.
  5711. */
  5712. AsyncLoop.prototype.breakLoop = function () {
  5713. this._done = true;
  5714. this._successCallback();
  5715. };
  5716. /**
  5717. * Helper function
  5718. */
  5719. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5720. if (offset === void 0) { offset = 0; }
  5721. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5722. loop.executeNext();
  5723. return loop;
  5724. };
  5725. /**
  5726. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5727. * @param iterations total number of iterations
  5728. * @param syncedIterations number of synchronous iterations in each async iteration.
  5729. * @param fn the function to call each iteration.
  5730. * @param callback a success call back that will be called when iterating stops.
  5731. * @param breakFunction a break condition (optional)
  5732. * @param timeout timeout settings for the setTimeout function. default - 0.
  5733. * @constructor
  5734. */
  5735. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5736. if (timeout === void 0) { timeout = 0; }
  5737. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5738. if (breakFunction && breakFunction())
  5739. loop.breakLoop();
  5740. else {
  5741. setTimeout(function () {
  5742. for (var i = 0; i < syncedIterations; ++i) {
  5743. var iteration = (loop.index * syncedIterations) + i;
  5744. if (iteration >= iterations)
  5745. break;
  5746. fn(iteration);
  5747. if (breakFunction && breakFunction()) {
  5748. loop.breakLoop();
  5749. break;
  5750. }
  5751. }
  5752. loop.executeNext();
  5753. }, timeout);
  5754. }
  5755. }, callback);
  5756. };
  5757. return AsyncLoop;
  5758. }());
  5759. BABYLON.AsyncLoop = AsyncLoop;
  5760. })(BABYLON || (BABYLON = {}));
  5761. var BABYLON;
  5762. (function (BABYLON) {
  5763. var Internals;
  5764. (function (Internals) {
  5765. var _AlphaState = (function () {
  5766. function _AlphaState() {
  5767. this._isAlphaBlendDirty = false;
  5768. this._isBlendFunctionParametersDirty = false;
  5769. this._alphaBlend = false;
  5770. this._blendFunctionParameters = new Array(4);
  5771. }
  5772. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5773. get: function () {
  5774. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5775. },
  5776. enumerable: true,
  5777. configurable: true
  5778. });
  5779. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5780. get: function () {
  5781. return this._alphaBlend;
  5782. },
  5783. set: function (value) {
  5784. if (this._alphaBlend === value) {
  5785. return;
  5786. }
  5787. this._alphaBlend = value;
  5788. this._isAlphaBlendDirty = true;
  5789. },
  5790. enumerable: true,
  5791. configurable: true
  5792. });
  5793. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5794. if (this._blendFunctionParameters[0] === value0 &&
  5795. this._blendFunctionParameters[1] === value1 &&
  5796. this._blendFunctionParameters[2] === value2 &&
  5797. this._blendFunctionParameters[3] === value3) {
  5798. return;
  5799. }
  5800. this._blendFunctionParameters[0] = value0;
  5801. this._blendFunctionParameters[1] = value1;
  5802. this._blendFunctionParameters[2] = value2;
  5803. this._blendFunctionParameters[3] = value3;
  5804. this._isBlendFunctionParametersDirty = true;
  5805. };
  5806. _AlphaState.prototype.reset = function () {
  5807. this._alphaBlend = false;
  5808. this._blendFunctionParameters[0] = null;
  5809. this._blendFunctionParameters[1] = null;
  5810. this._blendFunctionParameters[2] = null;
  5811. this._blendFunctionParameters[3] = null;
  5812. this._isAlphaBlendDirty = true;
  5813. this._isBlendFunctionParametersDirty = false;
  5814. };
  5815. _AlphaState.prototype.apply = function (gl) {
  5816. if (!this.isDirty) {
  5817. return;
  5818. }
  5819. // Alpha blend
  5820. if (this._isAlphaBlendDirty) {
  5821. if (this._alphaBlend) {
  5822. gl.enable(gl.BLEND);
  5823. }
  5824. else {
  5825. gl.disable(gl.BLEND);
  5826. }
  5827. this._isAlphaBlendDirty = false;
  5828. }
  5829. // Alpha function
  5830. if (this._isBlendFunctionParametersDirty) {
  5831. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5832. this._isBlendFunctionParametersDirty = false;
  5833. }
  5834. };
  5835. return _AlphaState;
  5836. }());
  5837. Internals._AlphaState = _AlphaState;
  5838. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5839. })(BABYLON || (BABYLON = {}));
  5840. var BABYLON;
  5841. (function (BABYLON) {
  5842. var Internals;
  5843. (function (Internals) {
  5844. var _DepthCullingState = (function () {
  5845. function _DepthCullingState() {
  5846. this._isDepthTestDirty = false;
  5847. this._isDepthMaskDirty = false;
  5848. this._isDepthFuncDirty = false;
  5849. this._isCullFaceDirty = false;
  5850. this._isCullDirty = false;
  5851. this._isZOffsetDirty = false;
  5852. }
  5853. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5854. get: function () {
  5855. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5856. },
  5857. enumerable: true,
  5858. configurable: true
  5859. });
  5860. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5861. get: function () {
  5862. return this._zOffset;
  5863. },
  5864. set: function (value) {
  5865. if (this._zOffset === value) {
  5866. return;
  5867. }
  5868. this._zOffset = value;
  5869. this._isZOffsetDirty = true;
  5870. },
  5871. enumerable: true,
  5872. configurable: true
  5873. });
  5874. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5875. get: function () {
  5876. return this._cullFace;
  5877. },
  5878. set: function (value) {
  5879. if (this._cullFace === value) {
  5880. return;
  5881. }
  5882. this._cullFace = value;
  5883. this._isCullFaceDirty = true;
  5884. },
  5885. enumerable: true,
  5886. configurable: true
  5887. });
  5888. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5889. get: function () {
  5890. return this._cull;
  5891. },
  5892. set: function (value) {
  5893. if (this._cull === value) {
  5894. return;
  5895. }
  5896. this._cull = value;
  5897. this._isCullDirty = true;
  5898. },
  5899. enumerable: true,
  5900. configurable: true
  5901. });
  5902. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5903. get: function () {
  5904. return this._depthFunc;
  5905. },
  5906. set: function (value) {
  5907. if (this._depthFunc === value) {
  5908. return;
  5909. }
  5910. this._depthFunc = value;
  5911. this._isDepthFuncDirty = true;
  5912. },
  5913. enumerable: true,
  5914. configurable: true
  5915. });
  5916. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5917. get: function () {
  5918. return this._depthMask;
  5919. },
  5920. set: function (value) {
  5921. if (this._depthMask === value) {
  5922. return;
  5923. }
  5924. this._depthMask = value;
  5925. this._isDepthMaskDirty = true;
  5926. },
  5927. enumerable: true,
  5928. configurable: true
  5929. });
  5930. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5931. get: function () {
  5932. return this._depthTest;
  5933. },
  5934. set: function (value) {
  5935. if (this._depthTest === value) {
  5936. return;
  5937. }
  5938. this._depthTest = value;
  5939. this._isDepthTestDirty = true;
  5940. },
  5941. enumerable: true,
  5942. configurable: true
  5943. });
  5944. _DepthCullingState.prototype.reset = function () {
  5945. this._depthMask = true;
  5946. this._depthTest = true;
  5947. this._depthFunc = null;
  5948. this._cullFace = null;
  5949. this._cull = null;
  5950. this._zOffset = 0;
  5951. this._isDepthTestDirty = true;
  5952. this._isDepthMaskDirty = true;
  5953. this._isDepthFuncDirty = false;
  5954. this._isCullFaceDirty = false;
  5955. this._isCullDirty = false;
  5956. this._isZOffsetDirty = false;
  5957. };
  5958. _DepthCullingState.prototype.apply = function (gl) {
  5959. if (!this.isDirty) {
  5960. return;
  5961. }
  5962. // Cull
  5963. if (this._isCullDirty) {
  5964. if (this.cull) {
  5965. gl.enable(gl.CULL_FACE);
  5966. }
  5967. else {
  5968. gl.disable(gl.CULL_FACE);
  5969. }
  5970. this._isCullDirty = false;
  5971. }
  5972. // Cull face
  5973. if (this._isCullFaceDirty) {
  5974. gl.cullFace(this.cullFace);
  5975. this._isCullFaceDirty = false;
  5976. }
  5977. // Depth mask
  5978. if (this._isDepthMaskDirty) {
  5979. gl.depthMask(this.depthMask);
  5980. this._isDepthMaskDirty = false;
  5981. }
  5982. // Depth test
  5983. if (this._isDepthTestDirty) {
  5984. if (this.depthTest) {
  5985. gl.enable(gl.DEPTH_TEST);
  5986. }
  5987. else {
  5988. gl.disable(gl.DEPTH_TEST);
  5989. }
  5990. this._isDepthTestDirty = false;
  5991. }
  5992. // Depth func
  5993. if (this._isDepthFuncDirty) {
  5994. gl.depthFunc(this.depthFunc);
  5995. this._isDepthFuncDirty = false;
  5996. }
  5997. // zOffset
  5998. if (this._isZOffsetDirty) {
  5999. if (this.zOffset) {
  6000. gl.enable(gl.POLYGON_OFFSET_FILL);
  6001. gl.polygonOffset(this.zOffset, 0);
  6002. }
  6003. else {
  6004. gl.disable(gl.POLYGON_OFFSET_FILL);
  6005. }
  6006. this._isZOffsetDirty = false;
  6007. }
  6008. };
  6009. return _DepthCullingState;
  6010. }());
  6011. Internals._DepthCullingState = _DepthCullingState;
  6012. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6013. })(BABYLON || (BABYLON = {}));
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. var Internals;
  6017. (function (Internals) {
  6018. var _StencilState = (function () {
  6019. function _StencilState() {
  6020. this._isStencilTestDirty = false;
  6021. this._isStencilMaskDirty = false;
  6022. this._isStencilFuncDirty = false;
  6023. this._isStencilOpDirty = false;
  6024. this.reset();
  6025. }
  6026. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6027. get: function () {
  6028. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6034. get: function () {
  6035. return this._stencilFunc;
  6036. },
  6037. set: function (value) {
  6038. if (this._stencilFunc === value) {
  6039. return;
  6040. }
  6041. this._stencilFunc = value;
  6042. this._isStencilFuncDirty = true;
  6043. },
  6044. enumerable: true,
  6045. configurable: true
  6046. });
  6047. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6048. get: function () {
  6049. return this._stencilFuncRef;
  6050. },
  6051. set: function (value) {
  6052. if (this._stencilFuncRef === value) {
  6053. return;
  6054. }
  6055. this._stencilFuncRef = value;
  6056. this._isStencilFuncDirty = true;
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6062. get: function () {
  6063. return this._stencilFuncMask;
  6064. },
  6065. set: function (value) {
  6066. if (this._stencilFuncMask === value) {
  6067. return;
  6068. }
  6069. this._stencilFuncMask = value;
  6070. this._isStencilFuncDirty = true;
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6076. get: function () {
  6077. return this._stencilOpStencilFail;
  6078. },
  6079. set: function (value) {
  6080. if (this._stencilOpStencilFail === value) {
  6081. return;
  6082. }
  6083. this._stencilOpStencilFail = value;
  6084. this._isStencilOpDirty = true;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6090. get: function () {
  6091. return this._stencilOpDepthFail;
  6092. },
  6093. set: function (value) {
  6094. if (this._stencilOpDepthFail === value) {
  6095. return;
  6096. }
  6097. this._stencilOpDepthFail = value;
  6098. this._isStencilOpDirty = true;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6104. get: function () {
  6105. return this._stencilOpStencilDepthPass;
  6106. },
  6107. set: function (value) {
  6108. if (this._stencilOpStencilDepthPass === value) {
  6109. return;
  6110. }
  6111. this._stencilOpStencilDepthPass = value;
  6112. this._isStencilOpDirty = true;
  6113. },
  6114. enumerable: true,
  6115. configurable: true
  6116. });
  6117. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6118. get: function () {
  6119. return this._stencilMask;
  6120. },
  6121. set: function (value) {
  6122. if (this._stencilMask === value) {
  6123. return;
  6124. }
  6125. this._stencilMask = value;
  6126. this._isStencilMaskDirty = true;
  6127. },
  6128. enumerable: true,
  6129. configurable: true
  6130. });
  6131. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6132. get: function () {
  6133. return this._stencilTest;
  6134. },
  6135. set: function (value) {
  6136. if (this._stencilTest === value) {
  6137. return;
  6138. }
  6139. this._stencilTest = value;
  6140. this._isStencilTestDirty = true;
  6141. },
  6142. enumerable: true,
  6143. configurable: true
  6144. });
  6145. _StencilState.prototype.reset = function () {
  6146. this._stencilTest = false;
  6147. this._stencilMask = 0xFF;
  6148. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6149. this._stencilFuncRef = 1;
  6150. this._stencilFuncMask = 0xFF;
  6151. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6152. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6153. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6154. this._isStencilTestDirty = true;
  6155. this._isStencilMaskDirty = true;
  6156. this._isStencilFuncDirty = true;
  6157. this._isStencilOpDirty = true;
  6158. };
  6159. _StencilState.prototype.apply = function (gl) {
  6160. if (!this.isDirty) {
  6161. return;
  6162. }
  6163. // Stencil test
  6164. if (this._isStencilTestDirty) {
  6165. if (this.stencilTest) {
  6166. gl.enable(gl.STENCIL_TEST);
  6167. }
  6168. else {
  6169. gl.disable(gl.STENCIL_TEST);
  6170. }
  6171. this._isStencilTestDirty = false;
  6172. }
  6173. // Stencil mask
  6174. if (this._isStencilMaskDirty) {
  6175. gl.stencilMask(this.stencilMask);
  6176. this._isStencilMaskDirty = false;
  6177. }
  6178. // Stencil func
  6179. if (this._isStencilFuncDirty) {
  6180. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6181. this._isStencilFuncDirty = false;
  6182. }
  6183. // Stencil op
  6184. if (this._isStencilOpDirty) {
  6185. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6186. this._isStencilOpDirty = false;
  6187. }
  6188. };
  6189. return _StencilState;
  6190. }());
  6191. Internals._StencilState = _StencilState;
  6192. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6193. })(BABYLON || (BABYLON = {}));
  6194. var BABYLON;
  6195. (function (BABYLON) {
  6196. var compileShader = function (gl, source, type, defines) {
  6197. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6198. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6199. gl.compileShader(shader);
  6200. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6201. throw new Error(gl.getShaderInfoLog(shader));
  6202. }
  6203. return shader;
  6204. };
  6205. var HALF_FLOAT_OES = 0x8D61;
  6206. var getWebGLTextureType = function (gl, type) {
  6207. if (type === Engine.TEXTURETYPE_FLOAT) {
  6208. return gl.FLOAT;
  6209. }
  6210. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6211. // Add Half Float Constant.
  6212. return HALF_FLOAT_OES;
  6213. }
  6214. return gl.UNSIGNED_BYTE;
  6215. };
  6216. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6217. var magFilter = gl.NEAREST;
  6218. var minFilter = gl.NEAREST;
  6219. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6220. magFilter = gl.LINEAR;
  6221. if (generateMipMaps) {
  6222. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6223. }
  6224. else {
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. }
  6228. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6229. magFilter = gl.LINEAR;
  6230. if (generateMipMaps) {
  6231. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6232. }
  6233. else {
  6234. minFilter = gl.LINEAR;
  6235. }
  6236. }
  6237. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6238. magFilter = gl.NEAREST;
  6239. if (generateMipMaps) {
  6240. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6241. }
  6242. else {
  6243. minFilter = gl.NEAREST;
  6244. }
  6245. }
  6246. return {
  6247. min: minFilter,
  6248. mag: magFilter
  6249. };
  6250. };
  6251. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6253. var engine = scene.getEngine();
  6254. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6255. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6256. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6258. texture._baseWidth = width;
  6259. texture._baseHeight = height;
  6260. texture._width = potWidth;
  6261. texture._height = potHeight;
  6262. texture.isReady = true;
  6263. processFunction(potWidth, potHeight);
  6264. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6267. if (!noMipmap && !isCompressed) {
  6268. gl.generateMipmap(gl.TEXTURE_2D);
  6269. }
  6270. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6271. engine.resetTextureCache();
  6272. scene._removePendingData(texture);
  6273. texture.onLoadedCallbacks.forEach(function (callback) {
  6274. callback();
  6275. });
  6276. texture.onLoadedCallbacks = [];
  6277. };
  6278. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6279. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6280. var img;
  6281. var onload = function () {
  6282. loadedImages[index] = img;
  6283. loadedImages._internalCount++;
  6284. scene._removePendingData(img);
  6285. if (loadedImages._internalCount === 6) {
  6286. onfinish(loadedImages);
  6287. }
  6288. };
  6289. var onerror = function () {
  6290. scene._removePendingData(img);
  6291. if (onErrorCallBack) {
  6292. onErrorCallBack();
  6293. }
  6294. };
  6295. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6296. scene._addPendingData(img);
  6297. };
  6298. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6299. if (onError === void 0) { onError = null; }
  6300. var loadedImages = [];
  6301. loadedImages._internalCount = 0;
  6302. for (var index = 0; index < 6; index++) {
  6303. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6304. }
  6305. };
  6306. var InstancingAttributeInfo = (function () {
  6307. function InstancingAttributeInfo() {
  6308. }
  6309. return InstancingAttributeInfo;
  6310. }());
  6311. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6312. var EngineCapabilities = (function () {
  6313. function EngineCapabilities() {
  6314. }
  6315. return EngineCapabilities;
  6316. }());
  6317. BABYLON.EngineCapabilities = EngineCapabilities;
  6318. /**
  6319. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6320. */
  6321. var Engine = (function () {
  6322. /**
  6323. * @constructor
  6324. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6325. * @param {boolean} [antialias] - enable antialias
  6326. * @param options - further options to be sent to the getContext function
  6327. */
  6328. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6329. var _this = this;
  6330. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6331. // Public members
  6332. this.isFullscreen = false;
  6333. this.isPointerLock = false;
  6334. this.cullBackFaces = true;
  6335. this.renderEvenInBackground = true;
  6336. // To enable/disable IDB support and avoid XHR on .manifest
  6337. this.enableOfflineSupport = true;
  6338. this.scenes = new Array();
  6339. this._windowIsBackground = false;
  6340. this._webGLVersion = "1.0";
  6341. this._badOS = false;
  6342. this._drawCalls = new BABYLON.PerfCounter();
  6343. this._renderingQueueLaunched = false;
  6344. this._activeRenderLoops = [];
  6345. // FPS
  6346. this.fpsRange = 60;
  6347. this.previousFramesDuration = [];
  6348. this.fps = 60;
  6349. this.deltaTime = 0;
  6350. // States
  6351. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6352. this._stencilState = new BABYLON.Internals._StencilState();
  6353. this._alphaState = new BABYLON.Internals._AlphaState();
  6354. this._alphaMode = Engine.ALPHA_DISABLE;
  6355. // Cache
  6356. this._loadedTexturesCache = new Array();
  6357. this._maxTextureChannels = 16;
  6358. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6359. this._compiledEffects = {};
  6360. this._vertexAttribArraysEnabled = [];
  6361. this._uintIndicesCurrentlySet = false;
  6362. this._currentBoundBuffer = new Array();
  6363. this._currentBufferPointers = [];
  6364. this._currentInstanceLocations = new Array();
  6365. this._currentInstanceBuffers = new Array();
  6366. this._onVRFullScreenTriggered = function () {
  6367. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6368. //get the old size before we change
  6369. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6370. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6371. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6372. //But actually, no browser follow the specs...
  6373. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6374. //get the width and height, change the render size
  6375. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6376. var width, height;
  6377. _this.setHardwareScalingLevel(1);
  6378. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6379. }
  6380. else {
  6381. //When the specs are implemented, need to uncomment this.
  6382. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6383. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6384. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6385. _this._vrDisplayEnabled = undefined;
  6386. }
  6387. };
  6388. this._renderingCanvas = canvas;
  6389. this._externalData = new BABYLON.StringDictionary();
  6390. options = options || {};
  6391. if (antialias != null) {
  6392. options.antialias = antialias;
  6393. }
  6394. if (options.preserveDrawingBuffer === undefined) {
  6395. options.preserveDrawingBuffer = false;
  6396. }
  6397. // Checks if some of the format renders first to allow the use of webgl inspector.
  6398. var renderToFullFloat = this._canRenderToFloatTexture();
  6399. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6400. // GL
  6401. //try {
  6402. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6403. // if (this._gl) {
  6404. // this._webGLVersion = "2.0";
  6405. // }
  6406. //} catch (e) {
  6407. // // Do nothing
  6408. //}
  6409. if (!this._gl) {
  6410. try {
  6411. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6412. }
  6413. catch (e) {
  6414. throw new Error("WebGL not supported");
  6415. }
  6416. }
  6417. if (!this._gl) {
  6418. throw new Error("WebGL not supported");
  6419. }
  6420. this._onBlur = function () {
  6421. _this._windowIsBackground = true;
  6422. };
  6423. this._onFocus = function () {
  6424. _this._windowIsBackground = false;
  6425. };
  6426. window.addEventListener("blur", this._onBlur);
  6427. window.addEventListener("focus", this._onFocus);
  6428. // Viewport
  6429. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6430. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6431. this.resize();
  6432. // Caps
  6433. this._isStencilEnable = options.stencil;
  6434. this._caps = new EngineCapabilities();
  6435. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6436. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6437. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6438. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6439. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6440. // Infos
  6441. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6442. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6443. if (rendererInfo != null) {
  6444. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6445. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6446. }
  6447. if (!this._glVendor) {
  6448. this._glVendor = "Unknown vendor";
  6449. }
  6450. if (!this._glRenderer) {
  6451. this._glRenderer = "Unknown renderer";
  6452. }
  6453. // Extensions
  6454. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6455. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6456. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6457. 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');
  6458. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6459. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6460. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6461. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6462. this._caps.highPrecisionShaderSupported = true;
  6463. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6464. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6465. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6466. this._caps.textureFloatRender = renderToFullFloat;
  6467. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6468. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6469. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6470. if (this._gl.getShaderPrecisionFormat) {
  6471. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6472. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6473. }
  6474. // Depth buffer
  6475. this.setDepthBuffer(true);
  6476. this.setDepthFunctionToLessOrEqual();
  6477. this.setDepthWrite(true);
  6478. // Fullscreen
  6479. this._onFullscreenChange = function () {
  6480. if (document.fullscreen !== undefined) {
  6481. _this.isFullscreen = document.fullscreen;
  6482. }
  6483. else if (document.mozFullScreen !== undefined) {
  6484. _this.isFullscreen = document.mozFullScreen;
  6485. }
  6486. else if (document.webkitIsFullScreen !== undefined) {
  6487. _this.isFullscreen = document.webkitIsFullScreen;
  6488. }
  6489. else if (document.msIsFullScreen !== undefined) {
  6490. _this.isFullscreen = document.msIsFullScreen;
  6491. }
  6492. // Pointer lock
  6493. if (_this.isFullscreen && _this._pointerLockRequested) {
  6494. canvas.requestPointerLock = canvas.requestPointerLock ||
  6495. canvas.msRequestPointerLock ||
  6496. canvas.mozRequestPointerLock ||
  6497. canvas.webkitRequestPointerLock;
  6498. if (canvas.requestPointerLock) {
  6499. canvas.requestPointerLock();
  6500. }
  6501. }
  6502. };
  6503. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6504. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6505. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6506. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6507. // Pointer lock
  6508. this._onPointerLockChange = function () {
  6509. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6510. document.webkitPointerLockElement === canvas ||
  6511. document.msPointerLockElement === canvas ||
  6512. document.pointerLockElement === canvas);
  6513. };
  6514. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6515. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6516. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6517. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6518. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6519. Engine.audioEngine = new BABYLON.AudioEngine();
  6520. }
  6521. //default loading screen
  6522. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6523. //Load WebVR Devices
  6524. if (options.autoEnableWebVR) {
  6525. this.initWebVR();
  6526. }
  6527. //Detect if we are running on a faulty buggy OS.
  6528. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6529. //ua sniffing is the tool of the devil.
  6530. this._badOS = regexp.test(navigator.userAgent);
  6531. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6532. }
  6533. Object.defineProperty(Engine, "NEVER", {
  6534. get: function () {
  6535. return Engine._NEVER;
  6536. },
  6537. enumerable: true,
  6538. configurable: true
  6539. });
  6540. Object.defineProperty(Engine, "ALWAYS", {
  6541. get: function () {
  6542. return Engine._ALWAYS;
  6543. },
  6544. enumerable: true,
  6545. configurable: true
  6546. });
  6547. Object.defineProperty(Engine, "LESS", {
  6548. get: function () {
  6549. return Engine._LESS;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(Engine, "EQUAL", {
  6555. get: function () {
  6556. return Engine._EQUAL;
  6557. },
  6558. enumerable: true,
  6559. configurable: true
  6560. });
  6561. Object.defineProperty(Engine, "LEQUAL", {
  6562. get: function () {
  6563. return Engine._LEQUAL;
  6564. },
  6565. enumerable: true,
  6566. configurable: true
  6567. });
  6568. Object.defineProperty(Engine, "GREATER", {
  6569. get: function () {
  6570. return Engine._GREATER;
  6571. },
  6572. enumerable: true,
  6573. configurable: true
  6574. });
  6575. Object.defineProperty(Engine, "GEQUAL", {
  6576. get: function () {
  6577. return Engine._GEQUAL;
  6578. },
  6579. enumerable: true,
  6580. configurable: true
  6581. });
  6582. Object.defineProperty(Engine, "NOTEQUAL", {
  6583. get: function () {
  6584. return Engine._NOTEQUAL;
  6585. },
  6586. enumerable: true,
  6587. configurable: true
  6588. });
  6589. Object.defineProperty(Engine, "KEEP", {
  6590. get: function () {
  6591. return Engine._KEEP;
  6592. },
  6593. enumerable: true,
  6594. configurable: true
  6595. });
  6596. Object.defineProperty(Engine, "REPLACE", {
  6597. get: function () {
  6598. return Engine._REPLACE;
  6599. },
  6600. enumerable: true,
  6601. configurable: true
  6602. });
  6603. Object.defineProperty(Engine, "INCR", {
  6604. get: function () {
  6605. return Engine._INCR;
  6606. },
  6607. enumerable: true,
  6608. configurable: true
  6609. });
  6610. Object.defineProperty(Engine, "DECR", {
  6611. get: function () {
  6612. return Engine._DECR;
  6613. },
  6614. enumerable: true,
  6615. configurable: true
  6616. });
  6617. Object.defineProperty(Engine, "INVERT", {
  6618. get: function () {
  6619. return Engine._INVERT;
  6620. },
  6621. enumerable: true,
  6622. configurable: true
  6623. });
  6624. Object.defineProperty(Engine, "INCR_WRAP", {
  6625. get: function () {
  6626. return Engine._INCR_WRAP;
  6627. },
  6628. enumerable: true,
  6629. configurable: true
  6630. });
  6631. Object.defineProperty(Engine, "DECR_WRAP", {
  6632. get: function () {
  6633. return Engine._DECR_WRAP;
  6634. },
  6635. enumerable: true,
  6636. configurable: true
  6637. });
  6638. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6639. get: function () {
  6640. return Engine._ALPHA_DISABLE;
  6641. },
  6642. enumerable: true,
  6643. configurable: true
  6644. });
  6645. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6646. get: function () {
  6647. return Engine._ALPHA_ONEONE;
  6648. },
  6649. enumerable: true,
  6650. configurable: true
  6651. });
  6652. Object.defineProperty(Engine, "ALPHA_ADD", {
  6653. get: function () {
  6654. return Engine._ALPHA_ADD;
  6655. },
  6656. enumerable: true,
  6657. configurable: true
  6658. });
  6659. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6660. get: function () {
  6661. return Engine._ALPHA_COMBINE;
  6662. },
  6663. enumerable: true,
  6664. configurable: true
  6665. });
  6666. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6667. get: function () {
  6668. return Engine._ALPHA_SUBTRACT;
  6669. },
  6670. enumerable: true,
  6671. configurable: true
  6672. });
  6673. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6674. get: function () {
  6675. return Engine._ALPHA_MULTIPLY;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6681. get: function () {
  6682. return Engine._ALPHA_MAXIMIZED;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6688. get: function () {
  6689. return Engine._DELAYLOADSTATE_NONE;
  6690. },
  6691. enumerable: true,
  6692. configurable: true
  6693. });
  6694. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6695. get: function () {
  6696. return Engine._DELAYLOADSTATE_LOADED;
  6697. },
  6698. enumerable: true,
  6699. configurable: true
  6700. });
  6701. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6702. get: function () {
  6703. return Engine._DELAYLOADSTATE_LOADING;
  6704. },
  6705. enumerable: true,
  6706. configurable: true
  6707. });
  6708. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6709. get: function () {
  6710. return Engine._DELAYLOADSTATE_NOTLOADED;
  6711. },
  6712. enumerable: true,
  6713. configurable: true
  6714. });
  6715. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6716. get: function () {
  6717. return Engine._TEXTUREFORMAT_ALPHA;
  6718. },
  6719. enumerable: true,
  6720. configurable: true
  6721. });
  6722. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6723. get: function () {
  6724. return Engine._TEXTUREFORMAT_LUMINANCE;
  6725. },
  6726. enumerable: true,
  6727. configurable: true
  6728. });
  6729. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6730. get: function () {
  6731. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6732. },
  6733. enumerable: true,
  6734. configurable: true
  6735. });
  6736. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6737. get: function () {
  6738. return Engine._TEXTUREFORMAT_RGB;
  6739. },
  6740. enumerable: true,
  6741. configurable: true
  6742. });
  6743. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6744. get: function () {
  6745. return Engine._TEXTUREFORMAT_RGBA;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6751. get: function () {
  6752. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6753. },
  6754. enumerable: true,
  6755. configurable: true
  6756. });
  6757. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6758. get: function () {
  6759. return Engine._TEXTURETYPE_FLOAT;
  6760. },
  6761. enumerable: true,
  6762. configurable: true
  6763. });
  6764. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6765. get: function () {
  6766. return Engine._TEXTURETYPE_HALF_FLOAT;
  6767. },
  6768. enumerable: true,
  6769. configurable: true
  6770. });
  6771. Object.defineProperty(Engine, "Version", {
  6772. get: function () {
  6773. return "2.5.-beta";
  6774. },
  6775. enumerable: true,
  6776. configurable: true
  6777. });
  6778. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6779. get: function () {
  6780. return this._webGLVersion;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6786. /**
  6787. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6788. */
  6789. get: function () {
  6790. return this._isStencilEnable;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Engine.prototype._prepareWorkingCanvas = function () {
  6796. if (this._workingCanvas) {
  6797. return;
  6798. }
  6799. this._workingCanvas = document.createElement("canvas");
  6800. this._workingContext = this._workingCanvas.getContext("2d");
  6801. };
  6802. Engine.prototype.resetTextureCache = function () {
  6803. for (var index = 0; index < this._maxTextureChannels; index++) {
  6804. this._activeTexturesCache[index] = null;
  6805. }
  6806. };
  6807. Engine.prototype.getGlInfo = function () {
  6808. return {
  6809. vendor: this._glVendor,
  6810. renderer: this._glRenderer,
  6811. version: this._glVersion
  6812. };
  6813. };
  6814. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6815. if (useScreen === void 0) { useScreen = false; }
  6816. var viewport = camera.viewport;
  6817. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6818. };
  6819. Engine.prototype.getRenderWidth = function (useScreen) {
  6820. if (useScreen === void 0) { useScreen = false; }
  6821. if (!useScreen && this._currentRenderTarget) {
  6822. return this._currentRenderTarget._width;
  6823. }
  6824. return this._renderingCanvas.width;
  6825. };
  6826. Engine.prototype.getRenderHeight = function (useScreen) {
  6827. if (useScreen === void 0) { useScreen = false; }
  6828. if (!useScreen && this._currentRenderTarget) {
  6829. return this._currentRenderTarget._height;
  6830. }
  6831. return this._renderingCanvas.height;
  6832. };
  6833. Engine.prototype.getRenderingCanvas = function () {
  6834. return this._renderingCanvas;
  6835. };
  6836. Engine.prototype.getRenderingCanvasClientRect = function () {
  6837. return this._renderingCanvas.getBoundingClientRect();
  6838. };
  6839. Engine.prototype.setHardwareScalingLevel = function (level) {
  6840. this._hardwareScalingLevel = level;
  6841. this.resize();
  6842. };
  6843. Engine.prototype.getHardwareScalingLevel = function () {
  6844. return this._hardwareScalingLevel;
  6845. };
  6846. Engine.prototype.getLoadedTexturesCache = function () {
  6847. return this._loadedTexturesCache;
  6848. };
  6849. Engine.prototype.getCaps = function () {
  6850. return this._caps;
  6851. };
  6852. Object.defineProperty(Engine.prototype, "drawCalls", {
  6853. get: function () {
  6854. return this._drawCalls.current;
  6855. },
  6856. enumerable: true,
  6857. configurable: true
  6858. });
  6859. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6860. get: function () {
  6861. return this._drawCalls;
  6862. },
  6863. enumerable: true,
  6864. configurable: true
  6865. });
  6866. Engine.prototype.getDepthFunction = function () {
  6867. return this._depthCullingState.depthFunc;
  6868. };
  6869. Engine.prototype.setDepthFunction = function (depthFunc) {
  6870. this._depthCullingState.depthFunc = depthFunc;
  6871. };
  6872. Engine.prototype.setDepthFunctionToGreater = function () {
  6873. this._depthCullingState.depthFunc = this._gl.GREATER;
  6874. };
  6875. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6876. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6877. };
  6878. Engine.prototype.setDepthFunctionToLess = function () {
  6879. this._depthCullingState.depthFunc = this._gl.LESS;
  6880. };
  6881. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6882. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6883. };
  6884. Engine.prototype.getStencilBuffer = function () {
  6885. return this._stencilState.stencilTest;
  6886. };
  6887. Engine.prototype.setStencilBuffer = function (enable) {
  6888. this._stencilState.stencilTest = enable;
  6889. };
  6890. Engine.prototype.getStencilMask = function () {
  6891. return this._stencilState.stencilMask;
  6892. };
  6893. Engine.prototype.setStencilMask = function (mask) {
  6894. this._stencilState.stencilMask = mask;
  6895. };
  6896. Engine.prototype.getStencilFunction = function () {
  6897. return this._stencilState.stencilFunc;
  6898. };
  6899. Engine.prototype.getStencilFunctionReference = function () {
  6900. return this._stencilState.stencilFuncRef;
  6901. };
  6902. Engine.prototype.getStencilFunctionMask = function () {
  6903. return this._stencilState.stencilFuncMask;
  6904. };
  6905. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6906. this._stencilState.stencilFunc = stencilFunc;
  6907. };
  6908. Engine.prototype.setStencilFunctionReference = function (reference) {
  6909. this._stencilState.stencilFuncRef = reference;
  6910. };
  6911. Engine.prototype.setStencilFunctionMask = function (mask) {
  6912. this._stencilState.stencilFuncMask = mask;
  6913. };
  6914. Engine.prototype.getStencilOperationFail = function () {
  6915. return this._stencilState.stencilOpStencilFail;
  6916. };
  6917. Engine.prototype.getStencilOperationDepthFail = function () {
  6918. return this._stencilState.stencilOpDepthFail;
  6919. };
  6920. Engine.prototype.getStencilOperationPass = function () {
  6921. return this._stencilState.stencilOpStencilDepthPass;
  6922. };
  6923. Engine.prototype.setStencilOperationFail = function (operation) {
  6924. this._stencilState.stencilOpStencilFail = operation;
  6925. };
  6926. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6927. this._stencilState.stencilOpDepthFail = operation;
  6928. };
  6929. Engine.prototype.setStencilOperationPass = function (operation) {
  6930. this._stencilState.stencilOpStencilDepthPass = operation;
  6931. };
  6932. /**
  6933. * stop executing a render loop function and remove it from the execution array
  6934. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6935. */
  6936. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6937. if (!renderFunction) {
  6938. this._activeRenderLoops = [];
  6939. return;
  6940. }
  6941. var index = this._activeRenderLoops.indexOf(renderFunction);
  6942. if (index >= 0) {
  6943. this._activeRenderLoops.splice(index, 1);
  6944. }
  6945. };
  6946. Engine.prototype._renderLoop = function () {
  6947. var shouldRender = true;
  6948. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6949. shouldRender = false;
  6950. }
  6951. if (shouldRender) {
  6952. // Start new frame
  6953. this.beginFrame();
  6954. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6955. var renderFunction = this._activeRenderLoops[index];
  6956. renderFunction();
  6957. }
  6958. // Present
  6959. this.endFrame();
  6960. }
  6961. if (this._activeRenderLoops.length > 0) {
  6962. // Register new frame
  6963. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6964. }
  6965. else {
  6966. this._renderingQueueLaunched = false;
  6967. }
  6968. };
  6969. /**
  6970. * Register and execute a render loop. The engine can have more than one render function.
  6971. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6972. * @example
  6973. * engine.runRenderLoop(function () {
  6974. * scene.render()
  6975. * })
  6976. */
  6977. Engine.prototype.runRenderLoop = function (renderFunction) {
  6978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6979. return;
  6980. }
  6981. this._activeRenderLoops.push(renderFunction);
  6982. if (!this._renderingQueueLaunched) {
  6983. this._renderingQueueLaunched = true;
  6984. this._bindedRenderFunction = this._renderLoop.bind(this);
  6985. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6986. }
  6987. };
  6988. /**
  6989. * Toggle full screen mode.
  6990. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6991. * @param {any} options - an options object to be sent to the requestFullscreen function
  6992. */
  6993. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6994. if (this.isFullscreen) {
  6995. BABYLON.Tools.ExitFullscreen();
  6996. }
  6997. else {
  6998. this._pointerLockRequested = requestPointerLock;
  6999. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7000. }
  7001. };
  7002. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7003. if (stencil === void 0) { stencil = false; }
  7004. this.applyStates();
  7005. var mode = 0;
  7006. if (backBuffer) {
  7007. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7008. mode |= this._gl.COLOR_BUFFER_BIT;
  7009. }
  7010. if (depth) {
  7011. this._gl.clearDepth(1.0);
  7012. mode |= this._gl.DEPTH_BUFFER_BIT;
  7013. }
  7014. if (stencil) {
  7015. this._gl.clearStencil(0);
  7016. mode |= this._gl.STENCIL_BUFFER_BIT;
  7017. }
  7018. this._gl.clear(mode);
  7019. };
  7020. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7021. var gl = this._gl;
  7022. // Save state
  7023. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7024. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7025. // Change state
  7026. gl.enable(gl.SCISSOR_TEST);
  7027. gl.scissor(x, y, width, height);
  7028. // Clear
  7029. this.clear(clearColor, true, true, true);
  7030. // Restore state
  7031. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7032. if (curScissor === true) {
  7033. gl.enable(gl.SCISSOR_TEST);
  7034. }
  7035. else {
  7036. gl.disable(gl.SCISSOR_TEST);
  7037. }
  7038. };
  7039. /**
  7040. * Set the WebGL's viewport
  7041. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7042. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7043. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7044. */
  7045. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7046. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7047. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7048. var x = viewport.x || 0;
  7049. var y = viewport.y || 0;
  7050. this._cachedViewport = viewport;
  7051. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7052. };
  7053. /**
  7054. * Directly set the WebGL Viewport
  7055. * The x, y, width & height are directly passed to the WebGL call
  7056. * @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.
  7057. */
  7058. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7059. var currentViewport = this._cachedViewport;
  7060. this._cachedViewport = null;
  7061. this._gl.viewport(x, y, width, height);
  7062. return currentViewport;
  7063. };
  7064. Engine.prototype.beginFrame = function () {
  7065. this._measureFps();
  7066. };
  7067. Engine.prototype.endFrame = function () {
  7068. //force a flush in case we are using a bad OS.
  7069. if (this._badOS) {
  7070. this.flushFramebuffer();
  7071. }
  7072. //submit frame to the vr device, if enabled
  7073. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7074. this._vrDisplayEnabled.submitFrame();
  7075. }
  7076. };
  7077. /**
  7078. * resize the view according to the canvas' size.
  7079. * @example
  7080. * window.addEventListener("resize", function () {
  7081. * engine.resize();
  7082. * });
  7083. */
  7084. Engine.prototype.resize = function () {
  7085. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7086. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7087. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7088. for (var index = 0; index < this.scenes.length; index++) {
  7089. var scene = this.scenes[index];
  7090. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7091. scene.debugLayer._syncPositions();
  7092. }
  7093. }
  7094. };
  7095. /**
  7096. * force a specific size of the canvas
  7097. * @param {number} width - the new canvas' width
  7098. * @param {number} height - the new canvas' height
  7099. */
  7100. Engine.prototype.setSize = function (width, height) {
  7101. this._renderingCanvas.width = width;
  7102. this._renderingCanvas.height = height;
  7103. for (var index = 0; index < this.scenes.length; index++) {
  7104. var scene = this.scenes[index];
  7105. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7106. var cam = scene.cameras[camIndex];
  7107. cam._currentRenderId = 0;
  7108. }
  7109. }
  7110. };
  7111. //WebVR functions
  7112. Engine.prototype.initWebVR = function () {
  7113. if (!this.vrDisplaysPromise) {
  7114. this._getVRDisplays();
  7115. }
  7116. };
  7117. Engine.prototype.enableVR = function (vrDevice) {
  7118. this._vrDisplayEnabled = vrDevice;
  7119. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7120. };
  7121. Engine.prototype.disableVR = function () {
  7122. if (this._vrDisplayEnabled) {
  7123. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7124. }
  7125. };
  7126. Engine.prototype._getVRDisplays = function () {
  7127. var _this = this;
  7128. var getWebVRDevices = function (devices) {
  7129. var size = devices.length;
  7130. var i = 0;
  7131. _this._vrDisplays = devices.filter(function (device) {
  7132. return devices[i] instanceof VRDisplay;
  7133. });
  7134. return _this._vrDisplays;
  7135. };
  7136. //using a key due to typescript
  7137. if (navigator.getVRDisplays) {
  7138. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7139. }
  7140. };
  7141. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7142. this._currentRenderTarget = texture;
  7143. this.bindUnboundFramebuffer(texture._framebuffer);
  7144. var gl = this._gl;
  7145. if (texture.isCube) {
  7146. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7147. }
  7148. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7149. this.wipeCaches();
  7150. };
  7151. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7152. if (this._currentFramebuffer !== framebuffer) {
  7153. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7154. this._currentFramebuffer = framebuffer;
  7155. }
  7156. };
  7157. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7158. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7159. this._currentRenderTarget = null;
  7160. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7161. var gl = this._gl;
  7162. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7163. gl.generateMipmap(gl.TEXTURE_2D);
  7164. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7165. }
  7166. this.bindUnboundFramebuffer(null);
  7167. };
  7168. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7169. if (texture.generateMipMaps) {
  7170. var gl = this._gl;
  7171. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7172. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7174. }
  7175. };
  7176. Engine.prototype.flushFramebuffer = function () {
  7177. this._gl.flush();
  7178. };
  7179. Engine.prototype.restoreDefaultFramebuffer = function () {
  7180. this._currentRenderTarget = null;
  7181. this.bindUnboundFramebuffer(null);
  7182. this.setViewport(this._cachedViewport);
  7183. this.wipeCaches();
  7184. };
  7185. // VBOs
  7186. Engine.prototype._resetVertexBufferBinding = function () {
  7187. this.bindArrayBuffer(null);
  7188. this._cachedVertexBuffers = null;
  7189. };
  7190. Engine.prototype.createVertexBuffer = function (vertices) {
  7191. var vbo = this._gl.createBuffer();
  7192. this.bindArrayBuffer(vbo);
  7193. if (vertices instanceof Float32Array) {
  7194. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7195. }
  7196. else {
  7197. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7198. }
  7199. this._resetVertexBufferBinding();
  7200. vbo.references = 1;
  7201. return vbo;
  7202. };
  7203. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7204. var vbo = this._gl.createBuffer();
  7205. this.bindArrayBuffer(vbo);
  7206. if (vertices instanceof Float32Array) {
  7207. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7208. }
  7209. else {
  7210. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7211. }
  7212. this._resetVertexBufferBinding();
  7213. vbo.references = 1;
  7214. return vbo;
  7215. };
  7216. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7217. this.bindArrayBuffer(vertexBuffer);
  7218. if (offset === undefined) {
  7219. offset = 0;
  7220. }
  7221. if (count === undefined) {
  7222. if (vertices instanceof Float32Array) {
  7223. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7224. }
  7225. else {
  7226. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7227. }
  7228. }
  7229. else {
  7230. if (vertices instanceof Float32Array) {
  7231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7232. }
  7233. else {
  7234. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7235. }
  7236. }
  7237. this._resetVertexBufferBinding();
  7238. };
  7239. Engine.prototype._resetIndexBufferBinding = function () {
  7240. this.bindIndexBuffer(null);
  7241. this._cachedIndexBuffer = null;
  7242. };
  7243. Engine.prototype.createIndexBuffer = function (indices) {
  7244. var vbo = this._gl.createBuffer();
  7245. this.bindIndexBuffer(vbo);
  7246. // Check for 32 bits indices
  7247. var arrayBuffer;
  7248. var need32Bits = false;
  7249. if (this._caps.uintIndices) {
  7250. for (var index = 0; index < indices.length; index++) {
  7251. if (indices[index] > 65535) {
  7252. need32Bits = true;
  7253. break;
  7254. }
  7255. }
  7256. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7257. }
  7258. else {
  7259. arrayBuffer = new Uint16Array(indices);
  7260. }
  7261. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7262. this._resetIndexBufferBinding();
  7263. vbo.references = 1;
  7264. vbo.is32Bits = need32Bits;
  7265. return vbo;
  7266. };
  7267. Engine.prototype.bindArrayBuffer = function (buffer) {
  7268. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7269. };
  7270. Engine.prototype.bindIndexBuffer = function (buffer) {
  7271. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7272. };
  7273. Engine.prototype.bindBuffer = function (buffer, target) {
  7274. if (this._currentBoundBuffer[target] !== buffer) {
  7275. this._gl.bindBuffer(target, buffer);
  7276. this._currentBoundBuffer[target] = buffer;
  7277. }
  7278. };
  7279. Engine.prototype.updateArrayBuffer = function (data) {
  7280. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7281. };
  7282. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7283. var pointer = this._currentBufferPointers[indx];
  7284. var changed = false;
  7285. if (!pointer) {
  7286. changed = true;
  7287. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7288. }
  7289. else {
  7290. if (pointer.buffer !== buffer) {
  7291. pointer.buffer = buffer;
  7292. changed = true;
  7293. }
  7294. if (pointer.size !== size) {
  7295. pointer.size = size;
  7296. changed = true;
  7297. }
  7298. if (pointer.type !== type) {
  7299. pointer.type = type;
  7300. changed = true;
  7301. }
  7302. if (pointer.normalized !== normalized) {
  7303. pointer.normalized = normalized;
  7304. changed = true;
  7305. }
  7306. if (pointer.stride !== stride) {
  7307. pointer.stride = stride;
  7308. changed = true;
  7309. }
  7310. if (pointer.offset !== offset) {
  7311. pointer.offset = offset;
  7312. changed = true;
  7313. }
  7314. }
  7315. if (changed) {
  7316. this.bindArrayBuffer(buffer);
  7317. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7318. }
  7319. };
  7320. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7321. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7322. this._cachedVertexBuffers = vertexBuffer;
  7323. this._cachedEffectForVertexBuffers = effect;
  7324. var attributesCount = effect.getAttributesCount();
  7325. var offset = 0;
  7326. for (var index = 0; index < attributesCount; index++) {
  7327. if (index < vertexDeclaration.length) {
  7328. var order = effect.getAttributeLocation(index);
  7329. if (order >= 0) {
  7330. if (!this._vertexAttribArraysEnabled[order]) {
  7331. this._gl.enableVertexAttribArray(order);
  7332. this._vertexAttribArraysEnabled[order] = true;
  7333. }
  7334. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7335. }
  7336. offset += vertexDeclaration[index] * 4;
  7337. }
  7338. else {
  7339. //disable effect attributes that have no data
  7340. var order = effect.getAttributeLocation(index);
  7341. if (this._vertexAttribArraysEnabled[order]) {
  7342. this._gl.disableVertexAttribArray(order);
  7343. this._vertexAttribArraysEnabled[order] = false;
  7344. }
  7345. }
  7346. }
  7347. }
  7348. if (this._cachedIndexBuffer !== indexBuffer) {
  7349. this._cachedIndexBuffer = indexBuffer;
  7350. this.bindIndexBuffer(indexBuffer);
  7351. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7352. }
  7353. };
  7354. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7355. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7356. this._cachedVertexBuffers = vertexBuffers;
  7357. this._cachedEffectForVertexBuffers = effect;
  7358. var attributes = effect.getAttributesNames();
  7359. for (var index = 0; index < attributes.length; index++) {
  7360. var order = effect.getAttributeLocation(index);
  7361. if (order >= 0) {
  7362. var vertexBuffer = vertexBuffers[attributes[index]];
  7363. if (!vertexBuffer) {
  7364. if (this._vertexAttribArraysEnabled[order]) {
  7365. this._gl.disableVertexAttribArray(order);
  7366. this._vertexAttribArraysEnabled[order] = false;
  7367. }
  7368. continue;
  7369. }
  7370. if (!this._vertexAttribArraysEnabled[order]) {
  7371. this._gl.enableVertexAttribArray(order);
  7372. this._vertexAttribArraysEnabled[order] = true;
  7373. }
  7374. var buffer = vertexBuffer.getBuffer();
  7375. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7376. if (vertexBuffer.getIsInstanced()) {
  7377. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7378. this._currentInstanceLocations.push(order);
  7379. this._currentInstanceBuffers.push(buffer);
  7380. }
  7381. }
  7382. }
  7383. }
  7384. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7385. this._cachedIndexBuffer = indexBuffer;
  7386. this.bindIndexBuffer(indexBuffer);
  7387. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7388. }
  7389. };
  7390. Engine.prototype.unbindInstanceAttributes = function () {
  7391. var boundBuffer;
  7392. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7393. var instancesBuffer = this._currentInstanceBuffers[i];
  7394. if (boundBuffer != instancesBuffer) {
  7395. boundBuffer = instancesBuffer;
  7396. this.bindArrayBuffer(instancesBuffer);
  7397. }
  7398. var offsetLocation = this._currentInstanceLocations[i];
  7399. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7400. }
  7401. this._currentInstanceBuffers.length = 0;
  7402. this._currentInstanceLocations.length = 0;
  7403. };
  7404. Engine.prototype._releaseBuffer = function (buffer) {
  7405. buffer.references--;
  7406. if (buffer.references === 0) {
  7407. this._gl.deleteBuffer(buffer);
  7408. return true;
  7409. }
  7410. return false;
  7411. };
  7412. Engine.prototype.createInstancesBuffer = function (capacity) {
  7413. var buffer = this._gl.createBuffer();
  7414. buffer.capacity = capacity;
  7415. this.bindArrayBuffer(buffer);
  7416. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7417. return buffer;
  7418. };
  7419. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7420. this._gl.deleteBuffer(buffer);
  7421. };
  7422. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7423. this.bindArrayBuffer(instancesBuffer);
  7424. if (data) {
  7425. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7426. }
  7427. if (offsetLocations[0].index !== undefined) {
  7428. var stride = 0;
  7429. for (var i = 0; i < offsetLocations.length; i++) {
  7430. var ai = offsetLocations[i];
  7431. stride += ai.attributeSize * 4;
  7432. }
  7433. for (var i = 0; i < offsetLocations.length; i++) {
  7434. var ai = offsetLocations[i];
  7435. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7436. this._gl.enableVertexAttribArray(ai.index);
  7437. this._vertexAttribArraysEnabled[ai.index] = true;
  7438. }
  7439. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7440. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7441. this._currentInstanceLocations.push(ai.index);
  7442. this._currentInstanceBuffers.push(instancesBuffer);
  7443. }
  7444. }
  7445. else {
  7446. for (var index = 0; index < 4; index++) {
  7447. var offsetLocation = offsetLocations[index];
  7448. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7449. this._gl.enableVertexAttribArray(offsetLocation);
  7450. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7451. }
  7452. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7453. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7454. this._currentInstanceLocations.push(offsetLocation);
  7455. this._currentInstanceBuffers.push(instancesBuffer);
  7456. }
  7457. }
  7458. };
  7459. Engine.prototype.applyStates = function () {
  7460. this._depthCullingState.apply(this._gl);
  7461. this._stencilState.apply(this._gl);
  7462. this._alphaState.apply(this._gl);
  7463. };
  7464. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7465. // Apply states
  7466. this.applyStates();
  7467. this._drawCalls.addCount(1, false);
  7468. // Render
  7469. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7470. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7471. if (instancesCount) {
  7472. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7473. return;
  7474. }
  7475. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7476. };
  7477. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7478. // Apply states
  7479. this.applyStates();
  7480. this._drawCalls.addCount(1, false);
  7481. if (instancesCount) {
  7482. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7483. return;
  7484. }
  7485. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7486. };
  7487. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7488. // Apply states
  7489. this.applyStates();
  7490. this._drawCalls.addCount(1, false);
  7491. if (instancesCount) {
  7492. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7493. return;
  7494. }
  7495. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7496. };
  7497. // Shaders
  7498. Engine.prototype._releaseEffect = function (effect) {
  7499. if (this._compiledEffects[effect._key]) {
  7500. delete this._compiledEffects[effect._key];
  7501. if (effect.getProgram()) {
  7502. this._gl.deleteProgram(effect.getProgram());
  7503. }
  7504. }
  7505. };
  7506. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7507. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7508. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7509. var name = vertex + "+" + fragment + "@" + defines;
  7510. if (this._compiledEffects[name]) {
  7511. return this._compiledEffects[name];
  7512. }
  7513. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7514. effect._key = name;
  7515. this._compiledEffects[name] = effect;
  7516. return effect;
  7517. };
  7518. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7519. if (uniformsNames === void 0) { uniformsNames = []; }
  7520. if (samplers === void 0) { samplers = []; }
  7521. if (defines === void 0) { defines = ""; }
  7522. return this.createEffect({
  7523. vertex: "particles",
  7524. fragmentElement: fragmentName
  7525. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7526. };
  7527. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7528. context = context || this._gl;
  7529. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7530. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7531. var shaderProgram = context.createProgram();
  7532. context.attachShader(shaderProgram, vertexShader);
  7533. context.attachShader(shaderProgram, fragmentShader);
  7534. context.linkProgram(shaderProgram);
  7535. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7536. if (!linked) {
  7537. var error = context.getProgramInfoLog(shaderProgram);
  7538. if (error) {
  7539. throw new Error(error);
  7540. }
  7541. }
  7542. context.deleteShader(vertexShader);
  7543. context.deleteShader(fragmentShader);
  7544. return shaderProgram;
  7545. };
  7546. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7547. var results = [];
  7548. for (var index = 0; index < uniformsNames.length; index++) {
  7549. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7550. }
  7551. return results;
  7552. };
  7553. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7554. var results = [];
  7555. for (var index = 0; index < attributesNames.length; index++) {
  7556. try {
  7557. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7558. }
  7559. catch (e) {
  7560. results.push(-1);
  7561. }
  7562. }
  7563. return results;
  7564. };
  7565. Engine.prototype.enableEffect = function (effect) {
  7566. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7567. if (effect && effect.onBind) {
  7568. effect.onBind(effect);
  7569. }
  7570. return;
  7571. }
  7572. // Use program
  7573. this.setProgram(effect.getProgram());
  7574. this._currentEffect = effect;
  7575. if (effect.onBind) {
  7576. effect.onBind(effect);
  7577. }
  7578. };
  7579. Engine.prototype.setIntArray = function (uniform, array) {
  7580. if (!uniform)
  7581. return;
  7582. this._gl.uniform1iv(uniform, array);
  7583. };
  7584. Engine.prototype.setIntArray2 = function (uniform, array) {
  7585. if (!uniform || array.length % 2 !== 0)
  7586. return;
  7587. this._gl.uniform2iv(uniform, array);
  7588. };
  7589. Engine.prototype.setIntArray3 = function (uniform, array) {
  7590. if (!uniform || array.length % 3 !== 0)
  7591. return;
  7592. this._gl.uniform3iv(uniform, array);
  7593. };
  7594. Engine.prototype.setIntArray4 = function (uniform, array) {
  7595. if (!uniform || array.length % 4 !== 0)
  7596. return;
  7597. this._gl.uniform4iv(uniform, array);
  7598. };
  7599. Engine.prototype.setFloatArray = function (uniform, array) {
  7600. if (!uniform)
  7601. return;
  7602. this._gl.uniform1fv(uniform, array);
  7603. };
  7604. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7605. if (!uniform || array.length % 2 !== 0)
  7606. return;
  7607. this._gl.uniform2fv(uniform, array);
  7608. };
  7609. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7610. if (!uniform || array.length % 3 !== 0)
  7611. return;
  7612. this._gl.uniform3fv(uniform, array);
  7613. };
  7614. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7615. if (!uniform || array.length % 4 !== 0)
  7616. return;
  7617. this._gl.uniform4fv(uniform, array);
  7618. };
  7619. Engine.prototype.setArray = function (uniform, array) {
  7620. if (!uniform)
  7621. return;
  7622. this._gl.uniform1fv(uniform, array);
  7623. };
  7624. Engine.prototype.setArray2 = function (uniform, array) {
  7625. if (!uniform || array.length % 2 !== 0)
  7626. return;
  7627. this._gl.uniform2fv(uniform, array);
  7628. };
  7629. Engine.prototype.setArray3 = function (uniform, array) {
  7630. if (!uniform || array.length % 3 !== 0)
  7631. return;
  7632. this._gl.uniform3fv(uniform, array);
  7633. };
  7634. Engine.prototype.setArray4 = function (uniform, array) {
  7635. if (!uniform || array.length % 4 !== 0)
  7636. return;
  7637. this._gl.uniform4fv(uniform, array);
  7638. };
  7639. Engine.prototype.setMatrices = function (uniform, matrices) {
  7640. if (!uniform)
  7641. return;
  7642. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7643. };
  7644. Engine.prototype.setMatrix = function (uniform, matrix) {
  7645. if (!uniform)
  7646. return;
  7647. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7648. };
  7649. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7650. if (!uniform)
  7651. return;
  7652. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7653. };
  7654. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7655. if (!uniform)
  7656. return;
  7657. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7658. };
  7659. Engine.prototype.setFloat = function (uniform, value) {
  7660. if (!uniform)
  7661. return;
  7662. this._gl.uniform1f(uniform, value);
  7663. };
  7664. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7665. if (!uniform)
  7666. return;
  7667. this._gl.uniform2f(uniform, x, y);
  7668. };
  7669. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7670. if (!uniform)
  7671. return;
  7672. this._gl.uniform3f(uniform, x, y, z);
  7673. };
  7674. Engine.prototype.setBool = function (uniform, bool) {
  7675. if (!uniform)
  7676. return;
  7677. this._gl.uniform1i(uniform, bool);
  7678. };
  7679. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7680. if (!uniform)
  7681. return;
  7682. this._gl.uniform4f(uniform, x, y, z, w);
  7683. };
  7684. Engine.prototype.setColor3 = function (uniform, color3) {
  7685. if (!uniform)
  7686. return;
  7687. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7688. };
  7689. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7690. if (!uniform)
  7691. return;
  7692. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7693. };
  7694. // States
  7695. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7696. if (zOffset === void 0) { zOffset = 0; }
  7697. if (reverseSide === void 0) { reverseSide = false; }
  7698. // Culling
  7699. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7700. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7701. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7702. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7703. if (culling) {
  7704. this._depthCullingState.cullFace = cullFace;
  7705. this._depthCullingState.cull = true;
  7706. }
  7707. else {
  7708. this._depthCullingState.cull = false;
  7709. }
  7710. }
  7711. // Z offset
  7712. this._depthCullingState.zOffset = zOffset;
  7713. };
  7714. Engine.prototype.setDepthBuffer = function (enable) {
  7715. this._depthCullingState.depthTest = enable;
  7716. };
  7717. Engine.prototype.getDepthWrite = function () {
  7718. return this._depthCullingState.depthMask;
  7719. };
  7720. Engine.prototype.setDepthWrite = function (enable) {
  7721. this._depthCullingState.depthMask = enable;
  7722. };
  7723. Engine.prototype.setColorWrite = function (enable) {
  7724. this._gl.colorMask(enable, enable, enable, enable);
  7725. };
  7726. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7727. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7728. if (this._alphaMode === mode) {
  7729. return;
  7730. }
  7731. switch (mode) {
  7732. case Engine.ALPHA_DISABLE:
  7733. this._alphaState.alphaBlend = false;
  7734. break;
  7735. case Engine.ALPHA_COMBINE:
  7736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7737. this._alphaState.alphaBlend = true;
  7738. break;
  7739. case Engine.ALPHA_ONEONE:
  7740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7741. this._alphaState.alphaBlend = true;
  7742. break;
  7743. case Engine.ALPHA_ADD:
  7744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7745. this._alphaState.alphaBlend = true;
  7746. break;
  7747. case Engine.ALPHA_SUBTRACT:
  7748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7749. this._alphaState.alphaBlend = true;
  7750. break;
  7751. case Engine.ALPHA_MULTIPLY:
  7752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7753. this._alphaState.alphaBlend = true;
  7754. break;
  7755. case Engine.ALPHA_MAXIMIZED:
  7756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7757. this._alphaState.alphaBlend = true;
  7758. break;
  7759. }
  7760. if (!noDepthWriteChange) {
  7761. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7762. }
  7763. this._alphaMode = mode;
  7764. };
  7765. Engine.prototype.getAlphaMode = function () {
  7766. return this._alphaMode;
  7767. };
  7768. Engine.prototype.setAlphaTesting = function (enable) {
  7769. this._alphaTest = enable;
  7770. };
  7771. Engine.prototype.getAlphaTesting = function () {
  7772. return this._alphaTest;
  7773. };
  7774. // Textures
  7775. Engine.prototype.wipeCaches = function () {
  7776. this.resetTextureCache();
  7777. this._currentEffect = null;
  7778. this._stencilState.reset();
  7779. this._depthCullingState.reset();
  7780. this.setDepthFunctionToLessOrEqual();
  7781. this._alphaState.reset();
  7782. this._cachedVertexBuffers = null;
  7783. this._cachedIndexBuffer = null;
  7784. this._cachedEffectForVertexBuffers = null;
  7785. };
  7786. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7787. var gl = this._gl;
  7788. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7789. var magFilter = gl.NEAREST;
  7790. var minFilter = gl.NEAREST;
  7791. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7792. magFilter = gl.LINEAR;
  7793. minFilter = gl.LINEAR;
  7794. }
  7795. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7796. magFilter = gl.LINEAR;
  7797. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7798. }
  7799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7801. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7802. texture.samplingMode = samplingMode;
  7803. };
  7804. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7805. var _this = this;
  7806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7807. if (onLoad === void 0) { onLoad = null; }
  7808. if (onError === void 0) { onError = null; }
  7809. if (buffer === void 0) { buffer = null; }
  7810. var texture = this._gl.createTexture();
  7811. var extension;
  7812. var fromData = false;
  7813. if (url.substr(0, 5) === "data:") {
  7814. fromData = true;
  7815. }
  7816. if (!fromData)
  7817. extension = url.substr(url.length - 4, 4).toLowerCase();
  7818. else {
  7819. var oldUrl = url;
  7820. fromData = oldUrl.split(':');
  7821. url = oldUrl;
  7822. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7823. }
  7824. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7825. var isTGA = (extension === ".tga");
  7826. scene._addPendingData(texture);
  7827. texture.url = url;
  7828. texture.noMipmap = noMipmap;
  7829. texture.references = 1;
  7830. texture.samplingMode = samplingMode;
  7831. texture.onLoadedCallbacks = [onLoad];
  7832. this._loadedTexturesCache.push(texture);
  7833. var onerror = function () {
  7834. scene._removePendingData(texture);
  7835. if (onError) {
  7836. onError();
  7837. }
  7838. };
  7839. var callback;
  7840. if (isTGA) {
  7841. callback = function (arrayBuffer) {
  7842. var data = new Uint8Array(arrayBuffer);
  7843. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7844. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7845. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7846. }, samplingMode);
  7847. };
  7848. if (!(fromData instanceof Array))
  7849. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7850. callback(arrayBuffer);
  7851. }, null, scene.database, true, onerror);
  7852. else
  7853. callback(buffer);
  7854. }
  7855. else if (isDDS) {
  7856. callback = function (data) {
  7857. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7858. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7859. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7860. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7861. }, samplingMode);
  7862. };
  7863. if (!(fromData instanceof Array))
  7864. BABYLON.Tools.LoadFile(url, function (data) {
  7865. callback(data);
  7866. }, null, scene.database, true, onerror);
  7867. else
  7868. callback(buffer);
  7869. }
  7870. else {
  7871. var onload = function (img) {
  7872. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7873. var isPot = (img.width === potWidth && img.height === potHeight);
  7874. if (!isPot) {
  7875. _this._prepareWorkingCanvas();
  7876. _this._workingCanvas.width = potWidth;
  7877. _this._workingCanvas.height = potHeight;
  7878. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7879. _this._workingContext.imageSmoothingEnabled = false;
  7880. _this._workingContext.mozImageSmoothingEnabled = false;
  7881. _this._workingContext.oImageSmoothingEnabled = false;
  7882. _this._workingContext.webkitImageSmoothingEnabled = false;
  7883. _this._workingContext.msImageSmoothingEnabled = false;
  7884. }
  7885. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7886. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7887. _this._workingContext.imageSmoothingEnabled = true;
  7888. _this._workingContext.mozImageSmoothingEnabled = true;
  7889. _this._workingContext.oImageSmoothingEnabled = true;
  7890. _this._workingContext.webkitImageSmoothingEnabled = true;
  7891. _this._workingContext.msImageSmoothingEnabled = true;
  7892. }
  7893. }
  7894. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7895. }, samplingMode);
  7896. };
  7897. if (!(fromData instanceof Array))
  7898. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7899. else
  7900. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7901. }
  7902. return texture;
  7903. };
  7904. Engine.prototype._getInternalFormat = function (format) {
  7905. var internalFormat = this._gl.RGBA;
  7906. switch (format) {
  7907. case Engine.TEXTUREFORMAT_ALPHA:
  7908. internalFormat = this._gl.ALPHA;
  7909. break;
  7910. case Engine.TEXTUREFORMAT_LUMINANCE:
  7911. internalFormat = this._gl.LUMINANCE;
  7912. break;
  7913. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7914. internalFormat = this._gl.LUMINANCE_ALPHA;
  7915. break;
  7916. case Engine.TEXTUREFORMAT_RGB:
  7917. internalFormat = this._gl.RGB;
  7918. break;
  7919. case Engine.TEXTUREFORMAT_RGBA:
  7920. internalFormat = this._gl.RGBA;
  7921. break;
  7922. }
  7923. return internalFormat;
  7924. };
  7925. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7926. if (compression === void 0) { compression = null; }
  7927. var internalFormat = this._getInternalFormat(format);
  7928. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7929. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7930. if (texture._width % 4 !== 0) {
  7931. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7932. }
  7933. if (compression) {
  7934. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7935. }
  7936. else {
  7937. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7938. }
  7939. if (texture.generateMipMaps) {
  7940. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7941. }
  7942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7943. this.resetTextureCache();
  7944. texture.isReady = true;
  7945. };
  7946. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7947. if (compression === void 0) { compression = null; }
  7948. var texture = this._gl.createTexture();
  7949. texture._baseWidth = width;
  7950. texture._baseHeight = height;
  7951. texture._width = width;
  7952. texture._height = height;
  7953. texture.references = 1;
  7954. this.updateRawTexture(texture, data, format, invertY, compression);
  7955. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7956. // Filters
  7957. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7959. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7960. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7961. texture.samplingMode = samplingMode;
  7962. this._loadedTexturesCache.push(texture);
  7963. return texture;
  7964. };
  7965. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7966. var texture = this._gl.createTexture();
  7967. texture._baseWidth = width;
  7968. texture._baseHeight = height;
  7969. if (generateMipMaps) {
  7970. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7971. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7972. }
  7973. this.resetTextureCache();
  7974. texture._width = width;
  7975. texture._height = height;
  7976. texture.isReady = false;
  7977. texture.generateMipMaps = generateMipMaps;
  7978. texture.references = 1;
  7979. texture.samplingMode = samplingMode;
  7980. this.updateTextureSamplingMode(samplingMode, texture);
  7981. this._loadedTexturesCache.push(texture);
  7982. return texture;
  7983. };
  7984. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7985. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7986. if (texture.isCube) {
  7987. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7988. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7989. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7990. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7991. }
  7992. else {
  7993. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7996. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7997. }
  7998. };
  7999. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8000. if (premulAlpha === void 0) { premulAlpha = false; }
  8001. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8002. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8003. if (premulAlpha) {
  8004. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8005. }
  8006. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8007. if (texture.generateMipMaps) {
  8008. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8009. }
  8010. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8011. if (premulAlpha) {
  8012. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8013. }
  8014. this.resetTextureCache();
  8015. texture.isReady = true;
  8016. };
  8017. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8018. if (texture._isDisabled) {
  8019. return;
  8020. }
  8021. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8022. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8023. try {
  8024. // Testing video texture support
  8025. if (this._videoTextureSupported === undefined) {
  8026. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8027. if (this._gl.getError() !== 0) {
  8028. this._videoTextureSupported = false;
  8029. }
  8030. else {
  8031. this._videoTextureSupported = true;
  8032. }
  8033. }
  8034. // Copy video through the current working canvas if video texture is not supported
  8035. if (!this._videoTextureSupported) {
  8036. if (!texture._workingCanvas) {
  8037. texture._workingCanvas = document.createElement("canvas");
  8038. texture._workingContext = texture._workingCanvas.getContext("2d");
  8039. texture._workingCanvas.width = texture._width;
  8040. texture._workingCanvas.height = texture._height;
  8041. }
  8042. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8043. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8044. }
  8045. else {
  8046. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8047. }
  8048. if (texture.generateMipMaps) {
  8049. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8050. }
  8051. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8052. this.resetTextureCache();
  8053. texture.isReady = true;
  8054. }
  8055. catch (ex) {
  8056. // Something unexpected
  8057. // Let's disable the texture
  8058. texture._isDisabled = true;
  8059. }
  8060. };
  8061. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8062. // old version had a "generateMipMaps" arg instead of options.
  8063. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8064. // in the same way, generateDepthBuffer is defaulted to true
  8065. var generateMipMaps = false;
  8066. var generateDepthBuffer = true;
  8067. var generateStencilBuffer = false;
  8068. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8069. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8070. if (options !== undefined) {
  8071. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8072. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8073. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8074. type = options.type === undefined ? type : options.type;
  8075. if (options.samplingMode !== undefined) {
  8076. samplingMode = options.samplingMode;
  8077. }
  8078. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8079. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8080. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8081. }
  8082. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8083. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8084. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8085. }
  8086. }
  8087. var gl = this._gl;
  8088. var texture = gl.createTexture();
  8089. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8090. var width = size.width || size;
  8091. var height = size.height || size;
  8092. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8093. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8094. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8095. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8096. }
  8097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8101. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8102. var depthStencilBuffer;
  8103. // Create the depth/stencil buffer
  8104. if (generateStencilBuffer) {
  8105. depthStencilBuffer = gl.createRenderbuffer();
  8106. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8107. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8108. }
  8109. else if (generateDepthBuffer) {
  8110. depthStencilBuffer = gl.createRenderbuffer();
  8111. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8112. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8113. }
  8114. // Create the framebuffer
  8115. var framebuffer = gl.createFramebuffer();
  8116. this.bindUnboundFramebuffer(framebuffer);
  8117. // Manage attachments
  8118. if (generateStencilBuffer) {
  8119. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8120. }
  8121. else if (generateDepthBuffer) {
  8122. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8123. }
  8124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8125. if (generateMipMaps) {
  8126. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8127. }
  8128. // Unbind
  8129. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8130. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8131. this.bindUnboundFramebuffer(null);
  8132. texture._framebuffer = framebuffer;
  8133. if (generateDepthBuffer) {
  8134. texture._depthBuffer = depthStencilBuffer;
  8135. }
  8136. texture._baseWidth = width;
  8137. texture._baseHeight = height;
  8138. texture._width = width;
  8139. texture._height = height;
  8140. texture.isReady = true;
  8141. texture.generateMipMaps = generateMipMaps;
  8142. texture.references = 1;
  8143. texture.samplingMode = samplingMode;
  8144. texture.type = type;
  8145. this.resetTextureCache();
  8146. this._loadedTexturesCache.push(texture);
  8147. return texture;
  8148. };
  8149. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8150. var gl = this._gl;
  8151. var texture = gl.createTexture();
  8152. var generateMipMaps = true;
  8153. var generateDepthBuffer = true;
  8154. var generateStencilBuffer = false;
  8155. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8156. if (options !== undefined) {
  8157. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8158. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8159. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8160. if (options.samplingMode !== undefined) {
  8161. samplingMode = options.samplingMode;
  8162. }
  8163. }
  8164. texture.isCube = true;
  8165. texture.references = 1;
  8166. texture.generateMipMaps = generateMipMaps;
  8167. texture.references = 1;
  8168. texture.samplingMode = samplingMode;
  8169. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8170. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8171. for (var face = 0; face < 6; face++) {
  8172. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8173. }
  8174. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8175. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8176. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8177. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8178. // Create the depth buffer
  8179. var depthStencilBuffer;
  8180. // Create the depth/stencil buffer
  8181. if (generateStencilBuffer) {
  8182. depthStencilBuffer = gl.createRenderbuffer();
  8183. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8184. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8185. }
  8186. else if (generateDepthBuffer) {
  8187. depthStencilBuffer = gl.createRenderbuffer();
  8188. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8189. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8190. }
  8191. // Create the framebuffer
  8192. var framebuffer = gl.createFramebuffer();
  8193. this.bindUnboundFramebuffer(framebuffer);
  8194. // Manage attachments
  8195. if (generateStencilBuffer) {
  8196. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8197. }
  8198. else if (generateDepthBuffer) {
  8199. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8200. }
  8201. // Mipmaps
  8202. if (texture.generateMipMaps) {
  8203. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8204. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8205. }
  8206. // Unbind
  8207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8208. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8209. this.bindUnboundFramebuffer(null);
  8210. texture._framebuffer = framebuffer;
  8211. if (generateDepthBuffer) {
  8212. texture._depthBuffer = depthStencilBuffer;
  8213. }
  8214. texture._width = size;
  8215. texture._height = size;
  8216. texture.isReady = true;
  8217. this.resetTextureCache();
  8218. this._loadedTexturesCache.push(texture);
  8219. return texture;
  8220. };
  8221. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8222. var _this = this;
  8223. if (onLoad === void 0) { onLoad = null; }
  8224. if (onError === void 0) { onError = null; }
  8225. var gl = this._gl;
  8226. var texture = gl.createTexture();
  8227. texture.isCube = true;
  8228. texture.url = rootUrl;
  8229. texture.references = 1;
  8230. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8231. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8232. if (isDDS) {
  8233. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8234. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8235. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8238. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8239. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8240. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8241. }
  8242. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8243. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8246. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8247. _this.resetTextureCache();
  8248. texture._width = info.width;
  8249. texture._height = info.height;
  8250. texture.isReady = true;
  8251. }, null, null, true, onError);
  8252. }
  8253. else {
  8254. cascadeLoad(rootUrl, scene, function (imgs) {
  8255. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8256. var height = width;
  8257. _this._prepareWorkingCanvas();
  8258. _this._workingCanvas.width = width;
  8259. _this._workingCanvas.height = height;
  8260. var faces = [
  8261. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8262. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8263. ];
  8264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8265. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8266. for (var index = 0; index < faces.length; index++) {
  8267. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8268. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8269. }
  8270. if (!noMipmap) {
  8271. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8272. }
  8273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8277. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8278. _this.resetTextureCache();
  8279. texture._width = width;
  8280. texture._height = height;
  8281. texture.isReady = true;
  8282. if (onLoad) {
  8283. onLoad();
  8284. }
  8285. }, files, onError);
  8286. }
  8287. this._loadedTexturesCache.push(texture);
  8288. return texture;
  8289. };
  8290. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8291. texture._width = width;
  8292. texture._height = height;
  8293. texture._size = width * height;
  8294. texture._baseWidth = width;
  8295. texture._baseHeight = height;
  8296. };
  8297. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8298. var _this = this;
  8299. var gl = this._gl;
  8300. var texture = gl.createTexture();
  8301. scene._addPendingData(texture);
  8302. texture.isCube = true;
  8303. texture.references = 1;
  8304. texture.url = url;
  8305. var internalFormat = this._getInternalFormat(format);
  8306. var textureType = gl.UNSIGNED_BYTE;
  8307. if (type === Engine.TEXTURETYPE_FLOAT) {
  8308. textureType = gl.FLOAT;
  8309. }
  8310. var width = size;
  8311. var height = width;
  8312. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8313. texture._width = width;
  8314. texture._height = height;
  8315. var onerror = function () {
  8316. scene._removePendingData(texture);
  8317. };
  8318. var internalCallback = function (data) {
  8319. var rgbeDataArrays = callback(data);
  8320. var facesIndex = [
  8321. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8322. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8323. ];
  8324. width = texture._width;
  8325. height = texture._height;
  8326. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8327. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8328. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8329. if (!noMipmap && isPot) {
  8330. if (mipmmapGenerator) {
  8331. var arrayTemp = [];
  8332. // Data are known to be in +X +Y +Z -X -Y -Z
  8333. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8334. arrayTemp.push(rgbeDataArrays[0]); // +X
  8335. arrayTemp.push(rgbeDataArrays[3]); // -X
  8336. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8337. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8338. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8339. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8340. var mipData = mipmmapGenerator(arrayTemp);
  8341. for (var level = 0; level < mipData.length; level++) {
  8342. var mipSize = width >> level;
  8343. // mipData is order in +X -X +Y -Y +Z -Z
  8344. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8345. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8346. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8347. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8348. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8349. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8350. }
  8351. }
  8352. else {
  8353. // Data are known to be in +X +Y +Z -X -Y -Z
  8354. for (var index = 0; index < facesIndex.length; index++) {
  8355. var faceData = rgbeDataArrays[index];
  8356. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8357. }
  8358. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8359. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8360. // By following the webgl standard changes from Revision 7, 2014/11/24
  8361. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8362. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8363. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8364. // Data are known to be in +X +Y +Z -X -Y -Z
  8365. for (var index = 0; index < facesIndex.length; index++) {
  8366. var faceData = rgbeDataArrays[index];
  8367. // Create a new RGBA Face.
  8368. var newFaceData = new Float32Array(width * height * 4);
  8369. for (var x = 0; x < width; x++) {
  8370. for (var y = 0; y < height; y++) {
  8371. var index_1 = (y * width + x) * 3;
  8372. var newIndex = (y * width + x) * 4;
  8373. // Map Old Value to new value.
  8374. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8375. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8376. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8377. // Add fully opaque alpha channel.
  8378. newFaceData[newIndex + 3] = 1;
  8379. }
  8380. }
  8381. // Reupload the face.
  8382. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8383. }
  8384. // Try to generate mipmap again.
  8385. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8386. }
  8387. }
  8388. }
  8389. else {
  8390. noMipmap = true;
  8391. }
  8392. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8395. }
  8396. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8399. }
  8400. else {
  8401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8403. }
  8404. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8406. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8407. texture.isReady = true;
  8408. _this.resetTextureCache();
  8409. scene._removePendingData(texture);
  8410. };
  8411. BABYLON.Tools.LoadFile(url, function (data) {
  8412. internalCallback(data);
  8413. }, onerror, scene.database, true);
  8414. return texture;
  8415. };
  8416. ;
  8417. Engine.prototype._releaseTexture = function (texture) {
  8418. var gl = this._gl;
  8419. if (texture._framebuffer) {
  8420. gl.deleteFramebuffer(texture._framebuffer);
  8421. }
  8422. if (texture._depthBuffer) {
  8423. gl.deleteRenderbuffer(texture._depthBuffer);
  8424. }
  8425. gl.deleteTexture(texture);
  8426. // Unbind channels
  8427. this.unbindAllTextures();
  8428. var index = this._loadedTexturesCache.indexOf(texture);
  8429. if (index !== -1) {
  8430. this._loadedTexturesCache.splice(index, 1);
  8431. }
  8432. };
  8433. Engine.prototype.setProgram = function (program) {
  8434. if (this._currentProgram !== program) {
  8435. this._gl.useProgram(program);
  8436. this._currentProgram = program;
  8437. }
  8438. };
  8439. Engine.prototype.bindSamplers = function (effect) {
  8440. this.setProgram(effect.getProgram());
  8441. var samplers = effect.getSamplers();
  8442. for (var index = 0; index < samplers.length; index++) {
  8443. var uniform = effect.getUniform(samplers[index]);
  8444. this._gl.uniform1i(uniform, index);
  8445. }
  8446. this._currentEffect = null;
  8447. };
  8448. Engine.prototype.activateTexture = function (texture) {
  8449. if (this._activeTexture !== texture) {
  8450. this._gl.activeTexture(texture);
  8451. this._activeTexture = texture;
  8452. }
  8453. };
  8454. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8455. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8456. this._gl.bindTexture(target, texture);
  8457. this._activeTexturesCache[this._activeTexture] = texture;
  8458. }
  8459. };
  8460. Engine.prototype._bindTexture = function (channel, texture) {
  8461. if (channel < 0) {
  8462. return;
  8463. }
  8464. this.activateTexture(this._gl["TEXTURE" + channel]);
  8465. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8466. };
  8467. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8468. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8469. };
  8470. Engine.prototype.unbindAllTextures = function () {
  8471. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8472. this.activateTexture(this._gl["TEXTURE" + channel]);
  8473. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8474. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8475. }
  8476. };
  8477. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8478. if (channel < 0) {
  8479. return;
  8480. }
  8481. this._gl.uniform1i(uniform, channel);
  8482. this._setTexture(channel, texture);
  8483. };
  8484. Engine.prototype._setTexture = function (channel, texture) {
  8485. // Not ready?
  8486. if (!texture || !texture.isReady()) {
  8487. if (this._activeTexturesCache[channel] != null) {
  8488. this.activateTexture(this._gl["TEXTURE" + channel]);
  8489. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8490. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8491. }
  8492. return;
  8493. }
  8494. // Video
  8495. var alreadyActivated = false;
  8496. if (texture instanceof BABYLON.VideoTexture) {
  8497. this.activateTexture(this._gl["TEXTURE" + channel]);
  8498. alreadyActivated = true;
  8499. texture.update();
  8500. }
  8501. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8502. texture.delayLoad();
  8503. return;
  8504. }
  8505. var internalTexture = texture.getInternalTexture();
  8506. if (this._activeTexturesCache[channel] === internalTexture) {
  8507. return;
  8508. }
  8509. if (!alreadyActivated) {
  8510. this.activateTexture(this._gl["TEXTURE" + channel]);
  8511. }
  8512. if (internalTexture.isCube) {
  8513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8514. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8515. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8516. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8517. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8518. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8519. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8520. }
  8521. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8522. }
  8523. else {
  8524. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8525. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8526. internalTexture._cachedWrapU = texture.wrapU;
  8527. switch (texture.wrapU) {
  8528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8530. break;
  8531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8533. break;
  8534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8536. break;
  8537. }
  8538. }
  8539. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8540. internalTexture._cachedWrapV = texture.wrapV;
  8541. switch (texture.wrapV) {
  8542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8544. break;
  8545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8547. break;
  8548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8550. break;
  8551. }
  8552. }
  8553. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8554. }
  8555. };
  8556. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8557. if (channel < 0) {
  8558. return;
  8559. }
  8560. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8561. this._textureUnits = new Int32Array(textures.length);
  8562. }
  8563. for (var i = 0; i < textures.length; i++) {
  8564. this._textureUnits[i] = channel + i;
  8565. }
  8566. this._gl.uniform1iv(uniform, this._textureUnits);
  8567. for (var index = 0; index < textures.length; index++) {
  8568. this._setTexture(channel + index, textures[index]);
  8569. }
  8570. };
  8571. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8572. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8573. var value = texture.anisotropicFilteringLevel;
  8574. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8575. value = 1;
  8576. }
  8577. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8578. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8579. texture._cachedAnisotropicFilteringLevel = value;
  8580. }
  8581. };
  8582. Engine.prototype.readPixels = function (x, y, width, height) {
  8583. var data = new Uint8Array(height * width * 4);
  8584. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8585. return data;
  8586. };
  8587. /**
  8588. * Add an externaly attached data from its key.
  8589. * This method call will fail and return false, if such key already exists.
  8590. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8591. * @param key the unique key that identifies the data
  8592. * @param data the data object to associate to the key for this Engine instance
  8593. * @return true if no such key were already present and the data was added successfully, false otherwise
  8594. */
  8595. Engine.prototype.addExternalData = function (key, data) {
  8596. return this._externalData.add(key, data);
  8597. };
  8598. /**
  8599. * Get an externaly attached data from its key
  8600. * @param key the unique key that identifies the data
  8601. * @return the associated data, if present (can be null), or undefined if not present
  8602. */
  8603. Engine.prototype.getExternalData = function (key) {
  8604. return this._externalData.get(key);
  8605. };
  8606. /**
  8607. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8608. * @param key the unique key that identifies the data
  8609. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8610. * @return the associated data, can be null if the factory returned null.
  8611. */
  8612. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8613. return this._externalData.getOrAddWithFactory(key, factory);
  8614. };
  8615. /**
  8616. * Remove an externaly attached data from the Engine instance
  8617. * @param key the unique key that identifies the data
  8618. * @return true if the data was successfully removed, false if it doesn't exist
  8619. */
  8620. Engine.prototype.removeExternalData = function (key) {
  8621. return this._externalData.remove(key);
  8622. };
  8623. Engine.prototype.releaseInternalTexture = function (texture) {
  8624. if (!texture) {
  8625. return;
  8626. }
  8627. texture.references--;
  8628. // Final reference ?
  8629. if (texture.references === 0) {
  8630. var texturesCache = this.getLoadedTexturesCache();
  8631. var index = texturesCache.indexOf(texture);
  8632. if (index > -1) {
  8633. texturesCache.splice(index, 1);
  8634. }
  8635. this._releaseTexture(texture);
  8636. }
  8637. };
  8638. // Dispose
  8639. Engine.prototype.dispose = function () {
  8640. this.hideLoadingUI();
  8641. this.stopRenderLoop();
  8642. // Release scenes
  8643. while (this.scenes.length) {
  8644. this.scenes[0].dispose();
  8645. }
  8646. // Release audio engine
  8647. Engine.audioEngine.dispose();
  8648. // Release effects
  8649. for (var name in this._compiledEffects) {
  8650. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8651. }
  8652. // Unbind
  8653. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8654. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8655. continue;
  8656. }
  8657. this._gl.disableVertexAttribArray(i);
  8658. }
  8659. this._gl = null;
  8660. //WebVR
  8661. this.disableVR();
  8662. // Events
  8663. window.removeEventListener("blur", this._onBlur);
  8664. window.removeEventListener("focus", this._onFocus);
  8665. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8666. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8667. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8668. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8669. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8670. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8671. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8672. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8673. };
  8674. // Loading screen
  8675. Engine.prototype.displayLoadingUI = function () {
  8676. this._loadingScreen.displayLoadingUI();
  8677. };
  8678. Engine.prototype.hideLoadingUI = function () {
  8679. this._loadingScreen.hideLoadingUI();
  8680. };
  8681. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8682. get: function () {
  8683. return this._loadingScreen;
  8684. },
  8685. set: function (loadingScreen) {
  8686. this._loadingScreen = loadingScreen;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8692. set: function (text) {
  8693. this._loadingScreen.loadingUIText = text;
  8694. },
  8695. enumerable: true,
  8696. configurable: true
  8697. });
  8698. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8699. set: function (color) {
  8700. this._loadingScreen.loadingUIBackgroundColor = color;
  8701. },
  8702. enumerable: true,
  8703. configurable: true
  8704. });
  8705. Engine.prototype.attachContextLostEvent = function (callback) {
  8706. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8707. };
  8708. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8709. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8710. };
  8711. // FPS
  8712. Engine.prototype.getFps = function () {
  8713. return this.fps;
  8714. };
  8715. Engine.prototype.getDeltaTime = function () {
  8716. return this.deltaTime;
  8717. };
  8718. Engine.prototype._measureFps = function () {
  8719. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8720. var length = this.previousFramesDuration.length;
  8721. if (length >= 2) {
  8722. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8723. }
  8724. if (length >= this.fpsRange) {
  8725. if (length > this.fpsRange) {
  8726. this.previousFramesDuration.splice(0, 1);
  8727. length = this.previousFramesDuration.length;
  8728. }
  8729. var sum = 0;
  8730. for (var id = 0; id < length - 1; id++) {
  8731. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8732. }
  8733. this.fps = 1000.0 / (sum / (length - 1));
  8734. }
  8735. };
  8736. Engine.prototype._canRenderToFloatTexture = function () {
  8737. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8738. };
  8739. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8740. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8741. };
  8742. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8743. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8744. var tempcanvas = document.createElement("canvas");
  8745. tempcanvas.height = 16;
  8746. tempcanvas.width = 16;
  8747. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8748. // extension.
  8749. var ext = gl.getExtension(extension);
  8750. if (!ext) {
  8751. return false;
  8752. }
  8753. // setup GLSL program
  8754. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8755. 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 }";
  8756. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8757. gl.useProgram(program);
  8758. // look up where the vertex data needs to go.
  8759. var positionLocation = gl.getAttribLocation(program, "a_position");
  8760. var colorLoc = gl.getUniformLocation(program, "u_color");
  8761. // provide texture coordinates for the rectangle.
  8762. var positionBuffer = gl.createBuffer();
  8763. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8764. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8765. -1.0, -1.0,
  8766. 1.0, -1.0,
  8767. -1.0, 1.0,
  8768. -1.0, 1.0,
  8769. 1.0, -1.0,
  8770. 1.0, 1.0]), gl.STATIC_DRAW);
  8771. gl.enableVertexAttribArray(positionLocation);
  8772. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8773. var whiteTex = gl.createTexture();
  8774. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8775. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8776. var tex = gl.createTexture();
  8777. gl.bindTexture(gl.TEXTURE_2D, tex);
  8778. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8781. var fb = gl.createFramebuffer();
  8782. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8783. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8784. var cleanup = function () {
  8785. gl.deleteProgram(program);
  8786. gl.disableVertexAttribArray(positionLocation);
  8787. gl.deleteBuffer(positionBuffer);
  8788. gl.deleteFramebuffer(fb);
  8789. gl.deleteTexture(whiteTex);
  8790. gl.deleteTexture(tex);
  8791. };
  8792. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8793. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8794. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8795. cleanup();
  8796. return false;
  8797. }
  8798. // Draw the rectangle.
  8799. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8800. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8801. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8802. gl.bindTexture(gl.TEXTURE_2D, tex);
  8803. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8804. gl.clearColor(1, 0, 0, 1);
  8805. gl.clear(gl.COLOR_BUFFER_BIT);
  8806. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8807. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8808. var pixel = new Uint8Array(4);
  8809. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8810. if (pixel[0] !== 0 ||
  8811. pixel[1] < 248 ||
  8812. pixel[2] < 248 ||
  8813. pixel[3] < 254) {
  8814. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8815. cleanup();
  8816. return false;
  8817. }
  8818. // Succesfully rendered to "format" texture.
  8819. cleanup();
  8820. return true;
  8821. };
  8822. // Statics
  8823. Engine.isSupported = function () {
  8824. try {
  8825. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8826. if (navigator.isCocoonJS) {
  8827. return true;
  8828. }
  8829. var tempcanvas = document.createElement("canvas");
  8830. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8831. return gl != null && !!window.WebGLRenderingContext;
  8832. }
  8833. catch (e) {
  8834. return false;
  8835. }
  8836. };
  8837. // Const statics
  8838. Engine._ALPHA_DISABLE = 0;
  8839. Engine._ALPHA_ADD = 1;
  8840. Engine._ALPHA_COMBINE = 2;
  8841. Engine._ALPHA_SUBTRACT = 3;
  8842. Engine._ALPHA_MULTIPLY = 4;
  8843. Engine._ALPHA_MAXIMIZED = 5;
  8844. Engine._ALPHA_ONEONE = 6;
  8845. Engine._DELAYLOADSTATE_NONE = 0;
  8846. Engine._DELAYLOADSTATE_LOADED = 1;
  8847. Engine._DELAYLOADSTATE_LOADING = 2;
  8848. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8849. Engine._TEXTUREFORMAT_ALPHA = 0;
  8850. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8851. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8852. Engine._TEXTUREFORMAT_RGB = 4;
  8853. Engine._TEXTUREFORMAT_RGBA = 5;
  8854. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8855. Engine._TEXTURETYPE_FLOAT = 1;
  8856. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8857. // Depht or Stencil test Constants.
  8858. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8859. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  8860. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  8861. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  8862. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  8863. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  8864. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  8865. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  8866. // Stencil Actions Constants.
  8867. Engine._KEEP = 0x1E00;
  8868. Engine._REPLACE = 0x1E01;
  8869. Engine._INCR = 0x1E02;
  8870. Engine._DECR = 0x1E03;
  8871. Engine._INVERT = 0x150A;
  8872. Engine._INCR_WRAP = 0x8507;
  8873. Engine._DECR_WRAP = 0x8508;
  8874. // Updatable statics so stick with vars here
  8875. Engine.CollisionsEpsilon = 0.001;
  8876. Engine.CodeRepository = "src/";
  8877. Engine.ShadersRepository = "src/Shaders/";
  8878. return Engine;
  8879. }());
  8880. BABYLON.Engine = Engine;
  8881. })(BABYLON || (BABYLON = {}));
  8882. var BABYLON;
  8883. (function (BABYLON) {
  8884. /**
  8885. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8886. */
  8887. var Node = (function () {
  8888. /**
  8889. * @constructor
  8890. * @param {string} name - the name and id to be given to this node
  8891. * @param {BABYLON.Scene} the scene this node will be added to
  8892. */
  8893. function Node(name, scene) {
  8894. this.state = "";
  8895. this.animations = new Array();
  8896. this._ranges = {};
  8897. this._childrenFlag = -1;
  8898. this._isEnabled = true;
  8899. this._isReady = true;
  8900. this._currentRenderId = -1;
  8901. this._parentRenderId = -1;
  8902. this.name = name;
  8903. this.id = name;
  8904. this._scene = scene;
  8905. this._initCache();
  8906. }
  8907. Object.defineProperty(Node.prototype, "parent", {
  8908. get: function () {
  8909. return this._parentNode;
  8910. },
  8911. set: function (parent) {
  8912. if (this._parentNode === parent) {
  8913. return;
  8914. }
  8915. if (this._parentNode) {
  8916. var index = this._parentNode._children.indexOf(this);
  8917. if (index !== -1) {
  8918. this._parentNode._children.splice(index, 1);
  8919. }
  8920. }
  8921. this._parentNode = parent;
  8922. if (this._parentNode) {
  8923. if (!this._parentNode._children) {
  8924. this._parentNode._children = new Array();
  8925. }
  8926. this._parentNode._children.push(this);
  8927. }
  8928. },
  8929. enumerable: true,
  8930. configurable: true
  8931. });
  8932. Node.prototype.getScene = function () {
  8933. return this._scene;
  8934. };
  8935. Node.prototype.getEngine = function () {
  8936. return this._scene.getEngine();
  8937. };
  8938. // override it in derived class
  8939. Node.prototype.getWorldMatrix = function () {
  8940. return BABYLON.Matrix.Identity();
  8941. };
  8942. // override it in derived class if you add new variables to the cache
  8943. // and call the parent class method
  8944. Node.prototype._initCache = function () {
  8945. this._cache = {};
  8946. this._cache.parent = undefined;
  8947. };
  8948. Node.prototype.updateCache = function (force) {
  8949. if (!force && this.isSynchronized())
  8950. return;
  8951. this._cache.parent = this.parent;
  8952. this._updateCache();
  8953. };
  8954. // override it in derived class if you add new variables to the cache
  8955. // and call the parent class method if !ignoreParentClass
  8956. Node.prototype._updateCache = function (ignoreParentClass) {
  8957. };
  8958. // override it in derived class if you add new variables to the cache
  8959. Node.prototype._isSynchronized = function () {
  8960. return true;
  8961. };
  8962. Node.prototype._markSyncedWithParent = function () {
  8963. this._parentRenderId = this.parent._currentRenderId;
  8964. };
  8965. Node.prototype.isSynchronizedWithParent = function () {
  8966. if (!this.parent) {
  8967. return true;
  8968. }
  8969. if (this._parentRenderId !== this.parent._currentRenderId) {
  8970. return false;
  8971. }
  8972. return this.parent.isSynchronized();
  8973. };
  8974. Node.prototype.isSynchronized = function (updateCache) {
  8975. var check = this.hasNewParent();
  8976. check = check || !this.isSynchronizedWithParent();
  8977. check = check || !this._isSynchronized();
  8978. if (updateCache)
  8979. this.updateCache(true);
  8980. return !check;
  8981. };
  8982. Node.prototype.hasNewParent = function (update) {
  8983. if (this._cache.parent === this.parent)
  8984. return false;
  8985. if (update)
  8986. this._cache.parent = this.parent;
  8987. return true;
  8988. };
  8989. /**
  8990. * Is this node ready to be used/rendered
  8991. * @return {boolean} is it ready
  8992. */
  8993. Node.prototype.isReady = function () {
  8994. return this._isReady;
  8995. };
  8996. /**
  8997. * Is this node enabled.
  8998. * If the node has a parent and is enabled, the parent will be inspected as well.
  8999. * @return {boolean} whether this node (and its parent) is enabled.
  9000. * @see setEnabled
  9001. */
  9002. Node.prototype.isEnabled = function () {
  9003. if (!this._isEnabled) {
  9004. return false;
  9005. }
  9006. if (this.parent) {
  9007. return this.parent.isEnabled();
  9008. }
  9009. return true;
  9010. };
  9011. /**
  9012. * Set the enabled state of this node.
  9013. * @param {boolean} value - the new enabled state
  9014. * @see isEnabled
  9015. */
  9016. Node.prototype.setEnabled = function (value) {
  9017. this._isEnabled = value;
  9018. };
  9019. /**
  9020. * Is this node a descendant of the given node.
  9021. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9022. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9023. * @see parent
  9024. */
  9025. Node.prototype.isDescendantOf = function (ancestor) {
  9026. if (this.parent) {
  9027. if (this.parent === ancestor) {
  9028. return true;
  9029. }
  9030. return this.parent.isDescendantOf(ancestor);
  9031. }
  9032. return false;
  9033. };
  9034. /**
  9035. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9036. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9037. * @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.
  9038. * @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.
  9039. */
  9040. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9041. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9042. if (!this._children) {
  9043. return;
  9044. }
  9045. for (var index = 0; index < this._children.length; index++) {
  9046. var item = this._children[index];
  9047. if (!predicate || predicate(item)) {
  9048. results.push(item);
  9049. }
  9050. if (!directDescendantsOnly) {
  9051. item._getDescendants(results, false, predicate);
  9052. }
  9053. }
  9054. };
  9055. /**
  9056. * Will return all nodes that have this node as ascendant.
  9057. * @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.
  9058. * @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.
  9059. * @return {BABYLON.Node[]} all children nodes of all types.
  9060. */
  9061. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9062. var results = [];
  9063. this._getDescendants(results, directDescendantsOnly, predicate);
  9064. return results;
  9065. };
  9066. /**
  9067. * @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.
  9068. * @Deprecated, legacy support.
  9069. * use getDecendants instead.
  9070. */
  9071. Node.prototype.getChildren = function (predicate) {
  9072. return this.getDescendants(true, predicate);
  9073. };
  9074. /**
  9075. * Get all child-meshes of this node.
  9076. */
  9077. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9078. var results = [];
  9079. this._getDescendants(results, directDecendantsOnly, function (node) {
  9080. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9081. });
  9082. return results;
  9083. };
  9084. Node.prototype._setReady = function (state) {
  9085. if (state === this._isReady) {
  9086. return;
  9087. }
  9088. if (!state) {
  9089. this._isReady = false;
  9090. return;
  9091. }
  9092. this._isReady = true;
  9093. if (this.onReady) {
  9094. this.onReady(this);
  9095. }
  9096. };
  9097. Node.prototype.getAnimationByName = function (name) {
  9098. for (var i = 0; i < this.animations.length; i++) {
  9099. var animation = this.animations[i];
  9100. if (animation.name === name) {
  9101. return animation;
  9102. }
  9103. }
  9104. return null;
  9105. };
  9106. Node.prototype.createAnimationRange = function (name, from, to) {
  9107. // check name not already in use
  9108. if (!this._ranges[name]) {
  9109. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9110. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9111. if (this.animations[i]) {
  9112. this.animations[i].createRange(name, from, to);
  9113. }
  9114. }
  9115. }
  9116. };
  9117. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9118. if (deleteFrames === void 0) { deleteFrames = true; }
  9119. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9120. if (this.animations[i]) {
  9121. this.animations[i].deleteRange(name, deleteFrames);
  9122. }
  9123. }
  9124. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9125. };
  9126. Node.prototype.getAnimationRange = function (name) {
  9127. return this._ranges[name];
  9128. };
  9129. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9130. var range = this.getAnimationRange(name);
  9131. if (!range) {
  9132. return null;
  9133. }
  9134. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9135. };
  9136. Node.prototype.serializeAnimationRanges = function () {
  9137. var serializationRanges = [];
  9138. for (var name in this._ranges) {
  9139. var range = {};
  9140. range.name = name;
  9141. range.from = this._ranges[name].from;
  9142. range.to = this._ranges[name].to;
  9143. serializationRanges.push(range);
  9144. }
  9145. return serializationRanges;
  9146. };
  9147. Node.prototype.dispose = function () {
  9148. this.parent = null;
  9149. };
  9150. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9151. if (parsedNode.ranges) {
  9152. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9153. var data = parsedNode.ranges[index];
  9154. node.createAnimationRange(data.name, data.from, data.to);
  9155. }
  9156. }
  9157. };
  9158. __decorate([
  9159. BABYLON.serialize()
  9160. ], Node.prototype, "name", void 0);
  9161. __decorate([
  9162. BABYLON.serialize()
  9163. ], Node.prototype, "id", void 0);
  9164. __decorate([
  9165. BABYLON.serialize()
  9166. ], Node.prototype, "uniqueId", void 0);
  9167. __decorate([
  9168. BABYLON.serialize()
  9169. ], Node.prototype, "state", void 0);
  9170. return Node;
  9171. }());
  9172. BABYLON.Node = Node;
  9173. })(BABYLON || (BABYLON = {}));
  9174. var BABYLON;
  9175. (function (BABYLON) {
  9176. var FilesInput = (function () {
  9177. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9178. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9179. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9180. this._engine = p_engine;
  9181. this._canvas = p_canvas;
  9182. this._currentScene = p_scene;
  9183. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9184. this._progressCallback = p_progressCallback;
  9185. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9186. this._textureLoadingCallback = p_textureLoadingCallback;
  9187. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9188. }
  9189. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9190. var _this = this;
  9191. if (p_elementToMonitor) {
  9192. this._elementToMonitor = p_elementToMonitor;
  9193. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9194. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9195. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9196. }
  9197. };
  9198. FilesInput.prototype.renderFunction = function () {
  9199. if (this._additionnalRenderLoopLogicCallback) {
  9200. this._additionnalRenderLoopLogicCallback();
  9201. }
  9202. if (this._currentScene) {
  9203. if (this._textureLoadingCallback) {
  9204. var remaining = this._currentScene.getWaitingItemsCount();
  9205. if (remaining > 0) {
  9206. this._textureLoadingCallback(remaining);
  9207. }
  9208. }
  9209. this._currentScene.render();
  9210. }
  9211. };
  9212. FilesInput.prototype.drag = function (e) {
  9213. e.stopPropagation();
  9214. e.preventDefault();
  9215. };
  9216. FilesInput.prototype.drop = function (eventDrop) {
  9217. eventDrop.stopPropagation();
  9218. eventDrop.preventDefault();
  9219. this.loadFiles(eventDrop);
  9220. };
  9221. FilesInput.prototype.loadFiles = function (event) {
  9222. if (this._startingProcessingFilesCallback)
  9223. this._startingProcessingFilesCallback();
  9224. // Handling data transfer via drag'n'drop
  9225. if (event && event.dataTransfer && event.dataTransfer.files) {
  9226. this._filesToLoad = event.dataTransfer.files;
  9227. }
  9228. // Handling files from input files
  9229. if (event && event.target && event.target.files) {
  9230. this._filesToLoad = event.target.files;
  9231. }
  9232. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9233. for (var i = 0; i < this._filesToLoad.length; i++) {
  9234. switch (this._filesToLoad[i].type) {
  9235. case "image/jpeg":
  9236. case "image/png":
  9237. case "image/bmp":
  9238. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9239. break;
  9240. case "image/targa":
  9241. case "image/vnd.ms-dds":
  9242. case "audio/wav":
  9243. case "audio/x-wav":
  9244. case "audio/mp3":
  9245. case "audio/mpeg":
  9246. case "audio/mpeg3":
  9247. case "audio/x-mpeg-3":
  9248. case "audio/ogg":
  9249. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9250. break;
  9251. default:
  9252. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9253. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9254. }
  9255. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9256. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9257. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9258. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9259. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9260. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9261. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9262. this._sceneFileToLoad = this._filesToLoad[i];
  9263. }
  9264. break;
  9265. }
  9266. }
  9267. this.reload();
  9268. }
  9269. };
  9270. FilesInput.prototype.reload = function () {
  9271. var _this = this;
  9272. var that = this;
  9273. // If a ".babylon" file has been provided
  9274. if (this._sceneFileToLoad) {
  9275. if (this._currentScene) {
  9276. if (BABYLON.Tools.errorsCount > 0) {
  9277. BABYLON.Tools.ClearLogCache();
  9278. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9279. }
  9280. this._engine.stopRenderLoop();
  9281. this._currentScene.dispose();
  9282. }
  9283. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9284. that._currentScene = newScene;
  9285. // Wait for textures and shaders to be ready
  9286. that._currentScene.executeWhenReady(function () {
  9287. // Attach camera to canvas inputs
  9288. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9289. that._currentScene.createDefaultCameraOrLight();
  9290. }
  9291. that._currentScene.activeCamera.attachControl(that._canvas);
  9292. if (that._sceneLoadedCallback) {
  9293. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9294. }
  9295. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9296. });
  9297. }, function (progress) {
  9298. if (_this._progressCallback) {
  9299. _this._progressCallback(progress);
  9300. }
  9301. });
  9302. }
  9303. else {
  9304. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9305. }
  9306. };
  9307. FilesInput.FilesTextures = new Array();
  9308. FilesInput.FilesToLoad = new Array();
  9309. return FilesInput;
  9310. }());
  9311. BABYLON.FilesInput = FilesInput;
  9312. })(BABYLON || (BABYLON = {}));
  9313. var BABYLON;
  9314. (function (BABYLON) {
  9315. var IntersectionInfo = (function () {
  9316. function IntersectionInfo(bu, bv, distance) {
  9317. this.bu = bu;
  9318. this.bv = bv;
  9319. this.distance = distance;
  9320. this.faceId = 0;
  9321. this.subMeshId = 0;
  9322. }
  9323. return IntersectionInfo;
  9324. }());
  9325. BABYLON.IntersectionInfo = IntersectionInfo;
  9326. var PickingInfo = (function () {
  9327. function PickingInfo() {
  9328. this.hit = false;
  9329. this.distance = 0;
  9330. this.pickedPoint = null;
  9331. this.pickedMesh = null;
  9332. this.bu = 0;
  9333. this.bv = 0;
  9334. this.faceId = -1;
  9335. this.subMeshId = 0;
  9336. this.pickedSprite = null;
  9337. }
  9338. // Methods
  9339. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9340. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9341. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9342. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9343. return null;
  9344. }
  9345. var indices = this.pickedMesh.getIndices();
  9346. var result;
  9347. if (useVerticesNormals) {
  9348. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9349. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9350. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9351. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9352. normal0 = normal0.scale(this.bu);
  9353. normal1 = normal1.scale(this.bv);
  9354. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9355. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9356. }
  9357. else {
  9358. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9359. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9360. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9361. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9362. var p1p2 = vertex1.subtract(vertex2);
  9363. var p3p2 = vertex3.subtract(vertex2);
  9364. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9365. }
  9366. if (useWorldCoordinates) {
  9367. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9368. }
  9369. return BABYLON.Vector3.Normalize(result);
  9370. };
  9371. PickingInfo.prototype.getTextureCoordinates = function () {
  9372. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9373. return null;
  9374. }
  9375. var indices = this.pickedMesh.getIndices();
  9376. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9377. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9378. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9379. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9380. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9381. uv1 = uv1.scale(this.bu);
  9382. uv2 = uv2.scale(this.bv);
  9383. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9384. };
  9385. return PickingInfo;
  9386. }());
  9387. BABYLON.PickingInfo = PickingInfo;
  9388. })(BABYLON || (BABYLON = {}));
  9389. var BABYLON;
  9390. (function (BABYLON) {
  9391. var BoundingSphere = (function () {
  9392. function BoundingSphere(minimum, maximum) {
  9393. this.minimum = minimum;
  9394. this.maximum = maximum;
  9395. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9396. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9397. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9398. this.radius = distance * 0.5;
  9399. this.centerWorld = BABYLON.Vector3.Zero();
  9400. this._update(BABYLON.Matrix.Identity());
  9401. }
  9402. // Methods
  9403. BoundingSphere.prototype._update = function (world) {
  9404. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9405. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9406. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9407. };
  9408. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9409. for (var i = 0; i < 6; i++) {
  9410. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9411. return false;
  9412. }
  9413. return true;
  9414. };
  9415. BoundingSphere.prototype.intersectsPoint = function (point) {
  9416. var x = this.centerWorld.x - point.x;
  9417. var y = this.centerWorld.y - point.y;
  9418. var z = this.centerWorld.z - point.z;
  9419. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9420. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9421. return false;
  9422. return true;
  9423. };
  9424. // Statics
  9425. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9426. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9427. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9428. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9429. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9430. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9431. return false;
  9432. return true;
  9433. };
  9434. return BoundingSphere;
  9435. }());
  9436. BABYLON.BoundingSphere = BoundingSphere;
  9437. })(BABYLON || (BABYLON = {}));
  9438. var BABYLON;
  9439. (function (BABYLON) {
  9440. var BoundingBox = (function () {
  9441. function BoundingBox(minimum, maximum) {
  9442. this.minimum = minimum;
  9443. this.maximum = maximum;
  9444. this.vectors = new Array();
  9445. this.vectorsWorld = new Array();
  9446. // Bounding vectors
  9447. this.vectors.push(this.minimum.clone());
  9448. this.vectors.push(this.maximum.clone());
  9449. this.vectors.push(this.minimum.clone());
  9450. this.vectors[2].x = this.maximum.x;
  9451. this.vectors.push(this.minimum.clone());
  9452. this.vectors[3].y = this.maximum.y;
  9453. this.vectors.push(this.minimum.clone());
  9454. this.vectors[4].z = this.maximum.z;
  9455. this.vectors.push(this.maximum.clone());
  9456. this.vectors[5].z = this.minimum.z;
  9457. this.vectors.push(this.maximum.clone());
  9458. this.vectors[6].x = this.minimum.x;
  9459. this.vectors.push(this.maximum.clone());
  9460. this.vectors[7].y = this.minimum.y;
  9461. // OBB
  9462. this.center = this.maximum.add(this.minimum).scale(0.5);
  9463. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9464. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9465. // World
  9466. for (var index = 0; index < this.vectors.length; index++) {
  9467. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9468. }
  9469. this.minimumWorld = BABYLON.Vector3.Zero();
  9470. this.maximumWorld = BABYLON.Vector3.Zero();
  9471. this._update(BABYLON.Matrix.Identity());
  9472. }
  9473. // Methods
  9474. BoundingBox.prototype.getWorldMatrix = function () {
  9475. return this._worldMatrix;
  9476. };
  9477. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9478. this._worldMatrix.copyFrom(matrix);
  9479. return this;
  9480. };
  9481. BoundingBox.prototype._update = function (world) {
  9482. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9483. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9484. for (var index = 0; index < this.vectors.length; index++) {
  9485. var v = this.vectorsWorld[index];
  9486. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9487. if (v.x < this.minimumWorld.x)
  9488. this.minimumWorld.x = v.x;
  9489. if (v.y < this.minimumWorld.y)
  9490. this.minimumWorld.y = v.y;
  9491. if (v.z < this.minimumWorld.z)
  9492. this.minimumWorld.z = v.z;
  9493. if (v.x > this.maximumWorld.x)
  9494. this.maximumWorld.x = v.x;
  9495. if (v.y > this.maximumWorld.y)
  9496. this.maximumWorld.y = v.y;
  9497. if (v.z > this.maximumWorld.z)
  9498. this.maximumWorld.z = v.z;
  9499. }
  9500. // OBB
  9501. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9502. this.center.scaleInPlace(0.5);
  9503. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9504. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9505. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9506. this._worldMatrix = world;
  9507. };
  9508. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9509. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9510. };
  9511. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9512. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9513. };
  9514. BoundingBox.prototype.intersectsPoint = function (point) {
  9515. var delta = -BABYLON.Epsilon;
  9516. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9517. return false;
  9518. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9519. return false;
  9520. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9521. return false;
  9522. return true;
  9523. };
  9524. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9525. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9526. };
  9527. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9528. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9529. return false;
  9530. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9531. return false;
  9532. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9533. return false;
  9534. return true;
  9535. };
  9536. // Statics
  9537. BoundingBox.Intersects = function (box0, box1) {
  9538. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9539. return false;
  9540. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9541. return false;
  9542. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9543. return false;
  9544. return true;
  9545. };
  9546. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9547. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9548. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9549. return (num <= (sphereRadius * sphereRadius));
  9550. };
  9551. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9552. for (var p = 0; p < 6; p++) {
  9553. for (var i = 0; i < 8; i++) {
  9554. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9555. return false;
  9556. }
  9557. }
  9558. }
  9559. return true;
  9560. };
  9561. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9562. for (var p = 0; p < 6; p++) {
  9563. var inCount = 8;
  9564. for (var i = 0; i < 8; i++) {
  9565. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9566. --inCount;
  9567. }
  9568. else {
  9569. break;
  9570. }
  9571. }
  9572. if (inCount === 0)
  9573. return false;
  9574. }
  9575. return true;
  9576. };
  9577. return BoundingBox;
  9578. }());
  9579. BABYLON.BoundingBox = BoundingBox;
  9580. })(BABYLON || (BABYLON = {}));
  9581. var BABYLON;
  9582. (function (BABYLON) {
  9583. var computeBoxExtents = function (axis, box) {
  9584. var p = BABYLON.Vector3.Dot(box.center, axis);
  9585. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9586. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9587. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9588. var r = r0 + r1 + r2;
  9589. return {
  9590. min: p - r,
  9591. max: p + r
  9592. };
  9593. };
  9594. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9595. var axisOverlap = function (axis, box0, box1) {
  9596. var result0 = computeBoxExtents(axis, box0);
  9597. var result1 = computeBoxExtents(axis, box1);
  9598. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9599. };
  9600. var BoundingInfo = (function () {
  9601. function BoundingInfo(minimum, maximum) {
  9602. this.minimum = minimum;
  9603. this.maximum = maximum;
  9604. this._isLocked = false;
  9605. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9606. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9607. }
  9608. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9609. get: function () {
  9610. return this._isLocked;
  9611. },
  9612. set: function (value) {
  9613. this._isLocked = value;
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. // Methods
  9619. BoundingInfo.prototype.update = function (world) {
  9620. if (this._isLocked) {
  9621. return;
  9622. }
  9623. this.boundingBox._update(world);
  9624. this.boundingSphere._update(world);
  9625. };
  9626. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9627. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9628. return false;
  9629. return this.boundingBox.isInFrustum(frustumPlanes);
  9630. };
  9631. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9632. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9633. };
  9634. BoundingInfo.prototype._checkCollision = function (collider) {
  9635. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9636. };
  9637. BoundingInfo.prototype.intersectsPoint = function (point) {
  9638. if (!this.boundingSphere.centerWorld) {
  9639. return false;
  9640. }
  9641. if (!this.boundingSphere.intersectsPoint(point)) {
  9642. return false;
  9643. }
  9644. if (!this.boundingBox.intersectsPoint(point)) {
  9645. return false;
  9646. }
  9647. return true;
  9648. };
  9649. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9650. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9651. return false;
  9652. }
  9653. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9654. return false;
  9655. }
  9656. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9657. return false;
  9658. }
  9659. if (!precise) {
  9660. return true;
  9661. }
  9662. var box0 = this.boundingBox;
  9663. var box1 = boundingInfo.boundingBox;
  9664. if (!axisOverlap(box0.directions[0], box0, box1))
  9665. return false;
  9666. if (!axisOverlap(box0.directions[1], box0, box1))
  9667. return false;
  9668. if (!axisOverlap(box0.directions[2], box0, box1))
  9669. return false;
  9670. if (!axisOverlap(box1.directions[0], box0, box1))
  9671. return false;
  9672. if (!axisOverlap(box1.directions[1], box0, box1))
  9673. return false;
  9674. if (!axisOverlap(box1.directions[2], box0, box1))
  9675. return false;
  9676. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9677. return false;
  9678. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9679. return false;
  9680. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9681. return false;
  9682. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9683. return false;
  9684. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9685. return false;
  9686. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9687. return false;
  9688. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9689. return false;
  9690. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9691. return false;
  9692. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9693. return false;
  9694. return true;
  9695. };
  9696. return BoundingInfo;
  9697. }());
  9698. BABYLON.BoundingInfo = BoundingInfo;
  9699. })(BABYLON || (BABYLON = {}));
  9700. var BABYLON;
  9701. (function (BABYLON) {
  9702. var Ray = (function () {
  9703. function Ray(origin, direction, length) {
  9704. if (length === void 0) { length = Number.MAX_VALUE; }
  9705. this.origin = origin;
  9706. this.direction = direction;
  9707. this.length = length;
  9708. }
  9709. // Methods
  9710. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9711. var d = 0.0;
  9712. var maxValue = Number.MAX_VALUE;
  9713. var inv;
  9714. var min;
  9715. var max;
  9716. var temp;
  9717. if (Math.abs(this.direction.x) < 0.0000001) {
  9718. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9719. return false;
  9720. }
  9721. }
  9722. else {
  9723. inv = 1.0 / this.direction.x;
  9724. min = (minimum.x - this.origin.x) * inv;
  9725. max = (maximum.x - this.origin.x) * inv;
  9726. if (max === -Infinity) {
  9727. max = Infinity;
  9728. }
  9729. if (min > max) {
  9730. temp = min;
  9731. min = max;
  9732. max = temp;
  9733. }
  9734. d = Math.max(min, d);
  9735. maxValue = Math.min(max, maxValue);
  9736. if (d > maxValue) {
  9737. return false;
  9738. }
  9739. }
  9740. if (Math.abs(this.direction.y) < 0.0000001) {
  9741. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9742. return false;
  9743. }
  9744. }
  9745. else {
  9746. inv = 1.0 / this.direction.y;
  9747. min = (minimum.y - this.origin.y) * inv;
  9748. max = (maximum.y - this.origin.y) * inv;
  9749. if (max === -Infinity) {
  9750. max = Infinity;
  9751. }
  9752. if (min > max) {
  9753. temp = min;
  9754. min = max;
  9755. max = temp;
  9756. }
  9757. d = Math.max(min, d);
  9758. maxValue = Math.min(max, maxValue);
  9759. if (d > maxValue) {
  9760. return false;
  9761. }
  9762. }
  9763. if (Math.abs(this.direction.z) < 0.0000001) {
  9764. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9765. return false;
  9766. }
  9767. }
  9768. else {
  9769. inv = 1.0 / this.direction.z;
  9770. min = (minimum.z - this.origin.z) * inv;
  9771. max = (maximum.z - this.origin.z) * inv;
  9772. if (max === -Infinity) {
  9773. max = Infinity;
  9774. }
  9775. if (min > max) {
  9776. temp = min;
  9777. min = max;
  9778. max = temp;
  9779. }
  9780. d = Math.max(min, d);
  9781. maxValue = Math.min(max, maxValue);
  9782. if (d > maxValue) {
  9783. return false;
  9784. }
  9785. }
  9786. return true;
  9787. };
  9788. Ray.prototype.intersectsBox = function (box) {
  9789. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9790. };
  9791. Ray.prototype.intersectsSphere = function (sphere) {
  9792. var x = sphere.center.x - this.origin.x;
  9793. var y = sphere.center.y - this.origin.y;
  9794. var z = sphere.center.z - this.origin.z;
  9795. var pyth = (x * x) + (y * y) + (z * z);
  9796. var rr = sphere.radius * sphere.radius;
  9797. if (pyth <= rr) {
  9798. return true;
  9799. }
  9800. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9801. if (dot < 0.0) {
  9802. return false;
  9803. }
  9804. var temp = pyth - (dot * dot);
  9805. return temp <= rr;
  9806. };
  9807. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9808. if (!this._edge1) {
  9809. this._edge1 = BABYLON.Vector3.Zero();
  9810. this._edge2 = BABYLON.Vector3.Zero();
  9811. this._pvec = BABYLON.Vector3.Zero();
  9812. this._tvec = BABYLON.Vector3.Zero();
  9813. this._qvec = BABYLON.Vector3.Zero();
  9814. }
  9815. vertex1.subtractToRef(vertex0, this._edge1);
  9816. vertex2.subtractToRef(vertex0, this._edge2);
  9817. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9818. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9819. if (det === 0) {
  9820. return null;
  9821. }
  9822. var invdet = 1 / det;
  9823. this.origin.subtractToRef(vertex0, this._tvec);
  9824. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9825. if (bu < 0 || bu > 1.0) {
  9826. return null;
  9827. }
  9828. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9829. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9830. if (bv < 0 || bu + bv > 1.0) {
  9831. return null;
  9832. }
  9833. //check if the distance is longer than the predefined length.
  9834. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9835. if (distance > this.length) {
  9836. return null;
  9837. }
  9838. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9839. };
  9840. Ray.prototype.intersectsPlane = function (plane) {
  9841. var distance;
  9842. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9843. if (Math.abs(result1) < 9.99999997475243E-07) {
  9844. return null;
  9845. }
  9846. else {
  9847. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9848. distance = (-plane.d - result2) / result1;
  9849. if (distance < 0.0) {
  9850. if (distance < -9.99999997475243E-07) {
  9851. return null;
  9852. }
  9853. else {
  9854. return 0;
  9855. }
  9856. }
  9857. return distance;
  9858. }
  9859. };
  9860. /**
  9861. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9862. * @param sega the first point of the segment to test the intersection against
  9863. * @param segb the second point of the segment to test the intersection against
  9864. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9865. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9866. */
  9867. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9868. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9869. var u = segb.subtract(sega);
  9870. var v = rsegb.subtract(this.origin);
  9871. var w = sega.subtract(this.origin);
  9872. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9873. var b = BABYLON.Vector3.Dot(u, v);
  9874. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9875. var d = BABYLON.Vector3.Dot(u, w);
  9876. var e = BABYLON.Vector3.Dot(v, w);
  9877. var D = a * c - b * b; // always >= 0
  9878. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9879. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9880. // compute the line parameters of the two closest points
  9881. if (D < Ray.smallnum) {
  9882. sN = 0.0; // force using point P0 on segment S1
  9883. sD = 1.0; // to prevent possible division by 0.0 later
  9884. tN = e;
  9885. tD = c;
  9886. }
  9887. else {
  9888. sN = (b * e - c * d);
  9889. tN = (a * e - b * d);
  9890. if (sN < 0.0) {
  9891. sN = 0.0;
  9892. tN = e;
  9893. tD = c;
  9894. }
  9895. else if (sN > sD) {
  9896. sN = sD;
  9897. tN = e + b;
  9898. tD = c;
  9899. }
  9900. }
  9901. if (tN < 0.0) {
  9902. tN = 0.0;
  9903. // recompute sc for this edge
  9904. if (-d < 0.0) {
  9905. sN = 0.0;
  9906. }
  9907. else if (-d > a)
  9908. sN = sD;
  9909. else {
  9910. sN = -d;
  9911. sD = a;
  9912. }
  9913. }
  9914. else if (tN > tD) {
  9915. tN = tD;
  9916. // recompute sc for this edge
  9917. if ((-d + b) < 0.0) {
  9918. sN = 0;
  9919. }
  9920. else if ((-d + b) > a) {
  9921. sN = sD;
  9922. }
  9923. else {
  9924. sN = (-d + b);
  9925. sD = a;
  9926. }
  9927. }
  9928. // finally do the division to get sc and tc
  9929. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9930. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9931. // get the difference of the two closest points
  9932. var qtc = v.multiplyByFloats(tc, tc, tc);
  9933. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9934. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9935. if (isIntersected) {
  9936. return qtc.length();
  9937. }
  9938. return -1;
  9939. };
  9940. // Statics
  9941. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9942. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9943. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9944. var direction = end.subtract(start);
  9945. direction.normalize();
  9946. return new Ray(start, direction);
  9947. };
  9948. /**
  9949. * 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
  9950. * transformed to the given world matrix.
  9951. * @param origin The origin point
  9952. * @param end The end point
  9953. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9954. */
  9955. Ray.CreateNewFromTo = function (origin, end, world) {
  9956. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9957. var direction = end.subtract(origin);
  9958. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9959. direction.normalize();
  9960. return Ray.Transform(new Ray(origin, direction, length), world);
  9961. };
  9962. Ray.Transform = function (ray, matrix) {
  9963. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9964. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9965. newDirection.normalize();
  9966. return new Ray(newOrigin, newDirection, ray.length);
  9967. };
  9968. Ray.smallnum = 0.00000001;
  9969. Ray.rayl = 10e8;
  9970. return Ray;
  9971. }());
  9972. BABYLON.Ray = Ray;
  9973. })(BABYLON || (BABYLON = {}));
  9974. var BABYLON;
  9975. (function (BABYLON) {
  9976. var AbstractMesh = (function (_super) {
  9977. __extends(AbstractMesh, _super);
  9978. // Constructor
  9979. function AbstractMesh(name, scene) {
  9980. var _this = this;
  9981. _super.call(this, name, scene);
  9982. // Events
  9983. /**
  9984. * An event triggered when the mesh is disposed.
  9985. * @type {BABYLON.Observable}
  9986. */
  9987. this.onDisposeObservable = new BABYLON.Observable();
  9988. /**
  9989. * An event triggered when this mesh collides with another one
  9990. * @type {BABYLON.Observable}
  9991. */
  9992. this.onCollideObservable = new BABYLON.Observable();
  9993. /**
  9994. * An event triggered when the collision's position changes
  9995. * @type {BABYLON.Observable}
  9996. */
  9997. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9998. /**
  9999. * An event triggered after the world matrix is updated
  10000. * @type {BABYLON.Observable}
  10001. */
  10002. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10003. // Properties
  10004. this.definedFacingForward = true; // orientation for POV movement & rotation
  10005. this.position = new BABYLON.Vector3(0, 0, 0);
  10006. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10007. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10008. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10009. this.visibility = 1.0;
  10010. this.alphaIndex = Number.MAX_VALUE;
  10011. this.infiniteDistance = false;
  10012. this.isVisible = true;
  10013. this.isPickable = true;
  10014. this.showBoundingBox = false;
  10015. this.showSubMeshesBoundingBox = false;
  10016. this.isBlocker = false;
  10017. this.renderingGroupId = 0;
  10018. this.receiveShadows = false;
  10019. this.renderOutline = false;
  10020. this.outlineColor = BABYLON.Color3.Red();
  10021. this.outlineWidth = 0.02;
  10022. this.renderOverlay = false;
  10023. this.overlayColor = BABYLON.Color3.Red();
  10024. this.overlayAlpha = 0.5;
  10025. this.hasVertexAlpha = false;
  10026. this.useVertexColors = true;
  10027. this.applyFog = true;
  10028. this.computeBonesUsingShaders = true;
  10029. this.scalingDeterminant = 1;
  10030. this.numBoneInfluencers = 4;
  10031. this.useOctreeForRenderingSelection = true;
  10032. this.useOctreeForPicking = true;
  10033. this.useOctreeForCollisions = true;
  10034. this.layerMask = 0x0FFFFFFF;
  10035. this.alwaysSelectAsActiveMesh = false;
  10036. // Collisions
  10037. this._checkCollisions = false;
  10038. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10039. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10040. this._collider = new BABYLON.Collider();
  10041. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10042. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10043. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10044. // Edges
  10045. this.edgesWidth = 1;
  10046. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10047. // Cache
  10048. this._localWorld = BABYLON.Matrix.Zero();
  10049. this._worldMatrix = BABYLON.Matrix.Zero();
  10050. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10051. this._absolutePosition = BABYLON.Vector3.Zero();
  10052. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10053. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10054. this._isDirty = false;
  10055. this._pivotMatrix = BABYLON.Matrix.Identity();
  10056. this._isDisposed = false;
  10057. this._renderId = 0;
  10058. this._intersectionsInProgress = new Array();
  10059. this._isWorldMatrixFrozen = false;
  10060. this._unIndexed = false;
  10061. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10062. if (collidedMesh === void 0) { collidedMesh = null; }
  10063. //TODO move this to the collision coordinator!
  10064. if (_this.getScene().workerCollisions)
  10065. newPosition.multiplyInPlace(_this._collider.radius);
  10066. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10067. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10068. _this.position.addInPlace(_this._diffPositionForCollisions);
  10069. }
  10070. if (collidedMesh) {
  10071. _this.onCollideObservable.notifyObservers(collidedMesh);
  10072. }
  10073. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10074. };
  10075. scene.addMesh(this);
  10076. }
  10077. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10078. get: function () {
  10079. return AbstractMesh._BILLBOARDMODE_NONE;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10085. get: function () {
  10086. return AbstractMesh._BILLBOARDMODE_X;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10092. get: function () {
  10093. return AbstractMesh._BILLBOARDMODE_Y;
  10094. },
  10095. enumerable: true,
  10096. configurable: true
  10097. });
  10098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10099. get: function () {
  10100. return AbstractMesh._BILLBOARDMODE_Z;
  10101. },
  10102. enumerable: true,
  10103. configurable: true
  10104. });
  10105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10106. get: function () {
  10107. return AbstractMesh._BILLBOARDMODE_ALL;
  10108. },
  10109. enumerable: true,
  10110. configurable: true
  10111. });
  10112. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10113. set: function (callback) {
  10114. if (this._onDisposeObserver) {
  10115. this.onDisposeObservable.remove(this._onDisposeObserver);
  10116. }
  10117. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10123. set: function (callback) {
  10124. if (this._onCollideObserver) {
  10125. this.onCollideObservable.remove(this._onCollideObserver);
  10126. }
  10127. this._onCollideObserver = this.onCollideObservable.add(callback);
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10133. set: function (callback) {
  10134. if (this._onCollisionPositionChangeObserver) {
  10135. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10136. }
  10137. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10143. get: function () {
  10144. return this._skeleton;
  10145. },
  10146. set: function (value) {
  10147. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10148. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10149. }
  10150. if (value && value.needInitialSkinMatrix) {
  10151. value._registerMeshWithPoseMatrix(this);
  10152. }
  10153. this._skeleton = value;
  10154. if (!this._skeleton) {
  10155. this._bonesTransformMatrices = null;
  10156. }
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. /**
  10162. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10163. */
  10164. AbstractMesh.prototype.toString = function (fullDetails) {
  10165. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10166. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10167. if (this._skeleton) {
  10168. ret += ", skeleton: " + this._skeleton.name;
  10169. }
  10170. if (fullDetails) {
  10171. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10172. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10173. }
  10174. return ret;
  10175. };
  10176. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10177. /**
  10178. * Getting the rotation object.
  10179. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10180. */
  10181. get: function () {
  10182. return this._rotation;
  10183. },
  10184. set: function (newRotation) {
  10185. this._rotation = newRotation;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10191. get: function () {
  10192. return this._scaling;
  10193. },
  10194. set: function (newScaling) {
  10195. this._scaling = newScaling;
  10196. if (this.physicsImpostor) {
  10197. this.physicsImpostor.forceUpdate();
  10198. }
  10199. },
  10200. enumerable: true,
  10201. configurable: true
  10202. });
  10203. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10204. get: function () {
  10205. return this._rotationQuaternion;
  10206. },
  10207. set: function (quaternion) {
  10208. this._rotationQuaternion = quaternion;
  10209. //reset the rotation vector.
  10210. if (quaternion && this.rotation.length()) {
  10211. this.rotation.copyFromFloats(0, 0, 0);
  10212. }
  10213. },
  10214. enumerable: true,
  10215. configurable: true
  10216. });
  10217. // Methods
  10218. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10219. this._poseMatrix.copyFrom(matrix);
  10220. };
  10221. AbstractMesh.prototype.getPoseMatrix = function () {
  10222. return this._poseMatrix;
  10223. };
  10224. AbstractMesh.prototype.disableEdgesRendering = function () {
  10225. if (this._edgesRenderer !== undefined) {
  10226. this._edgesRenderer.dispose();
  10227. this._edgesRenderer = undefined;
  10228. }
  10229. };
  10230. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10231. if (epsilon === void 0) { epsilon = 0.95; }
  10232. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10233. this.disableEdgesRendering();
  10234. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10235. };
  10236. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10237. get: function () {
  10238. return false;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. AbstractMesh.prototype.getLOD = function (camera) {
  10244. return this;
  10245. };
  10246. AbstractMesh.prototype.getTotalVertices = function () {
  10247. return 0;
  10248. };
  10249. AbstractMesh.prototype.getIndices = function () {
  10250. return null;
  10251. };
  10252. AbstractMesh.prototype.getVerticesData = function (kind) {
  10253. return null;
  10254. };
  10255. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10256. return false;
  10257. };
  10258. AbstractMesh.prototype.getBoundingInfo = function () {
  10259. if (this._masterMesh) {
  10260. return this._masterMesh.getBoundingInfo();
  10261. }
  10262. if (!this._boundingInfo) {
  10263. this._updateBoundingInfo();
  10264. }
  10265. return this._boundingInfo;
  10266. };
  10267. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10268. this._boundingInfo = boundingInfo;
  10269. };
  10270. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10271. get: function () {
  10272. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. AbstractMesh.prototype._preActivate = function () {
  10278. };
  10279. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10280. };
  10281. AbstractMesh.prototype._activate = function (renderId) {
  10282. this._renderId = renderId;
  10283. };
  10284. AbstractMesh.prototype.getWorldMatrix = function () {
  10285. if (this._masterMesh) {
  10286. return this._masterMesh.getWorldMatrix();
  10287. }
  10288. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10289. this.computeWorldMatrix();
  10290. }
  10291. return this._worldMatrix;
  10292. };
  10293. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10294. get: function () {
  10295. return this._worldMatrix;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10301. get: function () {
  10302. return this._absolutePosition;
  10303. },
  10304. enumerable: true,
  10305. configurable: true
  10306. });
  10307. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10308. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10309. this.computeWorldMatrix(true);
  10310. this._isWorldMatrixFrozen = true;
  10311. };
  10312. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10313. this._isWorldMatrixFrozen = false;
  10314. this.computeWorldMatrix(true);
  10315. };
  10316. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10317. get: function () {
  10318. return this._isWorldMatrixFrozen;
  10319. },
  10320. enumerable: true,
  10321. configurable: true
  10322. });
  10323. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10324. axis.normalize();
  10325. if (!this.rotationQuaternion) {
  10326. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10327. this.rotation = BABYLON.Vector3.Zero();
  10328. }
  10329. var rotationQuaternion;
  10330. if (!space || space === BABYLON.Space.LOCAL) {
  10331. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10332. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10333. }
  10334. else {
  10335. if (this.parent) {
  10336. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10337. invertParentWorldMatrix.invert();
  10338. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10339. }
  10340. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10341. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10342. }
  10343. };
  10344. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10345. var displacementVector = axis.scale(distance);
  10346. if (!space || space === BABYLON.Space.LOCAL) {
  10347. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10348. this.setPositionWithLocalVector(tempV3);
  10349. }
  10350. else {
  10351. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10352. }
  10353. };
  10354. AbstractMesh.prototype.getAbsolutePosition = function () {
  10355. this.computeWorldMatrix();
  10356. return this._absolutePosition;
  10357. };
  10358. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10359. if (!absolutePosition) {
  10360. return;
  10361. }
  10362. var absolutePositionX;
  10363. var absolutePositionY;
  10364. var absolutePositionZ;
  10365. if (absolutePosition.x === undefined) {
  10366. if (arguments.length < 3) {
  10367. return;
  10368. }
  10369. absolutePositionX = arguments[0];
  10370. absolutePositionY = arguments[1];
  10371. absolutePositionZ = arguments[2];
  10372. }
  10373. else {
  10374. absolutePositionX = absolutePosition.x;
  10375. absolutePositionY = absolutePosition.y;
  10376. absolutePositionZ = absolutePosition.z;
  10377. }
  10378. if (this.parent) {
  10379. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10380. invertParentWorldMatrix.invert();
  10381. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10382. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10383. }
  10384. else {
  10385. this.position.x = absolutePositionX;
  10386. this.position.y = absolutePositionY;
  10387. this.position.z = absolutePositionZ;
  10388. }
  10389. };
  10390. // ================================== Point of View Movement =================================
  10391. /**
  10392. * Perform relative position change from the point of view of behind the front of the mesh.
  10393. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10394. * Supports definition of mesh facing forward or backward.
  10395. * @param {number} amountRight
  10396. * @param {number} amountUp
  10397. * @param {number} amountForward
  10398. */
  10399. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10400. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10401. };
  10402. /**
  10403. * Calculate relative position change from the point of view of behind the front of the mesh.
  10404. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10405. * Supports definition of mesh facing forward or backward.
  10406. * @param {number} amountRight
  10407. * @param {number} amountUp
  10408. * @param {number} amountForward
  10409. */
  10410. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10411. var rotMatrix = new BABYLON.Matrix();
  10412. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10413. rotQuaternion.toRotationMatrix(rotMatrix);
  10414. var translationDelta = BABYLON.Vector3.Zero();
  10415. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10417. return translationDelta;
  10418. };
  10419. // ================================== Point of View Rotation =================================
  10420. /**
  10421. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10422. * Supports definition of mesh facing forward or backward.
  10423. * @param {number} flipBack
  10424. * @param {number} twirlClockwise
  10425. * @param {number} tiltRight
  10426. */
  10427. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10428. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10429. };
  10430. /**
  10431. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10432. * Supports definition of mesh facing forward or backward.
  10433. * @param {number} flipBack
  10434. * @param {number} twirlClockwise
  10435. * @param {number} tiltRight
  10436. */
  10437. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10438. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10439. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10440. };
  10441. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10442. this._pivotMatrix = matrix;
  10443. this._cache.pivotMatrixUpdated = true;
  10444. };
  10445. AbstractMesh.prototype.getPivotMatrix = function () {
  10446. return this._pivotMatrix;
  10447. };
  10448. AbstractMesh.prototype._isSynchronized = function () {
  10449. if (this._isDirty) {
  10450. return false;
  10451. }
  10452. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10453. return false;
  10454. if (this._cache.pivotMatrixUpdated) {
  10455. return false;
  10456. }
  10457. if (this.infiniteDistance) {
  10458. return false;
  10459. }
  10460. if (!this._cache.position.equals(this.position))
  10461. return false;
  10462. if (this.rotationQuaternion) {
  10463. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10464. return false;
  10465. }
  10466. if (!this._cache.rotation.equals(this.rotation))
  10467. return false;
  10468. if (!this._cache.scaling.equals(this.scaling))
  10469. return false;
  10470. return true;
  10471. };
  10472. AbstractMesh.prototype._initCache = function () {
  10473. _super.prototype._initCache.call(this);
  10474. this._cache.localMatrixUpdated = false;
  10475. this._cache.position = BABYLON.Vector3.Zero();
  10476. this._cache.scaling = BABYLON.Vector3.Zero();
  10477. this._cache.rotation = BABYLON.Vector3.Zero();
  10478. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10479. this._cache.billboardMode = -1;
  10480. };
  10481. AbstractMesh.prototype.markAsDirty = function (property) {
  10482. if (property === "rotation") {
  10483. this.rotationQuaternion = null;
  10484. }
  10485. this._currentRenderId = Number.MAX_VALUE;
  10486. this._isDirty = true;
  10487. };
  10488. AbstractMesh.prototype._updateBoundingInfo = function () {
  10489. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10490. this._boundingInfo.update(this.worldMatrixFromCache);
  10491. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10492. };
  10493. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10494. if (!this.subMeshes) {
  10495. return;
  10496. }
  10497. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10498. var subMesh = this.subMeshes[subIndex];
  10499. if (!subMesh.IsGlobal) {
  10500. subMesh.updateBoundingInfo(matrix);
  10501. }
  10502. }
  10503. };
  10504. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10505. if (this._isWorldMatrixFrozen) {
  10506. return this._worldMatrix;
  10507. }
  10508. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10509. this._currentRenderId = this.getScene().getRenderId();
  10510. return this._worldMatrix;
  10511. }
  10512. this._cache.position.copyFrom(this.position);
  10513. this._cache.scaling.copyFrom(this.scaling);
  10514. this._cache.pivotMatrixUpdated = false;
  10515. this._cache.billboardMode = this.billboardMode;
  10516. this._currentRenderId = this.getScene().getRenderId();
  10517. this._isDirty = false;
  10518. // Scaling
  10519. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10520. // Rotation
  10521. //rotate, if quaternion is set and rotation was used
  10522. if (this.rotationQuaternion) {
  10523. var len = this.rotation.length();
  10524. if (len) {
  10525. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10526. this.rotation.copyFromFloats(0, 0, 0);
  10527. }
  10528. }
  10529. if (this.rotationQuaternion) {
  10530. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10531. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10532. }
  10533. else {
  10534. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10535. this._cache.rotation.copyFrom(this.rotation);
  10536. }
  10537. // Translation
  10538. if (this.infiniteDistance && !this.parent) {
  10539. var camera = this.getScene().activeCamera;
  10540. if (camera) {
  10541. var cameraWorldMatrix = camera.getWorldMatrix();
  10542. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10543. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10544. }
  10545. }
  10546. else {
  10547. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10548. }
  10549. // Composing transformations
  10550. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10551. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10552. // Billboarding
  10553. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10554. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10555. var localPosition = BABYLON.Tmp.Vector3[0];
  10556. if (this.parent && this.parent.getWorldMatrix) {
  10557. this._markSyncedWithParent();
  10558. var parentMatrix;
  10559. if (this._meshToBoneReferal) {
  10560. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10561. parentMatrix = BABYLON.Tmp.Matrix[6];
  10562. }
  10563. else {
  10564. parentMatrix = this.parent.getWorldMatrix();
  10565. }
  10566. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10567. localPosition = BABYLON.Tmp.Vector3[1];
  10568. }
  10569. var zero = this.getScene().activeCamera.globalPosition.clone();
  10570. if (this.parent && this.parent.position) {
  10571. localPosition.addInPlace(this.parent.position);
  10572. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10573. }
  10574. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10575. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10576. zero.x = localPosition.x + BABYLON.Epsilon;
  10577. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10578. zero.y = localPosition.y + BABYLON.Epsilon;
  10579. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10580. zero.z = localPosition.z + BABYLON.Epsilon;
  10581. }
  10582. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10583. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10584. BABYLON.Tmp.Matrix[3].invert();
  10585. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10586. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10587. }
  10588. // Local world
  10589. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10590. // Parent
  10591. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10592. this._markSyncedWithParent();
  10593. if (this._meshToBoneReferal) {
  10594. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10595. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10596. }
  10597. else {
  10598. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10599. }
  10600. }
  10601. else {
  10602. this._worldMatrix.copyFrom(this._localWorld);
  10603. }
  10604. // Bounding info
  10605. this._updateBoundingInfo();
  10606. // Absolute position
  10607. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10608. // Callbacks
  10609. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10610. if (!this._poseMatrix) {
  10611. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10612. }
  10613. return this._worldMatrix;
  10614. };
  10615. /**
  10616. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10617. * @param func: callback function to add
  10618. */
  10619. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10620. this.onAfterWorldMatrixUpdateObservable.add(func);
  10621. };
  10622. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10623. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10624. };
  10625. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10626. this.computeWorldMatrix();
  10627. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10628. };
  10629. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10630. this.computeWorldMatrix();
  10631. var invLocalWorldMatrix = this._localWorld.clone();
  10632. invLocalWorldMatrix.invert();
  10633. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10634. };
  10635. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10636. this.computeWorldMatrix(true);
  10637. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10638. };
  10639. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10640. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10641. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10642. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10643. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10644. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10645. /// <returns>Mesh oriented towards targetMesh</returns>
  10646. if (yawCor === void 0) { yawCor = 0; }
  10647. if (pitchCor === void 0) { pitchCor = 0; }
  10648. if (rollCor === void 0) { rollCor = 0; }
  10649. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10650. var dv = AbstractMesh._lookAtVectorCache;
  10651. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10652. targetPoint.subtractToRef(pos, dv);
  10653. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10654. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10655. var pitch = Math.atan2(dv.y, len);
  10656. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10657. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10658. };
  10659. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10660. this._meshToBoneReferal = affectedMesh;
  10661. this.parent = bone;
  10662. if (bone.getWorldMatrix().determinant() < 0) {
  10663. this.scalingDeterminant *= -1;
  10664. }
  10665. };
  10666. AbstractMesh.prototype.detachFromBone = function () {
  10667. if (this.parent.getWorldMatrix().determinant() < 0) {
  10668. this.scalingDeterminant *= -1;
  10669. }
  10670. this._meshToBoneReferal = null;
  10671. this.parent = null;
  10672. };
  10673. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10674. return this._boundingInfo.isInFrustum(frustumPlanes);
  10675. };
  10676. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10677. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10678. ;
  10679. };
  10680. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10681. if (!this._boundingInfo || !mesh._boundingInfo) {
  10682. return false;
  10683. }
  10684. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10685. };
  10686. AbstractMesh.prototype.intersectsPoint = function (point) {
  10687. if (!this._boundingInfo) {
  10688. return false;
  10689. }
  10690. return this._boundingInfo.intersectsPoint(point);
  10691. };
  10692. // Physics
  10693. /**
  10694. * @Deprecated. Use new PhysicsImpostor instead.
  10695. * */
  10696. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10697. //legacy support
  10698. if (impostor.impostor) {
  10699. options = impostor;
  10700. impostor = impostor.impostor;
  10701. }
  10702. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10703. return this.physicsImpostor.physicsBody;
  10704. };
  10705. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10706. return this.physicsImpostor;
  10707. };
  10708. /**
  10709. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10710. */
  10711. AbstractMesh.prototype.getPhysicsMass = function () {
  10712. return this.physicsImpostor.getParam("mass");
  10713. };
  10714. /**
  10715. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10716. */
  10717. AbstractMesh.prototype.getPhysicsFriction = function () {
  10718. return this.physicsImpostor.getParam("friction");
  10719. };
  10720. /**
  10721. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10722. */
  10723. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10724. return this.physicsImpostor.getParam("restitution");
  10725. };
  10726. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10727. if (!camera) {
  10728. camera = this.getScene().activeCamera;
  10729. }
  10730. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10731. };
  10732. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10733. if (!camera) {
  10734. camera = this.getScene().activeCamera;
  10735. }
  10736. return this.absolutePosition.subtract(camera.position).length();
  10737. };
  10738. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10739. if (!this.physicsImpostor) {
  10740. return;
  10741. }
  10742. this.physicsImpostor.applyImpulse(force, contactPoint);
  10743. };
  10744. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10745. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10746. return;
  10747. }
  10748. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10749. mainPivot: pivot1,
  10750. connectedPivot: pivot2,
  10751. nativeParams: options
  10752. });
  10753. };
  10754. /**
  10755. * @Deprecated
  10756. */
  10757. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10758. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10759. this.updatePhysicsBody();
  10760. };
  10761. /**
  10762. * @Deprecated
  10763. * Calling this function is not needed anymore.
  10764. * The physics engine takes care of transofmration automatically.
  10765. */
  10766. AbstractMesh.prototype.updatePhysicsBody = function () {
  10767. //Unneeded
  10768. };
  10769. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10770. // Collisions
  10771. get: function () {
  10772. return this._checkCollisions;
  10773. },
  10774. set: function (collisionEnabled) {
  10775. this._checkCollisions = collisionEnabled;
  10776. if (this.getScene().workerCollisions) {
  10777. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10778. }
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10784. var globalPosition = this.getAbsolutePosition();
  10785. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10786. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10787. this._collider.radius = this.ellipsoid;
  10788. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10789. };
  10790. // Submeshes octree
  10791. /**
  10792. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10793. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10794. */
  10795. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10796. if (maxCapacity === void 0) { maxCapacity = 64; }
  10797. if (maxDepth === void 0) { maxDepth = 2; }
  10798. if (!this._submeshesOctree) {
  10799. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10800. }
  10801. this.computeWorldMatrix(true);
  10802. // Update octree
  10803. var bbox = this.getBoundingInfo().boundingBox;
  10804. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10805. return this._submeshesOctree;
  10806. };
  10807. // Collisions
  10808. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10809. this._generatePointsArray();
  10810. // Transformation
  10811. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10812. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10813. subMesh._lastColliderWorldVertices = [];
  10814. subMesh._trianglePlanes = [];
  10815. var start = subMesh.verticesStart;
  10816. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10817. for (var i = start; i < end; i++) {
  10818. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10819. }
  10820. }
  10821. // Collide
  10822. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10823. if (collider.collisionFound) {
  10824. collider.collidedMesh = this;
  10825. }
  10826. };
  10827. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10828. var subMeshes;
  10829. var len;
  10830. // Octrees
  10831. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10832. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10833. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10834. len = intersections.length;
  10835. subMeshes = intersections.data;
  10836. }
  10837. else {
  10838. subMeshes = this.subMeshes;
  10839. len = subMeshes.length;
  10840. }
  10841. for (var index = 0; index < len; index++) {
  10842. var subMesh = subMeshes[index];
  10843. // Bounding test
  10844. if (len > 1 && !subMesh._checkCollision(collider))
  10845. continue;
  10846. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10847. }
  10848. };
  10849. AbstractMesh.prototype._checkCollision = function (collider) {
  10850. // Bounding box test
  10851. if (!this._boundingInfo._checkCollision(collider))
  10852. return;
  10853. // Transformation matrix
  10854. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10855. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10856. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10857. };
  10858. // Picking
  10859. AbstractMesh.prototype._generatePointsArray = function () {
  10860. return false;
  10861. };
  10862. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10863. var pickingInfo = new BABYLON.PickingInfo();
  10864. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10865. return pickingInfo;
  10866. }
  10867. if (!this._generatePointsArray()) {
  10868. return pickingInfo;
  10869. }
  10870. var intersectInfo = null;
  10871. // Octrees
  10872. var subMeshes;
  10873. var len;
  10874. if (this._submeshesOctree && this.useOctreeForPicking) {
  10875. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10876. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10877. len = intersections.length;
  10878. subMeshes = intersections.data;
  10879. }
  10880. else {
  10881. subMeshes = this.subMeshes;
  10882. len = subMeshes.length;
  10883. }
  10884. for (var index = 0; index < len; index++) {
  10885. var subMesh = subMeshes[index];
  10886. // Bounding test
  10887. if (len > 1 && !subMesh.canIntersects(ray))
  10888. continue;
  10889. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10890. if (currentIntersectInfo) {
  10891. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10892. intersectInfo = currentIntersectInfo;
  10893. intersectInfo.subMeshId = index;
  10894. if (fastCheck) {
  10895. break;
  10896. }
  10897. }
  10898. }
  10899. }
  10900. if (intersectInfo) {
  10901. // Get picked point
  10902. var world = this.getWorldMatrix();
  10903. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10904. var direction = ray.direction.clone();
  10905. direction = direction.scale(intersectInfo.distance);
  10906. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10907. var pickedPoint = worldOrigin.add(worldDirection);
  10908. // Return result
  10909. pickingInfo.hit = true;
  10910. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10911. pickingInfo.pickedPoint = pickedPoint;
  10912. pickingInfo.pickedMesh = this;
  10913. pickingInfo.bu = intersectInfo.bu;
  10914. pickingInfo.bv = intersectInfo.bv;
  10915. pickingInfo.faceId = intersectInfo.faceId;
  10916. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10917. return pickingInfo;
  10918. }
  10919. return pickingInfo;
  10920. };
  10921. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10922. return null;
  10923. };
  10924. AbstractMesh.prototype.releaseSubMeshes = function () {
  10925. if (this.subMeshes) {
  10926. while (this.subMeshes.length) {
  10927. this.subMeshes[0].dispose();
  10928. }
  10929. }
  10930. else {
  10931. this.subMeshes = new Array();
  10932. }
  10933. };
  10934. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10935. var _this = this;
  10936. var index;
  10937. // Action manager
  10938. if (this.actionManager) {
  10939. this.actionManager.dispose();
  10940. this.actionManager = null;
  10941. }
  10942. // Skeleton
  10943. this.skeleton = null;
  10944. // Animations
  10945. this.getScene().stopAnimation(this);
  10946. // Physics
  10947. if (this.physicsImpostor) {
  10948. this.physicsImpostor.dispose();
  10949. }
  10950. // Intersections in progress
  10951. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10952. var other = this._intersectionsInProgress[index];
  10953. var pos = other._intersectionsInProgress.indexOf(this);
  10954. other._intersectionsInProgress.splice(pos, 1);
  10955. }
  10956. this._intersectionsInProgress = [];
  10957. // Lights
  10958. var lights = this.getScene().lights;
  10959. lights.forEach(function (light) {
  10960. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10961. if (meshIndex !== -1) {
  10962. light.includedOnlyMeshes.splice(meshIndex, 1);
  10963. }
  10964. meshIndex = light.excludedMeshes.indexOf(_this);
  10965. if (meshIndex !== -1) {
  10966. light.excludedMeshes.splice(meshIndex, 1);
  10967. }
  10968. // Shadow generators
  10969. var generator = light.getShadowGenerator();
  10970. if (generator) {
  10971. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  10972. if (meshIndex !== -1) {
  10973. generator.getShadowMap().renderList.splice(meshIndex, 1);
  10974. }
  10975. }
  10976. });
  10977. // Edges
  10978. if (this._edgesRenderer) {
  10979. this._edgesRenderer.dispose();
  10980. this._edgesRenderer = null;
  10981. }
  10982. // SubMeshes
  10983. this.releaseSubMeshes();
  10984. // Remove from scene
  10985. this.getScene().removeMesh(this);
  10986. if (!doNotRecurse) {
  10987. // Particles
  10988. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10989. if (this.getScene().particleSystems[index].emitter === this) {
  10990. this.getScene().particleSystems[index].dispose();
  10991. index--;
  10992. }
  10993. }
  10994. // Children
  10995. var objects = this.getDescendants(true);
  10996. for (index = 0; index < objects.length; index++) {
  10997. objects[index].dispose();
  10998. }
  10999. }
  11000. else {
  11001. var childMeshes = this.getChildMeshes(true);
  11002. for (index = 0; index < childMeshes.length; index++) {
  11003. var child = childMeshes[index];
  11004. child.parent = null;
  11005. child.computeWorldMatrix(true);
  11006. }
  11007. }
  11008. _super.prototype.dispose.call(this);
  11009. this.onAfterWorldMatrixUpdateObservable.clear();
  11010. this.onCollideObservable.clear();
  11011. this.onCollisionPositionChangeObservable.clear();
  11012. this._isDisposed = true;
  11013. // Callback
  11014. this.onDisposeObservable.notifyObservers(this);
  11015. this.onDisposeObservable.clear();
  11016. };
  11017. // Statics
  11018. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11019. AbstractMesh._BILLBOARDMODE_X = 1;
  11020. AbstractMesh._BILLBOARDMODE_Y = 2;
  11021. AbstractMesh._BILLBOARDMODE_Z = 4;
  11022. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11023. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11024. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11025. return AbstractMesh;
  11026. }(BABYLON.Node));
  11027. BABYLON.AbstractMesh = AbstractMesh;
  11028. })(BABYLON || (BABYLON = {}));
  11029. var BABYLON;
  11030. (function (BABYLON) {
  11031. var Light = (function (_super) {
  11032. __extends(Light, _super);
  11033. function Light(name, scene) {
  11034. _super.call(this, name, scene);
  11035. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11036. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11037. this.intensity = 1.0;
  11038. this.range = Number.MAX_VALUE;
  11039. this.includeOnlyWithLayerMask = 0;
  11040. this.includedOnlyMeshes = new Array();
  11041. this.excludedMeshes = new Array();
  11042. this.excludeWithLayerMask = 0;
  11043. this.lightmapMode = 0;
  11044. // PBR Properties.
  11045. this.radius = 0.00001;
  11046. this._excludedMeshesIds = new Array();
  11047. this._includedOnlyMeshesIds = new Array();
  11048. scene.addLight(this);
  11049. }
  11050. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11051. /**
  11052. * If every light affecting the material is in this lightmapMode,
  11053. * material.lightmapTexture adds or multiplies
  11054. * (depends on material.useLightmapAsShadowmap)
  11055. * after every other light calculations.
  11056. */
  11057. get: function () {
  11058. return Light._LIGHTMAP_DEFAULT;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11064. /**
  11065. * material.lightmapTexture as only diffuse lighting from this light
  11066. * adds pnly specular lighting from this light
  11067. * adds dynamic shadows
  11068. */
  11069. get: function () {
  11070. return Light._LIGHTMAP_SPECULAR;
  11071. },
  11072. enumerable: true,
  11073. configurable: true
  11074. });
  11075. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11076. /**
  11077. * material.lightmapTexture as only lighting
  11078. * no light calculation from this light
  11079. * only adds dynamic shadows from this light
  11080. */
  11081. get: function () {
  11082. return Light._LIGHTMAP_SHADOWSONLY;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. /**
  11088. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11089. */
  11090. Light.prototype.toString = function (fullDetails) {
  11091. var ret = "Name: " + this.name;
  11092. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11093. if (this.animations) {
  11094. for (var i = 0; i < this.animations.length; i++) {
  11095. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11096. }
  11097. }
  11098. if (fullDetails) {
  11099. }
  11100. return ret;
  11101. };
  11102. Light.prototype.getShadowGenerator = function () {
  11103. return this._shadowGenerator;
  11104. };
  11105. Light.prototype.getAbsolutePosition = function () {
  11106. return BABYLON.Vector3.Zero();
  11107. };
  11108. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11109. };
  11110. Light.prototype._getWorldMatrix = function () {
  11111. return BABYLON.Matrix.Identity();
  11112. };
  11113. Light.prototype.canAffectMesh = function (mesh) {
  11114. if (!mesh) {
  11115. return true;
  11116. }
  11117. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11118. return false;
  11119. }
  11120. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11121. return false;
  11122. }
  11123. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11124. return false;
  11125. }
  11126. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11127. return false;
  11128. }
  11129. return true;
  11130. };
  11131. Light.prototype.getWorldMatrix = function () {
  11132. this._currentRenderId = this.getScene().getRenderId();
  11133. var worldMatrix = this._getWorldMatrix();
  11134. if (this.parent && this.parent.getWorldMatrix) {
  11135. if (!this._parentedWorldMatrix) {
  11136. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11137. }
  11138. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11139. this._markSyncedWithParent();
  11140. return this._parentedWorldMatrix;
  11141. }
  11142. return worldMatrix;
  11143. };
  11144. Light.prototype.dispose = function () {
  11145. if (this._shadowGenerator) {
  11146. this._shadowGenerator.dispose();
  11147. this._shadowGenerator = null;
  11148. }
  11149. // Animations
  11150. this.getScene().stopAnimation(this);
  11151. // Remove from scene
  11152. this.getScene().removeLight(this);
  11153. _super.prototype.dispose.call(this);
  11154. };
  11155. Light.prototype.getTypeID = function () {
  11156. return 0;
  11157. };
  11158. Light.prototype.clone = function (name) {
  11159. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11160. };
  11161. Light.prototype.serialize = function () {
  11162. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11163. // Type
  11164. serializationObject.type = this.getTypeID();
  11165. // Parent
  11166. if (this.parent) {
  11167. serializationObject.parentId = this.parent.id;
  11168. }
  11169. // Inclusion / exclusions
  11170. if (this.excludedMeshes.length > 0) {
  11171. serializationObject.excludedMeshesIds = [];
  11172. this.excludedMeshes.forEach(function (mesh) {
  11173. serializationObject.excludedMeshesIds.push(mesh.id);
  11174. });
  11175. }
  11176. if (this.includedOnlyMeshes.length > 0) {
  11177. serializationObject.includedOnlyMeshesIds = [];
  11178. this.includedOnlyMeshes.forEach(function (mesh) {
  11179. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11180. });
  11181. }
  11182. // Animations
  11183. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11184. serializationObject.ranges = this.serializeAnimationRanges();
  11185. return serializationObject;
  11186. };
  11187. Light.GetConstructorFromName = function (type, name, scene) {
  11188. switch (type) {
  11189. case 0:
  11190. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11191. case 1:
  11192. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11193. case 2:
  11194. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11195. case 3:
  11196. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11197. }
  11198. };
  11199. Light.Parse = function (parsedLight, scene) {
  11200. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11201. // Inclusion / exclusions
  11202. if (parsedLight.excludedMeshesIds) {
  11203. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11204. }
  11205. if (parsedLight.includedOnlyMeshesIds) {
  11206. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11207. }
  11208. // Parent
  11209. if (parsedLight.parentId) {
  11210. light._waitingParentId = parsedLight.parentId;
  11211. }
  11212. // Animations
  11213. if (parsedLight.animations) {
  11214. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11215. var parsedAnimation = parsedLight.animations[animationIndex];
  11216. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11217. }
  11218. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11219. }
  11220. if (parsedLight.autoAnimate) {
  11221. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11222. }
  11223. return light;
  11224. };
  11225. //lightmapMode Consts
  11226. Light._LIGHTMAP_DEFAULT = 0;
  11227. Light._LIGHTMAP_SPECULAR = 1;
  11228. Light._LIGHTMAP_SHADOWSONLY = 2;
  11229. __decorate([
  11230. BABYLON.serializeAsColor3()
  11231. ], Light.prototype, "diffuse", void 0);
  11232. __decorate([
  11233. BABYLON.serializeAsColor3()
  11234. ], Light.prototype, "specular", void 0);
  11235. __decorate([
  11236. BABYLON.serialize()
  11237. ], Light.prototype, "intensity", void 0);
  11238. __decorate([
  11239. BABYLON.serialize()
  11240. ], Light.prototype, "range", void 0);
  11241. __decorate([
  11242. BABYLON.serialize()
  11243. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11244. __decorate([
  11245. BABYLON.serialize()
  11246. ], Light.prototype, "excludeWithLayerMask", void 0);
  11247. __decorate([
  11248. BABYLON.serialize()
  11249. ], Light.prototype, "lightmapMode", void 0);
  11250. __decorate([
  11251. BABYLON.serialize()
  11252. ], Light.prototype, "radius", void 0);
  11253. return Light;
  11254. }(BABYLON.Node));
  11255. BABYLON.Light = Light;
  11256. })(BABYLON || (BABYLON = {}));
  11257. var BABYLON;
  11258. (function (BABYLON) {
  11259. var PointLight = (function (_super) {
  11260. __extends(PointLight, _super);
  11261. function PointLight(name, position, scene) {
  11262. _super.call(this, name, scene);
  11263. this.position = position;
  11264. }
  11265. PointLight.prototype.getAbsolutePosition = function () {
  11266. return this.transformedPosition ? this.transformedPosition : this.position;
  11267. };
  11268. PointLight.prototype.computeTransformedPosition = function () {
  11269. if (this.parent && this.parent.getWorldMatrix) {
  11270. if (!this.transformedPosition) {
  11271. this.transformedPosition = BABYLON.Vector3.Zero();
  11272. }
  11273. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11274. return true;
  11275. }
  11276. return false;
  11277. };
  11278. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11279. if (this.parent && this.parent.getWorldMatrix) {
  11280. this.computeTransformedPosition();
  11281. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11282. return;
  11283. }
  11284. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11285. };
  11286. PointLight.prototype.needCube = function () {
  11287. return true;
  11288. };
  11289. PointLight.prototype.supportsVSM = function () {
  11290. return false;
  11291. };
  11292. PointLight.prototype.needRefreshPerFrame = function () {
  11293. return false;
  11294. };
  11295. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11296. switch (faceIndex) {
  11297. case 0:
  11298. return new BABYLON.Vector3(1, 0, 0);
  11299. case 1:
  11300. return new BABYLON.Vector3(-1, 0, 0);
  11301. case 2:
  11302. return new BABYLON.Vector3(0, -1, 0);
  11303. case 3:
  11304. return new BABYLON.Vector3(0, 1, 0);
  11305. case 4:
  11306. return new BABYLON.Vector3(0, 0, 1);
  11307. case 5:
  11308. return new BABYLON.Vector3(0, 0, -1);
  11309. }
  11310. return BABYLON.Vector3.Zero();
  11311. };
  11312. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11313. var activeCamera = this.getScene().activeCamera;
  11314. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11315. };
  11316. PointLight.prototype._getWorldMatrix = function () {
  11317. if (!this._worldMatrix) {
  11318. this._worldMatrix = BABYLON.Matrix.Identity();
  11319. }
  11320. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11321. return this._worldMatrix;
  11322. };
  11323. PointLight.prototype.getTypeID = function () {
  11324. return 0;
  11325. };
  11326. __decorate([
  11327. BABYLON.serializeAsVector3()
  11328. ], PointLight.prototype, "position", void 0);
  11329. return PointLight;
  11330. }(BABYLON.Light));
  11331. BABYLON.PointLight = PointLight;
  11332. })(BABYLON || (BABYLON = {}));
  11333. var BABYLON;
  11334. (function (BABYLON) {
  11335. var SpotLight = (function (_super) {
  11336. __extends(SpotLight, _super);
  11337. function SpotLight(name, position, direction, angle, exponent, scene) {
  11338. _super.call(this, name, scene);
  11339. this.position = position;
  11340. this.direction = direction;
  11341. this.angle = angle;
  11342. this.exponent = exponent;
  11343. }
  11344. SpotLight.prototype.getAbsolutePosition = function () {
  11345. return this.transformedPosition ? this.transformedPosition : this.position;
  11346. };
  11347. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11348. var activeCamera = this.getScene().activeCamera;
  11349. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11350. };
  11351. SpotLight.prototype.needCube = function () {
  11352. return false;
  11353. };
  11354. SpotLight.prototype.supportsVSM = function () {
  11355. return true;
  11356. };
  11357. SpotLight.prototype.needRefreshPerFrame = function () {
  11358. return false;
  11359. };
  11360. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11361. return this.direction;
  11362. };
  11363. SpotLight.prototype.setDirectionToTarget = function (target) {
  11364. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11365. return this.direction;
  11366. };
  11367. SpotLight.prototype.computeTransformedPosition = function () {
  11368. if (this.parent && this.parent.getWorldMatrix) {
  11369. if (!this.transformedPosition) {
  11370. this.transformedPosition = BABYLON.Vector3.Zero();
  11371. }
  11372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11373. return true;
  11374. }
  11375. return false;
  11376. };
  11377. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11378. var normalizeDirection;
  11379. if (this.parent && this.parent.getWorldMatrix) {
  11380. if (!this._transformedDirection) {
  11381. this._transformedDirection = BABYLON.Vector3.Zero();
  11382. }
  11383. this.computeTransformedPosition();
  11384. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11385. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11386. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11387. }
  11388. else {
  11389. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11390. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11391. }
  11392. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11393. };
  11394. SpotLight.prototype._getWorldMatrix = function () {
  11395. if (!this._worldMatrix) {
  11396. this._worldMatrix = BABYLON.Matrix.Identity();
  11397. }
  11398. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11399. return this._worldMatrix;
  11400. };
  11401. SpotLight.prototype.getTypeID = function () {
  11402. return 2;
  11403. };
  11404. __decorate([
  11405. BABYLON.serializeAsVector3()
  11406. ], SpotLight.prototype, "position", void 0);
  11407. __decorate([
  11408. BABYLON.serializeAsVector3()
  11409. ], SpotLight.prototype, "direction", void 0);
  11410. __decorate([
  11411. BABYLON.serialize()
  11412. ], SpotLight.prototype, "angle", void 0);
  11413. __decorate([
  11414. BABYLON.serialize()
  11415. ], SpotLight.prototype, "exponent", void 0);
  11416. return SpotLight;
  11417. }(BABYLON.Light));
  11418. BABYLON.SpotLight = SpotLight;
  11419. })(BABYLON || (BABYLON = {}));
  11420. var BABYLON;
  11421. (function (BABYLON) {
  11422. var HemisphericLight = (function (_super) {
  11423. __extends(HemisphericLight, _super);
  11424. function HemisphericLight(name, direction, scene) {
  11425. _super.call(this, name, scene);
  11426. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11427. this.direction = direction;
  11428. }
  11429. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11430. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11431. return this.direction;
  11432. };
  11433. HemisphericLight.prototype.getShadowGenerator = function () {
  11434. return null;
  11435. };
  11436. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11437. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11438. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11439. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11440. };
  11441. HemisphericLight.prototype._getWorldMatrix = function () {
  11442. if (!this._worldMatrix) {
  11443. this._worldMatrix = BABYLON.Matrix.Identity();
  11444. }
  11445. return this._worldMatrix;
  11446. };
  11447. HemisphericLight.prototype.getTypeID = function () {
  11448. return 3;
  11449. };
  11450. __decorate([
  11451. BABYLON.serializeAsColor3()
  11452. ], HemisphericLight.prototype, "groundColor", void 0);
  11453. __decorate([
  11454. BABYLON.serializeAsVector3()
  11455. ], HemisphericLight.prototype, "direction", void 0);
  11456. return HemisphericLight;
  11457. }(BABYLON.Light));
  11458. BABYLON.HemisphericLight = HemisphericLight;
  11459. })(BABYLON || (BABYLON = {}));
  11460. var BABYLON;
  11461. (function (BABYLON) {
  11462. var DirectionalLight = (function (_super) {
  11463. __extends(DirectionalLight, _super);
  11464. function DirectionalLight(name, direction, scene) {
  11465. _super.call(this, name, scene);
  11466. this.shadowOrthoScale = 0.5;
  11467. this.autoUpdateExtends = true;
  11468. // Cache
  11469. this._orthoLeft = Number.MAX_VALUE;
  11470. this._orthoRight = Number.MIN_VALUE;
  11471. this._orthoTop = Number.MIN_VALUE;
  11472. this._orthoBottom = Number.MAX_VALUE;
  11473. this.position = direction.scale(-1);
  11474. this.direction = direction;
  11475. }
  11476. DirectionalLight.prototype.getAbsolutePosition = function () {
  11477. return this.transformedPosition ? this.transformedPosition : this.position;
  11478. };
  11479. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11480. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11481. return this.direction;
  11482. };
  11483. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11484. var activeCamera = this.getScene().activeCamera;
  11485. // Check extends
  11486. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11487. var tempVector3 = BABYLON.Vector3.Zero();
  11488. this._orthoLeft = Number.MAX_VALUE;
  11489. this._orthoRight = Number.MIN_VALUE;
  11490. this._orthoTop = Number.MIN_VALUE;
  11491. this._orthoBottom = Number.MAX_VALUE;
  11492. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11493. var mesh = renderList[meshIndex];
  11494. if (!mesh) {
  11495. continue;
  11496. }
  11497. var boundingInfo = mesh.getBoundingInfo();
  11498. if (!boundingInfo) {
  11499. continue;
  11500. }
  11501. var boundingBox = boundingInfo.boundingBox;
  11502. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11503. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11504. if (tempVector3.x < this._orthoLeft)
  11505. this._orthoLeft = tempVector3.x;
  11506. if (tempVector3.y < this._orthoBottom)
  11507. this._orthoBottom = tempVector3.y;
  11508. if (tempVector3.x > this._orthoRight)
  11509. this._orthoRight = tempVector3.x;
  11510. if (tempVector3.y > this._orthoTop)
  11511. this._orthoTop = tempVector3.y;
  11512. }
  11513. }
  11514. }
  11515. var xOffset = this._orthoRight - this._orthoLeft;
  11516. var yOffset = this._orthoTop - this._orthoBottom;
  11517. 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);
  11518. };
  11519. DirectionalLight.prototype.supportsVSM = function () {
  11520. return true;
  11521. };
  11522. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11523. return true;
  11524. };
  11525. DirectionalLight.prototype.needCube = function () {
  11526. return false;
  11527. };
  11528. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11529. return this.direction;
  11530. };
  11531. DirectionalLight.prototype.computeTransformedPosition = function () {
  11532. if (this.parent && this.parent.getWorldMatrix) {
  11533. if (!this.transformedPosition) {
  11534. this.transformedPosition = BABYLON.Vector3.Zero();
  11535. }
  11536. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11537. return true;
  11538. }
  11539. return false;
  11540. };
  11541. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11542. if (this.parent && this.parent.getWorldMatrix) {
  11543. if (!this._transformedDirection) {
  11544. this._transformedDirection = BABYLON.Vector3.Zero();
  11545. }
  11546. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11547. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11548. return;
  11549. }
  11550. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11551. };
  11552. DirectionalLight.prototype._getWorldMatrix = function () {
  11553. if (!this._worldMatrix) {
  11554. this._worldMatrix = BABYLON.Matrix.Identity();
  11555. }
  11556. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11557. return this._worldMatrix;
  11558. };
  11559. DirectionalLight.prototype.getTypeID = function () {
  11560. return 1;
  11561. };
  11562. __decorate([
  11563. BABYLON.serializeAsVector3()
  11564. ], DirectionalLight.prototype, "position", void 0);
  11565. __decorate([
  11566. BABYLON.serializeAsVector3()
  11567. ], DirectionalLight.prototype, "direction", void 0);
  11568. __decorate([
  11569. BABYLON.serialize()
  11570. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11571. __decorate([
  11572. BABYLON.serialize()
  11573. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11574. return DirectionalLight;
  11575. }(BABYLON.Light));
  11576. BABYLON.DirectionalLight = DirectionalLight;
  11577. })(BABYLON || (BABYLON = {}));
  11578. var BABYLON;
  11579. (function (BABYLON) {
  11580. var ShadowGenerator = (function () {
  11581. function ShadowGenerator(mapSize, light) {
  11582. var _this = this;
  11583. // Members
  11584. this._filter = ShadowGenerator.FILTER_NONE;
  11585. this.blurScale = 2;
  11586. this._blurBoxOffset = 0;
  11587. this._bias = 0.00005;
  11588. this._lightDirection = BABYLON.Vector3.Zero();
  11589. this.forceBackFacesOnly = false;
  11590. this._darkness = 0;
  11591. this._transparencyShadow = false;
  11592. this._viewMatrix = BABYLON.Matrix.Zero();
  11593. this._projectionMatrix = BABYLON.Matrix.Zero();
  11594. this._transformMatrix = BABYLON.Matrix.Zero();
  11595. this._worldViewProjection = BABYLON.Matrix.Zero();
  11596. this._currentFaceIndex = 0;
  11597. this._currentFaceIndexCache = 0;
  11598. this._useFullFloat = true;
  11599. this._light = light;
  11600. this._scene = light.getScene();
  11601. this._mapSize = mapSize;
  11602. light._shadowGenerator = this;
  11603. // Texture type fallback from float to int if not supported.
  11604. var textureType;
  11605. var caps = this._scene.getEngine().getCaps();
  11606. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11607. this._useFullFloat = true;
  11608. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11609. }
  11610. else {
  11611. this._useFullFloat = false;
  11612. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11613. }
  11614. // Render target
  11615. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11616. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11617. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11618. this._shadowMap.anisotropicFilteringLevel = 1;
  11619. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11620. this._shadowMap.renderParticles = false;
  11621. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11622. _this._currentFaceIndex = faceIndex;
  11623. });
  11624. this._shadowMap.onAfterUnbindObservable.add(function () {
  11625. if (!_this.useBlurVarianceShadowMap) {
  11626. return;
  11627. }
  11628. if (!_this._shadowMap2) {
  11629. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11630. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11631. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11632. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11633. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11634. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11635. effect.setTexture("textureSampler", _this._shadowMap);
  11636. });
  11637. _this.blurBoxOffset = 1;
  11638. }
  11639. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11640. });
  11641. // Custom render function
  11642. var renderSubMesh = function (subMesh) {
  11643. var mesh = subMesh.getRenderingMesh();
  11644. var scene = _this._scene;
  11645. var engine = scene.getEngine();
  11646. // Culling
  11647. engine.setState(subMesh.getMaterial().backFaceCulling);
  11648. // Managing instances
  11649. var batch = mesh._getInstancesRenderList(subMesh._id);
  11650. if (batch.mustReturn) {
  11651. return;
  11652. }
  11653. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11654. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11655. engine.enableEffect(_this._effect);
  11656. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11657. var material = subMesh.getMaterial();
  11658. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11659. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11660. if (_this.getLight().needCube()) {
  11661. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11662. }
  11663. // Alpha test
  11664. if (material && material.needAlphaTesting()) {
  11665. var alphaTexture = material.getAlphaTestTexture();
  11666. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11667. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11668. }
  11669. // Bones
  11670. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11671. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11672. }
  11673. if (_this.forceBackFacesOnly) {
  11674. engine.setState(true, 0, false, true);
  11675. }
  11676. // Draw
  11677. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11678. if (_this.forceBackFacesOnly) {
  11679. engine.setState(true, 0, false, false);
  11680. }
  11681. }
  11682. else {
  11683. // Need to reset refresh rate of the shadowMap
  11684. _this._shadowMap.resetRefreshCounter();
  11685. }
  11686. };
  11687. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11688. var index;
  11689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11690. renderSubMesh(opaqueSubMeshes.data[index]);
  11691. }
  11692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11693. renderSubMesh(alphaTestSubMeshes.data[index]);
  11694. }
  11695. if (_this._transparencyShadow) {
  11696. for (index = 0; index < transparentSubMeshes.length; index++) {
  11697. renderSubMesh(transparentSubMeshes.data[index]);
  11698. }
  11699. }
  11700. };
  11701. this._shadowMap.onClearObservable.add(function (engine) {
  11702. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11703. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11704. }
  11705. else {
  11706. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11707. }
  11708. });
  11709. }
  11710. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11711. // Static
  11712. get: function () {
  11713. return ShadowGenerator._FILTER_NONE;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11719. get: function () {
  11720. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11726. get: function () {
  11727. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11733. get: function () {
  11734. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11740. get: function () {
  11741. return this._bias;
  11742. },
  11743. set: function (bias) {
  11744. this._bias = bias;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11750. get: function () {
  11751. return this._blurBoxOffset;
  11752. },
  11753. set: function (value) {
  11754. var _this = this;
  11755. if (this._blurBoxOffset === value) {
  11756. return;
  11757. }
  11758. this._blurBoxOffset = value;
  11759. if (this._boxBlurPostprocess) {
  11760. this._boxBlurPostprocess.dispose();
  11761. }
  11762. 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);
  11763. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11764. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11765. });
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11771. get: function () {
  11772. return this._filter;
  11773. },
  11774. set: function (value) {
  11775. if (this._filter === value) {
  11776. return;
  11777. }
  11778. this._filter = value;
  11779. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11780. this._shadowMap.anisotropicFilteringLevel = 16;
  11781. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11782. }
  11783. else {
  11784. this._shadowMap.anisotropicFilteringLevel = 1;
  11785. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11786. }
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11792. get: function () {
  11793. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11794. },
  11795. set: function (value) {
  11796. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11802. get: function () {
  11803. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11804. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11805. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11806. },
  11807. set: function (value) {
  11808. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11814. get: function () {
  11815. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11816. },
  11817. set: function (value) {
  11818. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11824. var defines = [];
  11825. if (this._useFullFloat) {
  11826. defines.push("#define FULLFLOAT");
  11827. }
  11828. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11829. defines.push("#define VSM");
  11830. }
  11831. if (this.getLight().needCube()) {
  11832. defines.push("#define CUBEMAP");
  11833. }
  11834. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11835. var mesh = subMesh.getMesh();
  11836. var material = subMesh.getMaterial();
  11837. // Alpha test
  11838. if (material && material.needAlphaTesting()) {
  11839. defines.push("#define ALPHATEST");
  11840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11841. attribs.push(BABYLON.VertexBuffer.UVKind);
  11842. defines.push("#define UV1");
  11843. }
  11844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11845. var alphaTexture = material.getAlphaTestTexture();
  11846. if (alphaTexture.coordinatesIndex === 1) {
  11847. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11848. defines.push("#define UV2");
  11849. }
  11850. }
  11851. }
  11852. // Bones
  11853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11856. if (mesh.numBoneInfluencers > 4) {
  11857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11859. }
  11860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11861. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11862. }
  11863. else {
  11864. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11865. }
  11866. // Instances
  11867. if (useInstances) {
  11868. defines.push("#define INSTANCES");
  11869. attribs.push("world0");
  11870. attribs.push("world1");
  11871. attribs.push("world2");
  11872. attribs.push("world3");
  11873. }
  11874. // Get correct effect
  11875. var join = defines.join("\n");
  11876. if (this._cachedDefines !== join) {
  11877. this._cachedDefines = join;
  11878. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11879. }
  11880. return this._effect.isReady();
  11881. };
  11882. ShadowGenerator.prototype.getShadowMap = function () {
  11883. return this._shadowMap;
  11884. };
  11885. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11886. if (this._shadowMap2) {
  11887. return this._shadowMap2;
  11888. }
  11889. return this._shadowMap;
  11890. };
  11891. ShadowGenerator.prototype.getLight = function () {
  11892. return this._light;
  11893. };
  11894. // Methods
  11895. ShadowGenerator.prototype.getTransformMatrix = function () {
  11896. var scene = this._scene;
  11897. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11898. return this._transformMatrix;
  11899. }
  11900. this._currentRenderID = scene.getRenderId();
  11901. this._currentFaceIndexCache = this._currentFaceIndex;
  11902. var lightPosition = this._light.position;
  11903. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11904. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11905. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11906. }
  11907. if (this._light.computeTransformedPosition()) {
  11908. lightPosition = this._light.transformedPosition;
  11909. }
  11910. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11911. this._cachedPosition = lightPosition.clone();
  11912. this._cachedDirection = this._lightDirection.clone();
  11913. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11914. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11915. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11916. }
  11917. return this._transformMatrix;
  11918. };
  11919. ShadowGenerator.prototype.getDarkness = function () {
  11920. return this._darkness;
  11921. };
  11922. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11923. if (darkness >= 1.0)
  11924. this._darkness = 1.0;
  11925. else if (darkness <= 0.0)
  11926. this._darkness = 0.0;
  11927. else
  11928. this._darkness = darkness;
  11929. };
  11930. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11931. this._transparencyShadow = hasShadow;
  11932. };
  11933. ShadowGenerator.prototype._packHalf = function (depth) {
  11934. var scale = depth * 255.0;
  11935. var fract = scale - Math.floor(scale);
  11936. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11937. };
  11938. ShadowGenerator.prototype.dispose = function () {
  11939. this._shadowMap.dispose();
  11940. if (this._shadowMap2) {
  11941. this._shadowMap2.dispose();
  11942. }
  11943. if (this._downSamplePostprocess) {
  11944. this._downSamplePostprocess.dispose();
  11945. }
  11946. if (this._boxBlurPostprocess) {
  11947. this._boxBlurPostprocess.dispose();
  11948. }
  11949. };
  11950. ShadowGenerator.prototype.serialize = function () {
  11951. var serializationObject = {};
  11952. serializationObject.lightId = this._light.id;
  11953. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11954. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11955. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11956. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11957. serializationObject.renderList = [];
  11958. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11959. var mesh = this.getShadowMap().renderList[meshIndex];
  11960. serializationObject.renderList.push(mesh.id);
  11961. }
  11962. return serializationObject;
  11963. };
  11964. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11965. //casting to point light, as light is missing the position attr and typescript complains.
  11966. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11967. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11968. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11969. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11970. meshes.forEach(function (mesh) {
  11971. shadowGenerator.getShadowMap().renderList.push(mesh);
  11972. });
  11973. }
  11974. if (parsedShadowGenerator.usePoissonSampling) {
  11975. shadowGenerator.usePoissonSampling = true;
  11976. }
  11977. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11978. shadowGenerator.useVarianceShadowMap = true;
  11979. }
  11980. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11981. shadowGenerator.useBlurVarianceShadowMap = true;
  11982. if (parsedShadowGenerator.blurScale) {
  11983. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11984. }
  11985. if (parsedShadowGenerator.blurBoxOffset) {
  11986. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11987. }
  11988. }
  11989. if (parsedShadowGenerator.bias !== undefined) {
  11990. shadowGenerator.bias = parsedShadowGenerator.bias;
  11991. }
  11992. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11993. return shadowGenerator;
  11994. };
  11995. ShadowGenerator._FILTER_NONE = 0;
  11996. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11997. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11998. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11999. return ShadowGenerator;
  12000. }());
  12001. BABYLON.ShadowGenerator = ShadowGenerator;
  12002. })(BABYLON || (BABYLON = {}));
  12003. var BABYLON;
  12004. (function (BABYLON) {
  12005. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12006. if (boxMin.x > sphereCenter.x + sphereRadius)
  12007. return false;
  12008. if (sphereCenter.x - sphereRadius > boxMax.x)
  12009. return false;
  12010. if (boxMin.y > sphereCenter.y + sphereRadius)
  12011. return false;
  12012. if (sphereCenter.y - sphereRadius > boxMax.y)
  12013. return false;
  12014. if (boxMin.z > sphereCenter.z + sphereRadius)
  12015. return false;
  12016. if (sphereCenter.z - sphereRadius > boxMax.z)
  12017. return false;
  12018. return true;
  12019. };
  12020. var getLowestRoot = (function () {
  12021. var result = { root: 0, found: false };
  12022. return function (a, b, c, maxR) {
  12023. result.root = 0;
  12024. result.found = false;
  12025. var determinant = b * b - 4.0 * a * c;
  12026. if (determinant < 0)
  12027. return result;
  12028. var sqrtD = Math.sqrt(determinant);
  12029. var r1 = (-b - sqrtD) / (2.0 * a);
  12030. var r2 = (-b + sqrtD) / (2.0 * a);
  12031. if (r1 > r2) {
  12032. var temp = r2;
  12033. r2 = r1;
  12034. r1 = temp;
  12035. }
  12036. if (r1 > 0 && r1 < maxR) {
  12037. result.root = r1;
  12038. result.found = true;
  12039. return result;
  12040. }
  12041. if (r2 > 0 && r2 < maxR) {
  12042. result.root = r2;
  12043. result.found = true;
  12044. return result;
  12045. }
  12046. return result;
  12047. };
  12048. })();
  12049. var Collider = (function () {
  12050. function Collider() {
  12051. this.radius = new BABYLON.Vector3(1, 1, 1);
  12052. this.retry = 0;
  12053. this.basePointWorld = BABYLON.Vector3.Zero();
  12054. this.velocityWorld = BABYLON.Vector3.Zero();
  12055. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12056. this._collisionPoint = BABYLON.Vector3.Zero();
  12057. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12058. this._tempVector = BABYLON.Vector3.Zero();
  12059. this._tempVector2 = BABYLON.Vector3.Zero();
  12060. this._tempVector3 = BABYLON.Vector3.Zero();
  12061. this._tempVector4 = BABYLON.Vector3.Zero();
  12062. this._edge = BABYLON.Vector3.Zero();
  12063. this._baseToVertex = BABYLON.Vector3.Zero();
  12064. this._destinationPoint = BABYLON.Vector3.Zero();
  12065. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12066. this._displacementVector = BABYLON.Vector3.Zero();
  12067. }
  12068. // Methods
  12069. Collider.prototype._initialize = function (source, dir, e) {
  12070. this.velocity = dir;
  12071. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12072. this.basePoint = source;
  12073. source.multiplyToRef(this.radius, this.basePointWorld);
  12074. dir.multiplyToRef(this.radius, this.velocityWorld);
  12075. this.velocityWorldLength = this.velocityWorld.length();
  12076. this.epsilon = e;
  12077. this.collisionFound = false;
  12078. };
  12079. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12080. pa.subtractToRef(point, this._tempVector);
  12081. pb.subtractToRef(point, this._tempVector2);
  12082. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12083. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12084. if (d < 0)
  12085. return false;
  12086. pc.subtractToRef(point, this._tempVector3);
  12087. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12088. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12089. if (d < 0)
  12090. return false;
  12091. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12092. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12093. return d >= 0;
  12094. };
  12095. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12096. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12097. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12098. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12099. return false;
  12100. }
  12101. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12102. return false;
  12103. return true;
  12104. };
  12105. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12106. var t0;
  12107. var embeddedInPlane = false;
  12108. //defensive programming, actually not needed.
  12109. if (!trianglePlaneArray) {
  12110. trianglePlaneArray = [];
  12111. }
  12112. if (!trianglePlaneArray[faceIndex]) {
  12113. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12114. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12115. }
  12116. var trianglePlane = trianglePlaneArray[faceIndex];
  12117. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12118. return;
  12119. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12120. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12121. if (normalDotVelocity == 0) {
  12122. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12123. return;
  12124. embeddedInPlane = true;
  12125. t0 = 0;
  12126. }
  12127. else {
  12128. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12129. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12130. if (t0 > t1) {
  12131. var temp = t1;
  12132. t1 = t0;
  12133. t0 = temp;
  12134. }
  12135. if (t0 > 1.0 || t1 < 0.0)
  12136. return;
  12137. if (t0 < 0)
  12138. t0 = 0;
  12139. if (t0 > 1.0)
  12140. t0 = 1.0;
  12141. }
  12142. this._collisionPoint.copyFromFloats(0, 0, 0);
  12143. var found = false;
  12144. var t = 1.0;
  12145. if (!embeddedInPlane) {
  12146. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12147. this.velocity.scaleToRef(t0, this._tempVector);
  12148. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12149. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12150. found = true;
  12151. t = t0;
  12152. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12153. }
  12154. }
  12155. if (!found) {
  12156. var velocitySquaredLength = this.velocity.lengthSquared();
  12157. var a = velocitySquaredLength;
  12158. this.basePoint.subtractToRef(p1, this._tempVector);
  12159. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12160. var c = this._tempVector.lengthSquared() - 1.0;
  12161. var lowestRoot = getLowestRoot(a, b, c, t);
  12162. if (lowestRoot.found) {
  12163. t = lowestRoot.root;
  12164. found = true;
  12165. this._collisionPoint.copyFrom(p1);
  12166. }
  12167. this.basePoint.subtractToRef(p2, this._tempVector);
  12168. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12169. c = this._tempVector.lengthSquared() - 1.0;
  12170. lowestRoot = getLowestRoot(a, b, c, t);
  12171. if (lowestRoot.found) {
  12172. t = lowestRoot.root;
  12173. found = true;
  12174. this._collisionPoint.copyFrom(p2);
  12175. }
  12176. this.basePoint.subtractToRef(p3, this._tempVector);
  12177. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12178. c = this._tempVector.lengthSquared() - 1.0;
  12179. lowestRoot = getLowestRoot(a, b, c, t);
  12180. if (lowestRoot.found) {
  12181. t = lowestRoot.root;
  12182. found = true;
  12183. this._collisionPoint.copyFrom(p3);
  12184. }
  12185. p2.subtractToRef(p1, this._edge);
  12186. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12187. var edgeSquaredLength = this._edge.lengthSquared();
  12188. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12189. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12190. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12191. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12192. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12193. lowestRoot = getLowestRoot(a, b, c, t);
  12194. if (lowestRoot.found) {
  12195. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12196. if (f >= 0.0 && f <= 1.0) {
  12197. t = lowestRoot.root;
  12198. found = true;
  12199. this._edge.scaleInPlace(f);
  12200. p1.addToRef(this._edge, this._collisionPoint);
  12201. }
  12202. }
  12203. p3.subtractToRef(p2, this._edge);
  12204. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12205. edgeSquaredLength = this._edge.lengthSquared();
  12206. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12207. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12208. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12209. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12210. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12211. lowestRoot = getLowestRoot(a, b, c, t);
  12212. if (lowestRoot.found) {
  12213. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12214. if (f >= 0.0 && f <= 1.0) {
  12215. t = lowestRoot.root;
  12216. found = true;
  12217. this._edge.scaleInPlace(f);
  12218. p2.addToRef(this._edge, this._collisionPoint);
  12219. }
  12220. }
  12221. p1.subtractToRef(p3, this._edge);
  12222. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12223. edgeSquaredLength = this._edge.lengthSquared();
  12224. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12225. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12226. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12227. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12228. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12229. lowestRoot = getLowestRoot(a, b, c, t);
  12230. if (lowestRoot.found) {
  12231. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12232. if (f >= 0.0 && f <= 1.0) {
  12233. t = lowestRoot.root;
  12234. found = true;
  12235. this._edge.scaleInPlace(f);
  12236. p3.addToRef(this._edge, this._collisionPoint);
  12237. }
  12238. }
  12239. }
  12240. if (found) {
  12241. var distToCollision = t * this.velocity.length();
  12242. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12243. if (!this.intersectionPoint) {
  12244. this.intersectionPoint = this._collisionPoint.clone();
  12245. }
  12246. else {
  12247. this.intersectionPoint.copyFrom(this._collisionPoint);
  12248. }
  12249. this.nearestDistance = distToCollision;
  12250. this.collisionFound = true;
  12251. }
  12252. }
  12253. };
  12254. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12255. for (var i = indexStart; i < indexEnd; i += 3) {
  12256. var p1 = pts[indices[i] - decal];
  12257. var p2 = pts[indices[i + 1] - decal];
  12258. var p3 = pts[indices[i + 2] - decal];
  12259. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12260. }
  12261. };
  12262. Collider.prototype._getResponse = function (pos, vel) {
  12263. pos.addToRef(vel, this._destinationPoint);
  12264. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12265. this.basePoint.addToRef(vel, pos);
  12266. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12267. this._slidePlaneNormal.normalize();
  12268. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12269. pos.addInPlace(this._displacementVector);
  12270. this.intersectionPoint.addInPlace(this._displacementVector);
  12271. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12272. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12273. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12274. };
  12275. return Collider;
  12276. }());
  12277. BABYLON.Collider = Collider;
  12278. })(BABYLON || (BABYLON = {}));
  12279. var BABYLON;
  12280. (function (BABYLON) {
  12281. //WebWorker code will be inserted to this variable.
  12282. BABYLON.CollisionWorker = "";
  12283. (function (WorkerTaskType) {
  12284. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12285. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12286. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12287. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12288. var WorkerTaskType = BABYLON.WorkerTaskType;
  12289. (function (WorkerReplyType) {
  12290. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12291. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12292. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12293. var WorkerReplyType = BABYLON.WorkerReplyType;
  12294. var CollisionCoordinatorWorker = (function () {
  12295. function CollisionCoordinatorWorker() {
  12296. var _this = this;
  12297. this._scaledPosition = BABYLON.Vector3.Zero();
  12298. this._scaledVelocity = BABYLON.Vector3.Zero();
  12299. this.onMeshUpdated = function (mesh) {
  12300. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12301. };
  12302. this.onGeometryUpdated = function (geometry) {
  12303. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12304. };
  12305. this._afterRender = function () {
  12306. if (!_this._init)
  12307. return;
  12308. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12309. return;
  12310. }
  12311. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12312. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12313. if (_this._runningUpdated > 4) {
  12314. return;
  12315. }
  12316. ++_this._runningUpdated;
  12317. var payload = {
  12318. updatedMeshes: _this._addUpdateMeshesList,
  12319. updatedGeometries: _this._addUpdateGeometriesList,
  12320. removedGeometries: _this._toRemoveGeometryArray,
  12321. removedMeshes: _this._toRemoveMeshesArray
  12322. };
  12323. var message = {
  12324. payload: payload,
  12325. taskType: WorkerTaskType.UPDATE
  12326. };
  12327. var serializable = [];
  12328. for (var id in payload.updatedGeometries) {
  12329. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12330. //prepare transferables
  12331. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12332. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12333. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12334. }
  12335. }
  12336. _this._worker.postMessage(message, serializable);
  12337. _this._addUpdateMeshesList = {};
  12338. _this._addUpdateGeometriesList = {};
  12339. _this._toRemoveGeometryArray = [];
  12340. _this._toRemoveMeshesArray = [];
  12341. };
  12342. this._onMessageFromWorker = function (e) {
  12343. var returnData = e.data;
  12344. if (returnData.error != WorkerReplyType.SUCCESS) {
  12345. //TODO what errors can be returned from the worker?
  12346. BABYLON.Tools.Warn("error returned from worker!");
  12347. return;
  12348. }
  12349. switch (returnData.taskType) {
  12350. case WorkerTaskType.INIT:
  12351. _this._init = true;
  12352. //Update the worked with ALL of the scene's current state
  12353. _this._scene.meshes.forEach(function (mesh) {
  12354. _this.onMeshAdded(mesh);
  12355. });
  12356. _this._scene.getGeometries().forEach(function (geometry) {
  12357. _this.onGeometryAdded(geometry);
  12358. });
  12359. break;
  12360. case WorkerTaskType.UPDATE:
  12361. _this._runningUpdated--;
  12362. break;
  12363. case WorkerTaskType.COLLIDE:
  12364. _this._runningCollisionTask = false;
  12365. var returnPayload = returnData.payload;
  12366. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12367. return;
  12368. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12369. //cleanup
  12370. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12371. break;
  12372. }
  12373. };
  12374. this._collisionsCallbackArray = [];
  12375. this._init = false;
  12376. this._runningUpdated = 0;
  12377. this._runningCollisionTask = false;
  12378. this._addUpdateMeshesList = {};
  12379. this._addUpdateGeometriesList = {};
  12380. this._toRemoveGeometryArray = [];
  12381. this._toRemoveMeshesArray = [];
  12382. }
  12383. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12384. if (!this._init)
  12385. return;
  12386. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12387. return;
  12388. position.divideToRef(collider.radius, this._scaledPosition);
  12389. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12390. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12391. var payload = {
  12392. collider: {
  12393. position: this._scaledPosition.asArray(),
  12394. velocity: this._scaledVelocity.asArray(),
  12395. radius: collider.radius.asArray()
  12396. },
  12397. collisionId: collisionIndex,
  12398. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12399. maximumRetry: maximumRetry
  12400. };
  12401. var message = {
  12402. payload: payload,
  12403. taskType: WorkerTaskType.COLLIDE
  12404. };
  12405. this._worker.postMessage(message);
  12406. };
  12407. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12408. this._scene = scene;
  12409. this._scene.registerAfterRender(this._afterRender);
  12410. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12411. this._worker = new Worker(workerUrl);
  12412. this._worker.onmessage = this._onMessageFromWorker;
  12413. var message = {
  12414. payload: {},
  12415. taskType: WorkerTaskType.INIT
  12416. };
  12417. this._worker.postMessage(message);
  12418. };
  12419. CollisionCoordinatorWorker.prototype.destroy = function () {
  12420. this._scene.unregisterAfterRender(this._afterRender);
  12421. this._worker.terminate();
  12422. };
  12423. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12424. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12425. this.onMeshUpdated(mesh);
  12426. };
  12427. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12428. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12429. };
  12430. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12431. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12432. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12433. this.onGeometryUpdated(geometry);
  12434. };
  12435. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12436. this._toRemoveGeometryArray.push(geometry.id);
  12437. };
  12438. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12439. var submeshes = [];
  12440. if (mesh.subMeshes) {
  12441. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12442. return {
  12443. position: idx,
  12444. verticesStart: sm.verticesStart,
  12445. verticesCount: sm.verticesCount,
  12446. indexStart: sm.indexStart,
  12447. indexCount: sm.indexCount,
  12448. hasMaterial: !!sm.getMaterial(),
  12449. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12450. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12451. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12452. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12453. };
  12454. });
  12455. }
  12456. var geometryId = null;
  12457. if (mesh instanceof BABYLON.Mesh) {
  12458. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12459. }
  12460. else if (mesh instanceof BABYLON.InstancedMesh) {
  12461. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12462. }
  12463. return {
  12464. uniqueId: mesh.uniqueId,
  12465. id: mesh.id,
  12466. name: mesh.name,
  12467. geometryId: geometryId,
  12468. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12469. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12470. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12471. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12472. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12473. subMeshes: submeshes,
  12474. checkCollisions: mesh.checkCollisions
  12475. };
  12476. };
  12477. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12478. return {
  12479. id: geometry.id,
  12480. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12481. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12482. indices: new Int32Array(geometry.getIndices() || []),
  12483. };
  12484. };
  12485. return CollisionCoordinatorWorker;
  12486. }());
  12487. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12488. var CollisionCoordinatorLegacy = (function () {
  12489. function CollisionCoordinatorLegacy() {
  12490. this._scaledPosition = BABYLON.Vector3.Zero();
  12491. this._scaledVelocity = BABYLON.Vector3.Zero();
  12492. this._finalPosition = BABYLON.Vector3.Zero();
  12493. }
  12494. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12495. position.divideToRef(collider.radius, this._scaledPosition);
  12496. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12497. collider.collidedMesh = null;
  12498. collider.retry = 0;
  12499. collider.initialVelocity = this._scaledVelocity;
  12500. collider.initialPosition = this._scaledPosition;
  12501. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12502. this._finalPosition.multiplyInPlace(collider.radius);
  12503. //run the callback
  12504. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12505. };
  12506. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12507. this._scene = scene;
  12508. };
  12509. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12510. //Legacy need no destruction method.
  12511. };
  12512. //No update in legacy mode
  12513. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12514. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12515. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12516. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12517. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12518. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12519. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12520. if (excludedMesh === void 0) { excludedMesh = null; }
  12521. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12522. if (collider.retry >= maximumRetry) {
  12523. finalPosition.copyFrom(position);
  12524. return;
  12525. }
  12526. collider._initialize(position, velocity, closeDistance);
  12527. // Check all meshes
  12528. for (var index = 0; index < this._scene.meshes.length; index++) {
  12529. var mesh = this._scene.meshes[index];
  12530. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12531. mesh._checkCollision(collider);
  12532. }
  12533. }
  12534. if (!collider.collisionFound) {
  12535. position.addToRef(velocity, finalPosition);
  12536. return;
  12537. }
  12538. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12539. collider._getResponse(position, velocity);
  12540. }
  12541. if (velocity.length() <= closeDistance) {
  12542. finalPosition.copyFrom(position);
  12543. return;
  12544. }
  12545. collider.retry++;
  12546. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12547. };
  12548. return CollisionCoordinatorLegacy;
  12549. }());
  12550. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12551. })(BABYLON || (BABYLON = {}));
  12552. var BABYLON;
  12553. (function (BABYLON) {
  12554. var Camera = (function (_super) {
  12555. __extends(Camera, _super);
  12556. function Camera(name, position, scene) {
  12557. _super.call(this, name, scene);
  12558. this.upVector = BABYLON.Vector3.Up();
  12559. this.orthoLeft = null;
  12560. this.orthoRight = null;
  12561. this.orthoBottom = null;
  12562. this.orthoTop = null;
  12563. this.fov = 0.8;
  12564. this.minZ = 1.0;
  12565. this.maxZ = 10000.0;
  12566. this.inertia = 0.9;
  12567. this.mode = Camera.PERSPECTIVE_CAMERA;
  12568. this.isIntermediate = false;
  12569. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12570. this.layerMask = 0x0FFFFFFF;
  12571. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12572. // Camera rig members
  12573. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12574. this._rigCameras = new Array();
  12575. // Cache
  12576. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12577. this._projectionMatrix = new BABYLON.Matrix();
  12578. this._postProcesses = new Array();
  12579. this._transformMatrix = BABYLON.Matrix.Zero();
  12580. this._activeMeshes = new BABYLON.SmartArray(256);
  12581. this._globalPosition = BABYLON.Vector3.Zero();
  12582. this._refreshFrustumPlanes = true;
  12583. scene.addCamera(this);
  12584. if (!scene.activeCamera) {
  12585. scene.activeCamera = this;
  12586. }
  12587. this.position = position;
  12588. }
  12589. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12590. get: function () {
  12591. return Camera._PERSPECTIVE_CAMERA;
  12592. },
  12593. enumerable: true,
  12594. configurable: true
  12595. });
  12596. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12597. get: function () {
  12598. return Camera._ORTHOGRAPHIC_CAMERA;
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12604. get: function () {
  12605. return Camera._FOVMODE_VERTICAL_FIXED;
  12606. },
  12607. enumerable: true,
  12608. configurable: true
  12609. });
  12610. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12611. get: function () {
  12612. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12613. },
  12614. enumerable: true,
  12615. configurable: true
  12616. });
  12617. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12618. get: function () {
  12619. return Camera._RIG_MODE_NONE;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12625. get: function () {
  12626. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12627. },
  12628. enumerable: true,
  12629. configurable: true
  12630. });
  12631. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12632. get: function () {
  12633. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12639. get: function () {
  12640. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12641. },
  12642. enumerable: true,
  12643. configurable: true
  12644. });
  12645. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12646. get: function () {
  12647. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12653. get: function () {
  12654. return Camera._RIG_MODE_VR;
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12660. get: function () {
  12661. return Camera._RIG_MODE_WEBVR;
  12662. },
  12663. enumerable: true,
  12664. configurable: true
  12665. });
  12666. /**
  12667. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12668. */
  12669. Camera.prototype.toString = function (fullDetails) {
  12670. var ret = "Name: " + this.name;
  12671. ret += ", type: " + this.getTypeName();
  12672. if (this.animations) {
  12673. for (var i = 0; i < this.animations.length; i++) {
  12674. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12675. }
  12676. }
  12677. if (fullDetails) {
  12678. }
  12679. return ret;
  12680. };
  12681. Object.defineProperty(Camera.prototype, "globalPosition", {
  12682. get: function () {
  12683. return this._globalPosition;
  12684. },
  12685. enumerable: true,
  12686. configurable: true
  12687. });
  12688. Camera.prototype.getActiveMeshes = function () {
  12689. return this._activeMeshes;
  12690. };
  12691. Camera.prototype.isActiveMesh = function (mesh) {
  12692. return (this._activeMeshes.indexOf(mesh) !== -1);
  12693. };
  12694. //Cache
  12695. Camera.prototype._initCache = function () {
  12696. _super.prototype._initCache.call(this);
  12697. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12698. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12699. this._cache.mode = undefined;
  12700. this._cache.minZ = undefined;
  12701. this._cache.maxZ = undefined;
  12702. this._cache.fov = undefined;
  12703. this._cache.fovMode = undefined;
  12704. this._cache.aspectRatio = undefined;
  12705. this._cache.orthoLeft = undefined;
  12706. this._cache.orthoRight = undefined;
  12707. this._cache.orthoBottom = undefined;
  12708. this._cache.orthoTop = undefined;
  12709. this._cache.renderWidth = undefined;
  12710. this._cache.renderHeight = undefined;
  12711. };
  12712. Camera.prototype._updateCache = function (ignoreParentClass) {
  12713. if (!ignoreParentClass) {
  12714. _super.prototype._updateCache.call(this);
  12715. }
  12716. var engine = this.getEngine();
  12717. this._cache.position.copyFrom(this.position);
  12718. this._cache.upVector.copyFrom(this.upVector);
  12719. this._cache.mode = this.mode;
  12720. this._cache.minZ = this.minZ;
  12721. this._cache.maxZ = this.maxZ;
  12722. this._cache.fov = this.fov;
  12723. this._cache.fovMode = this.fovMode;
  12724. this._cache.aspectRatio = engine.getAspectRatio(this);
  12725. this._cache.orthoLeft = this.orthoLeft;
  12726. this._cache.orthoRight = this.orthoRight;
  12727. this._cache.orthoBottom = this.orthoBottom;
  12728. this._cache.orthoTop = this.orthoTop;
  12729. this._cache.renderWidth = engine.getRenderWidth();
  12730. this._cache.renderHeight = engine.getRenderHeight();
  12731. };
  12732. Camera.prototype._updateFromScene = function () {
  12733. this.updateCache();
  12734. this.update();
  12735. };
  12736. // Synchronized
  12737. Camera.prototype._isSynchronized = function () {
  12738. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12739. };
  12740. Camera.prototype._isSynchronizedViewMatrix = function () {
  12741. if (!_super.prototype._isSynchronized.call(this))
  12742. return false;
  12743. return this._cache.position.equals(this.position)
  12744. && this._cache.upVector.equals(this.upVector)
  12745. && this.isSynchronizedWithParent();
  12746. };
  12747. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12748. var check = this._cache.mode === this.mode
  12749. && this._cache.minZ === this.minZ
  12750. && this._cache.maxZ === this.maxZ;
  12751. if (!check) {
  12752. return false;
  12753. }
  12754. var engine = this.getEngine();
  12755. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12756. check = this._cache.fov === this.fov
  12757. && this._cache.fovMode === this.fovMode
  12758. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12759. }
  12760. else {
  12761. check = this._cache.orthoLeft === this.orthoLeft
  12762. && this._cache.orthoRight === this.orthoRight
  12763. && this._cache.orthoBottom === this.orthoBottom
  12764. && this._cache.orthoTop === this.orthoTop
  12765. && this._cache.renderWidth === engine.getRenderWidth()
  12766. && this._cache.renderHeight === engine.getRenderHeight();
  12767. }
  12768. return check;
  12769. };
  12770. // Controls
  12771. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12772. };
  12773. Camera.prototype.detachControl = function (element) {
  12774. };
  12775. Camera.prototype.update = function () {
  12776. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12777. this._updateRigCameras();
  12778. }
  12779. this._checkInputs();
  12780. };
  12781. Camera.prototype._checkInputs = function () {
  12782. };
  12783. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12784. // invalidate framebuffer
  12785. if (this._postProcesses.length > 0) {
  12786. this._postProcesses[0].markTextureDirty();
  12787. }
  12788. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12789. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12790. var cam = this._rigCameras[i];
  12791. var rigPostProcess = cam._rigPostProcess;
  12792. // for VR rig, there does not have to be a post process
  12793. if (rigPostProcess) {
  12794. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12795. if (isPass) {
  12796. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12797. cam.isIntermediate = this._postProcesses.length === 0;
  12798. }
  12799. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12800. rigPostProcess.markTextureDirty();
  12801. }
  12802. else {
  12803. cam._postProcesses = this._postProcesses.slice(0);
  12804. }
  12805. }
  12806. };
  12807. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12808. if (insertAt === void 0) { insertAt = null; }
  12809. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12810. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12811. return 0;
  12812. }
  12813. if (insertAt == null || insertAt < 0) {
  12814. this._postProcesses.push(postProcess);
  12815. }
  12816. else {
  12817. this._postProcesses.splice(insertAt, 0, postProcess);
  12818. }
  12819. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12820. return this._postProcesses.indexOf(postProcess);
  12821. };
  12822. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12823. if (atIndices === void 0) { atIndices = null; }
  12824. var result = [];
  12825. var i;
  12826. var index;
  12827. if (!atIndices) {
  12828. var idx = this._postProcesses.indexOf(postProcess);
  12829. if (idx !== -1) {
  12830. this._postProcesses.splice(idx, 1);
  12831. }
  12832. }
  12833. else {
  12834. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12835. // iterate descending, so can just splice as we go
  12836. for (i = atIndices.length - 1; i >= 0; i--) {
  12837. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12838. result.push(i);
  12839. continue;
  12840. }
  12841. this._postProcesses.splice(index, 1);
  12842. }
  12843. }
  12844. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12845. return result;
  12846. };
  12847. Camera.prototype.getWorldMatrix = function () {
  12848. if (!this._worldMatrix) {
  12849. this._worldMatrix = BABYLON.Matrix.Identity();
  12850. }
  12851. var viewMatrix = this.getViewMatrix();
  12852. viewMatrix.invertToRef(this._worldMatrix);
  12853. return this._worldMatrix;
  12854. };
  12855. Camera.prototype._getViewMatrix = function () {
  12856. return BABYLON.Matrix.Identity();
  12857. };
  12858. Camera.prototype.getViewMatrix = function (force) {
  12859. this._computedViewMatrix = this._computeViewMatrix(force);
  12860. if (!force && this._isSynchronizedViewMatrix()) {
  12861. return this._computedViewMatrix;
  12862. }
  12863. this._refreshFrustumPlanes = true;
  12864. if (!this.parent || !this.parent.getWorldMatrix) {
  12865. this._globalPosition.copyFrom(this.position);
  12866. }
  12867. else {
  12868. if (!this._worldMatrix) {
  12869. this._worldMatrix = BABYLON.Matrix.Identity();
  12870. }
  12871. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12872. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12873. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12874. this._computedViewMatrix.invert();
  12875. this._markSyncedWithParent();
  12876. }
  12877. this._currentRenderId = this.getScene().getRenderId();
  12878. return this._computedViewMatrix;
  12879. };
  12880. Camera.prototype._computeViewMatrix = function (force) {
  12881. if (!force && this._isSynchronizedViewMatrix()) {
  12882. return this._computedViewMatrix;
  12883. }
  12884. this._computedViewMatrix = this._getViewMatrix();
  12885. this._currentRenderId = this.getScene().getRenderId();
  12886. return this._computedViewMatrix;
  12887. };
  12888. Camera.prototype.getProjectionMatrix = function (force) {
  12889. if (!force && this._isSynchronizedProjectionMatrix()) {
  12890. return this._projectionMatrix;
  12891. }
  12892. this._refreshFrustumPlanes = true;
  12893. var engine = this.getEngine();
  12894. var scene = this.getScene();
  12895. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12896. if (this.minZ <= 0) {
  12897. this.minZ = 0.1;
  12898. }
  12899. if (scene.useRightHandedSystem) {
  12900. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12901. }
  12902. else {
  12903. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12904. }
  12905. return this._projectionMatrix;
  12906. }
  12907. var halfWidth = engine.getRenderWidth() / 2.0;
  12908. var halfHeight = engine.getRenderHeight() / 2.0;
  12909. if (scene.useRightHandedSystem) {
  12910. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12911. }
  12912. else {
  12913. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12914. }
  12915. return this._projectionMatrix;
  12916. };
  12917. Camera.prototype.getTranformationMatrix = function () {
  12918. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12919. return this._transformMatrix;
  12920. };
  12921. Camera.prototype.updateFrustumPlanes = function () {
  12922. if (!this._refreshFrustumPlanes) {
  12923. return;
  12924. }
  12925. this.getTranformationMatrix();
  12926. if (!this._frustumPlanes) {
  12927. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12928. }
  12929. else {
  12930. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12931. }
  12932. this._refreshFrustumPlanes = false;
  12933. };
  12934. Camera.prototype.isInFrustum = function (target) {
  12935. this.updateFrustumPlanes();
  12936. return target.isInFrustum(this._frustumPlanes);
  12937. };
  12938. Camera.prototype.isCompletelyInFrustum = function (target) {
  12939. this.updateFrustumPlanes();
  12940. return target.isCompletelyInFrustum(this._frustumPlanes);
  12941. };
  12942. Camera.prototype.dispose = function () {
  12943. // Animations
  12944. this.getScene().stopAnimation(this);
  12945. // Remove from scene
  12946. this.getScene().removeCamera(this);
  12947. while (this._rigCameras.length > 0) {
  12948. this._rigCameras.pop().dispose();
  12949. }
  12950. // Postprocesses
  12951. for (var i = 0; i < this._postProcesses.length; ++i) {
  12952. this._postProcesses[i].dispose(this);
  12953. }
  12954. _super.prototype.dispose.call(this);
  12955. };
  12956. // ---- Camera rigs section ----
  12957. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12958. while (this._rigCameras.length > 0) {
  12959. this._rigCameras.pop().dispose();
  12960. }
  12961. this.cameraRigMode = mode;
  12962. this._cameraRigParams = {};
  12963. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12964. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12965. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12966. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12967. // create the rig cameras, unless none
  12968. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12969. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12970. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12971. }
  12972. switch (this.cameraRigMode) {
  12973. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12974. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12975. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12976. break;
  12977. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12978. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12979. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12980. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12981. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12982. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12983. break;
  12984. case Camera.RIG_MODE_VR:
  12985. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12986. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12987. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12988. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12989. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12990. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12991. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12992. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12993. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12994. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12995. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12996. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12997. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12998. if (metrics.compensateDistortion) {
  12999. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13000. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13001. }
  13002. break;
  13003. case Camera.RIG_MODE_WEBVR:
  13004. if (rigParams.vrDisplay) {
  13005. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13006. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13007. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13008. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  13009. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13010. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13011. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13012. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13013. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  13014. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13015. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13016. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13017. }
  13018. break;
  13019. }
  13020. this._cascadePostProcessesToRigCams();
  13021. this.
  13022. update();
  13023. };
  13024. Camera.prototype._getVRProjectionMatrix = function () {
  13025. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13026. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13027. return this._projectionMatrix;
  13028. };
  13029. Camera.prototype._getWebVRProjectionMatrix = function () {
  13030. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13031. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  13032. return this._projectionMatrix;
  13033. };
  13034. Camera.prototype.setCameraRigParameter = function (name, value) {
  13035. if (!this._cameraRigParams) {
  13036. this._cameraRigParams = {};
  13037. }
  13038. this._cameraRigParams[name] = value;
  13039. //provisionnally:
  13040. if (name === "interaxialDistance") {
  13041. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13042. }
  13043. };
  13044. /**
  13045. * needs to be overridden by children so sub has required properties to be copied
  13046. */
  13047. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13048. return null;
  13049. };
  13050. /**
  13051. * May need to be overridden by children
  13052. */
  13053. Camera.prototype._updateRigCameras = function () {
  13054. for (var i = 0; i < this._rigCameras.length; i++) {
  13055. this._rigCameras[i].minZ = this.minZ;
  13056. this._rigCameras[i].maxZ = this.maxZ;
  13057. this._rigCameras[i].fov = this.fov;
  13058. }
  13059. // only update viewport when ANAGLYPH
  13060. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13061. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13062. }
  13063. };
  13064. Camera.prototype._setupInputs = function () {
  13065. };
  13066. Camera.prototype.serialize = function () {
  13067. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13068. // Type
  13069. serializationObject.type = this.getTypeName();
  13070. // Parent
  13071. if (this.parent) {
  13072. serializationObject.parentId = this.parent.id;
  13073. }
  13074. if (this.inputs) {
  13075. this.inputs.serialize(serializationObject);
  13076. }
  13077. // Animations
  13078. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13079. serializationObject.ranges = this.serializeAnimationRanges();
  13080. return serializationObject;
  13081. };
  13082. Camera.prototype.getTypeName = function () {
  13083. return "Camera";
  13084. };
  13085. Camera.prototype.clone = function (name) {
  13086. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13087. };
  13088. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13089. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13090. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13091. switch (type) {
  13092. case "ArcRotateCamera":
  13093. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13094. case "DeviceOrientationCamera":
  13095. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13096. case "FollowCamera":
  13097. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13098. case "ArcFollowCamera":
  13099. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13100. case "GamepadCamera":
  13101. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13102. case "TouchCamera":
  13103. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13104. case "VirtualJoysticksCamera":
  13105. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13106. case "WebVRFreeCamera":
  13107. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13108. case "VRDeviceOrientationFreeCamera":
  13109. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13110. case "AnaglyphArcRotateCamera":
  13111. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13112. case "AnaglyphFreeCamera":
  13113. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13114. case "AnaglyphGamepadCamera":
  13115. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13116. case "AnaglyphUniversalCamera":
  13117. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13118. case "StereoscopicArcRotateCamera":
  13119. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13120. case "StereoscopicFreeCamera":
  13121. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13122. case "StereoscopicGamepadCamera":
  13123. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13124. case "StereoscopicUniversalCamera":
  13125. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13126. case "FreeCamera":
  13127. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13128. default:
  13129. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13130. }
  13131. };
  13132. Camera.Parse = function (parsedCamera, scene) {
  13133. var type = parsedCamera.type;
  13134. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13135. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13136. // Parent
  13137. if (parsedCamera.parentId) {
  13138. camera._waitingParentId = parsedCamera.parentId;
  13139. }
  13140. //If camera has an input manager, let it parse inputs settings
  13141. if (camera.inputs) {
  13142. camera.inputs.parse(parsedCamera);
  13143. camera._setupInputs();
  13144. }
  13145. // Target
  13146. if (parsedCamera.target) {
  13147. if (camera.setTarget) {
  13148. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13149. }
  13150. }
  13151. // Apply 3d rig, when found
  13152. if (parsedCamera.cameraRigMode) {
  13153. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13154. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13155. }
  13156. // Animations
  13157. if (parsedCamera.animations) {
  13158. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13159. var parsedAnimation = parsedCamera.animations[animationIndex];
  13160. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13161. }
  13162. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13163. }
  13164. if (parsedCamera.autoAnimate) {
  13165. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13166. }
  13167. return camera;
  13168. };
  13169. // Statics
  13170. Camera._PERSPECTIVE_CAMERA = 0;
  13171. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13172. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13173. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13174. Camera._RIG_MODE_NONE = 0;
  13175. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13176. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13177. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13178. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13179. Camera._RIG_MODE_VR = 20;
  13180. Camera._RIG_MODE_WEBVR = 21;
  13181. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13182. __decorate([
  13183. BABYLON.serializeAsVector3()
  13184. ], Camera.prototype, "position", void 0);
  13185. __decorate([
  13186. BABYLON.serializeAsVector3()
  13187. ], Camera.prototype, "upVector", void 0);
  13188. __decorate([
  13189. BABYLON.serialize()
  13190. ], Camera.prototype, "orthoLeft", void 0);
  13191. __decorate([
  13192. BABYLON.serialize()
  13193. ], Camera.prototype, "orthoRight", void 0);
  13194. __decorate([
  13195. BABYLON.serialize()
  13196. ], Camera.prototype, "orthoBottom", void 0);
  13197. __decorate([
  13198. BABYLON.serialize()
  13199. ], Camera.prototype, "orthoTop", void 0);
  13200. __decorate([
  13201. BABYLON.serialize()
  13202. ], Camera.prototype, "fov", void 0);
  13203. __decorate([
  13204. BABYLON.serialize()
  13205. ], Camera.prototype, "minZ", void 0);
  13206. __decorate([
  13207. BABYLON.serialize()
  13208. ], Camera.prototype, "maxZ", void 0);
  13209. __decorate([
  13210. BABYLON.serialize()
  13211. ], Camera.prototype, "inertia", void 0);
  13212. __decorate([
  13213. BABYLON.serialize()
  13214. ], Camera.prototype, "mode", void 0);
  13215. __decorate([
  13216. BABYLON.serialize()
  13217. ], Camera.prototype, "layerMask", void 0);
  13218. __decorate([
  13219. BABYLON.serialize()
  13220. ], Camera.prototype, "fovMode", void 0);
  13221. __decorate([
  13222. BABYLON.serialize()
  13223. ], Camera.prototype, "cameraRigMode", void 0);
  13224. __decorate([
  13225. BABYLON.serialize()
  13226. ], Camera.prototype, "interaxialDistance", void 0);
  13227. __decorate([
  13228. BABYLON.serialize()
  13229. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13230. return Camera;
  13231. }(BABYLON.Node));
  13232. BABYLON.Camera = Camera;
  13233. })(BABYLON || (BABYLON = {}));
  13234. var BABYLON;
  13235. (function (BABYLON) {
  13236. BABYLON.CameraInputTypes = {};
  13237. var CameraInputsManager = (function () {
  13238. function CameraInputsManager(camera) {
  13239. this.attached = {};
  13240. this.camera = camera;
  13241. this.checkInputs = function () { };
  13242. }
  13243. CameraInputsManager.prototype.add = function (input) {
  13244. var type = input.getSimpleName();
  13245. if (this.attached[type]) {
  13246. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13247. return;
  13248. }
  13249. this.attached[type] = input;
  13250. input.camera = this.camera;
  13251. //for checkInputs, we are dynamically creating a function
  13252. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13253. if (input.checkInputs) {
  13254. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13255. }
  13256. if (this.attachedElement) {
  13257. input.attachControl(this.attachedElement);
  13258. }
  13259. };
  13260. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13261. for (var cam in this.attached) {
  13262. var input = this.attached[cam];
  13263. if (input === inputToRemove) {
  13264. input.detachControl(this.attachedElement);
  13265. delete this.attached[cam];
  13266. this.rebuildInputCheck();
  13267. }
  13268. }
  13269. };
  13270. CameraInputsManager.prototype.removeByType = function (inputType) {
  13271. for (var cam in this.attached) {
  13272. var input = this.attached[cam];
  13273. if (input.getTypeName() === inputType) {
  13274. input.detachControl(this.attachedElement);
  13275. delete this.attached[cam];
  13276. this.rebuildInputCheck();
  13277. }
  13278. }
  13279. };
  13280. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13281. var current = this.checkInputs;
  13282. return function () {
  13283. current();
  13284. fn();
  13285. };
  13286. };
  13287. CameraInputsManager.prototype.attachInput = function (input) {
  13288. input.attachControl(this.attachedElement, this.noPreventDefault);
  13289. };
  13290. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13291. if (this.attachedElement) {
  13292. return;
  13293. }
  13294. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13295. this.attachedElement = element;
  13296. this.noPreventDefault = noPreventDefault;
  13297. for (var cam in this.attached) {
  13298. var input = this.attached[cam];
  13299. this.attached[cam].attachControl(element, noPreventDefault);
  13300. }
  13301. };
  13302. CameraInputsManager.prototype.detachElement = function (element) {
  13303. if (this.attachedElement !== element) {
  13304. return;
  13305. }
  13306. for (var cam in this.attached) {
  13307. var input = this.attached[cam];
  13308. this.attached[cam].detachControl(element);
  13309. }
  13310. this.attachedElement = null;
  13311. };
  13312. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13313. this.checkInputs = function () { };
  13314. for (var cam in this.attached) {
  13315. var input = this.attached[cam];
  13316. if (input.checkInputs) {
  13317. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13318. }
  13319. }
  13320. };
  13321. CameraInputsManager.prototype.clear = function () {
  13322. if (this.attachedElement) {
  13323. this.detachElement(this.attachedElement);
  13324. }
  13325. this.attached = {};
  13326. this.attachedElement = null;
  13327. this.checkInputs = function () { };
  13328. };
  13329. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13330. var inputs = {};
  13331. for (var cam in this.attached) {
  13332. var input = this.attached[cam];
  13333. var res = BABYLON.SerializationHelper.Serialize(input);
  13334. inputs[input.getTypeName()] = res;
  13335. }
  13336. serializedCamera.inputsmgr = inputs;
  13337. };
  13338. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13339. var parsedInputs = parsedCamera.inputsmgr;
  13340. if (parsedInputs) {
  13341. this.clear();
  13342. for (var n in parsedInputs) {
  13343. var construct = BABYLON.CameraInputTypes[n];
  13344. if (construct) {
  13345. var parsedinput = parsedInputs[n];
  13346. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13347. this.add(input);
  13348. }
  13349. }
  13350. }
  13351. else {
  13352. //2016-03-08 this part is for managing backward compatibility
  13353. for (var n in this.attached) {
  13354. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13355. if (construct) {
  13356. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13357. this.remove(this.attached[n]);
  13358. this.add(input);
  13359. }
  13360. }
  13361. }
  13362. };
  13363. return CameraInputsManager;
  13364. }());
  13365. BABYLON.CameraInputsManager = CameraInputsManager;
  13366. })(BABYLON || (BABYLON = {}));
  13367. var BABYLON;
  13368. (function (BABYLON) {
  13369. var FreeCameraMouseInput = (function () {
  13370. function FreeCameraMouseInput(touchEnabled) {
  13371. if (touchEnabled === void 0) { touchEnabled = true; }
  13372. this.touchEnabled = touchEnabled;
  13373. this.angularSensibility = 2000.0;
  13374. }
  13375. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13376. var _this = this;
  13377. var engine = this.camera.getEngine();
  13378. if (!this._pointerInput) {
  13379. this._pointerInput = function (p, s) {
  13380. var evt = p.event;
  13381. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13382. return;
  13383. }
  13384. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13385. try {
  13386. evt.srcElement.setPointerCapture(evt.pointerId);
  13387. }
  13388. catch (e) {
  13389. }
  13390. _this.previousPosition = {
  13391. x: evt.clientX,
  13392. y: evt.clientY
  13393. };
  13394. if (!noPreventDefault) {
  13395. evt.preventDefault();
  13396. element.focus();
  13397. }
  13398. }
  13399. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13400. try {
  13401. evt.srcElement.releasePointerCapture(evt.pointerId);
  13402. }
  13403. catch (e) {
  13404. }
  13405. _this.previousPosition = null;
  13406. if (!noPreventDefault) {
  13407. evt.preventDefault();
  13408. }
  13409. }
  13410. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13411. if (!_this.previousPosition || engine.isPointerLock) {
  13412. return;
  13413. }
  13414. var offsetX = evt.clientX - _this.previousPosition.x;
  13415. var offsetY = evt.clientY - _this.previousPosition.y;
  13416. if (_this.camera.getScene().useRightHandedSystem) {
  13417. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13418. }
  13419. else {
  13420. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13421. }
  13422. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13423. _this.previousPosition = {
  13424. x: evt.clientX,
  13425. y: evt.clientY
  13426. };
  13427. if (!noPreventDefault) {
  13428. evt.preventDefault();
  13429. }
  13430. }
  13431. };
  13432. }
  13433. this._onMouseMove = function (evt) {
  13434. if (!engine.isPointerLock) {
  13435. return;
  13436. }
  13437. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13438. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13439. if (_this.camera.getScene().useRightHandedSystem) {
  13440. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13441. }
  13442. else {
  13443. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13444. }
  13445. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13446. _this.previousPosition = null;
  13447. if (!noPreventDefault) {
  13448. evt.preventDefault();
  13449. }
  13450. };
  13451. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13452. element.addEventListener("mousemove", this._onMouseMove, false);
  13453. };
  13454. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13455. if (this._observer && element) {
  13456. this.camera.getScene().onPointerObservable.remove(this._observer);
  13457. element.removeEventListener("mousemove", this._onMouseMove);
  13458. this._observer = null;
  13459. this._onMouseMove = null;
  13460. this.previousPosition = null;
  13461. }
  13462. };
  13463. FreeCameraMouseInput.prototype.getTypeName = function () {
  13464. return "FreeCameraMouseInput";
  13465. };
  13466. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13467. return "mouse";
  13468. };
  13469. __decorate([
  13470. BABYLON.serialize()
  13471. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13472. return FreeCameraMouseInput;
  13473. }());
  13474. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13475. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13476. })(BABYLON || (BABYLON = {}));
  13477. var BABYLON;
  13478. (function (BABYLON) {
  13479. var FreeCameraKeyboardMoveInput = (function () {
  13480. function FreeCameraKeyboardMoveInput() {
  13481. this._keys = [];
  13482. this.keysUp = [38];
  13483. this.keysDown = [40];
  13484. this.keysLeft = [37];
  13485. this.keysRight = [39];
  13486. }
  13487. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13488. var _this = this;
  13489. if (!this._onKeyDown) {
  13490. element.tabIndex = 1;
  13491. this._onKeyDown = function (evt) {
  13492. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13493. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13494. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13495. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13496. var index = _this._keys.indexOf(evt.keyCode);
  13497. if (index === -1) {
  13498. _this._keys.push(evt.keyCode);
  13499. }
  13500. if (!noPreventDefault) {
  13501. evt.preventDefault();
  13502. }
  13503. }
  13504. };
  13505. this._onKeyUp = function (evt) {
  13506. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13507. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13508. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13509. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13510. var index = _this._keys.indexOf(evt.keyCode);
  13511. if (index >= 0) {
  13512. _this._keys.splice(index, 1);
  13513. }
  13514. if (!noPreventDefault) {
  13515. evt.preventDefault();
  13516. }
  13517. }
  13518. };
  13519. element.addEventListener("keydown", this._onKeyDown, false);
  13520. element.addEventListener("keyup", this._onKeyUp, false);
  13521. BABYLON.Tools.RegisterTopRootEvents([
  13522. { name: "blur", handler: this._onLostFocus }
  13523. ]);
  13524. }
  13525. };
  13526. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13527. if (this._onKeyDown) {
  13528. element.removeEventListener("keydown", this._onKeyDown);
  13529. element.removeEventListener("keyup", this._onKeyUp);
  13530. BABYLON.Tools.UnregisterTopRootEvents([
  13531. { name: "blur", handler: this._onLostFocus }
  13532. ]);
  13533. this._keys = [];
  13534. this._onKeyDown = null;
  13535. this._onKeyUp = null;
  13536. }
  13537. };
  13538. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13539. if (this._onKeyDown) {
  13540. var camera = this.camera;
  13541. // Keyboard
  13542. for (var index = 0; index < this._keys.length; index++) {
  13543. var keyCode = this._keys[index];
  13544. var speed = camera._computeLocalCameraSpeed();
  13545. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13546. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13547. }
  13548. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13549. camera._localDirection.copyFromFloats(0, 0, speed);
  13550. }
  13551. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13552. camera._localDirection.copyFromFloats(speed, 0, 0);
  13553. }
  13554. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13555. camera._localDirection.copyFromFloats(0, 0, -speed);
  13556. }
  13557. if (camera.getScene().useRightHandedSystem) {
  13558. camera._localDirection.z *= -1;
  13559. }
  13560. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13561. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13562. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13563. }
  13564. }
  13565. };
  13566. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13567. return "FreeCameraKeyboardMoveInput";
  13568. };
  13569. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13570. this._keys = [];
  13571. };
  13572. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13573. return "keyboard";
  13574. };
  13575. __decorate([
  13576. BABYLON.serialize()
  13577. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13578. __decorate([
  13579. BABYLON.serialize()
  13580. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13581. __decorate([
  13582. BABYLON.serialize()
  13583. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13584. __decorate([
  13585. BABYLON.serialize()
  13586. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13587. return FreeCameraKeyboardMoveInput;
  13588. }());
  13589. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13590. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13591. })(BABYLON || (BABYLON = {}));
  13592. var BABYLON;
  13593. (function (BABYLON) {
  13594. var FreeCameraTouchInput = (function () {
  13595. function FreeCameraTouchInput() {
  13596. this._offsetX = null;
  13597. this._offsetY = null;
  13598. this._pointerCount = 0;
  13599. this._pointerPressed = [];
  13600. this.touchAngularSensibility = 200000.0;
  13601. this.touchMoveSensibility = 250.0;
  13602. }
  13603. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13604. var _this = this;
  13605. var previousPosition;
  13606. if (this._pointerInput === undefined) {
  13607. this._onLostFocus = function (evt) {
  13608. _this._offsetX = null;
  13609. _this._offsetY = null;
  13610. };
  13611. this._pointerInput = function (p, s) {
  13612. var evt = p.event;
  13613. if (evt.pointerType === "mouse") {
  13614. return;
  13615. }
  13616. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13617. if (!noPreventDefault) {
  13618. evt.preventDefault();
  13619. }
  13620. _this._pointerPressed.push(evt.pointerId);
  13621. if (_this._pointerPressed.length !== 1) {
  13622. return;
  13623. }
  13624. previousPosition = {
  13625. x: evt.clientX,
  13626. y: evt.clientY
  13627. };
  13628. }
  13629. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13630. if (!noPreventDefault) {
  13631. evt.preventDefault();
  13632. }
  13633. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13634. if (index === -1) {
  13635. return;
  13636. }
  13637. _this._pointerPressed.splice(index, 1);
  13638. if (index != 0) {
  13639. return;
  13640. }
  13641. previousPosition = null;
  13642. _this._offsetX = null;
  13643. _this._offsetY = null;
  13644. }
  13645. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13646. if (!noPreventDefault) {
  13647. evt.preventDefault();
  13648. }
  13649. if (!previousPosition) {
  13650. return;
  13651. }
  13652. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13653. if (index != 0) {
  13654. return;
  13655. }
  13656. _this._offsetX = evt.clientX - previousPosition.x;
  13657. _this._offsetY = -(evt.clientY - previousPosition.y);
  13658. }
  13659. };
  13660. }
  13661. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13662. element.addEventListener("blur", this._onLostFocus);
  13663. };
  13664. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13665. if (this._pointerInput && element) {
  13666. this.camera.getScene().onPointerObservable.remove(this._observer);
  13667. this._observer = null;
  13668. element.removeEventListener("blur", this._onLostFocus);
  13669. this._onLostFocus = null;
  13670. this._pointerPressed = [];
  13671. this._offsetX = null;
  13672. this._offsetY = null;
  13673. this._pointerCount = 0;
  13674. }
  13675. };
  13676. FreeCameraTouchInput.prototype.checkInputs = function () {
  13677. if (this._offsetX) {
  13678. var camera = this.camera;
  13679. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13680. if (this._pointerPressed.length > 1) {
  13681. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13682. }
  13683. else {
  13684. var speed = camera._computeLocalCameraSpeed();
  13685. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13686. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13687. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13688. }
  13689. }
  13690. };
  13691. FreeCameraTouchInput.prototype.getTypeName = function () {
  13692. return "FreeCameraTouchInput";
  13693. };
  13694. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13695. return "touch";
  13696. };
  13697. __decorate([
  13698. BABYLON.serialize()
  13699. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13700. __decorate([
  13701. BABYLON.serialize()
  13702. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13703. return FreeCameraTouchInput;
  13704. }());
  13705. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13706. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13707. })(BABYLON || (BABYLON = {}));
  13708. var BABYLON;
  13709. (function (BABYLON) {
  13710. var FreeCameraDeviceOrientationInput = (function () {
  13711. function FreeCameraDeviceOrientationInput() {
  13712. var _this = this;
  13713. this._screenOrientationAngle = 0;
  13714. this._screenQuaternion = new BABYLON.Quaternion();
  13715. this._alpha = 0;
  13716. this._beta = 0;
  13717. this._gamma = 0;
  13718. this._orientationChanged = function () {
  13719. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13720. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13721. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13722. };
  13723. this._deviceOrientation = function (evt) {
  13724. _this._alpha = evt.alpha;
  13725. _this._beta = evt.beta;
  13726. _this._gamma = evt.gamma;
  13727. };
  13728. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13729. this._orientationChanged();
  13730. }
  13731. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13732. get: function () {
  13733. return this._camera;
  13734. },
  13735. set: function (camera) {
  13736. this._camera = camera;
  13737. if (!this._camera.rotationQuaternion)
  13738. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13739. },
  13740. enumerable: true,
  13741. configurable: true
  13742. });
  13743. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13744. window.addEventListener("orientationchange", this._orientationChanged);
  13745. window.addEventListener("deviceorientation", this._deviceOrientation);
  13746. //In certain cases, the attach control is called AFTER orientation was changed,
  13747. //So this is needed.
  13748. this._orientationChanged();
  13749. };
  13750. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13751. window.removeEventListener("orientationchange", this._orientationChanged);
  13752. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13753. };
  13754. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13755. //if no device orientation provided, don't update the rotation.
  13756. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13757. if (!this._alpha)
  13758. return;
  13759. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13760. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13761. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13762. //Mirror on XY Plane
  13763. this._camera.rotationQuaternion.z *= -1;
  13764. this._camera.rotationQuaternion.w *= -1;
  13765. };
  13766. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13767. return "FreeCameraDeviceOrientationInput";
  13768. };
  13769. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13770. return "deviceOrientation";
  13771. };
  13772. return FreeCameraDeviceOrientationInput;
  13773. }());
  13774. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13775. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13776. })(BABYLON || (BABYLON = {}));
  13777. var BABYLON;
  13778. (function (BABYLON) {
  13779. var FreeCameraGamepadInput = (function () {
  13780. function FreeCameraGamepadInput() {
  13781. this.gamepadAngularSensibility = 200;
  13782. this.gamepadMoveSensibility = 40;
  13783. }
  13784. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13785. var _this = this;
  13786. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13787. };
  13788. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13789. if (this._gamepads) {
  13790. this._gamepads.dispose();
  13791. }
  13792. this.gamepad = null;
  13793. };
  13794. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13795. if (this.gamepad) {
  13796. var camera = this.camera;
  13797. var LSValues = this.gamepad.leftStick;
  13798. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13799. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13800. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13801. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13802. var RSValues = this.gamepad.rightStick;
  13803. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13804. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13805. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13806. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13807. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13808. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13809. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13810. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13811. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13812. }
  13813. };
  13814. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13815. // Only the first gamepad can control the camera
  13816. if (gamepad.index === 0) {
  13817. this.gamepad = gamepad;
  13818. }
  13819. };
  13820. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13821. return "FreeCameraGamepadInput";
  13822. };
  13823. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13824. return "gamepad";
  13825. };
  13826. __decorate([
  13827. BABYLON.serialize()
  13828. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13829. __decorate([
  13830. BABYLON.serialize()
  13831. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13832. return FreeCameraGamepadInput;
  13833. }());
  13834. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13835. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13836. })(BABYLON || (BABYLON = {}));
  13837. var BABYLON;
  13838. (function (BABYLON) {
  13839. var ArcRotateCameraKeyboardMoveInput = (function () {
  13840. function ArcRotateCameraKeyboardMoveInput() {
  13841. this._keys = [];
  13842. this.keysUp = [38];
  13843. this.keysDown = [40];
  13844. this.keysLeft = [37];
  13845. this.keysRight = [39];
  13846. }
  13847. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13848. var _this = this;
  13849. element.tabIndex = 1;
  13850. this._onKeyDown = function (evt) {
  13851. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13852. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13853. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13854. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13855. var index = _this._keys.indexOf(evt.keyCode);
  13856. if (index === -1) {
  13857. _this._keys.push(evt.keyCode);
  13858. }
  13859. if (evt.preventDefault) {
  13860. if (!noPreventDefault) {
  13861. evt.preventDefault();
  13862. }
  13863. }
  13864. }
  13865. };
  13866. this._onKeyUp = function (evt) {
  13867. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13868. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13869. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13870. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13871. var index = _this._keys.indexOf(evt.keyCode);
  13872. if (index >= 0) {
  13873. _this._keys.splice(index, 1);
  13874. }
  13875. if (evt.preventDefault) {
  13876. if (!noPreventDefault) {
  13877. evt.preventDefault();
  13878. }
  13879. }
  13880. }
  13881. };
  13882. this._onLostFocus = function () {
  13883. _this._keys = [];
  13884. };
  13885. element.addEventListener("keydown", this._onKeyDown, false);
  13886. element.addEventListener("keyup", this._onKeyUp, false);
  13887. BABYLON.Tools.RegisterTopRootEvents([
  13888. { name: "blur", handler: this._onLostFocus }
  13889. ]);
  13890. };
  13891. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13892. if (element) {
  13893. element.removeEventListener("keydown", this._onKeyDown);
  13894. element.removeEventListener("keyup", this._onKeyUp);
  13895. }
  13896. BABYLON.Tools.UnregisterTopRootEvents([
  13897. { name: "blur", handler: this._onLostFocus }
  13898. ]);
  13899. this._keys = [];
  13900. this._onKeyDown = null;
  13901. this._onKeyUp = null;
  13902. this._onLostFocus = null;
  13903. };
  13904. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13905. if (this._onKeyDown) {
  13906. var camera = this.camera;
  13907. for (var index = 0; index < this._keys.length; index++) {
  13908. var keyCode = this._keys[index];
  13909. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13910. camera.inertialAlphaOffset -= 0.01;
  13911. }
  13912. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13913. camera.inertialBetaOffset -= 0.01;
  13914. }
  13915. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13916. camera.inertialAlphaOffset += 0.01;
  13917. }
  13918. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13919. camera.inertialBetaOffset += 0.01;
  13920. }
  13921. }
  13922. }
  13923. };
  13924. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13925. return "ArcRotateCameraKeyboardMoveInput";
  13926. };
  13927. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13928. return "keyboard";
  13929. };
  13930. __decorate([
  13931. BABYLON.serialize()
  13932. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13933. __decorate([
  13934. BABYLON.serialize()
  13935. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13936. __decorate([
  13937. BABYLON.serialize()
  13938. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13939. __decorate([
  13940. BABYLON.serialize()
  13941. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13942. return ArcRotateCameraKeyboardMoveInput;
  13943. }());
  13944. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13945. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13946. })(BABYLON || (BABYLON = {}));
  13947. var BABYLON;
  13948. (function (BABYLON) {
  13949. var ArcRotateCameraMouseWheelInput = (function () {
  13950. function ArcRotateCameraMouseWheelInput() {
  13951. this.wheelPrecision = 3.0;
  13952. }
  13953. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13954. var _this = this;
  13955. this._wheel = function (p, s) {
  13956. //sanity check - this should be a PointerWheel event.
  13957. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13958. return;
  13959. var event = p.event;
  13960. var delta = 0;
  13961. if (event.wheelDelta) {
  13962. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13963. }
  13964. else if (event.detail) {
  13965. delta = -event.detail / _this.wheelPrecision;
  13966. }
  13967. if (delta)
  13968. _this.camera.inertialRadiusOffset += delta;
  13969. if (event.preventDefault) {
  13970. if (!noPreventDefault) {
  13971. event.preventDefault();
  13972. }
  13973. }
  13974. };
  13975. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13976. };
  13977. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13978. if (this._observer && element) {
  13979. this.camera.getScene().onPointerObservable.remove(this._observer);
  13980. this._observer = null;
  13981. this._wheel = null;
  13982. }
  13983. };
  13984. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13985. return "ArcRotateCameraMouseWheelInput";
  13986. };
  13987. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13988. return "mousewheel";
  13989. };
  13990. __decorate([
  13991. BABYLON.serialize()
  13992. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13993. return ArcRotateCameraMouseWheelInput;
  13994. }());
  13995. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13996. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13997. })(BABYLON || (BABYLON = {}));
  13998. var BABYLON;
  13999. (function (BABYLON) {
  14000. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14001. var ArcRotateCameraPointersInput = (function () {
  14002. function ArcRotateCameraPointersInput() {
  14003. this.angularSensibilityX = 1000.0;
  14004. this.angularSensibilityY = 1000.0;
  14005. this.pinchPrecision = 6.0;
  14006. this.panningSensibility = 50.0;
  14007. this._isPanClick = false;
  14008. this.pinchInwards = true;
  14009. }
  14010. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14011. var _this = this;
  14012. var engine = this.camera.getEngine();
  14013. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14014. var pointA, pointB;
  14015. var previousPinchDistance = 0;
  14016. this._pointerInput = function (p, s) {
  14017. var evt = p.event;
  14018. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14019. try {
  14020. evt.srcElement.setPointerCapture(evt.pointerId);
  14021. }
  14022. catch (e) {
  14023. }
  14024. // Manage panning with pan button click
  14025. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14026. // manage pointers
  14027. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14028. if (pointA === undefined) {
  14029. pointA = cacheSoloPointer;
  14030. }
  14031. else if (pointB === undefined) {
  14032. pointB = cacheSoloPointer;
  14033. }
  14034. if (!noPreventDefault) {
  14035. evt.preventDefault();
  14036. element.focus();
  14037. }
  14038. }
  14039. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14040. try {
  14041. evt.srcElement.releasePointerCapture(evt.pointerId);
  14042. }
  14043. catch (e) {
  14044. }
  14045. cacheSoloPointer = null;
  14046. previousPinchDistance = 0;
  14047. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14048. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14049. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14050. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14051. pointA = pointB = undefined;
  14052. if (!noPreventDefault) {
  14053. evt.preventDefault();
  14054. }
  14055. }
  14056. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14057. if (!noPreventDefault) {
  14058. evt.preventDefault();
  14059. }
  14060. // One button down
  14061. if (pointA && pointB === undefined) {
  14062. if (_this.panningSensibility !== 0 &&
  14063. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14064. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14065. _this.camera
  14066. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14067. _this.camera
  14068. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14069. }
  14070. else {
  14071. var offsetX = evt.clientX - cacheSoloPointer.x;
  14072. var offsetY = evt.clientY - cacheSoloPointer.y;
  14073. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14074. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14075. }
  14076. cacheSoloPointer.x = evt.clientX;
  14077. cacheSoloPointer.y = evt.clientY;
  14078. }
  14079. else if (pointA && pointB) {
  14080. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14081. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14082. ed.x = evt.clientX;
  14083. ed.y = evt.clientY;
  14084. var direction = _this.pinchInwards ? 1 : -1;
  14085. var distX = pointA.x - pointB.x;
  14086. var distY = pointA.y - pointB.y;
  14087. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14088. if (previousPinchDistance === 0) {
  14089. previousPinchDistance = pinchSquaredDistance;
  14090. return;
  14091. }
  14092. if (pinchSquaredDistance !== previousPinchDistance) {
  14093. _this.camera
  14094. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14095. (_this.pinchPrecision *
  14096. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14097. direction);
  14098. previousPinchDistance = pinchSquaredDistance;
  14099. }
  14100. }
  14101. }
  14102. };
  14103. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14104. this._onContextMenu = function (evt) {
  14105. evt.preventDefault();
  14106. };
  14107. if (!this.camera._useCtrlForPanning) {
  14108. element.addEventListener("contextmenu", this._onContextMenu, false);
  14109. }
  14110. this._onLostFocus = function () {
  14111. //this._keys = [];
  14112. pointA = pointB = undefined;
  14113. previousPinchDistance = 0;
  14114. cacheSoloPointer = null;
  14115. };
  14116. this._onMouseMove = function (evt) {
  14117. if (!engine.isPointerLock) {
  14118. return;
  14119. }
  14120. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14121. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14122. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14123. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14124. if (!noPreventDefault) {
  14125. evt.preventDefault();
  14126. }
  14127. };
  14128. this._onGestureStart = function (e) {
  14129. if (window.MSGesture === undefined) {
  14130. return;
  14131. }
  14132. if (!_this._MSGestureHandler) {
  14133. _this._MSGestureHandler = new MSGesture();
  14134. _this._MSGestureHandler.target = element;
  14135. }
  14136. _this._MSGestureHandler.addPointer(e.pointerId);
  14137. };
  14138. this._onGesture = function (e) {
  14139. _this.camera.radius *= e.scale;
  14140. if (e.preventDefault) {
  14141. if (!noPreventDefault) {
  14142. e.stopPropagation();
  14143. e.preventDefault();
  14144. }
  14145. }
  14146. };
  14147. element.addEventListener("mousemove", this._onMouseMove, false);
  14148. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14149. element.addEventListener("MSGestureChange", this._onGesture, false);
  14150. element.addEventListener("keydown", this._onKeyDown, false);
  14151. element.addEventListener("keyup", this._onKeyUp, false);
  14152. BABYLON.Tools.RegisterTopRootEvents([
  14153. { name: "blur", handler: this._onLostFocus }
  14154. ]);
  14155. };
  14156. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14157. if (element && this._observer) {
  14158. this.camera.getScene().onPointerObservable.remove(this._observer);
  14159. this._observer = null;
  14160. element.removeEventListener("contextmenu", this._onContextMenu);
  14161. element.removeEventListener("mousemove", this._onMouseMove);
  14162. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14163. element.removeEventListener("MSGestureChange", this._onGesture);
  14164. element.removeEventListener("keydown", this._onKeyDown);
  14165. element.removeEventListener("keyup", this._onKeyUp);
  14166. this._isPanClick = false;
  14167. this.pinchInwards = true;
  14168. this._onKeyDown = null;
  14169. this._onKeyUp = null;
  14170. this._onMouseMove = null;
  14171. this._onGestureStart = null;
  14172. this._onGesture = null;
  14173. this._MSGestureHandler = null;
  14174. this._onLostFocus = null;
  14175. this._onContextMenu = null;
  14176. }
  14177. BABYLON.Tools.UnregisterTopRootEvents([
  14178. { name: "blur", handler: this._onLostFocus }
  14179. ]);
  14180. };
  14181. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14182. return "ArcRotateCameraPointersInput";
  14183. };
  14184. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14185. return "pointers";
  14186. };
  14187. __decorate([
  14188. BABYLON.serialize()
  14189. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14190. __decorate([
  14191. BABYLON.serialize()
  14192. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14193. __decorate([
  14194. BABYLON.serialize()
  14195. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14196. __decorate([
  14197. BABYLON.serialize()
  14198. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14199. return ArcRotateCameraPointersInput;
  14200. }());
  14201. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14202. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14203. })(BABYLON || (BABYLON = {}));
  14204. var BABYLON;
  14205. (function (BABYLON) {
  14206. var ArcRotateCameraGamepadInput = (function () {
  14207. function ArcRotateCameraGamepadInput() {
  14208. this.gamepadRotationSensibility = 80;
  14209. this.gamepadMoveSensibility = 40;
  14210. }
  14211. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14212. var _this = this;
  14213. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14214. };
  14215. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14216. if (this._gamepads) {
  14217. this._gamepads.dispose();
  14218. }
  14219. this.gamepad = null;
  14220. };
  14221. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14222. if (this.gamepad) {
  14223. var camera = this.camera;
  14224. var RSValues = this.gamepad.rightStick;
  14225. if (RSValues.x != 0) {
  14226. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14227. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14228. camera.inertialAlphaOffset += normalizedRX;
  14229. }
  14230. }
  14231. if (RSValues.y != 0) {
  14232. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14233. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14234. camera.inertialBetaOffset += normalizedRY;
  14235. }
  14236. }
  14237. var LSValues = this.gamepad.leftStick;
  14238. if (LSValues.y != 0) {
  14239. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14240. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14241. this.camera.inertialRadiusOffset -= normalizedLY;
  14242. }
  14243. }
  14244. }
  14245. };
  14246. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14247. // Only the first gamepad can control the camera
  14248. if (gamepad.index === 0) {
  14249. this.gamepad = gamepad;
  14250. }
  14251. };
  14252. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14253. return "ArcRotateCameraGamepadInput";
  14254. };
  14255. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14256. return "gamepad";
  14257. };
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14261. __decorate([
  14262. BABYLON.serialize()
  14263. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14264. return ArcRotateCameraGamepadInput;
  14265. }());
  14266. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14267. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14268. })(BABYLON || (BABYLON = {}));
  14269. var BABYLON;
  14270. (function (BABYLON) {
  14271. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14272. function ArcRotateCameraVRDeviceOrientationInput() {
  14273. this.alphaCorrection = 1;
  14274. this.betaCorrection = 1;
  14275. this.gammaCorrection = 1;
  14276. this._alpha = 0;
  14277. this._beta = 0;
  14278. this._gamma = 0;
  14279. this._dirty = false;
  14280. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14281. }
  14282. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14283. this.camera.attachControl(element, noPreventDefault);
  14284. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14285. };
  14286. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14287. var camera = this.camera;
  14288. this._alpha = +evt.alpha | 0;
  14289. this._beta = +evt.beta | 0;
  14290. this._gamma = +evt.gamma | 0;
  14291. this._dirty = true;
  14292. };
  14293. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14294. if (this._dirty) {
  14295. this._dirty = false;
  14296. if (this._gamma < 0) {
  14297. this._gamma = 180 + this._gamma;
  14298. }
  14299. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14300. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14301. }
  14302. };
  14303. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14304. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14305. };
  14306. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14307. return "ArcRotateCameraVRDeviceOrientationInput";
  14308. };
  14309. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14310. return "VRDeviceOrientation";
  14311. };
  14312. return ArcRotateCameraVRDeviceOrientationInput;
  14313. }());
  14314. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14315. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14316. })(BABYLON || (BABYLON = {}));
  14317. var BABYLON;
  14318. (function (BABYLON) {
  14319. var TargetCamera = (function (_super) {
  14320. __extends(TargetCamera, _super);
  14321. function TargetCamera(name, position, scene) {
  14322. _super.call(this, name, position, scene);
  14323. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14324. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14325. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14326. this.speed = 2.0;
  14327. this.noRotationConstraint = false;
  14328. this.lockedTarget = null;
  14329. this._currentTarget = BABYLON.Vector3.Zero();
  14330. this._viewMatrix = BABYLON.Matrix.Zero();
  14331. this._camMatrix = BABYLON.Matrix.Zero();
  14332. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14333. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14334. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14335. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14336. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14337. this._lookAtTemp = BABYLON.Matrix.Zero();
  14338. this._tempMatrix = BABYLON.Matrix.Zero();
  14339. }
  14340. TargetCamera.prototype.getFrontPosition = function (distance) {
  14341. var direction = this.getTarget().subtract(this.position);
  14342. direction.normalize();
  14343. direction.scaleInPlace(distance);
  14344. return this.globalPosition.add(direction);
  14345. };
  14346. TargetCamera.prototype._getLockedTargetPosition = function () {
  14347. if (!this.lockedTarget) {
  14348. return null;
  14349. }
  14350. return this.lockedTarget.position || this.lockedTarget;
  14351. };
  14352. // Cache
  14353. TargetCamera.prototype._initCache = function () {
  14354. _super.prototype._initCache.call(this);
  14355. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14356. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14357. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14358. };
  14359. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14360. if (!ignoreParentClass) {
  14361. _super.prototype._updateCache.call(this);
  14362. }
  14363. var lockedTargetPosition = this._getLockedTargetPosition();
  14364. if (!lockedTargetPosition) {
  14365. this._cache.lockedTarget = null;
  14366. }
  14367. else {
  14368. if (!this._cache.lockedTarget) {
  14369. this._cache.lockedTarget = lockedTargetPosition.clone();
  14370. }
  14371. else {
  14372. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14373. }
  14374. }
  14375. this._cache.rotation.copyFrom(this.rotation);
  14376. if (this.rotationQuaternion)
  14377. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14378. };
  14379. // Synchronized
  14380. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14381. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14382. return false;
  14383. }
  14384. var lockedTargetPosition = this._getLockedTargetPosition();
  14385. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14386. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14387. };
  14388. // Methods
  14389. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14390. var engine = this.getEngine();
  14391. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14392. };
  14393. // Target
  14394. TargetCamera.prototype.setTarget = function (target) {
  14395. this.upVector.normalize();
  14396. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14397. this._camMatrix.invert();
  14398. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14399. var vDir = target.subtract(this.position);
  14400. if (vDir.x >= 0.0) {
  14401. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14402. }
  14403. else {
  14404. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14405. }
  14406. this.rotation.z = 0;
  14407. if (isNaN(this.rotation.x)) {
  14408. this.rotation.x = 0;
  14409. }
  14410. if (isNaN(this.rotation.y)) {
  14411. this.rotation.y = 0;
  14412. }
  14413. if (isNaN(this.rotation.z)) {
  14414. this.rotation.z = 0;
  14415. }
  14416. if (this.rotationQuaternion) {
  14417. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14418. }
  14419. };
  14420. TargetCamera.prototype.getTarget = function () {
  14421. return this._currentTarget;
  14422. };
  14423. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14424. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14425. };
  14426. TargetCamera.prototype._updatePosition = function () {
  14427. this.position.addInPlace(this.cameraDirection);
  14428. };
  14429. TargetCamera.prototype._checkInputs = function () {
  14430. var needToMove = this._decideIfNeedsToMove();
  14431. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14432. // Move
  14433. if (needToMove) {
  14434. this._updatePosition();
  14435. }
  14436. // Rotate
  14437. if (needToRotate) {
  14438. this.rotation.x += this.cameraRotation.x;
  14439. this.rotation.y += this.cameraRotation.y;
  14440. if (!this.noRotationConstraint) {
  14441. var limit = (Math.PI / 2) * 0.95;
  14442. if (this.rotation.x > limit)
  14443. this.rotation.x = limit;
  14444. if (this.rotation.x < -limit)
  14445. this.rotation.x = -limit;
  14446. }
  14447. }
  14448. // Inertia
  14449. if (needToMove) {
  14450. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14451. this.cameraDirection.x = 0;
  14452. }
  14453. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14454. this.cameraDirection.y = 0;
  14455. }
  14456. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14457. this.cameraDirection.z = 0;
  14458. }
  14459. this.cameraDirection.scaleInPlace(this.inertia);
  14460. }
  14461. if (needToRotate) {
  14462. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14463. this.cameraRotation.x = 0;
  14464. }
  14465. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14466. this.cameraRotation.y = 0;
  14467. }
  14468. this.cameraRotation.scaleInPlace(this.inertia);
  14469. }
  14470. _super.prototype._checkInputs.call(this);
  14471. };
  14472. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14473. if (this.rotationQuaternion) {
  14474. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14475. //update the up vector!
  14476. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14477. }
  14478. else {
  14479. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14480. }
  14481. };
  14482. TargetCamera.prototype._getViewMatrix = function () {
  14483. if (!this.lockedTarget) {
  14484. // Compute
  14485. this._updateCameraRotationMatrix();
  14486. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14487. // Computing target and final matrix
  14488. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14489. }
  14490. else {
  14491. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14492. }
  14493. if (this.getScene().useRightHandedSystem) {
  14494. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14495. }
  14496. else {
  14497. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14498. }
  14499. return this._viewMatrix;
  14500. };
  14501. /**
  14502. * @override
  14503. * Override Camera.createRigCamera
  14504. */
  14505. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14506. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14507. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14508. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14509. if (!this.rotationQuaternion) {
  14510. this.rotationQuaternion = new BABYLON.Quaternion();
  14511. }
  14512. rigCamera._cameraRigParams = {};
  14513. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14514. }
  14515. return rigCamera;
  14516. }
  14517. return null;
  14518. };
  14519. /**
  14520. * @override
  14521. * Override Camera._updateRigCameras
  14522. */
  14523. TargetCamera.prototype._updateRigCameras = function () {
  14524. var camLeft = this._rigCameras[0];
  14525. var camRight = this._rigCameras[1];
  14526. switch (this.cameraRigMode) {
  14527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14530. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14531. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14532. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14533. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14534. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14535. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14536. camLeft.setTarget(this.getTarget());
  14537. camRight.setTarget(this.getTarget());
  14538. break;
  14539. case BABYLON.Camera.RIG_MODE_VR:
  14540. case BABYLON.Camera.RIG_MODE_WEBVR:
  14541. if (camLeft.rotationQuaternion) {
  14542. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14543. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14544. }
  14545. else {
  14546. camLeft.rotation.copyFrom(this.rotation);
  14547. camRight.rotation.copyFrom(this.rotation);
  14548. }
  14549. camLeft.position.copyFrom(this.position);
  14550. camRight.position.copyFrom(this.position);
  14551. break;
  14552. }
  14553. _super.prototype._updateRigCameras.call(this);
  14554. };
  14555. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14556. if (!this._rigCamTransformMatrix) {
  14557. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14558. }
  14559. var target = this.getTarget();
  14560. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14561. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14562. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14563. };
  14564. TargetCamera.prototype.getTypeName = function () {
  14565. return "TargetCamera";
  14566. };
  14567. __decorate([
  14568. BABYLON.serializeAsVector3()
  14569. ], TargetCamera.prototype, "rotation", void 0);
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], TargetCamera.prototype, "speed", void 0);
  14573. __decorate([
  14574. BABYLON.serializeAsMeshReference("lockedTargetId")
  14575. ], TargetCamera.prototype, "lockedTarget", void 0);
  14576. return TargetCamera;
  14577. }(BABYLON.Camera));
  14578. BABYLON.TargetCamera = TargetCamera;
  14579. })(BABYLON || (BABYLON = {}));
  14580. var BABYLON;
  14581. (function (BABYLON) {
  14582. var FreeCamera = (function (_super) {
  14583. __extends(FreeCamera, _super);
  14584. function FreeCamera(name, position, scene) {
  14585. var _this = this;
  14586. _super.call(this, name, position, scene);
  14587. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14588. this.checkCollisions = false;
  14589. this.applyGravity = false;
  14590. this._collider = new BABYLON.Collider();
  14591. this._needMoveForGravity = false;
  14592. this._oldPosition = BABYLON.Vector3.Zero();
  14593. this._diffPosition = BABYLON.Vector3.Zero();
  14594. this._newPosition = BABYLON.Vector3.Zero();
  14595. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14596. if (collidedMesh === void 0) { collidedMesh = null; }
  14597. //TODO move this to the collision coordinator!
  14598. if (_this.getScene().workerCollisions)
  14599. newPosition.multiplyInPlace(_this._collider.radius);
  14600. var updatePosition = function (newPos) {
  14601. _this._newPosition.copyFrom(newPos);
  14602. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14603. var oldPosition = _this.position.clone();
  14604. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14605. _this.position.addInPlace(_this._diffPosition);
  14606. if (_this.onCollide && collidedMesh) {
  14607. _this.onCollide(collidedMesh);
  14608. }
  14609. }
  14610. };
  14611. updatePosition(newPosition);
  14612. };
  14613. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14614. this.inputs.addKeyboard().addMouse();
  14615. }
  14616. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14617. //-- begin properties for backward compatibility for inputs
  14618. get: function () {
  14619. var mouse = this.inputs.attached["mouse"];
  14620. if (mouse)
  14621. return mouse.angularSensibility;
  14622. },
  14623. set: function (value) {
  14624. var mouse = this.inputs.attached["mouse"];
  14625. if (mouse)
  14626. mouse.angularSensibility = value;
  14627. },
  14628. enumerable: true,
  14629. configurable: true
  14630. });
  14631. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14632. get: function () {
  14633. var keyboard = this.inputs.attached["keyboard"];
  14634. if (keyboard)
  14635. return keyboard.keysUp;
  14636. },
  14637. set: function (value) {
  14638. var keyboard = this.inputs.attached["keyboard"];
  14639. if (keyboard)
  14640. keyboard.keysUp = value;
  14641. },
  14642. enumerable: true,
  14643. configurable: true
  14644. });
  14645. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14646. get: function () {
  14647. var keyboard = this.inputs.attached["keyboard"];
  14648. if (keyboard)
  14649. return keyboard.keysDown;
  14650. },
  14651. set: function (value) {
  14652. var keyboard = this.inputs.attached["keyboard"];
  14653. if (keyboard)
  14654. keyboard.keysDown = value;
  14655. },
  14656. enumerable: true,
  14657. configurable: true
  14658. });
  14659. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14660. get: function () {
  14661. var keyboard = this.inputs.attached["keyboard"];
  14662. if (keyboard)
  14663. return keyboard.keysLeft;
  14664. },
  14665. set: function (value) {
  14666. var keyboard = this.inputs.attached["keyboard"];
  14667. if (keyboard)
  14668. keyboard.keysLeft = value;
  14669. },
  14670. enumerable: true,
  14671. configurable: true
  14672. });
  14673. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14674. get: function () {
  14675. var keyboard = this.inputs.attached["keyboard"];
  14676. if (keyboard)
  14677. return keyboard.keysRight;
  14678. },
  14679. set: function (value) {
  14680. var keyboard = this.inputs.attached["keyboard"];
  14681. if (keyboard)
  14682. keyboard.keysRight = value;
  14683. },
  14684. enumerable: true,
  14685. configurable: true
  14686. });
  14687. // Controls
  14688. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14689. this.inputs.attachElement(element, noPreventDefault);
  14690. };
  14691. FreeCamera.prototype.detachControl = function (element) {
  14692. this.inputs.detachElement(element);
  14693. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14694. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14695. };
  14696. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14697. var globalPosition;
  14698. if (this.parent) {
  14699. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14700. }
  14701. else {
  14702. globalPosition = this.position;
  14703. }
  14704. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14705. this._collider.radius = this.ellipsoid;
  14706. //no need for clone, as long as gravity is not on.
  14707. var actualVelocity = velocity;
  14708. //add gravity to the velocity to prevent the dual-collision checking
  14709. if (this.applyGravity) {
  14710. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14711. actualVelocity = velocity.add(this.getScene().gravity);
  14712. }
  14713. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14714. };
  14715. FreeCamera.prototype._checkInputs = function () {
  14716. if (!this._localDirection) {
  14717. this._localDirection = BABYLON.Vector3.Zero();
  14718. this._transformedDirection = BABYLON.Vector3.Zero();
  14719. }
  14720. this.inputs.checkInputs();
  14721. _super.prototype._checkInputs.call(this);
  14722. };
  14723. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14724. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14725. };
  14726. FreeCamera.prototype._updatePosition = function () {
  14727. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14728. this._collideWithWorld(this.cameraDirection);
  14729. }
  14730. else {
  14731. this.position.addInPlace(this.cameraDirection);
  14732. }
  14733. };
  14734. FreeCamera.prototype.dispose = function () {
  14735. this.inputs.clear();
  14736. _super.prototype.dispose.call(this);
  14737. };
  14738. FreeCamera.prototype.getTypeName = function () {
  14739. return "FreeCamera";
  14740. };
  14741. __decorate([
  14742. BABYLON.serializeAsVector3()
  14743. ], FreeCamera.prototype, "ellipsoid", void 0);
  14744. __decorate([
  14745. BABYLON.serialize()
  14746. ], FreeCamera.prototype, "checkCollisions", void 0);
  14747. __decorate([
  14748. BABYLON.serialize()
  14749. ], FreeCamera.prototype, "applyGravity", void 0);
  14750. return FreeCamera;
  14751. }(BABYLON.TargetCamera));
  14752. BABYLON.FreeCamera = FreeCamera;
  14753. })(BABYLON || (BABYLON = {}));
  14754. var BABYLON;
  14755. (function (BABYLON) {
  14756. var FreeCameraInputsManager = (function (_super) {
  14757. __extends(FreeCameraInputsManager, _super);
  14758. function FreeCameraInputsManager(camera) {
  14759. _super.call(this, camera);
  14760. }
  14761. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14762. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14763. return this;
  14764. };
  14765. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14766. if (touchEnabled === void 0) { touchEnabled = true; }
  14767. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14768. return this;
  14769. };
  14770. FreeCameraInputsManager.prototype.addGamepad = function () {
  14771. this.add(new BABYLON.FreeCameraGamepadInput());
  14772. return this;
  14773. };
  14774. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14775. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14776. return this;
  14777. };
  14778. FreeCameraInputsManager.prototype.addTouch = function () {
  14779. this.add(new BABYLON.FreeCameraTouchInput());
  14780. return this;
  14781. };
  14782. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14783. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14784. return this;
  14785. };
  14786. return FreeCameraInputsManager;
  14787. }(BABYLON.CameraInputsManager));
  14788. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14789. })(BABYLON || (BABYLON = {}));
  14790. var BABYLON;
  14791. (function (BABYLON) {
  14792. var FollowCamera = (function (_super) {
  14793. __extends(FollowCamera, _super);
  14794. function FollowCamera(name, position, scene, target) {
  14795. _super.call(this, name, position, scene);
  14796. this.radius = 12;
  14797. this.rotationOffset = 0;
  14798. this.heightOffset = 4;
  14799. this.cameraAcceleration = 0.05;
  14800. this.maxCameraSpeed = 20;
  14801. this.target = target;
  14802. }
  14803. FollowCamera.prototype.getRadians = function (degrees) {
  14804. return degrees * Math.PI / 180;
  14805. };
  14806. FollowCamera.prototype.follow = function (cameraTarget) {
  14807. if (!cameraTarget)
  14808. return;
  14809. var yRotation;
  14810. if (cameraTarget.rotationQuaternion) {
  14811. var rotMatrix = new BABYLON.Matrix();
  14812. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14813. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14814. }
  14815. else {
  14816. yRotation = cameraTarget.rotation.y;
  14817. }
  14818. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14819. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14820. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14821. var dx = targetX - this.position.x;
  14822. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14823. var dz = (targetZ) - this.position.z;
  14824. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14825. var vy = dy * this.cameraAcceleration;
  14826. var vz = dz * this.cameraAcceleration * 2;
  14827. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14828. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14829. }
  14830. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14831. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14832. }
  14833. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14834. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14835. }
  14836. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14837. this.setTarget(cameraTarget.position);
  14838. };
  14839. FollowCamera.prototype._checkInputs = function () {
  14840. _super.prototype._checkInputs.call(this);
  14841. this.follow(this.target);
  14842. };
  14843. FollowCamera.prototype.getTypeName = function () {
  14844. return "FollowCamera";
  14845. };
  14846. __decorate([
  14847. BABYLON.serialize()
  14848. ], FollowCamera.prototype, "radius", void 0);
  14849. __decorate([
  14850. BABYLON.serialize()
  14851. ], FollowCamera.prototype, "rotationOffset", void 0);
  14852. __decorate([
  14853. BABYLON.serialize()
  14854. ], FollowCamera.prototype, "heightOffset", void 0);
  14855. __decorate([
  14856. BABYLON.serialize()
  14857. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14858. __decorate([
  14859. BABYLON.serialize()
  14860. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14861. __decorate([
  14862. BABYLON.serializeAsMeshReference("lockedTargetId")
  14863. ], FollowCamera.prototype, "target", void 0);
  14864. return FollowCamera;
  14865. }(BABYLON.TargetCamera));
  14866. BABYLON.FollowCamera = FollowCamera;
  14867. var ArcFollowCamera = (function (_super) {
  14868. __extends(ArcFollowCamera, _super);
  14869. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14870. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14871. this.alpha = alpha;
  14872. this.beta = beta;
  14873. this.radius = radius;
  14874. this.target = target;
  14875. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14876. this.follow();
  14877. }
  14878. ArcFollowCamera.prototype.follow = function () {
  14879. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14880. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14881. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14882. this.position = this.target.position.add(this._cartesianCoordinates);
  14883. this.setTarget(this.target.position);
  14884. };
  14885. ArcFollowCamera.prototype._checkInputs = function () {
  14886. _super.prototype._checkInputs.call(this);
  14887. this.follow();
  14888. };
  14889. ArcFollowCamera.prototype.getTypeName = function () {
  14890. return "ArcFollowCamera";
  14891. };
  14892. return ArcFollowCamera;
  14893. }(BABYLON.TargetCamera));
  14894. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14895. })(BABYLON || (BABYLON = {}));
  14896. var BABYLON;
  14897. (function (BABYLON) {
  14898. // We're mainly based on the logic defined into the FreeCamera code
  14899. var TouchCamera = (function (_super) {
  14900. __extends(TouchCamera, _super);
  14901. //-- end properties for backward compatibility for inputs
  14902. function TouchCamera(name, position, scene) {
  14903. _super.call(this, name, position, scene);
  14904. this.inputs.addTouch();
  14905. this._setupInputs();
  14906. }
  14907. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14908. //-- Begin properties for backward compatibility for inputs
  14909. get: function () {
  14910. var touch = this.inputs.attached["touch"];
  14911. if (touch)
  14912. return touch.touchAngularSensibility;
  14913. },
  14914. set: function (value) {
  14915. var touch = this.inputs.attached["touch"];
  14916. if (touch)
  14917. touch.touchAngularSensibility = value;
  14918. },
  14919. enumerable: true,
  14920. configurable: true
  14921. });
  14922. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14923. get: function () {
  14924. var touch = this.inputs.attached["touch"];
  14925. if (touch)
  14926. return touch.touchMoveSensibility;
  14927. },
  14928. set: function (value) {
  14929. var touch = this.inputs.attached["touch"];
  14930. if (touch)
  14931. touch.touchMoveSensibility = value;
  14932. },
  14933. enumerable: true,
  14934. configurable: true
  14935. });
  14936. TouchCamera.prototype.getTypeName = function () {
  14937. return "TouchCamera";
  14938. };
  14939. TouchCamera.prototype._setupInputs = function () {
  14940. var mouse = this.inputs.attached["mouse"];
  14941. if (mouse) {
  14942. mouse.touchEnabled = false;
  14943. }
  14944. };
  14945. return TouchCamera;
  14946. }(BABYLON.FreeCamera));
  14947. BABYLON.TouchCamera = TouchCamera;
  14948. })(BABYLON || (BABYLON = {}));
  14949. var BABYLON;
  14950. (function (BABYLON) {
  14951. var ArcRotateCamera = (function (_super) {
  14952. __extends(ArcRotateCamera, _super);
  14953. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14954. var _this = this;
  14955. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14956. this.inertialAlphaOffset = 0;
  14957. this.inertialBetaOffset = 0;
  14958. this.inertialRadiusOffset = 0;
  14959. this.lowerAlphaLimit = null;
  14960. this.upperAlphaLimit = null;
  14961. this.lowerBetaLimit = 0.01;
  14962. this.upperBetaLimit = Math.PI;
  14963. this.lowerRadiusLimit = null;
  14964. this.upperRadiusLimit = null;
  14965. this.inertialPanningX = 0;
  14966. this.inertialPanningY = 0;
  14967. //-- end properties for backward compatibility for inputs
  14968. this.zoomOnFactor = 1;
  14969. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14970. this.allowUpsideDown = true;
  14971. this._viewMatrix = new BABYLON.Matrix();
  14972. // Panning
  14973. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14974. this.checkCollisions = false;
  14975. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14976. this._collider = new BABYLON.Collider();
  14977. this._previousPosition = BABYLON.Vector3.Zero();
  14978. this._collisionVelocity = BABYLON.Vector3.Zero();
  14979. this._newPosition = BABYLON.Vector3.Zero();
  14980. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14981. if (collidedMesh === void 0) { collidedMesh = null; }
  14982. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14983. newPosition.multiplyInPlace(_this._collider.radius);
  14984. }
  14985. if (!collidedMesh) {
  14986. _this._previousPosition.copyFrom(_this.position);
  14987. }
  14988. else {
  14989. _this.setPosition(newPosition);
  14990. if (_this.onCollide) {
  14991. _this.onCollide(collidedMesh);
  14992. }
  14993. }
  14994. // Recompute because of constraints
  14995. var cosa = Math.cos(_this.alpha);
  14996. var sina = Math.sin(_this.alpha);
  14997. var cosb = Math.cos(_this.beta);
  14998. var sinb = Math.sin(_this.beta);
  14999. if (sinb === 0) {
  15000. sinb = 0.0001;
  15001. }
  15002. var target = _this._getTargetPosition();
  15003. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15004. _this.position.copyFrom(_this._newPosition);
  15005. var up = _this.upVector;
  15006. if (_this.allowUpsideDown && _this.beta < 0) {
  15007. up = up.clone();
  15008. up = up.negate();
  15009. }
  15010. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15011. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15012. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15013. _this._collisionTriggered = false;
  15014. };
  15015. if (!target) {
  15016. this.target = BABYLON.Vector3.Zero();
  15017. }
  15018. else {
  15019. this.target = target;
  15020. }
  15021. this.alpha = alpha;
  15022. this.beta = beta;
  15023. this.radius = radius;
  15024. this.getViewMatrix();
  15025. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15026. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15027. }
  15028. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15029. //-- begin properties for backward compatibility for inputs
  15030. get: function () {
  15031. var pointers = this.inputs.attached["pointers"];
  15032. if (pointers)
  15033. return pointers.angularSensibilityX;
  15034. },
  15035. set: function (value) {
  15036. var pointers = this.inputs.attached["pointers"];
  15037. if (pointers) {
  15038. pointers.angularSensibilityX = value;
  15039. }
  15040. },
  15041. enumerable: true,
  15042. configurable: true
  15043. });
  15044. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15045. get: function () {
  15046. var pointers = this.inputs.attached["pointers"];
  15047. if (pointers)
  15048. return pointers.angularSensibilityY;
  15049. },
  15050. set: function (value) {
  15051. var pointers = this.inputs.attached["pointers"];
  15052. if (pointers) {
  15053. pointers.angularSensibilityY = value;
  15054. }
  15055. },
  15056. enumerable: true,
  15057. configurable: true
  15058. });
  15059. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15060. get: function () {
  15061. var pointers = this.inputs.attached["pointers"];
  15062. if (pointers)
  15063. return pointers.pinchPrecision;
  15064. },
  15065. set: function (value) {
  15066. var pointers = this.inputs.attached["pointers"];
  15067. if (pointers) {
  15068. pointers.pinchPrecision = value;
  15069. }
  15070. },
  15071. enumerable: true,
  15072. configurable: true
  15073. });
  15074. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15075. get: function () {
  15076. var pointers = this.inputs.attached["pointers"];
  15077. if (pointers)
  15078. return pointers.panningSensibility;
  15079. },
  15080. set: function (value) {
  15081. var pointers = this.inputs.attached["pointers"];
  15082. if (pointers) {
  15083. pointers.panningSensibility = value;
  15084. }
  15085. },
  15086. enumerable: true,
  15087. configurable: true
  15088. });
  15089. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15090. get: function () {
  15091. var keyboard = this.inputs.attached["keyboard"];
  15092. if (keyboard)
  15093. return keyboard.keysUp;
  15094. },
  15095. set: function (value) {
  15096. var keyboard = this.inputs.attached["keyboard"];
  15097. if (keyboard)
  15098. keyboard.keysUp = value;
  15099. },
  15100. enumerable: true,
  15101. configurable: true
  15102. });
  15103. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15104. get: function () {
  15105. var keyboard = this.inputs.attached["keyboard"];
  15106. if (keyboard)
  15107. return keyboard.keysDown;
  15108. },
  15109. set: function (value) {
  15110. var keyboard = this.inputs.attached["keyboard"];
  15111. if (keyboard)
  15112. keyboard.keysDown = value;
  15113. },
  15114. enumerable: true,
  15115. configurable: true
  15116. });
  15117. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15118. get: function () {
  15119. var keyboard = this.inputs.attached["keyboard"];
  15120. if (keyboard)
  15121. return keyboard.keysLeft;
  15122. },
  15123. set: function (value) {
  15124. var keyboard = this.inputs.attached["keyboard"];
  15125. if (keyboard)
  15126. keyboard.keysLeft = value;
  15127. },
  15128. enumerable: true,
  15129. configurable: true
  15130. });
  15131. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15132. get: function () {
  15133. var keyboard = this.inputs.attached["keyboard"];
  15134. if (keyboard)
  15135. return keyboard.keysRight;
  15136. },
  15137. set: function (value) {
  15138. var keyboard = this.inputs.attached["keyboard"];
  15139. if (keyboard)
  15140. keyboard.keysRight = value;
  15141. },
  15142. enumerable: true,
  15143. configurable: true
  15144. });
  15145. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15146. get: function () {
  15147. var mousewheel = this.inputs.attached["mousewheel"];
  15148. if (mousewheel)
  15149. return mousewheel.wheelPrecision;
  15150. },
  15151. set: function (value) {
  15152. var mousewheel = this.inputs.attached["mousewheel"];
  15153. if (mousewheel)
  15154. mousewheel.wheelPrecision = value;
  15155. },
  15156. enumerable: true,
  15157. configurable: true
  15158. });
  15159. // Cache
  15160. ArcRotateCamera.prototype._initCache = function () {
  15161. _super.prototype._initCache.call(this);
  15162. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15163. this._cache.alpha = undefined;
  15164. this._cache.beta = undefined;
  15165. this._cache.radius = undefined;
  15166. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15167. };
  15168. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15169. if (!ignoreParentClass) {
  15170. _super.prototype._updateCache.call(this);
  15171. }
  15172. this._cache.target.copyFrom(this._getTargetPosition());
  15173. this._cache.alpha = this.alpha;
  15174. this._cache.beta = this.beta;
  15175. this._cache.radius = this.radius;
  15176. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15177. };
  15178. ArcRotateCamera.prototype._getTargetPosition = function () {
  15179. if (this.target.getAbsolutePosition) {
  15180. var pos = this.target.getAbsolutePosition();
  15181. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15182. }
  15183. return this.target;
  15184. };
  15185. // Synchronized
  15186. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15187. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15188. return false;
  15189. return this._cache.target.equals(this.target)
  15190. && this._cache.alpha === this.alpha
  15191. && this._cache.beta === this.beta
  15192. && this._cache.radius === this.radius
  15193. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15194. };
  15195. // Methods
  15196. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15197. var _this = this;
  15198. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15199. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15200. this._useCtrlForPanning = useCtrlForPanning;
  15201. this._panningMouseButton = panningMouseButton;
  15202. this.inputs.attachElement(element, noPreventDefault);
  15203. this._reset = function () {
  15204. _this.inertialAlphaOffset = 0;
  15205. _this.inertialBetaOffset = 0;
  15206. _this.inertialRadiusOffset = 0;
  15207. };
  15208. };
  15209. ArcRotateCamera.prototype.detachControl = function (element) {
  15210. this.inputs.detachElement(element);
  15211. if (this._reset) {
  15212. this._reset();
  15213. }
  15214. };
  15215. ArcRotateCamera.prototype._checkInputs = function () {
  15216. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15217. if (this._collisionTriggered) {
  15218. return;
  15219. }
  15220. this.inputs.checkInputs();
  15221. // Inertia
  15222. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15223. this.beta += this.inertialBetaOffset;
  15224. if (this.getScene().useRightHandedSystem) {
  15225. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15226. }
  15227. else {
  15228. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15229. }
  15230. this.radius -= this.inertialRadiusOffset;
  15231. this.inertialAlphaOffset *= this.inertia;
  15232. this.inertialBetaOffset *= this.inertia;
  15233. this.inertialRadiusOffset *= this.inertia;
  15234. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15235. this.inertialAlphaOffset = 0;
  15236. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15237. this.inertialBetaOffset = 0;
  15238. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15239. this.inertialRadiusOffset = 0;
  15240. }
  15241. // Panning inertia
  15242. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15243. if (!this._localDirection) {
  15244. this._localDirection = BABYLON.Vector3.Zero();
  15245. this._transformedDirection = BABYLON.Vector3.Zero();
  15246. }
  15247. this.inertialPanningX *= this.inertia;
  15248. this.inertialPanningY *= this.inertia;
  15249. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15250. this.inertialPanningX = 0;
  15251. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15252. this.inertialPanningY = 0;
  15253. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15254. this._localDirection.multiplyInPlace(this.panningAxis);
  15255. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15256. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15257. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15258. if (!this.panningAxis.y) {
  15259. this._transformedDirection.y = 0;
  15260. }
  15261. if (!this.target.getAbsolutePosition) {
  15262. this.target.addInPlace(this._transformedDirection);
  15263. }
  15264. }
  15265. // Limits
  15266. this._checkLimits();
  15267. _super.prototype._checkInputs.call(this);
  15268. };
  15269. ArcRotateCamera.prototype._checkLimits = function () {
  15270. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15271. if (this.allowUpsideDown && this.beta > Math.PI) {
  15272. this.beta = this.beta - (2 * Math.PI);
  15273. }
  15274. }
  15275. else {
  15276. if (this.beta < this.lowerBetaLimit) {
  15277. this.beta = this.lowerBetaLimit;
  15278. }
  15279. }
  15280. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15281. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15282. this.beta = this.beta + (2 * Math.PI);
  15283. }
  15284. }
  15285. else {
  15286. if (this.beta > this.upperBetaLimit) {
  15287. this.beta = this.upperBetaLimit;
  15288. }
  15289. }
  15290. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15291. this.alpha = this.lowerAlphaLimit;
  15292. }
  15293. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15294. this.alpha = this.upperAlphaLimit;
  15295. }
  15296. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15297. this.radius = this.lowerRadiusLimit;
  15298. }
  15299. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15300. this.radius = this.upperRadiusLimit;
  15301. }
  15302. };
  15303. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15304. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15305. this.radius = radiusv3.length();
  15306. // Alpha
  15307. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15308. if (radiusv3.z < 0) {
  15309. this.alpha = 2 * Math.PI - this.alpha;
  15310. }
  15311. // Beta
  15312. this.beta = Math.acos(radiusv3.y / this.radius);
  15313. this._checkLimits();
  15314. };
  15315. ArcRotateCamera.prototype.setPosition = function (position) {
  15316. if (this.position.equals(position)) {
  15317. return;
  15318. }
  15319. this.position.copyFrom(position);
  15320. this.rebuildAnglesAndRadius();
  15321. };
  15322. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15323. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15324. if (this._getTargetPosition().equals(target)) {
  15325. return;
  15326. }
  15327. if (toBoundingCenter && target.getBoundingInfo) {
  15328. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15329. }
  15330. else {
  15331. this._targetBoundingCenter = null;
  15332. }
  15333. this.target = target;
  15334. this.rebuildAnglesAndRadius();
  15335. };
  15336. ArcRotateCamera.prototype._getViewMatrix = function () {
  15337. // Compute
  15338. var cosa = Math.cos(this.alpha);
  15339. var sina = Math.sin(this.alpha);
  15340. var cosb = Math.cos(this.beta);
  15341. var sinb = Math.sin(this.beta);
  15342. if (sinb === 0) {
  15343. sinb = 0.0001;
  15344. }
  15345. var target = this._getTargetPosition();
  15346. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15347. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15348. this._collider.radius = this.collisionRadius;
  15349. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15350. this._collisionTriggered = true;
  15351. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15352. }
  15353. else {
  15354. this.position.copyFrom(this._newPosition);
  15355. var up = this.upVector;
  15356. if (this.allowUpsideDown && this.beta < 0) {
  15357. up = up.clone();
  15358. up = up.negate();
  15359. }
  15360. if (this.getScene().useRightHandedSystem) {
  15361. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15362. }
  15363. else {
  15364. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15365. }
  15366. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15367. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15368. }
  15369. return this._viewMatrix;
  15370. };
  15371. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15372. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15373. meshes = meshes || this.getScene().meshes;
  15374. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15375. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15376. this.radius = distance * this.zoomOnFactor;
  15377. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15378. };
  15379. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15380. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15381. var meshesOrMinMaxVector;
  15382. var distance;
  15383. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15384. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15385. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15386. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15387. }
  15388. else {
  15389. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15390. distance = meshesOrMinMaxVectorAndDistance.distance;
  15391. }
  15392. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15393. if (!doNotUpdateMaxZ) {
  15394. this.maxZ = distance * 2;
  15395. }
  15396. };
  15397. /**
  15398. * @override
  15399. * Override Camera.createRigCamera
  15400. */
  15401. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15402. var alphaShift;
  15403. switch (this.cameraRigMode) {
  15404. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15405. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15406. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15407. case BABYLON.Camera.RIG_MODE_VR:
  15408. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15409. break;
  15410. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15411. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15412. break;
  15413. }
  15414. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15415. rigCam._cameraRigParams = {};
  15416. return rigCam;
  15417. };
  15418. /**
  15419. * @override
  15420. * Override Camera._updateRigCameras
  15421. */
  15422. ArcRotateCamera.prototype._updateRigCameras = function () {
  15423. var camLeft = this._rigCameras[0];
  15424. var camRight = this._rigCameras[1];
  15425. camLeft.beta = camRight.beta = this.beta;
  15426. camLeft.radius = camRight.radius = this.radius;
  15427. switch (this.cameraRigMode) {
  15428. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15429. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15430. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15431. case BABYLON.Camera.RIG_MODE_VR:
  15432. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15433. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15434. break;
  15435. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15436. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15437. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15438. break;
  15439. }
  15440. _super.prototype._updateRigCameras.call(this);
  15441. };
  15442. ArcRotateCamera.prototype.dispose = function () {
  15443. this.inputs.clear();
  15444. _super.prototype.dispose.call(this);
  15445. };
  15446. ArcRotateCamera.prototype.getTypeName = function () {
  15447. return "ArcRotateCamera";
  15448. };
  15449. __decorate([
  15450. BABYLON.serialize()
  15451. ], ArcRotateCamera.prototype, "alpha", void 0);
  15452. __decorate([
  15453. BABYLON.serialize()
  15454. ], ArcRotateCamera.prototype, "beta", void 0);
  15455. __decorate([
  15456. BABYLON.serialize()
  15457. ], ArcRotateCamera.prototype, "radius", void 0);
  15458. __decorate([
  15459. BABYLON.serializeAsVector3()
  15460. ], ArcRotateCamera.prototype, "target", void 0);
  15461. __decorate([
  15462. BABYLON.serialize()
  15463. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15464. __decorate([
  15465. BABYLON.serialize()
  15466. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15467. __decorate([
  15468. BABYLON.serialize()
  15469. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15470. __decorate([
  15471. BABYLON.serialize()
  15472. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15473. __decorate([
  15474. BABYLON.serialize()
  15475. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15476. __decorate([
  15477. BABYLON.serialize()
  15478. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15479. __decorate([
  15480. BABYLON.serialize()
  15481. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15482. __decorate([
  15483. BABYLON.serialize()
  15484. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15485. __decorate([
  15486. BABYLON.serialize()
  15487. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15488. __decorate([
  15489. BABYLON.serialize()
  15490. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15491. __decorate([
  15492. BABYLON.serialize()
  15493. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15494. __decorate([
  15495. BABYLON.serialize()
  15496. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15497. __decorate([
  15498. BABYLON.serialize()
  15499. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15500. return ArcRotateCamera;
  15501. }(BABYLON.TargetCamera));
  15502. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15503. })(BABYLON || (BABYLON = {}));
  15504. var BABYLON;
  15505. (function (BABYLON) {
  15506. var ArcRotateCameraInputsManager = (function (_super) {
  15507. __extends(ArcRotateCameraInputsManager, _super);
  15508. function ArcRotateCameraInputsManager(camera) {
  15509. _super.call(this, camera);
  15510. }
  15511. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15512. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15513. return this;
  15514. };
  15515. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15516. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15517. return this;
  15518. };
  15519. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15520. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15521. return this;
  15522. };
  15523. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15524. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15525. return this;
  15526. };
  15527. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15528. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15529. return this;
  15530. };
  15531. return ArcRotateCameraInputsManager;
  15532. }(BABYLON.CameraInputsManager));
  15533. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15534. })(BABYLON || (BABYLON = {}));
  15535. var BABYLON;
  15536. (function (BABYLON) {
  15537. var RenderingManager = (function () {
  15538. function RenderingManager(scene) {
  15539. this._renderingGroups = new Array();
  15540. this._autoClearDepthStencil = {};
  15541. this._customOpaqueSortCompareFn = {};
  15542. this._customAlphaTestSortCompareFn = {};
  15543. this._customTransparentSortCompareFn = {};
  15544. this._scene = scene;
  15545. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15546. this._autoClearDepthStencil[i] = true;
  15547. }
  15548. }
  15549. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15550. if (this._scene._activeParticleSystems.length === 0) {
  15551. return;
  15552. }
  15553. // Particles
  15554. var activeCamera = this._scene.activeCamera;
  15555. this._scene._particlesDuration.beginMonitoring();
  15556. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15557. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15558. if (particleSystem.renderingGroupId !== index) {
  15559. continue;
  15560. }
  15561. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15562. continue;
  15563. }
  15564. this._clearDepthStencilBuffer();
  15565. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15566. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15567. }
  15568. }
  15569. this._scene._particlesDuration.endMonitoring(false);
  15570. };
  15571. RenderingManager.prototype._renderSprites = function (index) {
  15572. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15573. return;
  15574. }
  15575. // Sprites
  15576. var activeCamera = this._scene.activeCamera;
  15577. this._scene._spritesDuration.beginMonitoring();
  15578. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15579. var spriteManager = this._scene.spriteManagers[id];
  15580. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15581. this._clearDepthStencilBuffer();
  15582. spriteManager.render();
  15583. }
  15584. }
  15585. this._scene._spritesDuration.endMonitoring(false);
  15586. };
  15587. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15588. if (this._depthStencilBufferAlreadyCleaned) {
  15589. return;
  15590. }
  15591. this._scene.getEngine().clear(0, false, true, true);
  15592. this._depthStencilBufferAlreadyCleaned = true;
  15593. };
  15594. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15595. if (this._currentRenderSprites) {
  15596. this._renderSprites(this._currentIndex);
  15597. }
  15598. if (this._currentRenderParticles) {
  15599. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15600. }
  15601. };
  15602. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15603. this._currentActiveMeshes = activeMeshes;
  15604. this._currentRenderParticles = renderParticles;
  15605. this._currentRenderSprites = renderSprites;
  15606. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15607. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15608. var renderingGroup = this._renderingGroups[index];
  15609. var needToStepBack = false;
  15610. this._currentIndex = index;
  15611. if (renderingGroup) {
  15612. if (this._autoClearDepthStencil[index]) {
  15613. this._clearDepthStencilBuffer();
  15614. }
  15615. if (!renderingGroup.onBeforeTransparentRendering) {
  15616. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15617. }
  15618. if (!renderingGroup.render(customRenderFunction)) {
  15619. this._renderingGroups.splice(index, 1);
  15620. needToStepBack = true;
  15621. this._renderSpritesAndParticles();
  15622. }
  15623. }
  15624. else {
  15625. this._renderSpritesAndParticles();
  15626. }
  15627. if (needToStepBack) {
  15628. index--;
  15629. }
  15630. }
  15631. };
  15632. RenderingManager.prototype.reset = function () {
  15633. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15634. var renderingGroup = this._renderingGroups[index];
  15635. if (renderingGroup) {
  15636. renderingGroup.prepare();
  15637. }
  15638. }
  15639. };
  15640. RenderingManager.prototype.dispatch = function (subMesh) {
  15641. var mesh = subMesh.getMesh();
  15642. var renderingGroupId = mesh.renderingGroupId || 0;
  15643. if (!this._renderingGroups[renderingGroupId]) {
  15644. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15645. }
  15646. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15647. };
  15648. /**
  15649. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15650. * This allowed control for front to back rendering or reversly depending of the special needs.
  15651. *
  15652. * @param renderingGroupId The rendering group id corresponding to its index
  15653. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15654. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15655. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15656. */
  15657. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15658. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15659. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15660. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15661. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15662. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15663. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15664. if (this._renderingGroups[renderingGroupId]) {
  15665. var group = this._renderingGroups[renderingGroupId];
  15666. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15667. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15668. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15669. }
  15670. };
  15671. /**
  15672. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15673. *
  15674. * @param renderingGroupId The rendering group id corresponding to its index
  15675. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15676. */
  15677. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15678. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15679. };
  15680. /**
  15681. * The max id used for rendering groups (not included)
  15682. */
  15683. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15684. /**
  15685. * The min id used for rendering groups (included)
  15686. */
  15687. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15688. return RenderingManager;
  15689. }());
  15690. BABYLON.RenderingManager = RenderingManager;
  15691. })(BABYLON || (BABYLON = {}));
  15692. var BABYLON;
  15693. (function (BABYLON) {
  15694. var RenderingGroup = (function () {
  15695. /**
  15696. * Creates a new rendering group.
  15697. * @param index The rendering group index
  15698. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15699. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15700. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15701. */
  15702. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15703. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15704. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15705. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15706. this.index = index;
  15707. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15708. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15709. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15710. this._scene = scene;
  15711. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15712. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15713. this.transparentSortCompareFn = transparentSortCompareFn;
  15714. }
  15715. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15716. /**
  15717. * Set the opaque sort comparison function.
  15718. * If null the sub meshes will be render in the order they were created
  15719. */
  15720. set: function (value) {
  15721. this._opaqueSortCompareFn = value;
  15722. if (value) {
  15723. this._renderOpaque = this.renderOpaqueSorted;
  15724. }
  15725. else {
  15726. this._renderOpaque = RenderingGroup.renderUnsorted;
  15727. }
  15728. },
  15729. enumerable: true,
  15730. configurable: true
  15731. });
  15732. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15733. /**
  15734. * Set the alpha test sort comparison function.
  15735. * If null the sub meshes will be render in the order they were created
  15736. */
  15737. set: function (value) {
  15738. this._alphaTestSortCompareFn = value;
  15739. if (value) {
  15740. this._renderAlphaTest = this.renderAlphaTestSorted;
  15741. }
  15742. else {
  15743. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15744. }
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15750. /**
  15751. * Set the transparent sort comparison function.
  15752. * If null the sub meshes will be render in the order they were created
  15753. */
  15754. set: function (value) {
  15755. if (value) {
  15756. this._transparentSortCompareFn = value;
  15757. }
  15758. else {
  15759. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15760. }
  15761. this._renderTransparent = this.renderTransparentSorted;
  15762. },
  15763. enumerable: true,
  15764. configurable: true
  15765. });
  15766. /**
  15767. * Render all the sub meshes contained in the group.
  15768. * @param customRenderFunction Used to override the default render behaviour of the group.
  15769. * @returns true if rendered some submeshes.
  15770. */
  15771. RenderingGroup.prototype.render = function (customRenderFunction) {
  15772. if (customRenderFunction) {
  15773. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15774. return true;
  15775. }
  15776. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15777. if (this.onBeforeTransparentRendering) {
  15778. this.onBeforeTransparentRendering();
  15779. }
  15780. return false;
  15781. }
  15782. var engine = this._scene.getEngine();
  15783. // Opaque
  15784. this._renderOpaque(this._opaqueSubMeshes);
  15785. // Alpha test
  15786. engine.setAlphaTesting(true);
  15787. this._renderAlphaTest(this._alphaTestSubMeshes);
  15788. engine.setAlphaTesting(false);
  15789. if (this.onBeforeTransparentRendering) {
  15790. this.onBeforeTransparentRendering();
  15791. }
  15792. // Transparent
  15793. this._renderTransparent(this._transparentSubMeshes);
  15794. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15795. return true;
  15796. };
  15797. /**
  15798. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15799. * @param subMeshes The submeshes to render
  15800. */
  15801. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15802. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15803. };
  15804. /**
  15805. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15806. * @param subMeshes The submeshes to render
  15807. */
  15808. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15809. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15810. };
  15811. /**
  15812. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15813. * @param subMeshes The submeshes to render
  15814. */
  15815. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15816. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15817. };
  15818. /**
  15819. * Renders the submeshes in a specified order.
  15820. * @param subMeshes The submeshes to sort before render
  15821. * @param sortCompareFn The comparison function use to sort
  15822. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15823. * @param transparent Specifies to activate blending if true
  15824. */
  15825. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15826. var subIndex = 0;
  15827. var subMesh;
  15828. for (; subIndex < subMeshes.length; subIndex++) {
  15829. subMesh = subMeshes.data[subIndex];
  15830. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15831. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15832. }
  15833. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15834. sortedArray.sort(sortCompareFn);
  15835. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15836. subMesh = sortedArray[subIndex];
  15837. subMesh.render(transparent);
  15838. }
  15839. };
  15840. /**
  15841. * Renders the submeshes in the order they were dispatched (no sort applied).
  15842. * @param subMeshes The submeshes to render
  15843. */
  15844. RenderingGroup.renderUnsorted = function (subMeshes) {
  15845. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15846. var submesh = subMeshes.data[subIndex];
  15847. submesh.render(false);
  15848. }
  15849. };
  15850. /**
  15851. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15852. * are rendered back to front if in the same alpha index.
  15853. *
  15854. * @param a The first submesh
  15855. * @param b The second submesh
  15856. * @returns The result of the comparison
  15857. */
  15858. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15859. // Alpha index first
  15860. if (a._alphaIndex > b._alphaIndex) {
  15861. return 1;
  15862. }
  15863. if (a._alphaIndex < b._alphaIndex) {
  15864. return -1;
  15865. }
  15866. // Then distance to camera
  15867. return RenderingGroup.backToFrontSortCompare(a, b);
  15868. };
  15869. /**
  15870. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15871. * are rendered back to front.
  15872. *
  15873. * @param a The first submesh
  15874. * @param b The second submesh
  15875. * @returns The result of the comparison
  15876. */
  15877. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15878. // Then distance to camera
  15879. if (a._distanceToCamera < b._distanceToCamera) {
  15880. return 1;
  15881. }
  15882. if (a._distanceToCamera > b._distanceToCamera) {
  15883. return -1;
  15884. }
  15885. return 0;
  15886. };
  15887. /**
  15888. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15889. * are rendered front to back (prevent overdraw).
  15890. *
  15891. * @param a The first submesh
  15892. * @param b The second submesh
  15893. * @returns The result of the comparison
  15894. */
  15895. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15896. // Then distance to camera
  15897. if (a._distanceToCamera < b._distanceToCamera) {
  15898. return -1;
  15899. }
  15900. if (a._distanceToCamera > b._distanceToCamera) {
  15901. return 1;
  15902. }
  15903. return 0;
  15904. };
  15905. /**
  15906. * Resets the different lists of submeshes to prepare a new frame.
  15907. */
  15908. RenderingGroup.prototype.prepare = function () {
  15909. this._opaqueSubMeshes.reset();
  15910. this._transparentSubMeshes.reset();
  15911. this._alphaTestSubMeshes.reset();
  15912. };
  15913. /**
  15914. * Inserts the submesh in its correct queue depending on its material.
  15915. * @param subMesh The submesh to dispatch
  15916. */
  15917. RenderingGroup.prototype.dispatch = function (subMesh) {
  15918. var material = subMesh.getMaterial();
  15919. var mesh = subMesh.getMesh();
  15920. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15921. this._transparentSubMeshes.push(subMesh);
  15922. }
  15923. else if (material.needAlphaTesting()) {
  15924. this._alphaTestSubMeshes.push(subMesh);
  15925. }
  15926. else {
  15927. this._opaqueSubMeshes.push(subMesh); // Opaque
  15928. }
  15929. };
  15930. return RenderingGroup;
  15931. }());
  15932. BABYLON.RenderingGroup = RenderingGroup;
  15933. })(BABYLON || (BABYLON = {}));
  15934. var BABYLON;
  15935. (function (BABYLON) {
  15936. var PointerEventTypes = (function () {
  15937. function PointerEventTypes() {
  15938. }
  15939. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15940. get: function () {
  15941. return PointerEventTypes._POINTERDOWN;
  15942. },
  15943. enumerable: true,
  15944. configurable: true
  15945. });
  15946. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15947. get: function () {
  15948. return PointerEventTypes._POINTERUP;
  15949. },
  15950. enumerable: true,
  15951. configurable: true
  15952. });
  15953. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15954. get: function () {
  15955. return PointerEventTypes._POINTERMOVE;
  15956. },
  15957. enumerable: true,
  15958. configurable: true
  15959. });
  15960. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15961. get: function () {
  15962. return PointerEventTypes._POINTERWHEEL;
  15963. },
  15964. enumerable: true,
  15965. configurable: true
  15966. });
  15967. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15968. get: function () {
  15969. return PointerEventTypes._POINTERPICK;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. PointerEventTypes._POINTERDOWN = 0x01;
  15975. PointerEventTypes._POINTERUP = 0x02;
  15976. PointerEventTypes._POINTERMOVE = 0x04;
  15977. PointerEventTypes._POINTERWHEEL = 0x08;
  15978. PointerEventTypes._POINTERPICK = 0x10;
  15979. return PointerEventTypes;
  15980. }());
  15981. BABYLON.PointerEventTypes = PointerEventTypes;
  15982. var PointerInfoBase = (function () {
  15983. function PointerInfoBase(type, event) {
  15984. this.type = type;
  15985. this.event = event;
  15986. }
  15987. return PointerInfoBase;
  15988. }());
  15989. BABYLON.PointerInfoBase = PointerInfoBase;
  15990. /**
  15991. * This class is used to store pointer related info for the onPrePointerObservable event.
  15992. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15993. */
  15994. var PointerInfoPre = (function (_super) {
  15995. __extends(PointerInfoPre, _super);
  15996. function PointerInfoPre(type, event, localX, localY) {
  15997. _super.call(this, type, event);
  15998. this.skipOnPointerObservable = false;
  15999. this.localPosition = new BABYLON.Vector2(localX, localY);
  16000. }
  16001. return PointerInfoPre;
  16002. }(PointerInfoBase));
  16003. BABYLON.PointerInfoPre = PointerInfoPre;
  16004. /**
  16005. * This type contains all the data related to a pointer event in Babylon.js.
  16006. * 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.
  16007. */
  16008. var PointerInfo = (function (_super) {
  16009. __extends(PointerInfo, _super);
  16010. function PointerInfo(type, event, pickInfo) {
  16011. _super.call(this, type, event);
  16012. this.pickInfo = pickInfo;
  16013. }
  16014. return PointerInfo;
  16015. }(PointerInfoBase));
  16016. BABYLON.PointerInfo = PointerInfo;
  16017. /**
  16018. * Represents a scene to be rendered by the engine.
  16019. * @see http://doc.babylonjs.com/page.php?p=21911
  16020. */
  16021. var Scene = (function () {
  16022. /**
  16023. * @constructor
  16024. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16025. */
  16026. function Scene(engine) {
  16027. // Members
  16028. this.autoClear = true;
  16029. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16030. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16031. this.forceWireframe = false;
  16032. this.forcePointsCloud = false;
  16033. this.forceShowBoundingBoxes = false;
  16034. this.animationsEnabled = true;
  16035. this.constantlyUpdateMeshUnderPointer = false;
  16036. this.useRightHandedSystem = false;
  16037. this.hoverCursor = "pointer";
  16038. // Events
  16039. /**
  16040. * An event triggered when the scene is disposed.
  16041. * @type {BABYLON.Observable}
  16042. */
  16043. this.onDisposeObservable = new BABYLON.Observable();
  16044. /**
  16045. * An event triggered before rendering the scene
  16046. * @type {BABYLON.Observable}
  16047. */
  16048. this.onBeforeRenderObservable = new BABYLON.Observable();
  16049. /**
  16050. * An event triggered after rendering the scene
  16051. * @type {BABYLON.Observable}
  16052. */
  16053. this.onAfterRenderObservable = new BABYLON.Observable();
  16054. /**
  16055. * An event triggered when the scene is ready
  16056. * @type {BABYLON.Observable}
  16057. */
  16058. this.onReadyObservable = new BABYLON.Observable();
  16059. /**
  16060. * An event triggered before rendering a camera
  16061. * @type {BABYLON.Observable}
  16062. */
  16063. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16064. /**
  16065. * An event triggered after rendering a camera
  16066. * @type {BABYLON.Observable}
  16067. */
  16068. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16069. /**
  16070. * An event triggered when a camera is created
  16071. * @type {BABYLON.Observable}
  16072. */
  16073. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16074. /**
  16075. * An event triggered when a camera is removed
  16076. * @type {BABYLON.Observable}
  16077. */
  16078. this.onCameraRemovedObservable = new BABYLON.Observable();
  16079. /**
  16080. * An event triggered when a light is created
  16081. * @type {BABYLON.Observable}
  16082. */
  16083. this.onNewLightAddedObservable = new BABYLON.Observable();
  16084. /**
  16085. * An event triggered when a light is removed
  16086. * @type {BABYLON.Observable}
  16087. */
  16088. this.onLightRemovedObservable = new BABYLON.Observable();
  16089. /**
  16090. * An event triggered when a geometry is created
  16091. * @type {BABYLON.Observable}
  16092. */
  16093. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16094. /**
  16095. * An event triggered when a geometry is removed
  16096. * @type {BABYLON.Observable}
  16097. */
  16098. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16099. /**
  16100. * An event triggered when a mesh is created
  16101. * @type {BABYLON.Observable}
  16102. */
  16103. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16104. /**
  16105. * An event triggered when a mesh is removed
  16106. * @type {BABYLON.Observable}
  16107. */
  16108. this.onMeshRemovedObservable = new BABYLON.Observable();
  16109. // Animations
  16110. this.animations = [];
  16111. /**
  16112. * 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).
  16113. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16114. */
  16115. this.onPrePointerObservable = new BABYLON.Observable();
  16116. /**
  16117. * Observable event triggered each time an input event is received from the rendering canvas
  16118. */
  16119. this.onPointerObservable = new BABYLON.Observable();
  16120. 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
  16121. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16122. this._startingPointerTime = 0;
  16123. // Fog
  16124. /**
  16125. * is fog enabled on this scene.
  16126. * @type {boolean}
  16127. */
  16128. this.fogEnabled = true;
  16129. this.fogMode = Scene.FOGMODE_NONE;
  16130. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16131. this.fogDensity = 0.1;
  16132. this.fogStart = 0;
  16133. this.fogEnd = 1000.0;
  16134. // Lights
  16135. /**
  16136. * is shadow enabled on this scene.
  16137. * @type {boolean}
  16138. */
  16139. this.shadowsEnabled = true;
  16140. /**
  16141. * is light enabled on this scene.
  16142. * @type {boolean}
  16143. */
  16144. this.lightsEnabled = true;
  16145. /**
  16146. * All of the lights added to this scene.
  16147. * @see BABYLON.Light
  16148. * @type {BABYLON.Light[]}
  16149. */
  16150. this.lights = new Array();
  16151. // Cameras
  16152. /**
  16153. * All of the cameras added to this scene.
  16154. * @see BABYLON.Camera
  16155. * @type {BABYLON.Camera[]}
  16156. */
  16157. this.cameras = new Array();
  16158. this.activeCameras = new Array();
  16159. // Meshes
  16160. /**
  16161. * All of the (abstract) meshes added to this scene.
  16162. * @see BABYLON.AbstractMesh
  16163. * @type {BABYLON.AbstractMesh[]}
  16164. */
  16165. this.meshes = new Array();
  16166. // Geometries
  16167. this._geometries = new Array();
  16168. this.materials = new Array();
  16169. this.multiMaterials = new Array();
  16170. // Textures
  16171. this.texturesEnabled = true;
  16172. this.textures = new Array();
  16173. // Particles
  16174. this.particlesEnabled = true;
  16175. this.particleSystems = new Array();
  16176. // Sprites
  16177. this.spritesEnabled = true;
  16178. this.spriteManagers = new Array();
  16179. // Layers
  16180. this.layers = new Array();
  16181. this.highlightLayers = new Array();
  16182. // Skeletons
  16183. this.skeletonsEnabled = true;
  16184. this.skeletons = new Array();
  16185. // Lens flares
  16186. this.lensFlaresEnabled = true;
  16187. this.lensFlareSystems = new Array();
  16188. // Collisions
  16189. this.collisionsEnabled = true;
  16190. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16191. // Postprocesses
  16192. this.postProcessesEnabled = true;
  16193. // Customs render targets
  16194. this.renderTargetsEnabled = true;
  16195. this.dumpNextRenderTargets = false;
  16196. this.customRenderTargets = new Array();
  16197. // Imported meshes
  16198. this.importedMeshesFiles = new Array();
  16199. // Probes
  16200. this.probesEnabled = true;
  16201. this.reflectionProbes = new Array();
  16202. this._actionManagers = new Array();
  16203. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16204. // Procedural textures
  16205. this.proceduralTexturesEnabled = true;
  16206. this._proceduralTextures = new Array();
  16207. this.soundTracks = new Array();
  16208. this._audioEnabled = true;
  16209. this._headphone = false;
  16210. // Performance counters
  16211. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16212. this._totalLightsCounter = new BABYLON.PerfCounter();
  16213. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16214. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16215. this._totalVertices = new BABYLON.PerfCounter();
  16216. this._activeIndices = new BABYLON.PerfCounter();
  16217. this._activeParticles = new BABYLON.PerfCounter();
  16218. this._lastFrameDuration = new BABYLON.PerfCounter();
  16219. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16220. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16221. this._particlesDuration = new BABYLON.PerfCounter();
  16222. this._renderDuration = new BABYLON.PerfCounter();
  16223. this._spritesDuration = new BABYLON.PerfCounter();
  16224. this._activeBones = new BABYLON.PerfCounter();
  16225. this._renderId = 0;
  16226. this._executeWhenReadyTimeoutId = -1;
  16227. this._intermediateRendering = false;
  16228. this._toBeDisposed = new BABYLON.SmartArray(256);
  16229. this._pendingData = []; //ANY
  16230. this._activeMeshes = new BABYLON.SmartArray(256);
  16231. this._processedMaterials = new BABYLON.SmartArray(256);
  16232. this._renderTargets = new BABYLON.SmartArray(256);
  16233. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16234. this._activeSkeletons = new BABYLON.SmartArray(32);
  16235. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16236. this._activeAnimatables = new Array();
  16237. this._transformMatrix = BABYLON.Matrix.Zero();
  16238. this._edgesRenderers = new BABYLON.SmartArray(16);
  16239. this._uniqueIdCounter = 0;
  16240. this._engine = engine;
  16241. engine.scenes.push(this);
  16242. this._renderingManager = new BABYLON.RenderingManager(this);
  16243. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16244. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16245. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16246. if (BABYLON.OutlineRenderer) {
  16247. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16248. }
  16249. this.attachControl();
  16250. if (BABYLON.SoundTrack) {
  16251. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16252. }
  16253. //simplification queue
  16254. if (BABYLON.SimplificationQueue) {
  16255. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16256. }
  16257. //collision coordinator initialization. For now legacy per default.
  16258. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16259. }
  16260. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16261. get: function () {
  16262. return Scene._FOGMODE_NONE;
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16268. get: function () {
  16269. return Scene._FOGMODE_EXP;
  16270. },
  16271. enumerable: true,
  16272. configurable: true
  16273. });
  16274. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16275. get: function () {
  16276. return Scene._FOGMODE_EXP2;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16282. get: function () {
  16283. return Scene._FOGMODE_LINEAR;
  16284. },
  16285. enumerable: true,
  16286. configurable: true
  16287. });
  16288. Object.defineProperty(Scene.prototype, "onDispose", {
  16289. set: function (callback) {
  16290. if (this._onDisposeObserver) {
  16291. this.onDisposeObservable.remove(this._onDisposeObserver);
  16292. }
  16293. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(Scene.prototype, "beforeRender", {
  16299. set: function (callback) {
  16300. if (this._onBeforeRenderObserver) {
  16301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16302. }
  16303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16304. },
  16305. enumerable: true,
  16306. configurable: true
  16307. });
  16308. Object.defineProperty(Scene.prototype, "afterRender", {
  16309. set: function (callback) {
  16310. if (this._onAfterRenderObserver) {
  16311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16312. }
  16313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16314. },
  16315. enumerable: true,
  16316. configurable: true
  16317. });
  16318. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16319. set: function (callback) {
  16320. if (this._onBeforeCameraRenderObserver) {
  16321. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16322. }
  16323. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16324. },
  16325. enumerable: true,
  16326. configurable: true
  16327. });
  16328. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16329. set: function (callback) {
  16330. if (this._onAfterCameraRenderObserver) {
  16331. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16332. }
  16333. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16334. },
  16335. enumerable: true,
  16336. configurable: true
  16337. });
  16338. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16339. get: function () {
  16340. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16341. },
  16342. enumerable: true,
  16343. configurable: true
  16344. });
  16345. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16346. get: function () {
  16347. if (!this._defaultMaterial) {
  16348. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16349. }
  16350. return this._defaultMaterial;
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(Scene.prototype, "debugLayer", {
  16356. // Properties
  16357. get: function () {
  16358. if (!this._debugLayer) {
  16359. this._debugLayer = new BABYLON.DebugLayer(this);
  16360. }
  16361. return this._debugLayer;
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16367. get: function () {
  16368. return this._workerCollisions;
  16369. },
  16370. set: function (enabled) {
  16371. enabled = (enabled && !!Worker);
  16372. this._workerCollisions = enabled;
  16373. if (this.collisionCoordinator) {
  16374. this.collisionCoordinator.destroy();
  16375. }
  16376. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16377. this.collisionCoordinator.init(this);
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16383. get: function () {
  16384. return this._selectionOctree;
  16385. },
  16386. enumerable: true,
  16387. configurable: true
  16388. });
  16389. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16390. /**
  16391. * The mesh that is currently under the pointer.
  16392. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16393. */
  16394. get: function () {
  16395. return this._pointerOverMesh;
  16396. },
  16397. enumerable: true,
  16398. configurable: true
  16399. });
  16400. Object.defineProperty(Scene.prototype, "pointerX", {
  16401. /**
  16402. * Current on-screen X position of the pointer
  16403. * @return {number} X position of the pointer
  16404. */
  16405. get: function () {
  16406. return this._pointerX;
  16407. },
  16408. enumerable: true,
  16409. configurable: true
  16410. });
  16411. Object.defineProperty(Scene.prototype, "pointerY", {
  16412. /**
  16413. * Current on-screen Y position of the pointer
  16414. * @return {number} Y position of the pointer
  16415. */
  16416. get: function () {
  16417. return this._pointerY;
  16418. },
  16419. enumerable: true,
  16420. configurable: true
  16421. });
  16422. Scene.prototype.getCachedMaterial = function () {
  16423. return this._cachedMaterial;
  16424. };
  16425. Scene.prototype.getBoundingBoxRenderer = function () {
  16426. return this._boundingBoxRenderer;
  16427. };
  16428. Scene.prototype.getOutlineRenderer = function () {
  16429. return this._outlineRenderer;
  16430. };
  16431. Scene.prototype.getEngine = function () {
  16432. return this._engine;
  16433. };
  16434. Scene.prototype.getTotalVertices = function () {
  16435. return this._totalVertices.current;
  16436. };
  16437. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16438. get: function () {
  16439. return this._totalVertices;
  16440. },
  16441. enumerable: true,
  16442. configurable: true
  16443. });
  16444. Scene.prototype.getActiveIndices = function () {
  16445. return this._activeIndices.current;
  16446. };
  16447. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16448. get: function () {
  16449. return this._activeIndices;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Scene.prototype.getActiveParticles = function () {
  16455. return this._activeParticles.current;
  16456. };
  16457. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16458. get: function () {
  16459. return this._activeParticles;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Scene.prototype.getActiveBones = function () {
  16465. return this._activeBones.current;
  16466. };
  16467. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16468. get: function () {
  16469. return this._activeBones;
  16470. },
  16471. enumerable: true,
  16472. configurable: true
  16473. });
  16474. // Stats
  16475. Scene.prototype.getLastFrameDuration = function () {
  16476. return this._lastFrameDuration.current;
  16477. };
  16478. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16479. get: function () {
  16480. return this._lastFrameDuration;
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16486. return this._evaluateActiveMeshesDuration.current;
  16487. };
  16488. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16489. get: function () {
  16490. return this._evaluateActiveMeshesDuration;
  16491. },
  16492. enumerable: true,
  16493. configurable: true
  16494. });
  16495. Scene.prototype.getActiveMeshes = function () {
  16496. return this._activeMeshes;
  16497. };
  16498. Scene.prototype.getRenderTargetsDuration = function () {
  16499. return this._renderTargetsDuration.current;
  16500. };
  16501. Scene.prototype.getRenderDuration = function () {
  16502. return this._renderDuration.current;
  16503. };
  16504. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16505. get: function () {
  16506. return this._renderDuration;
  16507. },
  16508. enumerable: true,
  16509. configurable: true
  16510. });
  16511. Scene.prototype.getParticlesDuration = function () {
  16512. return this._particlesDuration.current;
  16513. };
  16514. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16515. get: function () {
  16516. return this._particlesDuration;
  16517. },
  16518. enumerable: true,
  16519. configurable: true
  16520. });
  16521. Scene.prototype.getSpritesDuration = function () {
  16522. return this._spritesDuration.current;
  16523. };
  16524. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16525. get: function () {
  16526. return this._spritesDuration;
  16527. },
  16528. enumerable: true,
  16529. configurable: true
  16530. });
  16531. Scene.prototype.getAnimationRatio = function () {
  16532. return this._animationRatio;
  16533. };
  16534. Scene.prototype.getRenderId = function () {
  16535. return this._renderId;
  16536. };
  16537. Scene.prototype.incrementRenderId = function () {
  16538. this._renderId++;
  16539. };
  16540. Scene.prototype._updatePointerPosition = function (evt) {
  16541. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16542. this._pointerX = evt.clientX - canvasRect.left;
  16543. this._pointerY = evt.clientY - canvasRect.top;
  16544. this._unTranslatedPointerX = this._pointerX;
  16545. this._unTranslatedPointerY = this._pointerY;
  16546. if (this.cameraToUseForPointers) {
  16547. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16548. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16549. }
  16550. };
  16551. // Pointers handling
  16552. /**
  16553. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16554. * @param attachUp defines if you want to attach events to pointerup
  16555. * @param attachDown defines if you want to attach events to pointerdown
  16556. * @param attachMove defines if you want to attach events to pointermove
  16557. */
  16558. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16559. var _this = this;
  16560. if (attachUp === void 0) { attachUp = true; }
  16561. if (attachDown === void 0) { attachDown = true; }
  16562. if (attachMove === void 0) { attachMove = true; }
  16563. var spritePredicate = function (sprite) {
  16564. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16565. };
  16566. this._onPointerMove = function (evt) {
  16567. _this._updatePointerPosition(evt);
  16568. // PreObservable support
  16569. if (_this.onPrePointerObservable.hasObservers()) {
  16570. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16571. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16572. _this.onPrePointerObservable.notifyObservers(pi, type);
  16573. if (pi.skipOnPointerObservable) {
  16574. return;
  16575. }
  16576. }
  16577. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16578. return;
  16579. }
  16580. var canvas = _this._engine.getRenderingCanvas();
  16581. if (!_this.pointerMovePredicate) {
  16582. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16583. }
  16584. // Meshes
  16585. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16586. if (pickResult.hit && pickResult.pickedMesh) {
  16587. _this.setPointerOverSprite(null);
  16588. _this.setPointerOverMesh(pickResult.pickedMesh);
  16589. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16590. canvas.style.cursor = _this.hoverCursor;
  16591. }
  16592. else {
  16593. canvas.style.cursor = "";
  16594. }
  16595. }
  16596. else {
  16597. _this.setPointerOverMesh(null);
  16598. // Sprites
  16599. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16600. if (pickResult.hit && pickResult.pickedSprite) {
  16601. canvas.style.cursor = _this.hoverCursor;
  16602. _this.setPointerOverSprite(pickResult.pickedSprite);
  16603. }
  16604. else {
  16605. _this.setPointerOverSprite(null);
  16606. // Restore pointer
  16607. canvas.style.cursor = "";
  16608. }
  16609. }
  16610. if (_this.onPointerMove) {
  16611. _this.onPointerMove(evt, pickResult);
  16612. }
  16613. if (_this.onPointerObservable.hasObservers()) {
  16614. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16615. var pi = new PointerInfo(type, evt, pickResult);
  16616. _this.onPointerObservable.notifyObservers(pi, type);
  16617. }
  16618. };
  16619. this._onPointerDown = function (evt) {
  16620. _this._updatePointerPosition(evt);
  16621. // PreObservable support
  16622. if (_this.onPrePointerObservable.hasObservers()) {
  16623. var type = PointerEventTypes.POINTERDOWN;
  16624. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16625. _this.onPrePointerObservable.notifyObservers(pi, type);
  16626. if (pi.skipOnPointerObservable) {
  16627. return;
  16628. }
  16629. }
  16630. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16631. return;
  16632. }
  16633. _this._startingPointerPosition.x = _this._pointerX;
  16634. _this._startingPointerPosition.y = _this._pointerY;
  16635. _this._startingPointerTime = new Date().getTime();
  16636. if (!_this.pointerDownPredicate) {
  16637. _this.pointerDownPredicate = function (mesh) {
  16638. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16639. };
  16640. }
  16641. // Meshes
  16642. _this._pickedDownMesh = null;
  16643. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16644. if (pickResult.hit && pickResult.pickedMesh) {
  16645. if (pickResult.pickedMesh.actionManager) {
  16646. _this._pickedDownMesh = pickResult.pickedMesh;
  16647. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16648. switch (evt.button) {
  16649. case 0:
  16650. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16651. break;
  16652. case 1:
  16653. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16654. break;
  16655. case 2:
  16656. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16657. break;
  16658. }
  16659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16660. }
  16661. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16662. var that = _this;
  16663. window.setTimeout(function () {
  16664. 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);
  16665. if (pickResult.hit && pickResult.pickedMesh) {
  16666. if (pickResult.pickedMesh.actionManager) {
  16667. 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)) {
  16668. that._startingPointerTime = 0;
  16669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16670. }
  16671. }
  16672. }
  16673. }, BABYLON.ActionManager.LongPressDelay);
  16674. }
  16675. }
  16676. }
  16677. if (_this.onPointerDown) {
  16678. _this.onPointerDown(evt, pickResult);
  16679. }
  16680. if (_this.onPointerObservable.hasObservers()) {
  16681. var type = PointerEventTypes.POINTERDOWN;
  16682. var pi = new PointerInfo(type, evt, pickResult);
  16683. _this.onPointerObservable.notifyObservers(pi, type);
  16684. }
  16685. // Sprites
  16686. _this._pickedDownSprite = null;
  16687. if (_this.spriteManagers.length > 0) {
  16688. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16689. if (pickResult.hit && pickResult.pickedSprite) {
  16690. if (pickResult.pickedSprite.actionManager) {
  16691. _this._pickedDownSprite = pickResult.pickedSprite;
  16692. switch (evt.button) {
  16693. case 0:
  16694. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16695. break;
  16696. case 1:
  16697. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16698. break;
  16699. case 2:
  16700. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16701. break;
  16702. }
  16703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16704. }
  16705. }
  16706. }
  16707. };
  16708. this._onPointerUp = function (evt) {
  16709. _this._updatePointerPosition(evt);
  16710. // PreObservable support
  16711. if (_this.onPrePointerObservable.hasObservers()) {
  16712. var type = PointerEventTypes.POINTERUP;
  16713. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16714. _this.onPrePointerObservable.notifyObservers(pi, type);
  16715. if (pi.skipOnPointerObservable) {
  16716. return;
  16717. }
  16718. }
  16719. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16720. return;
  16721. }
  16722. if (!_this.pointerUpPredicate) {
  16723. _this.pointerUpPredicate = function (mesh) {
  16724. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16725. };
  16726. }
  16727. // Meshes
  16728. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16729. if (pickResult.hit && pickResult.pickedMesh) {
  16730. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16731. if (_this.onPointerPick) {
  16732. _this.onPointerPick(evt, pickResult);
  16733. }
  16734. if (_this.onPointerObservable.hasObservers()) {
  16735. var type = PointerEventTypes.POINTERPICK;
  16736. var pi = new PointerInfo(type, evt, pickResult);
  16737. _this.onPointerObservable.notifyObservers(pi, type);
  16738. }
  16739. }
  16740. if (pickResult.pickedMesh.actionManager) {
  16741. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16742. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16743. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16744. }
  16745. }
  16746. }
  16747. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16748. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16749. }
  16750. if (_this.onPointerUp) {
  16751. _this.onPointerUp(evt, pickResult);
  16752. }
  16753. if (_this.onPointerObservable.hasObservers()) {
  16754. var type = PointerEventTypes.POINTERUP;
  16755. var pi = new PointerInfo(type, evt, pickResult);
  16756. _this.onPointerObservable.notifyObservers(pi, type);
  16757. }
  16758. _this._startingPointerTime = 0;
  16759. // Sprites
  16760. if (_this.spriteManagers.length > 0) {
  16761. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16762. if (pickResult.hit && pickResult.pickedSprite) {
  16763. if (pickResult.pickedSprite.actionManager) {
  16764. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16765. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16766. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16767. }
  16768. }
  16769. }
  16770. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16771. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16772. }
  16773. }
  16774. };
  16775. this._onKeyDown = function (evt) {
  16776. if (_this.actionManager) {
  16777. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16778. }
  16779. };
  16780. this._onKeyUp = function (evt) {
  16781. if (_this.actionManager) {
  16782. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16783. }
  16784. };
  16785. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16786. var canvas = this._engine.getRenderingCanvas();
  16787. if (attachMove) {
  16788. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16789. // Wheel
  16790. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16791. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16792. }
  16793. if (attachDown) {
  16794. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16795. }
  16796. if (attachUp) {
  16797. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16798. }
  16799. canvas.tabIndex = 1;
  16800. canvas.addEventListener("keydown", this._onKeyDown, false);
  16801. canvas.addEventListener("keyup", this._onKeyUp, false);
  16802. };
  16803. Scene.prototype.detachControl = function () {
  16804. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16805. var canvas = this._engine.getRenderingCanvas();
  16806. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16807. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16808. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16809. // Wheel
  16810. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16811. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16812. canvas.removeEventListener("keydown", this._onKeyDown);
  16813. canvas.removeEventListener("keyup", this._onKeyUp);
  16814. };
  16815. // Ready
  16816. Scene.prototype.isReady = function () {
  16817. if (this._pendingData.length > 0) {
  16818. return false;
  16819. }
  16820. var index;
  16821. for (index = 0; index < this._geometries.length; index++) {
  16822. var geometry = this._geometries[index];
  16823. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16824. return false;
  16825. }
  16826. }
  16827. for (index = 0; index < this.meshes.length; index++) {
  16828. var mesh = this.meshes[index];
  16829. if (!mesh.isReady()) {
  16830. return false;
  16831. }
  16832. var mat = mesh.material;
  16833. if (mat) {
  16834. if (!mat.isReady(mesh)) {
  16835. return false;
  16836. }
  16837. }
  16838. }
  16839. return true;
  16840. };
  16841. Scene.prototype.resetCachedMaterial = function () {
  16842. this._cachedMaterial = null;
  16843. };
  16844. Scene.prototype.registerBeforeRender = function (func) {
  16845. this.onBeforeRenderObservable.add(func);
  16846. };
  16847. Scene.prototype.unregisterBeforeRender = function (func) {
  16848. this.onBeforeRenderObservable.removeCallback(func);
  16849. };
  16850. Scene.prototype.registerAfterRender = function (func) {
  16851. this.onAfterRenderObservable.add(func);
  16852. };
  16853. Scene.prototype.unregisterAfterRender = function (func) {
  16854. this.onAfterRenderObservable.removeCallback(func);
  16855. };
  16856. Scene.prototype._addPendingData = function (data) {
  16857. this._pendingData.push(data);
  16858. };
  16859. Scene.prototype._removePendingData = function (data) {
  16860. var index = this._pendingData.indexOf(data);
  16861. if (index !== -1) {
  16862. this._pendingData.splice(index, 1);
  16863. }
  16864. };
  16865. Scene.prototype.getWaitingItemsCount = function () {
  16866. return this._pendingData.length;
  16867. };
  16868. /**
  16869. * Registers a function to be executed when the scene is ready.
  16870. * @param {Function} func - the function to be executed.
  16871. */
  16872. Scene.prototype.executeWhenReady = function (func) {
  16873. var _this = this;
  16874. this.onReadyObservable.add(func);
  16875. if (this._executeWhenReadyTimeoutId !== -1) {
  16876. return;
  16877. }
  16878. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16879. _this._checkIsReady();
  16880. }, 150);
  16881. };
  16882. Scene.prototype._checkIsReady = function () {
  16883. var _this = this;
  16884. if (this.isReady()) {
  16885. this.onReadyObservable.notifyObservers(this);
  16886. this.onReadyObservable.clear();
  16887. this._executeWhenReadyTimeoutId = -1;
  16888. return;
  16889. }
  16890. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16891. _this._checkIsReady();
  16892. }, 150);
  16893. };
  16894. // Animations
  16895. /**
  16896. * Will start the animation sequence of a given target
  16897. * @param target - the target
  16898. * @param {number} from - from which frame should animation start
  16899. * @param {number} to - till which frame should animation run.
  16900. * @param {boolean} [loop] - should the animation loop
  16901. * @param {number} [speedRatio] - the speed in which to run the animation
  16902. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16903. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16904. * @return {BABYLON.Animatable} the animatable object created for this animation
  16905. * @see BABYLON.Animatable
  16906. * @see http://doc.babylonjs.com/page.php?p=22081
  16907. */
  16908. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16909. if (speedRatio === void 0) { speedRatio = 1.0; }
  16910. this.stopAnimation(target);
  16911. if (!animatable) {
  16912. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16913. }
  16914. // Local animations
  16915. if (target.animations) {
  16916. animatable.appendAnimations(target, target.animations);
  16917. }
  16918. // Children animations
  16919. if (target.getAnimatables) {
  16920. var animatables = target.getAnimatables();
  16921. for (var index = 0; index < animatables.length; index++) {
  16922. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16923. }
  16924. }
  16925. animatable.reset();
  16926. return animatable;
  16927. };
  16928. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16929. if (speedRatio === undefined) {
  16930. speedRatio = 1.0;
  16931. }
  16932. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16933. return animatable;
  16934. };
  16935. Scene.prototype.getAnimatableByTarget = function (target) {
  16936. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16937. if (this._activeAnimatables[index].target === target) {
  16938. return this._activeAnimatables[index];
  16939. }
  16940. }
  16941. return null;
  16942. };
  16943. Object.defineProperty(Scene.prototype, "Animatables", {
  16944. get: function () {
  16945. return this._activeAnimatables;
  16946. },
  16947. enumerable: true,
  16948. configurable: true
  16949. });
  16950. /**
  16951. * Will stop the animation of the given target
  16952. * @param target - the target
  16953. * @see beginAnimation
  16954. */
  16955. Scene.prototype.stopAnimation = function (target) {
  16956. var animatable = this.getAnimatableByTarget(target);
  16957. if (animatable) {
  16958. animatable.stop();
  16959. }
  16960. };
  16961. Scene.prototype._animate = function () {
  16962. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16963. return;
  16964. }
  16965. if (!this._animationStartDate) {
  16966. if (this._pendingData.length > 0) {
  16967. return;
  16968. }
  16969. this._animationStartDate = BABYLON.Tools.Now;
  16970. }
  16971. // Getting time
  16972. var now = BABYLON.Tools.Now;
  16973. var delay = now - this._animationStartDate;
  16974. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16975. this._activeAnimatables[index]._animate(delay);
  16976. }
  16977. };
  16978. // Matrix
  16979. Scene.prototype.getViewMatrix = function () {
  16980. return this._viewMatrix;
  16981. };
  16982. Scene.prototype.getProjectionMatrix = function () {
  16983. return this._projectionMatrix;
  16984. };
  16985. Scene.prototype.getTransformMatrix = function () {
  16986. return this._transformMatrix;
  16987. };
  16988. Scene.prototype.setTransformMatrix = function (view, projection) {
  16989. this._viewMatrix = view;
  16990. this._projectionMatrix = projection;
  16991. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16992. // Update frustum
  16993. if (!this._frustumPlanes) {
  16994. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16995. }
  16996. else {
  16997. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16998. }
  16999. };
  17000. // Methods
  17001. Scene.prototype.addMesh = function (newMesh) {
  17002. newMesh.uniqueId = this._uniqueIdCounter++;
  17003. var position = this.meshes.push(newMesh);
  17004. //notify the collision coordinator
  17005. this.collisionCoordinator.onMeshAdded(newMesh);
  17006. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17007. };
  17008. Scene.prototype.removeMesh = function (toRemove) {
  17009. var index = this.meshes.indexOf(toRemove);
  17010. if (index !== -1) {
  17011. // Remove from the scene if mesh found
  17012. this.meshes.splice(index, 1);
  17013. }
  17014. //notify the collision coordinator
  17015. this.collisionCoordinator.onMeshRemoved(toRemove);
  17016. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17017. return index;
  17018. };
  17019. Scene.prototype.removeSkeleton = function (toRemove) {
  17020. var index = this.skeletons.indexOf(toRemove);
  17021. if (index !== -1) {
  17022. // Remove from the scene if mesh found
  17023. this.skeletons.splice(index, 1);
  17024. }
  17025. return index;
  17026. };
  17027. Scene.prototype.removeLight = function (toRemove) {
  17028. var index = this.lights.indexOf(toRemove);
  17029. if (index !== -1) {
  17030. // Remove from the scene if mesh found
  17031. this.lights.splice(index, 1);
  17032. }
  17033. this.onLightRemovedObservable.notifyObservers(toRemove);
  17034. return index;
  17035. };
  17036. Scene.prototype.removeCamera = function (toRemove) {
  17037. var index = this.cameras.indexOf(toRemove);
  17038. if (index !== -1) {
  17039. // Remove from the scene if mesh found
  17040. this.cameras.splice(index, 1);
  17041. }
  17042. // Remove from activeCameras
  17043. var index2 = this.activeCameras.indexOf(toRemove);
  17044. if (index2 !== -1) {
  17045. // Remove from the scene if mesh found
  17046. this.activeCameras.splice(index2, 1);
  17047. }
  17048. // Reset the activeCamera
  17049. if (this.activeCamera === toRemove) {
  17050. if (this.cameras.length > 0) {
  17051. this.activeCamera = this.cameras[0];
  17052. }
  17053. else {
  17054. this.activeCamera = null;
  17055. }
  17056. }
  17057. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17058. return index;
  17059. };
  17060. Scene.prototype.addLight = function (newLight) {
  17061. newLight.uniqueId = this._uniqueIdCounter++;
  17062. var position = this.lights.push(newLight);
  17063. this.onNewLightAddedObservable.notifyObservers(newLight);
  17064. };
  17065. Scene.prototype.addCamera = function (newCamera) {
  17066. newCamera.uniqueId = this._uniqueIdCounter++;
  17067. var position = this.cameras.push(newCamera);
  17068. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17069. };
  17070. /**
  17071. * Switch active camera
  17072. * @param {Camera} newCamera - new active camera
  17073. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17074. */
  17075. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17076. if (attachControl === void 0) { attachControl = true; }
  17077. var canvas = this._engine.getRenderingCanvas();
  17078. this.activeCamera.detachControl(canvas);
  17079. this.activeCamera = newCamera;
  17080. if (attachControl) {
  17081. newCamera.attachControl(canvas);
  17082. }
  17083. };
  17084. /**
  17085. * sets the active camera of the scene using its ID
  17086. * @param {string} id - the camera's ID
  17087. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17088. * @see activeCamera
  17089. */
  17090. Scene.prototype.setActiveCameraByID = function (id) {
  17091. var camera = this.getCameraByID(id);
  17092. if (camera) {
  17093. this.activeCamera = camera;
  17094. return camera;
  17095. }
  17096. return null;
  17097. };
  17098. /**
  17099. * sets the active camera of the scene using its name
  17100. * @param {string} name - the camera's name
  17101. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17102. * @see activeCamera
  17103. */
  17104. Scene.prototype.setActiveCameraByName = function (name) {
  17105. var camera = this.getCameraByName(name);
  17106. if (camera) {
  17107. this.activeCamera = camera;
  17108. return camera;
  17109. }
  17110. return null;
  17111. };
  17112. /**
  17113. * get a material using its id
  17114. * @param {string} the material's ID
  17115. * @return {BABYLON.Material|null} the material or null if none found.
  17116. */
  17117. Scene.prototype.getMaterialByID = function (id) {
  17118. for (var index = 0; index < this.materials.length; index++) {
  17119. if (this.materials[index].id === id) {
  17120. return this.materials[index];
  17121. }
  17122. }
  17123. return null;
  17124. };
  17125. /**
  17126. * get a material using its name
  17127. * @param {string} the material's name
  17128. * @return {BABYLON.Material|null} the material or null if none found.
  17129. */
  17130. Scene.prototype.getMaterialByName = function (name) {
  17131. for (var index = 0; index < this.materials.length; index++) {
  17132. if (this.materials[index].name === name) {
  17133. return this.materials[index];
  17134. }
  17135. }
  17136. return null;
  17137. };
  17138. Scene.prototype.getLensFlareSystemByName = function (name) {
  17139. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17140. if (this.lensFlareSystems[index].name === name) {
  17141. return this.lensFlareSystems[index];
  17142. }
  17143. }
  17144. return null;
  17145. };
  17146. Scene.prototype.getLensFlareSystemByID = function (id) {
  17147. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17148. if (this.lensFlareSystems[index].id === id) {
  17149. return this.lensFlareSystems[index];
  17150. }
  17151. }
  17152. return null;
  17153. };
  17154. Scene.prototype.getCameraByID = function (id) {
  17155. for (var index = 0; index < this.cameras.length; index++) {
  17156. if (this.cameras[index].id === id) {
  17157. return this.cameras[index];
  17158. }
  17159. }
  17160. return null;
  17161. };
  17162. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17163. for (var index = 0; index < this.cameras.length; index++) {
  17164. if (this.cameras[index].uniqueId === uniqueId) {
  17165. return this.cameras[index];
  17166. }
  17167. }
  17168. return null;
  17169. };
  17170. /**
  17171. * get a camera using its name
  17172. * @param {string} the camera's name
  17173. * @return {BABYLON.Camera|null} the camera or null if none found.
  17174. */
  17175. Scene.prototype.getCameraByName = function (name) {
  17176. for (var index = 0; index < this.cameras.length; index++) {
  17177. if (this.cameras[index].name === name) {
  17178. return this.cameras[index];
  17179. }
  17180. }
  17181. return null;
  17182. };
  17183. /**
  17184. * get a bone using its id
  17185. * @param {string} the bone's id
  17186. * @return {BABYLON.Bone|null} the bone or null if not found
  17187. */
  17188. Scene.prototype.getBoneByID = function (id) {
  17189. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17190. var skeleton = this.skeletons[skeletonIndex];
  17191. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17192. if (skeleton.bones[boneIndex].id === id) {
  17193. return skeleton.bones[boneIndex];
  17194. }
  17195. }
  17196. }
  17197. return null;
  17198. };
  17199. /**
  17200. * get a bone using its id
  17201. * @param {string} the bone's name
  17202. * @return {BABYLON.Bone|null} the bone or null if not found
  17203. */
  17204. Scene.prototype.getBoneByName = function (name) {
  17205. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17206. var skeleton = this.skeletons[skeletonIndex];
  17207. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17208. if (skeleton.bones[boneIndex].name === name) {
  17209. return skeleton.bones[boneIndex];
  17210. }
  17211. }
  17212. }
  17213. return null;
  17214. };
  17215. /**
  17216. * get a light node using its name
  17217. * @param {string} the light's name
  17218. * @return {BABYLON.Light|null} the light or null if none found.
  17219. */
  17220. Scene.prototype.getLightByName = function (name) {
  17221. for (var index = 0; index < this.lights.length; index++) {
  17222. if (this.lights[index].name === name) {
  17223. return this.lights[index];
  17224. }
  17225. }
  17226. return null;
  17227. };
  17228. /**
  17229. * get a light node using its ID
  17230. * @param {string} the light's id
  17231. * @return {BABYLON.Light|null} the light or null if none found.
  17232. */
  17233. Scene.prototype.getLightByID = function (id) {
  17234. for (var index = 0; index < this.lights.length; index++) {
  17235. if (this.lights[index].id === id) {
  17236. return this.lights[index];
  17237. }
  17238. }
  17239. return null;
  17240. };
  17241. /**
  17242. * get a light node using its scene-generated unique ID
  17243. * @param {number} the light's unique id
  17244. * @return {BABYLON.Light|null} the light or null if none found.
  17245. */
  17246. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17247. for (var index = 0; index < this.lights.length; index++) {
  17248. if (this.lights[index].uniqueId === uniqueId) {
  17249. return this.lights[index];
  17250. }
  17251. }
  17252. return null;
  17253. };
  17254. /**
  17255. * get a particle system by id
  17256. * @param id {number} the particle system id
  17257. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17258. */
  17259. Scene.prototype.getParticleSystemByID = function (id) {
  17260. for (var index = 0; index < this.particleSystems.length; index++) {
  17261. if (this.particleSystems[index].id === id) {
  17262. return this.particleSystems[index];
  17263. }
  17264. }
  17265. return null;
  17266. };
  17267. /**
  17268. * get a geometry using its ID
  17269. * @param {string} the geometry's id
  17270. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17271. */
  17272. Scene.prototype.getGeometryByID = function (id) {
  17273. for (var index = 0; index < this._geometries.length; index++) {
  17274. if (this._geometries[index].id === id) {
  17275. return this._geometries[index];
  17276. }
  17277. }
  17278. return null;
  17279. };
  17280. /**
  17281. * add a new geometry to this scene.
  17282. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17283. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17284. * @return {boolean} was the geometry added or not
  17285. */
  17286. Scene.prototype.pushGeometry = function (geometry, force) {
  17287. if (!force && this.getGeometryByID(geometry.id)) {
  17288. return false;
  17289. }
  17290. this._geometries.push(geometry);
  17291. //notify the collision coordinator
  17292. this.collisionCoordinator.onGeometryAdded(geometry);
  17293. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17294. return true;
  17295. };
  17296. /**
  17297. * Removes an existing geometry
  17298. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17299. * @return {boolean} was the geometry removed or not
  17300. */
  17301. Scene.prototype.removeGeometry = function (geometry) {
  17302. var index = this._geometries.indexOf(geometry);
  17303. if (index > -1) {
  17304. this._geometries.splice(index, 1);
  17305. //notify the collision coordinator
  17306. this.collisionCoordinator.onGeometryDeleted(geometry);
  17307. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17308. return true;
  17309. }
  17310. return false;
  17311. };
  17312. Scene.prototype.getGeometries = function () {
  17313. return this._geometries;
  17314. };
  17315. /**
  17316. * Get the first added mesh found of a given ID
  17317. * @param {string} id - the id to search for
  17318. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17319. */
  17320. Scene.prototype.getMeshByID = function (id) {
  17321. for (var index = 0; index < this.meshes.length; index++) {
  17322. if (this.meshes[index].id === id) {
  17323. return this.meshes[index];
  17324. }
  17325. }
  17326. return null;
  17327. };
  17328. Scene.prototype.getMeshesByID = function (id) {
  17329. return this.meshes.filter(function (m) {
  17330. return m.id === id;
  17331. });
  17332. };
  17333. /**
  17334. * Get a mesh with its auto-generated unique id
  17335. * @param {number} uniqueId - the unique id to search for
  17336. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17337. */
  17338. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17339. for (var index = 0; index < this.meshes.length; index++) {
  17340. if (this.meshes[index].uniqueId === uniqueId) {
  17341. return this.meshes[index];
  17342. }
  17343. }
  17344. return null;
  17345. };
  17346. /**
  17347. * Get a the last added mesh found of a given ID
  17348. * @param {string} id - the id to search for
  17349. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17350. */
  17351. Scene.prototype.getLastMeshByID = function (id) {
  17352. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17353. if (this.meshes[index].id === id) {
  17354. return this.meshes[index];
  17355. }
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17361. * @param {string} id - the id to search for
  17362. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17363. */
  17364. Scene.prototype.getLastEntryByID = function (id) {
  17365. var index;
  17366. for (index = this.meshes.length - 1; index >= 0; index--) {
  17367. if (this.meshes[index].id === id) {
  17368. return this.meshes[index];
  17369. }
  17370. }
  17371. for (index = this.cameras.length - 1; index >= 0; index--) {
  17372. if (this.cameras[index].id === id) {
  17373. return this.cameras[index];
  17374. }
  17375. }
  17376. for (index = this.lights.length - 1; index >= 0; index--) {
  17377. if (this.lights[index].id === id) {
  17378. return this.lights[index];
  17379. }
  17380. }
  17381. return null;
  17382. };
  17383. Scene.prototype.getNodeByID = function (id) {
  17384. var mesh = this.getMeshByID(id);
  17385. if (mesh) {
  17386. return mesh;
  17387. }
  17388. var light = this.getLightByID(id);
  17389. if (light) {
  17390. return light;
  17391. }
  17392. var camera = this.getCameraByID(id);
  17393. if (camera) {
  17394. return camera;
  17395. }
  17396. var bone = this.getBoneByID(id);
  17397. return bone;
  17398. };
  17399. Scene.prototype.getNodeByName = function (name) {
  17400. var mesh = this.getMeshByName(name);
  17401. if (mesh) {
  17402. return mesh;
  17403. }
  17404. var light = this.getLightByName(name);
  17405. if (light) {
  17406. return light;
  17407. }
  17408. var camera = this.getCameraByName(name);
  17409. if (camera) {
  17410. return camera;
  17411. }
  17412. var bone = this.getBoneByName(name);
  17413. return bone;
  17414. };
  17415. Scene.prototype.getMeshByName = function (name) {
  17416. for (var index = 0; index < this.meshes.length; index++) {
  17417. if (this.meshes[index].name === name) {
  17418. return this.meshes[index];
  17419. }
  17420. }
  17421. return null;
  17422. };
  17423. Scene.prototype.getSoundByName = function (name) {
  17424. var index;
  17425. if (BABYLON.AudioEngine) {
  17426. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17427. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17428. return this.mainSoundTrack.soundCollection[index];
  17429. }
  17430. }
  17431. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17432. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17433. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17434. return this.soundTracks[sdIndex].soundCollection[index];
  17435. }
  17436. }
  17437. }
  17438. }
  17439. return null;
  17440. };
  17441. Scene.prototype.getLastSkeletonByID = function (id) {
  17442. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17443. if (this.skeletons[index].id === id) {
  17444. return this.skeletons[index];
  17445. }
  17446. }
  17447. return null;
  17448. };
  17449. Scene.prototype.getSkeletonById = function (id) {
  17450. for (var index = 0; index < this.skeletons.length; index++) {
  17451. if (this.skeletons[index].id === id) {
  17452. return this.skeletons[index];
  17453. }
  17454. }
  17455. return null;
  17456. };
  17457. Scene.prototype.getSkeletonByName = function (name) {
  17458. for (var index = 0; index < this.skeletons.length; index++) {
  17459. if (this.skeletons[index].name === name) {
  17460. return this.skeletons[index];
  17461. }
  17462. }
  17463. return null;
  17464. };
  17465. Scene.prototype.isActiveMesh = function (mesh) {
  17466. return (this._activeMeshes.indexOf(mesh) !== -1);
  17467. };
  17468. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17469. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17470. var material = subMesh.getMaterial();
  17471. if (mesh.showSubMeshesBoundingBox) {
  17472. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17473. }
  17474. if (material) {
  17475. // Render targets
  17476. if (material.getRenderTargetTextures) {
  17477. if (this._processedMaterials.indexOf(material) === -1) {
  17478. this._processedMaterials.push(material);
  17479. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17480. }
  17481. }
  17482. // Dispatch
  17483. this._activeIndices.addCount(subMesh.indexCount, false);
  17484. this._renderingManager.dispatch(subMesh);
  17485. }
  17486. }
  17487. };
  17488. Scene.prototype._isInIntermediateRendering = function () {
  17489. return this._intermediateRendering;
  17490. };
  17491. Scene.prototype._evaluateActiveMeshes = function () {
  17492. this.activeCamera._activeMeshes.reset();
  17493. this._activeMeshes.reset();
  17494. this._renderingManager.reset();
  17495. this._processedMaterials.reset();
  17496. this._activeParticleSystems.reset();
  17497. this._activeSkeletons.reset();
  17498. this._softwareSkinnedMeshes.reset();
  17499. this._boundingBoxRenderer.reset();
  17500. this._edgesRenderers.reset();
  17501. // Meshes
  17502. var meshes;
  17503. var len;
  17504. if (this._selectionOctree) {
  17505. var selection = this._selectionOctree.select(this._frustumPlanes);
  17506. meshes = selection.data;
  17507. len = selection.length;
  17508. }
  17509. else {
  17510. len = this.meshes.length;
  17511. meshes = this.meshes;
  17512. }
  17513. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17514. var mesh = meshes[meshIndex];
  17515. if (mesh.isBlocked) {
  17516. continue;
  17517. }
  17518. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17519. if (!mesh.isReady() || !mesh.isEnabled()) {
  17520. continue;
  17521. }
  17522. mesh.computeWorldMatrix();
  17523. // Intersections
  17524. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17525. this._meshesForIntersections.pushNoDuplicate(mesh);
  17526. }
  17527. // Switch to current LOD
  17528. var meshLOD = mesh.getLOD(this.activeCamera);
  17529. if (!meshLOD) {
  17530. continue;
  17531. }
  17532. mesh._preActivate();
  17533. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17534. this._activeMeshes.push(mesh);
  17535. this.activeCamera._activeMeshes.push(mesh);
  17536. mesh._activate(this._renderId);
  17537. this._activeMesh(mesh, meshLOD);
  17538. }
  17539. }
  17540. // Particle systems
  17541. this._particlesDuration.beginMonitoring();
  17542. var beforeParticlesDate = BABYLON.Tools.Now;
  17543. if (this.particlesEnabled) {
  17544. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17545. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17546. var particleSystem = this.particleSystems[particleIndex];
  17547. if (!particleSystem.isStarted()) {
  17548. continue;
  17549. }
  17550. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17551. this._activeParticleSystems.push(particleSystem);
  17552. particleSystem.animate();
  17553. }
  17554. }
  17555. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17556. }
  17557. this._particlesDuration.endMonitoring(false);
  17558. };
  17559. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17560. if (mesh.skeleton && this.skeletonsEnabled) {
  17561. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17562. mesh.skeleton.prepare();
  17563. }
  17564. if (!mesh.computeBonesUsingShaders) {
  17565. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17566. }
  17567. }
  17568. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17569. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17570. }
  17571. if (sourceMesh._edgesRenderer) {
  17572. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17573. }
  17574. if (mesh && mesh.subMeshes) {
  17575. // Submeshes Octrees
  17576. var len;
  17577. var subMeshes;
  17578. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17579. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17580. len = intersections.length;
  17581. subMeshes = intersections.data;
  17582. }
  17583. else {
  17584. subMeshes = mesh.subMeshes;
  17585. len = subMeshes.length;
  17586. }
  17587. for (var subIndex = 0; subIndex < len; subIndex++) {
  17588. var subMesh = subMeshes[subIndex];
  17589. this._evaluateSubMesh(subMesh, mesh);
  17590. }
  17591. }
  17592. };
  17593. Scene.prototype.updateTransformMatrix = function (force) {
  17594. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17595. };
  17596. Scene.prototype._renderForCamera = function (camera) {
  17597. var engine = this._engine;
  17598. var startTime = BABYLON.Tools.Now;
  17599. this.activeCamera = camera;
  17600. if (!this.activeCamera)
  17601. throw new Error("Active camera not set");
  17602. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17603. // Viewport
  17604. engine.setViewport(this.activeCamera.viewport);
  17605. // Camera
  17606. this.resetCachedMaterial();
  17607. this._renderId++;
  17608. this.updateTransformMatrix();
  17609. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17610. // Meshes
  17611. this._evaluateActiveMeshesDuration.beginMonitoring();
  17612. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17613. this._evaluateActiveMeshes();
  17614. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17615. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17616. // Software skinning
  17617. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17618. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17619. mesh.applySkeleton(mesh.skeleton);
  17620. }
  17621. // Render targets
  17622. this._renderTargetsDuration.beginMonitoring();
  17623. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17624. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17625. this._intermediateRendering = true;
  17626. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17627. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17628. var renderTarget = this._renderTargets.data[renderIndex];
  17629. if (renderTarget._shouldRender()) {
  17630. this._renderId++;
  17631. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17632. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17633. }
  17634. }
  17635. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17636. this._intermediateRendering = false;
  17637. this._renderId++;
  17638. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17639. }
  17640. this._renderTargetsDuration.endMonitoring(false);
  17641. // Prepare Frame
  17642. this.postProcessManager._prepareFrame();
  17643. this._renderDuration.beginMonitoring();
  17644. // Backgrounds
  17645. var layerIndex;
  17646. var layer;
  17647. if (this.layers.length) {
  17648. engine.setDepthBuffer(false);
  17649. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17650. layer = this.layers[layerIndex];
  17651. if (layer.isBackground) {
  17652. layer.render();
  17653. }
  17654. }
  17655. engine.setDepthBuffer(true);
  17656. }
  17657. // Render
  17658. BABYLON.Tools.StartPerformanceCounter("Main render");
  17659. // Activate HighlightLayer stencil
  17660. var stencilState = this._engine.getStencilBuffer();
  17661. var renderhighlights = false;
  17662. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17663. for (var i = 0; i < this.highlightLayers.length; i++) {
  17664. if (this.highlightLayers[i].shouldRender()) {
  17665. renderhighlights = true;
  17666. this._engine.setStencilBuffer(true);
  17667. break;
  17668. }
  17669. }
  17670. }
  17671. this._renderingManager.render(null, null, true, true);
  17672. // Restore HighlightLayer stencil
  17673. if (renderhighlights) {
  17674. this._engine.setStencilBuffer(stencilState);
  17675. }
  17676. BABYLON.Tools.EndPerformanceCounter("Main render");
  17677. // Bounding boxes
  17678. this._boundingBoxRenderer.render();
  17679. // Edges
  17680. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17681. this._edgesRenderers.data[edgesRendererIndex].render();
  17682. }
  17683. // Lens flares
  17684. if (this.lensFlaresEnabled) {
  17685. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17686. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17687. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17688. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17689. lensFlareSystem.render();
  17690. }
  17691. }
  17692. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17693. }
  17694. // Foregrounds
  17695. if (this.layers.length) {
  17696. engine.setDepthBuffer(false);
  17697. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17698. layer = this.layers[layerIndex];
  17699. if (!layer.isBackground) {
  17700. layer.render();
  17701. }
  17702. }
  17703. engine.setDepthBuffer(true);
  17704. }
  17705. // Highlight Layer
  17706. if (renderhighlights) {
  17707. engine.setDepthBuffer(false);
  17708. for (var i = 0; i < this.highlightLayers.length; i++) {
  17709. if (this.highlightLayers[i].shouldRender()) {
  17710. this.highlightLayers[i].render();
  17711. }
  17712. }
  17713. engine.setDepthBuffer(true);
  17714. }
  17715. this._renderDuration.endMonitoring(false);
  17716. // Finalize frame
  17717. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17718. // Update camera
  17719. this.activeCamera._updateFromScene();
  17720. // Reset some special arrays
  17721. this._renderTargets.reset();
  17722. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17723. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17724. };
  17725. Scene.prototype._processSubCameras = function (camera) {
  17726. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17727. this._renderForCamera(camera);
  17728. return;
  17729. }
  17730. // rig cameras
  17731. for (var index = 0; index < camera._rigCameras.length; index++) {
  17732. this._renderForCamera(camera._rigCameras[index]);
  17733. }
  17734. this.activeCamera = camera;
  17735. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17736. // Update camera
  17737. this.activeCamera._updateFromScene();
  17738. };
  17739. Scene.prototype._checkIntersections = function () {
  17740. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17741. var sourceMesh = this._meshesForIntersections.data[index];
  17742. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17743. var action = sourceMesh.actionManager.actions[actionIndex];
  17744. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17745. var parameters = action.getTriggerParameter();
  17746. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17747. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17748. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17749. if (areIntersecting && currentIntersectionInProgress === -1) {
  17750. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17751. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17752. sourceMesh._intersectionsInProgress.push(otherMesh);
  17753. }
  17754. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17755. sourceMesh._intersectionsInProgress.push(otherMesh);
  17756. }
  17757. }
  17758. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17759. //They intersected, and now they don't.
  17760. //is this trigger an exit trigger? execute an event.
  17761. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17762. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17763. }
  17764. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17765. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17766. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17767. }
  17768. }
  17769. }
  17770. }
  17771. }
  17772. };
  17773. Scene.prototype.render = function () {
  17774. this._lastFrameDuration.beginMonitoring();
  17775. this._particlesDuration.fetchNewFrame();
  17776. this._spritesDuration.fetchNewFrame();
  17777. this._activeParticles.fetchNewFrame();
  17778. this._renderDuration.fetchNewFrame();
  17779. this._renderTargetsDuration.fetchNewFrame();
  17780. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17781. this._totalVertices.fetchNewFrame();
  17782. this._activeIndices.fetchNewFrame();
  17783. this._activeBones.fetchNewFrame();
  17784. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17785. this._meshesForIntersections.reset();
  17786. this.resetCachedMaterial();
  17787. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17788. // Actions
  17789. if (this.actionManager) {
  17790. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17791. }
  17792. //Simplification Queue
  17793. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17794. this.simplificationQueue.executeNext();
  17795. }
  17796. // Animations
  17797. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17798. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17799. this._animate();
  17800. // Physics
  17801. if (this._physicsEngine) {
  17802. BABYLON.Tools.StartPerformanceCounter("Physics");
  17803. this._physicsEngine._step(deltaTime / 1000.0);
  17804. BABYLON.Tools.EndPerformanceCounter("Physics");
  17805. }
  17806. // Before render
  17807. this.onBeforeRenderObservable.notifyObservers(this);
  17808. // Customs render targets
  17809. this._renderTargetsDuration.beginMonitoring();
  17810. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17811. var engine = this.getEngine();
  17812. var currentActiveCamera = this.activeCamera;
  17813. if (this.renderTargetsEnabled) {
  17814. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17815. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17816. var renderTarget = this.customRenderTargets[customIndex];
  17817. if (renderTarget._shouldRender()) {
  17818. this._renderId++;
  17819. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17820. if (!this.activeCamera)
  17821. throw new Error("Active camera not set");
  17822. // Viewport
  17823. engine.setViewport(this.activeCamera.viewport);
  17824. // Camera
  17825. this.updateTransformMatrix();
  17826. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17827. }
  17828. }
  17829. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17830. this._renderId++;
  17831. }
  17832. if (this.customRenderTargets.length > 0) {
  17833. engine.restoreDefaultFramebuffer();
  17834. }
  17835. this._renderTargetsDuration.endMonitoring();
  17836. this.activeCamera = currentActiveCamera;
  17837. // Procedural textures
  17838. if (this.proceduralTexturesEnabled) {
  17839. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17840. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17841. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17842. if (proceduralTexture._shouldRender()) {
  17843. proceduralTexture.render();
  17844. }
  17845. }
  17846. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17847. }
  17848. // Clear
  17849. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17850. // Shadows
  17851. if (this.shadowsEnabled) {
  17852. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17853. var light = this.lights[lightIndex];
  17854. var shadowGenerator = light.getShadowGenerator();
  17855. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17856. this._renderTargets.push(shadowGenerator.getShadowMap());
  17857. }
  17858. }
  17859. }
  17860. // Depth renderer
  17861. if (this._depthRenderer) {
  17862. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17863. }
  17864. // HighlightLayer
  17865. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17866. for (var i = 0; i < this.highlightLayers.length; i++) {
  17867. if (this.highlightLayers[i].shouldRender()) {
  17868. this._renderTargets.push(this.highlightLayers[i]._mainTexture);
  17869. }
  17870. }
  17871. }
  17872. // RenderPipeline
  17873. this.postProcessRenderPipelineManager.update();
  17874. // Multi-cameras?
  17875. if (this.activeCameras.length > 0) {
  17876. var currentRenderId = this._renderId;
  17877. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17878. this._renderId = currentRenderId;
  17879. if (cameraIndex > 0) {
  17880. this._engine.clear(0, false, true, true);
  17881. }
  17882. this._processSubCameras(this.activeCameras[cameraIndex]);
  17883. }
  17884. }
  17885. else {
  17886. if (!this.activeCamera) {
  17887. throw new Error("No camera defined");
  17888. }
  17889. this._processSubCameras(this.activeCamera);
  17890. }
  17891. // Intersection checks
  17892. this._checkIntersections();
  17893. // Update the audio listener attached to the camera
  17894. if (BABYLON.AudioEngine) {
  17895. this._updateAudioParameters();
  17896. }
  17897. // After render
  17898. if (this.afterRender) {
  17899. this.afterRender();
  17900. }
  17901. this.onAfterRenderObservable.notifyObservers(this);
  17902. // Cleaning
  17903. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17904. this._toBeDisposed.data[index].dispose();
  17905. this._toBeDisposed[index] = null;
  17906. }
  17907. this._toBeDisposed.reset();
  17908. if (this.dumpNextRenderTargets) {
  17909. this.dumpNextRenderTargets = false;
  17910. }
  17911. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17912. this._lastFrameDuration.endMonitoring();
  17913. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17914. this._totalLightsCounter.addCount(this.lights.length, true);
  17915. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17916. this._totalTexturesCounter.addCount(this.textures.length, true);
  17917. this._activeBones.addCount(0, true);
  17918. this._activeIndices.addCount(0, true);
  17919. this._activeParticles.addCount(0, true);
  17920. };
  17921. Scene.prototype._updateAudioParameters = function () {
  17922. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17923. return;
  17924. }
  17925. var listeningCamera;
  17926. var audioEngine = BABYLON.Engine.audioEngine;
  17927. if (this.activeCameras.length > 0) {
  17928. listeningCamera = this.activeCameras[0];
  17929. }
  17930. else {
  17931. listeningCamera = this.activeCamera;
  17932. }
  17933. if (listeningCamera && audioEngine.canUseWebAudio) {
  17934. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17935. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17936. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17937. cameraDirection.normalize();
  17938. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17939. var i;
  17940. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17941. var sound = this.mainSoundTrack.soundCollection[i];
  17942. if (sound.useCustomAttenuation) {
  17943. sound.updateDistanceFromListener();
  17944. }
  17945. }
  17946. for (i = 0; i < this.soundTracks.length; i++) {
  17947. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17948. sound = this.soundTracks[i].soundCollection[j];
  17949. if (sound.useCustomAttenuation) {
  17950. sound.updateDistanceFromListener();
  17951. }
  17952. }
  17953. }
  17954. }
  17955. };
  17956. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17957. // Audio
  17958. get: function () {
  17959. return this._audioEnabled;
  17960. },
  17961. set: function (value) {
  17962. this._audioEnabled = value;
  17963. if (BABYLON.AudioEngine) {
  17964. if (this._audioEnabled) {
  17965. this._enableAudio();
  17966. }
  17967. else {
  17968. this._disableAudio();
  17969. }
  17970. }
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. Scene.prototype._disableAudio = function () {
  17976. var i;
  17977. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17978. this.mainSoundTrack.soundCollection[i].pause();
  17979. }
  17980. for (i = 0; i < this.soundTracks.length; i++) {
  17981. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17982. this.soundTracks[i].soundCollection[j].pause();
  17983. }
  17984. }
  17985. };
  17986. Scene.prototype._enableAudio = function () {
  17987. var i;
  17988. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17989. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17990. this.mainSoundTrack.soundCollection[i].play();
  17991. }
  17992. }
  17993. for (i = 0; i < this.soundTracks.length; i++) {
  17994. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17995. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17996. this.soundTracks[i].soundCollection[j].play();
  17997. }
  17998. }
  17999. }
  18000. };
  18001. Object.defineProperty(Scene.prototype, "headphone", {
  18002. get: function () {
  18003. return this._headphone;
  18004. },
  18005. set: function (value) {
  18006. this._headphone = value;
  18007. if (BABYLON.AudioEngine) {
  18008. if (this._headphone) {
  18009. this._switchAudioModeForHeadphones();
  18010. }
  18011. else {
  18012. this._switchAudioModeForNormalSpeakers();
  18013. }
  18014. }
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Scene.prototype._switchAudioModeForHeadphones = function () {
  18020. this.mainSoundTrack.switchPanningModelToHRTF();
  18021. for (var i = 0; i < this.soundTracks.length; i++) {
  18022. this.soundTracks[i].switchPanningModelToHRTF();
  18023. }
  18024. };
  18025. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18026. this.mainSoundTrack.switchPanningModelToEqualPower();
  18027. for (var i = 0; i < this.soundTracks.length; i++) {
  18028. this.soundTracks[i].switchPanningModelToEqualPower();
  18029. }
  18030. };
  18031. Scene.prototype.enableDepthRenderer = function () {
  18032. if (this._depthRenderer) {
  18033. return this._depthRenderer;
  18034. }
  18035. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18036. return this._depthRenderer;
  18037. };
  18038. Scene.prototype.disableDepthRenderer = function () {
  18039. if (!this._depthRenderer) {
  18040. return;
  18041. }
  18042. this._depthRenderer.dispose();
  18043. this._depthRenderer = null;
  18044. };
  18045. Scene.prototype.freezeMaterials = function () {
  18046. for (var i = 0; i < this.materials.length; i++) {
  18047. this.materials[i].freeze();
  18048. }
  18049. };
  18050. Scene.prototype.unfreezeMaterials = function () {
  18051. for (var i = 0; i < this.materials.length; i++) {
  18052. this.materials[i].unfreeze();
  18053. }
  18054. };
  18055. Scene.prototype.dispose = function () {
  18056. this.beforeRender = null;
  18057. this.afterRender = null;
  18058. this.skeletons = [];
  18059. this._boundingBoxRenderer.dispose();
  18060. if (this._depthRenderer) {
  18061. this._depthRenderer.dispose();
  18062. }
  18063. // Debug layer
  18064. if (this._debugLayer) {
  18065. this._debugLayer.hide();
  18066. }
  18067. // Events
  18068. this.onDisposeObservable.notifyObservers(this);
  18069. this.onDisposeObservable.clear();
  18070. this.onBeforeRenderObservable.clear();
  18071. this.onAfterRenderObservable.clear();
  18072. this.detachControl();
  18073. // Release sounds & sounds tracks
  18074. if (BABYLON.AudioEngine) {
  18075. this.disposeSounds();
  18076. }
  18077. // Detach cameras
  18078. var canvas = this._engine.getRenderingCanvas();
  18079. var index;
  18080. for (index = 0; index < this.cameras.length; index++) {
  18081. this.cameras[index].detachControl(canvas);
  18082. }
  18083. // Release lights
  18084. while (this.lights.length) {
  18085. this.lights[0].dispose();
  18086. }
  18087. // Release meshes
  18088. while (this.meshes.length) {
  18089. this.meshes[0].dispose(true);
  18090. }
  18091. // Release cameras
  18092. while (this.cameras.length) {
  18093. this.cameras[0].dispose();
  18094. }
  18095. // Release materials
  18096. while (this.materials.length) {
  18097. this.materials[0].dispose();
  18098. }
  18099. // Release particles
  18100. while (this.particleSystems.length) {
  18101. this.particleSystems[0].dispose();
  18102. }
  18103. // Release sprites
  18104. while (this.spriteManagers.length) {
  18105. this.spriteManagers[0].dispose();
  18106. }
  18107. // Release layers
  18108. while (this.layers.length) {
  18109. this.layers[0].dispose();
  18110. }
  18111. while (this.highlightLayers.length) {
  18112. this.highlightLayers[0].dispose();
  18113. }
  18114. // Release textures
  18115. while (this.textures.length) {
  18116. this.textures[0].dispose();
  18117. }
  18118. // Post-processes
  18119. this.postProcessManager.dispose();
  18120. // Physics
  18121. if (this._physicsEngine) {
  18122. this.disablePhysicsEngine();
  18123. }
  18124. // Remove from engine
  18125. index = this._engine.scenes.indexOf(this);
  18126. if (index > -1) {
  18127. this._engine.scenes.splice(index, 1);
  18128. }
  18129. this._engine.wipeCaches();
  18130. };
  18131. // Release sounds & sounds tracks
  18132. Scene.prototype.disposeSounds = function () {
  18133. this.mainSoundTrack.dispose();
  18134. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18135. this.soundTracks[scIndex].dispose();
  18136. }
  18137. };
  18138. // Octrees
  18139. Scene.prototype.getWorldExtends = function () {
  18140. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18141. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18142. for (var index = 0; index < this.meshes.length; index++) {
  18143. var mesh = this.meshes[index];
  18144. mesh.computeWorldMatrix(true);
  18145. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18146. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18147. BABYLON.Tools.CheckExtends(minBox, min, max);
  18148. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18149. }
  18150. return {
  18151. min: min,
  18152. max: max
  18153. };
  18154. };
  18155. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18156. if (maxCapacity === void 0) { maxCapacity = 64; }
  18157. if (maxDepth === void 0) { maxDepth = 2; }
  18158. if (!this._selectionOctree) {
  18159. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18160. }
  18161. var worldExtends = this.getWorldExtends();
  18162. // Update octree
  18163. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18164. return this._selectionOctree;
  18165. };
  18166. // Picking
  18167. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18168. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18169. var engine = this._engine;
  18170. if (!camera) {
  18171. if (!this.activeCamera)
  18172. throw new Error("Active camera not set");
  18173. camera = this.activeCamera;
  18174. }
  18175. var cameraViewport = camera.viewport;
  18176. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18177. // Moving coordinates to local viewport world
  18178. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18179. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18180. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18181. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18182. };
  18183. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18184. var engine = this._engine;
  18185. if (!camera) {
  18186. if (!this.activeCamera)
  18187. throw new Error("Active camera not set");
  18188. camera = this.activeCamera;
  18189. }
  18190. var cameraViewport = camera.viewport;
  18191. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18192. var identity = BABYLON.Matrix.Identity();
  18193. // Moving coordinates to local viewport world
  18194. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18195. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18196. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18197. };
  18198. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18199. var pickingInfo = null;
  18200. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18201. var mesh = this.meshes[meshIndex];
  18202. if (predicate) {
  18203. if (!predicate(mesh)) {
  18204. continue;
  18205. }
  18206. }
  18207. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18208. continue;
  18209. }
  18210. var world = mesh.getWorldMatrix();
  18211. var ray = rayFunction(world);
  18212. var result = mesh.intersects(ray, fastCheck);
  18213. if (!result || !result.hit)
  18214. continue;
  18215. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18216. continue;
  18217. pickingInfo = result;
  18218. if (fastCheck) {
  18219. break;
  18220. }
  18221. }
  18222. return pickingInfo || new BABYLON.PickingInfo();
  18223. };
  18224. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18225. var pickingInfo = null;
  18226. camera = camera || this.activeCamera;
  18227. if (this.spriteManagers.length > 0) {
  18228. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18229. var spriteManager = this.spriteManagers[spriteIndex];
  18230. if (!spriteManager.isPickable) {
  18231. continue;
  18232. }
  18233. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18234. if (!result || !result.hit)
  18235. continue;
  18236. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18237. continue;
  18238. pickingInfo = result;
  18239. if (fastCheck) {
  18240. break;
  18241. }
  18242. }
  18243. }
  18244. return pickingInfo || new BABYLON.PickingInfo();
  18245. };
  18246. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18247. var _this = this;
  18248. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18249. /// <param name="x">X position on screen</param>
  18250. /// <param name="y">Y position on screen</param>
  18251. /// <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>
  18252. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18253. /// <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>
  18254. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18255. };
  18256. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18257. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18258. /// <param name="x">X position on screen</param>
  18259. /// <param name="y">Y position on screen</param>
  18260. /// <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>
  18261. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18262. /// <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>
  18263. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18264. };
  18265. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18266. var _this = this;
  18267. return this._internalPick(function (world) {
  18268. if (!_this._pickWithRayInverseMatrix) {
  18269. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18270. }
  18271. world.invertToRef(_this._pickWithRayInverseMatrix);
  18272. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18273. }, predicate, fastCheck);
  18274. };
  18275. Scene.prototype.setPointerOverMesh = function (mesh) {
  18276. if (this._pointerOverMesh === mesh) {
  18277. return;
  18278. }
  18279. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18280. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18281. }
  18282. this._pointerOverMesh = mesh;
  18283. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18284. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18285. }
  18286. };
  18287. Scene.prototype.getPointerOverMesh = function () {
  18288. return this._pointerOverMesh;
  18289. };
  18290. Scene.prototype.setPointerOverSprite = function (sprite) {
  18291. if (this._pointerOverSprite === sprite) {
  18292. return;
  18293. }
  18294. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18295. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18296. }
  18297. this._pointerOverSprite = sprite;
  18298. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18299. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18300. }
  18301. };
  18302. Scene.prototype.getPointerOverSprite = function () {
  18303. return this._pointerOverSprite;
  18304. };
  18305. // Physics
  18306. Scene.prototype.getPhysicsEngine = function () {
  18307. return this._physicsEngine;
  18308. };
  18309. /**
  18310. * Enables physics to the current scene
  18311. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18312. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18313. * @return {boolean} was the physics engine initialized
  18314. */
  18315. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18316. if (this._physicsEngine) {
  18317. return true;
  18318. }
  18319. try {
  18320. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18321. return true;
  18322. }
  18323. catch (e) {
  18324. BABYLON.Tools.Error(e.message);
  18325. return false;
  18326. }
  18327. };
  18328. Scene.prototype.disablePhysicsEngine = function () {
  18329. if (!this._physicsEngine) {
  18330. return;
  18331. }
  18332. this._physicsEngine.dispose();
  18333. this._physicsEngine = undefined;
  18334. };
  18335. Scene.prototype.isPhysicsEnabled = function () {
  18336. return this._physicsEngine !== undefined;
  18337. };
  18338. /**
  18339. *
  18340. * Sets the gravity of the physics engine (and NOT of the scene)
  18341. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18342. */
  18343. Scene.prototype.setGravity = function (gravity) {
  18344. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18345. if (!this._physicsEngine) {
  18346. return;
  18347. }
  18348. this._physicsEngine.setGravity(gravity);
  18349. };
  18350. /**
  18351. * Legacy support, using the new API
  18352. * @Deprecated
  18353. */
  18354. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18355. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18356. if (parts.parts) {
  18357. options = parts;
  18358. parts = parts.parts;
  18359. }
  18360. var mainMesh = parts[0].mesh;
  18361. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18362. for (var index = 1; index < parts.length; index++) {
  18363. var mesh = parts[index].mesh;
  18364. if (mesh.parent !== mainMesh) {
  18365. mesh.position = mesh.position.subtract(mainMesh.position);
  18366. mesh.parent = mainMesh;
  18367. }
  18368. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18369. }
  18370. mainMesh.physicsImpostor.forceUpdate();
  18371. };
  18372. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18373. var mesh = compound.parts[0].mesh;
  18374. mesh.physicsImpostor.dispose();
  18375. mesh.physicsImpostor = null;
  18376. };
  18377. // Misc.
  18378. Scene.prototype.createDefaultCameraOrLight = function () {
  18379. // Light
  18380. if (this.lights.length === 0) {
  18381. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18382. }
  18383. // Camera
  18384. if (!this.activeCamera) {
  18385. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18386. // Compute position
  18387. var worldExtends = this.getWorldExtends();
  18388. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18389. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18390. camera.setTarget(worldCenter);
  18391. this.activeCamera = camera;
  18392. }
  18393. };
  18394. // Tags
  18395. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18396. if (tagsQuery === undefined) {
  18397. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18398. return list;
  18399. }
  18400. var listByTags = [];
  18401. forEach = forEach || (function (item) { return; });
  18402. for (var i in list) {
  18403. var item = list[i];
  18404. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18405. listByTags.push(item);
  18406. forEach(item);
  18407. }
  18408. }
  18409. return listByTags;
  18410. };
  18411. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18412. return this._getByTags(this.meshes, tagsQuery, forEach);
  18413. };
  18414. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18415. return this._getByTags(this.cameras, tagsQuery, forEach);
  18416. };
  18417. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18418. return this._getByTags(this.lights, tagsQuery, forEach);
  18419. };
  18420. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18421. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18422. };
  18423. /**
  18424. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18425. * This allowed control for front to back rendering or reversly depending of the special needs.
  18426. *
  18427. * @param renderingGroupId The rendering group id corresponding to its index
  18428. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18429. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18430. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18431. */
  18432. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18433. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18434. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18435. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18436. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18437. };
  18438. /**
  18439. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18440. *
  18441. * @param renderingGroupId The rendering group id corresponding to its index
  18442. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18443. */
  18444. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18445. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18446. };
  18447. // Statics
  18448. Scene._FOGMODE_NONE = 0;
  18449. Scene._FOGMODE_EXP = 1;
  18450. Scene._FOGMODE_EXP2 = 2;
  18451. Scene._FOGMODE_LINEAR = 3;
  18452. Scene.MinDeltaTime = 1.0;
  18453. Scene.MaxDeltaTime = 1000.0;
  18454. return Scene;
  18455. }());
  18456. BABYLON.Scene = Scene;
  18457. })(BABYLON || (BABYLON = {}));
  18458. var BABYLON;
  18459. (function (BABYLON) {
  18460. var Buffer = (function () {
  18461. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18462. if (engine instanceof BABYLON.Mesh) {
  18463. this._engine = engine.getScene().getEngine();
  18464. }
  18465. else {
  18466. this._engine = engine;
  18467. }
  18468. this._updatable = updatable;
  18469. this._data = data;
  18470. this._strideSize = stride;
  18471. if (!postponeInternalCreation) {
  18472. this.create();
  18473. }
  18474. this._instanced = instanced;
  18475. }
  18476. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18477. // a lot of these parameters are ignored as they are overriden by the buffer
  18478. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18479. };
  18480. // Properties
  18481. Buffer.prototype.isUpdatable = function () {
  18482. return this._updatable;
  18483. };
  18484. Buffer.prototype.getData = function () {
  18485. return this._data;
  18486. };
  18487. Buffer.prototype.getBuffer = function () {
  18488. return this._buffer;
  18489. };
  18490. Buffer.prototype.getStrideSize = function () {
  18491. return this._strideSize;
  18492. };
  18493. Buffer.prototype.getIsInstanced = function () {
  18494. return this._instanced;
  18495. };
  18496. // Methods
  18497. Buffer.prototype.create = function (data) {
  18498. if (!data && this._buffer) {
  18499. return; // nothing to do
  18500. }
  18501. data = data || this._data;
  18502. if (!this._buffer) {
  18503. if (this._updatable) {
  18504. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18505. this._data = data;
  18506. }
  18507. else {
  18508. this._buffer = this._engine.createVertexBuffer(data);
  18509. }
  18510. }
  18511. else if (this._updatable) {
  18512. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18513. this._data = data;
  18514. }
  18515. };
  18516. Buffer.prototype.update = function (data) {
  18517. this.create(data);
  18518. };
  18519. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18520. if (!this._buffer) {
  18521. return;
  18522. }
  18523. if (this._updatable) {
  18524. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18525. this._data = null;
  18526. }
  18527. };
  18528. Buffer.prototype.dispose = function () {
  18529. if (!this._buffer) {
  18530. return;
  18531. }
  18532. if (this._engine._releaseBuffer(this._buffer)) {
  18533. this._buffer = null;
  18534. }
  18535. };
  18536. return Buffer;
  18537. }());
  18538. BABYLON.Buffer = Buffer;
  18539. })(BABYLON || (BABYLON = {}));
  18540. var BABYLON;
  18541. (function (BABYLON) {
  18542. var VertexBuffer = (function () {
  18543. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18544. if (!stride) {
  18545. // Deduce stride from kind
  18546. switch (kind) {
  18547. case VertexBuffer.PositionKind:
  18548. stride = 3;
  18549. break;
  18550. case VertexBuffer.NormalKind:
  18551. stride = 3;
  18552. break;
  18553. case VertexBuffer.UVKind:
  18554. case VertexBuffer.UV2Kind:
  18555. case VertexBuffer.UV3Kind:
  18556. case VertexBuffer.UV4Kind:
  18557. case VertexBuffer.UV5Kind:
  18558. case VertexBuffer.UV6Kind:
  18559. stride = 2;
  18560. break;
  18561. case VertexBuffer.ColorKind:
  18562. stride = 4;
  18563. break;
  18564. case VertexBuffer.MatricesIndicesKind:
  18565. case VertexBuffer.MatricesIndicesExtraKind:
  18566. stride = 4;
  18567. break;
  18568. case VertexBuffer.MatricesWeightsKind:
  18569. case VertexBuffer.MatricesWeightsExtraKind:
  18570. stride = 4;
  18571. break;
  18572. }
  18573. }
  18574. if (data instanceof BABYLON.Buffer) {
  18575. if (!stride) {
  18576. stride = data.getStrideSize();
  18577. }
  18578. this._buffer = data;
  18579. this._ownsBuffer = false;
  18580. }
  18581. else {
  18582. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18583. this._ownsBuffer = true;
  18584. }
  18585. this._stride = stride;
  18586. this._offset = offset ? offset : 0;
  18587. this._size = size ? size : stride;
  18588. this._kind = kind;
  18589. }
  18590. VertexBuffer.prototype.getKind = function () {
  18591. return this._kind;
  18592. };
  18593. // Properties
  18594. VertexBuffer.prototype.isUpdatable = function () {
  18595. return this._buffer.isUpdatable();
  18596. };
  18597. VertexBuffer.prototype.getData = function () {
  18598. return this._buffer.getData();
  18599. };
  18600. VertexBuffer.prototype.getBuffer = function () {
  18601. return this._buffer.getBuffer();
  18602. };
  18603. VertexBuffer.prototype.getStrideSize = function () {
  18604. return this._stride;
  18605. };
  18606. VertexBuffer.prototype.getOffset = function () {
  18607. return this._offset;
  18608. };
  18609. VertexBuffer.prototype.getSize = function () {
  18610. return this._size;
  18611. };
  18612. VertexBuffer.prototype.getIsInstanced = function () {
  18613. return this._buffer.getIsInstanced();
  18614. };
  18615. // Methods
  18616. VertexBuffer.prototype.create = function (data) {
  18617. return this._buffer.create(data);
  18618. };
  18619. VertexBuffer.prototype.update = function (data) {
  18620. return this._buffer.update(data);
  18621. };
  18622. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18623. return this._buffer.updateDirectly(data, offset);
  18624. };
  18625. VertexBuffer.prototype.dispose = function () {
  18626. if (this._ownsBuffer) {
  18627. this._buffer.dispose();
  18628. }
  18629. };
  18630. Object.defineProperty(VertexBuffer, "PositionKind", {
  18631. get: function () {
  18632. return VertexBuffer._PositionKind;
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. Object.defineProperty(VertexBuffer, "NormalKind", {
  18638. get: function () {
  18639. return VertexBuffer._NormalKind;
  18640. },
  18641. enumerable: true,
  18642. configurable: true
  18643. });
  18644. Object.defineProperty(VertexBuffer, "UVKind", {
  18645. get: function () {
  18646. return VertexBuffer._UVKind;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18652. get: function () {
  18653. return VertexBuffer._UV2Kind;
  18654. },
  18655. enumerable: true,
  18656. configurable: true
  18657. });
  18658. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18659. get: function () {
  18660. return VertexBuffer._UV3Kind;
  18661. },
  18662. enumerable: true,
  18663. configurable: true
  18664. });
  18665. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18666. get: function () {
  18667. return VertexBuffer._UV4Kind;
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18673. get: function () {
  18674. return VertexBuffer._UV5Kind;
  18675. },
  18676. enumerable: true,
  18677. configurable: true
  18678. });
  18679. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18680. get: function () {
  18681. return VertexBuffer._UV6Kind;
  18682. },
  18683. enumerable: true,
  18684. configurable: true
  18685. });
  18686. Object.defineProperty(VertexBuffer, "ColorKind", {
  18687. get: function () {
  18688. return VertexBuffer._ColorKind;
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18694. get: function () {
  18695. return VertexBuffer._MatricesIndicesKind;
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18701. get: function () {
  18702. return VertexBuffer._MatricesWeightsKind;
  18703. },
  18704. enumerable: true,
  18705. configurable: true
  18706. });
  18707. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18708. get: function () {
  18709. return VertexBuffer._MatricesIndicesExtraKind;
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18715. get: function () {
  18716. return VertexBuffer._MatricesWeightsExtraKind;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. // Enums
  18722. VertexBuffer._PositionKind = "position";
  18723. VertexBuffer._NormalKind = "normal";
  18724. VertexBuffer._UVKind = "uv";
  18725. VertexBuffer._UV2Kind = "uv2";
  18726. VertexBuffer._UV3Kind = "uv3";
  18727. VertexBuffer._UV4Kind = "uv4";
  18728. VertexBuffer._UV5Kind = "uv5";
  18729. VertexBuffer._UV6Kind = "uv6";
  18730. VertexBuffer._ColorKind = "color";
  18731. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18732. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18733. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18734. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18735. return VertexBuffer;
  18736. }());
  18737. BABYLON.VertexBuffer = VertexBuffer;
  18738. })(BABYLON || (BABYLON = {}));
  18739. var BABYLON;
  18740. (function (BABYLON) {
  18741. /**
  18742. * Creates an instance based on a source mesh.
  18743. */
  18744. var InstancedMesh = (function (_super) {
  18745. __extends(InstancedMesh, _super);
  18746. function InstancedMesh(name, source) {
  18747. _super.call(this, name, source.getScene());
  18748. source.instances.push(this);
  18749. this._sourceMesh = source;
  18750. this.position.copyFrom(source.position);
  18751. this.rotation.copyFrom(source.rotation);
  18752. this.scaling.copyFrom(source.scaling);
  18753. if (source.rotationQuaternion) {
  18754. this.rotationQuaternion = source.rotationQuaternion.clone();
  18755. }
  18756. this.infiniteDistance = source.infiniteDistance;
  18757. this.setPivotMatrix(source.getPivotMatrix());
  18758. this.refreshBoundingInfo();
  18759. this._syncSubMeshes();
  18760. }
  18761. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18762. // Methods
  18763. get: function () {
  18764. return this._sourceMesh.receiveShadows;
  18765. },
  18766. enumerable: true,
  18767. configurable: true
  18768. });
  18769. Object.defineProperty(InstancedMesh.prototype, "material", {
  18770. get: function () {
  18771. return this._sourceMesh.material;
  18772. },
  18773. enumerable: true,
  18774. configurable: true
  18775. });
  18776. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18777. get: function () {
  18778. return this._sourceMesh.visibility;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18784. get: function () {
  18785. return this._sourceMesh.skeleton;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18791. get: function () {
  18792. return this._sourceMesh.renderingGroupId;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. InstancedMesh.prototype.getTotalVertices = function () {
  18798. return this._sourceMesh.getTotalVertices();
  18799. };
  18800. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18801. get: function () {
  18802. return this._sourceMesh;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18808. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18809. };
  18810. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18811. return this._sourceMesh.isVerticesDataPresent(kind);
  18812. };
  18813. InstancedMesh.prototype.getIndices = function () {
  18814. return this._sourceMesh.getIndices();
  18815. };
  18816. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18817. get: function () {
  18818. return this._sourceMesh._positions;
  18819. },
  18820. enumerable: true,
  18821. configurable: true
  18822. });
  18823. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18824. var meshBB = this._sourceMesh.getBoundingInfo();
  18825. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18826. this._updateBoundingInfo();
  18827. };
  18828. InstancedMesh.prototype._preActivate = function () {
  18829. if (this._currentLOD) {
  18830. this._currentLOD._preActivate();
  18831. }
  18832. };
  18833. InstancedMesh.prototype._activate = function (renderId) {
  18834. if (this._currentLOD) {
  18835. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18836. }
  18837. };
  18838. InstancedMesh.prototype.getLOD = function (camera) {
  18839. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18840. if (this._currentLOD === this.sourceMesh) {
  18841. return this;
  18842. }
  18843. return this._currentLOD;
  18844. };
  18845. InstancedMesh.prototype._syncSubMeshes = function () {
  18846. this.releaseSubMeshes();
  18847. if (this._sourceMesh.subMeshes) {
  18848. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18849. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18850. }
  18851. }
  18852. };
  18853. InstancedMesh.prototype._generatePointsArray = function () {
  18854. return this._sourceMesh._generatePointsArray();
  18855. };
  18856. // Clone
  18857. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18858. var result = this._sourceMesh.createInstance(name);
  18859. // Deep copy
  18860. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18861. // Bounding info
  18862. this.refreshBoundingInfo();
  18863. // Parent
  18864. if (newParent) {
  18865. result.parent = newParent;
  18866. }
  18867. if (!doNotCloneChildren) {
  18868. // Children
  18869. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18870. var mesh = this.getScene().meshes[index];
  18871. if (mesh.parent === this) {
  18872. mesh.clone(mesh.name, result);
  18873. }
  18874. }
  18875. }
  18876. result.computeWorldMatrix(true);
  18877. return result;
  18878. };
  18879. // Dispoe
  18880. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18881. // Remove from mesh
  18882. var index = this._sourceMesh.instances.indexOf(this);
  18883. this._sourceMesh.instances.splice(index, 1);
  18884. _super.prototype.dispose.call(this, doNotRecurse);
  18885. };
  18886. return InstancedMesh;
  18887. }(BABYLON.AbstractMesh));
  18888. BABYLON.InstancedMesh = InstancedMesh;
  18889. })(BABYLON || (BABYLON = {}));
  18890. var BABYLON;
  18891. (function (BABYLON) {
  18892. var _InstancesBatch = (function () {
  18893. function _InstancesBatch() {
  18894. this.mustReturn = false;
  18895. this.visibleInstances = new Array();
  18896. this.renderSelf = new Array();
  18897. }
  18898. return _InstancesBatch;
  18899. }());
  18900. BABYLON._InstancesBatch = _InstancesBatch;
  18901. var Mesh = (function (_super) {
  18902. __extends(Mesh, _super);
  18903. /**
  18904. * @constructor
  18905. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18906. * @param {Scene} scene The scene to add this mesh to.
  18907. * @param {Node} parent The parent of this mesh, if it has one
  18908. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18909. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18910. * When false, achieved by calling a clone(), also passing False.
  18911. * This will make creation of children, recursive.
  18912. */
  18913. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18914. if (parent === void 0) { parent = null; }
  18915. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18916. _super.call(this, name, scene);
  18917. // Events
  18918. /**
  18919. * An event triggered before rendering the mesh
  18920. * @type {BABYLON.Observable}
  18921. */
  18922. this.onBeforeRenderObservable = new BABYLON.Observable();
  18923. /**
  18924. * An event triggered after rendering the mesh
  18925. * @type {BABYLON.Observable}
  18926. */
  18927. this.onAfterRenderObservable = new BABYLON.Observable();
  18928. /**
  18929. * An event triggered before drawing the mesh
  18930. * @type {BABYLON.Observable}
  18931. */
  18932. this.onBeforeDrawObservable = new BABYLON.Observable();
  18933. // Members
  18934. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18935. this.instances = new Array();
  18936. this._LODLevels = new Array();
  18937. this._visibleInstances = {};
  18938. this._renderIdForInstances = new Array();
  18939. this._batchCache = new _InstancesBatch();
  18940. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18941. this._sideOrientation = Mesh._DEFAULTSIDE;
  18942. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18943. if (source) {
  18944. // Geometry
  18945. if (source._geometry) {
  18946. source._geometry.applyToMesh(this);
  18947. }
  18948. // Deep copy
  18949. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18950. // Pivot
  18951. this.setPivotMatrix(source.getPivotMatrix());
  18952. this.id = name + "." + source.id;
  18953. // Material
  18954. this.material = source.material;
  18955. var index;
  18956. if (!doNotCloneChildren) {
  18957. // Children
  18958. for (index = 0; index < scene.meshes.length; index++) {
  18959. var mesh = scene.meshes[index];
  18960. if (mesh.parent === source) {
  18961. // doNotCloneChildren is always going to be False
  18962. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18963. }
  18964. }
  18965. }
  18966. // Physics clone
  18967. var physicsEngine = this.getScene().getPhysicsEngine();
  18968. if (clonePhysicsImpostor && physicsEngine) {
  18969. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18970. if (impostor) {
  18971. this.physicsImpostor = impostor.clone(this);
  18972. }
  18973. }
  18974. // Particles
  18975. for (index = 0; index < scene.particleSystems.length; index++) {
  18976. var system = scene.particleSystems[index];
  18977. if (system.emitter === source) {
  18978. system.clone(system.name, this);
  18979. }
  18980. }
  18981. this.computeWorldMatrix(true);
  18982. }
  18983. // Parent
  18984. if (parent !== null) {
  18985. this.parent = parent;
  18986. }
  18987. }
  18988. Object.defineProperty(Mesh, "FRONTSIDE", {
  18989. /**
  18990. * Mesh side orientation : usually the external or front surface
  18991. */
  18992. get: function () {
  18993. return Mesh._FRONTSIDE;
  18994. },
  18995. enumerable: true,
  18996. configurable: true
  18997. });
  18998. Object.defineProperty(Mesh, "BACKSIDE", {
  18999. /**
  19000. * Mesh side orientation : usually the internal or back surface
  19001. */
  19002. get: function () {
  19003. return Mesh._BACKSIDE;
  19004. },
  19005. enumerable: true,
  19006. configurable: true
  19007. });
  19008. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19009. /**
  19010. * Mesh side orientation : both internal and external or front and back surfaces
  19011. */
  19012. get: function () {
  19013. return Mesh._DOUBLESIDE;
  19014. },
  19015. enumerable: true,
  19016. configurable: true
  19017. });
  19018. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19019. /**
  19020. * Mesh side orientation : by default, `FRONTSIDE`
  19021. */
  19022. get: function () {
  19023. return Mesh._DEFAULTSIDE;
  19024. },
  19025. enumerable: true,
  19026. configurable: true
  19027. });
  19028. Object.defineProperty(Mesh, "NO_CAP", {
  19029. /**
  19030. * Mesh cap setting : no cap
  19031. */
  19032. get: function () {
  19033. return Mesh._NO_CAP;
  19034. },
  19035. enumerable: true,
  19036. configurable: true
  19037. });
  19038. Object.defineProperty(Mesh, "CAP_START", {
  19039. /**
  19040. * Mesh cap setting : one cap at the beginning of the mesh
  19041. */
  19042. get: function () {
  19043. return Mesh._CAP_START;
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. Object.defineProperty(Mesh, "CAP_END", {
  19049. /**
  19050. * Mesh cap setting : one cap at the end of the mesh
  19051. */
  19052. get: function () {
  19053. return Mesh._CAP_END;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. Object.defineProperty(Mesh, "CAP_ALL", {
  19059. /**
  19060. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19061. */
  19062. get: function () {
  19063. return Mesh._CAP_ALL;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19069. set: function (callback) {
  19070. if (this._onBeforeDrawObserver) {
  19071. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19072. }
  19073. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. // Methods
  19079. /**
  19080. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19081. */
  19082. Mesh.prototype.toString = function (fullDetails) {
  19083. var ret = _super.prototype.toString.call(this, fullDetails);
  19084. ret += ", n vertices: " + this.getTotalVertices();
  19085. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19086. if (this.animations) {
  19087. for (var i = 0; i < this.animations.length; i++) {
  19088. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19089. }
  19090. }
  19091. if (fullDetails) {
  19092. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19093. }
  19094. return ret;
  19095. };
  19096. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19097. get: function () {
  19098. return this._LODLevels.length > 0;
  19099. },
  19100. enumerable: true,
  19101. configurable: true
  19102. });
  19103. Mesh.prototype._sortLODLevels = function () {
  19104. this._LODLevels.sort(function (a, b) {
  19105. if (a.distance < b.distance) {
  19106. return 1;
  19107. }
  19108. if (a.distance > b.distance) {
  19109. return -1;
  19110. }
  19111. return 0;
  19112. });
  19113. };
  19114. /**
  19115. * Add a mesh as LOD level triggered at the given distance.
  19116. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19117. * @param {number} distance The distance from the center of the object to show this level
  19118. * @param {Mesh} mesh The mesh to be added as LOD level
  19119. * @return {Mesh} This mesh (for chaining)
  19120. */
  19121. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19122. if (mesh && mesh._masterMesh) {
  19123. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19124. return this;
  19125. }
  19126. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19127. this._LODLevels.push(level);
  19128. if (mesh) {
  19129. mesh._masterMesh = this;
  19130. }
  19131. this._sortLODLevels();
  19132. return this;
  19133. };
  19134. /**
  19135. * Returns the LOD level mesh at the passed distance or null if not found.
  19136. * It is related to the method `addLODLevel(distance, mesh)`.
  19137. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19138. */
  19139. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19140. for (var index = 0; index < this._LODLevels.length; index++) {
  19141. var level = this._LODLevels[index];
  19142. if (level.distance === distance) {
  19143. return level.mesh;
  19144. }
  19145. }
  19146. return null;
  19147. };
  19148. /**
  19149. * Remove a mesh from the LOD array
  19150. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19151. * @param {Mesh} mesh The mesh to be removed.
  19152. * @return {Mesh} This mesh (for chaining)
  19153. */
  19154. Mesh.prototype.removeLODLevel = function (mesh) {
  19155. for (var index = 0; index < this._LODLevels.length; index++) {
  19156. if (this._LODLevels[index].mesh === mesh) {
  19157. this._LODLevels.splice(index, 1);
  19158. if (mesh) {
  19159. mesh._masterMesh = null;
  19160. }
  19161. }
  19162. }
  19163. this._sortLODLevels();
  19164. return this;
  19165. };
  19166. /**
  19167. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19168. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19169. */
  19170. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19171. if (!this._LODLevels || this._LODLevels.length === 0) {
  19172. return this;
  19173. }
  19174. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19175. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19176. if (this.onLODLevelSelection) {
  19177. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19178. }
  19179. return this;
  19180. }
  19181. for (var index = 0; index < this._LODLevels.length; index++) {
  19182. var level = this._LODLevels[index];
  19183. if (level.distance < distanceToCamera) {
  19184. if (level.mesh) {
  19185. level.mesh._preActivate();
  19186. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19187. }
  19188. if (this.onLODLevelSelection) {
  19189. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19190. }
  19191. return level.mesh;
  19192. }
  19193. }
  19194. if (this.onLODLevelSelection) {
  19195. this.onLODLevelSelection(distanceToCamera, this, this);
  19196. }
  19197. return this;
  19198. };
  19199. Object.defineProperty(Mesh.prototype, "geometry", {
  19200. /**
  19201. * Returns the mesh internal Geometry object.
  19202. */
  19203. get: function () {
  19204. return this._geometry;
  19205. },
  19206. enumerable: true,
  19207. configurable: true
  19208. });
  19209. /**
  19210. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19211. */
  19212. Mesh.prototype.getTotalVertices = function () {
  19213. if (!this._geometry) {
  19214. return 0;
  19215. }
  19216. return this._geometry.getTotalVertices();
  19217. };
  19218. /**
  19219. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19220. * 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.
  19221. * Returns null if the mesh has no geometry or no vertex buffer.
  19222. * Possible `kind` values :
  19223. * - BABYLON.VertexBuffer.PositionKind
  19224. * - BABYLON.VertexBuffer.UVKind
  19225. * - BABYLON.VertexBuffer.UV2Kind
  19226. * - BABYLON.VertexBuffer.UV3Kind
  19227. * - BABYLON.VertexBuffer.UV4Kind
  19228. * - BABYLON.VertexBuffer.UV5Kind
  19229. * - BABYLON.VertexBuffer.UV6Kind
  19230. * - BABYLON.VertexBuffer.ColorKind
  19231. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19232. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19233. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19234. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19235. */
  19236. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19237. if (!this._geometry) {
  19238. return null;
  19239. }
  19240. return this._geometry.getVerticesData(kind, copyWhenShared);
  19241. };
  19242. /**
  19243. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19244. * Returns `undefined` if the mesh has no geometry.
  19245. * Possible `kind` values :
  19246. * - BABYLON.VertexBuffer.PositionKind
  19247. * - BABYLON.VertexBuffer.UVKind
  19248. * - BABYLON.VertexBuffer.UV2Kind
  19249. * - BABYLON.VertexBuffer.UV3Kind
  19250. * - BABYLON.VertexBuffer.UV4Kind
  19251. * - BABYLON.VertexBuffer.UV5Kind
  19252. * - BABYLON.VertexBuffer.UV6Kind
  19253. * - BABYLON.VertexBuffer.ColorKind
  19254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19258. */
  19259. Mesh.prototype.getVertexBuffer = function (kind) {
  19260. if (!this._geometry) {
  19261. return undefined;
  19262. }
  19263. return this._geometry.getVertexBuffer(kind);
  19264. };
  19265. /**
  19266. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19267. * Possible `kind` values :
  19268. * - BABYLON.VertexBuffer.PositionKind
  19269. * - BABYLON.VertexBuffer.UVKind
  19270. * - BABYLON.VertexBuffer.UV2Kind
  19271. * - BABYLON.VertexBuffer.UV3Kind
  19272. * - BABYLON.VertexBuffer.UV4Kind
  19273. * - BABYLON.VertexBuffer.UV5Kind
  19274. * - BABYLON.VertexBuffer.UV6Kind
  19275. * - BABYLON.VertexBuffer.ColorKind
  19276. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19277. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19278. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19279. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19280. */
  19281. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19282. if (!this._geometry) {
  19283. if (this._delayInfo) {
  19284. return this._delayInfo.indexOf(kind) !== -1;
  19285. }
  19286. return false;
  19287. }
  19288. return this._geometry.isVerticesDataPresent(kind);
  19289. };
  19290. /**
  19291. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19292. * Possible `kind` values :
  19293. * - BABYLON.VertexBuffer.PositionKind
  19294. * - BABYLON.VertexBuffer.UVKind
  19295. * - BABYLON.VertexBuffer.UV2Kind
  19296. * - BABYLON.VertexBuffer.UV3Kind
  19297. * - BABYLON.VertexBuffer.UV4Kind
  19298. * - BABYLON.VertexBuffer.UV5Kind
  19299. * - BABYLON.VertexBuffer.UV6Kind
  19300. * - BABYLON.VertexBuffer.ColorKind
  19301. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19302. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19303. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19304. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19305. */
  19306. Mesh.prototype.getVerticesDataKinds = function () {
  19307. if (!this._geometry) {
  19308. var result = [];
  19309. if (this._delayInfo) {
  19310. for (var kind in this._delayInfo) {
  19311. result.push(kind);
  19312. }
  19313. }
  19314. return result;
  19315. }
  19316. return this._geometry.getVerticesDataKinds();
  19317. };
  19318. /**
  19319. * Returns a positive integer : the total number of indices in this mesh geometry.
  19320. * Returns zero if the mesh has no geometry.
  19321. */
  19322. Mesh.prototype.getTotalIndices = function () {
  19323. if (!this._geometry) {
  19324. return 0;
  19325. }
  19326. return this._geometry.getTotalIndices();
  19327. };
  19328. /**
  19329. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19330. * 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.
  19331. * Returns an empty array if the mesh has no geometry.
  19332. */
  19333. Mesh.prototype.getIndices = function (copyWhenShared) {
  19334. if (!this._geometry) {
  19335. return [];
  19336. }
  19337. return this._geometry.getIndices(copyWhenShared);
  19338. };
  19339. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19340. get: function () {
  19341. return this._masterMesh !== null && this._masterMesh !== undefined;
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. /**
  19347. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19348. */
  19349. Mesh.prototype.isReady = function () {
  19350. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19351. return false;
  19352. }
  19353. return _super.prototype.isReady.call(this);
  19354. };
  19355. /**
  19356. * Boolean : true if the mesh has been disposed.
  19357. */
  19358. Mesh.prototype.isDisposed = function () {
  19359. return this._isDisposed;
  19360. };
  19361. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19362. get: function () {
  19363. return this._sideOrientation;
  19364. },
  19365. /**
  19366. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19367. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19368. */
  19369. set: function (sideO) {
  19370. this._sideOrientation = sideO;
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19376. /**
  19377. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19378. * This property is pertinent only for updatable parametric shapes.
  19379. */
  19380. get: function () {
  19381. return this._areNormalsFrozen;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. /**
  19387. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19388. * It has no effect at all on other shapes.
  19389. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19390. */
  19391. Mesh.prototype.freezeNormals = function () {
  19392. this._areNormalsFrozen = true;
  19393. };
  19394. /**
  19395. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19396. * It has no effect at all on other shapes.
  19397. * It reactivates the mesh normals computation if it was previously frozen.
  19398. */
  19399. Mesh.prototype.unfreezeNormals = function () {
  19400. this._areNormalsFrozen = false;
  19401. };
  19402. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19403. /**
  19404. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19405. */
  19406. set: function (count) {
  19407. this._overridenInstanceCount = count;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. // Methods
  19413. Mesh.prototype._preActivate = function () {
  19414. var sceneRenderId = this.getScene().getRenderId();
  19415. if (this._preActivateId === sceneRenderId) {
  19416. return;
  19417. }
  19418. this._preActivateId = sceneRenderId;
  19419. this._visibleInstances = null;
  19420. };
  19421. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19422. if (this._visibleInstances) {
  19423. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19424. }
  19425. };
  19426. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19427. if (!this._visibleInstances) {
  19428. this._visibleInstances = {};
  19429. this._visibleInstances.defaultRenderId = renderId;
  19430. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19431. }
  19432. if (!this._visibleInstances[renderId]) {
  19433. this._visibleInstances[renderId] = new Array();
  19434. }
  19435. this._visibleInstances[renderId].push(instance);
  19436. };
  19437. /**
  19438. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19439. * This means the mesh underlying bounding box and sphere are recomputed.
  19440. */
  19441. Mesh.prototype.refreshBoundingInfo = function () {
  19442. if (this._boundingInfo.isLocked) {
  19443. return;
  19444. }
  19445. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19446. if (data) {
  19447. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19448. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19449. }
  19450. if (this.subMeshes) {
  19451. for (var index = 0; index < this.subMeshes.length; index++) {
  19452. this.subMeshes[index].refreshBoundingInfo();
  19453. }
  19454. }
  19455. this._updateBoundingInfo();
  19456. };
  19457. Mesh.prototype._createGlobalSubMesh = function () {
  19458. var totalVertices = this.getTotalVertices();
  19459. if (!totalVertices || !this.getIndices()) {
  19460. return null;
  19461. }
  19462. this.releaseSubMeshes();
  19463. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19464. };
  19465. Mesh.prototype.subdivide = function (count) {
  19466. if (count < 1) {
  19467. return;
  19468. }
  19469. var totalIndices = this.getTotalIndices();
  19470. var subdivisionSize = (totalIndices / count) | 0;
  19471. var offset = 0;
  19472. // Ensure that subdivisionSize is a multiple of 3
  19473. while (subdivisionSize % 3 !== 0) {
  19474. subdivisionSize++;
  19475. }
  19476. this.releaseSubMeshes();
  19477. for (var index = 0; index < count; index++) {
  19478. if (offset >= totalIndices) {
  19479. break;
  19480. }
  19481. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19482. offset += subdivisionSize;
  19483. }
  19484. this.synchronizeInstances();
  19485. };
  19486. /**
  19487. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19488. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19489. * The `data` are either a numeric array either a Float32Array.
  19490. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19491. * 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).
  19492. * Note that a new underlying VertexBuffer object is created each call.
  19493. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19494. *
  19495. * Possible `kind` values :
  19496. * - BABYLON.VertexBuffer.PositionKind
  19497. * - BABYLON.VertexBuffer.UVKind
  19498. * - BABYLON.VertexBuffer.UV2Kind
  19499. * - BABYLON.VertexBuffer.UV3Kind
  19500. * - BABYLON.VertexBuffer.UV4Kind
  19501. * - BABYLON.VertexBuffer.UV5Kind
  19502. * - BABYLON.VertexBuffer.UV6Kind
  19503. * - BABYLON.VertexBuffer.ColorKind
  19504. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19505. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19506. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19507. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19508. */
  19509. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19510. if (!this._geometry) {
  19511. var vertexData = new BABYLON.VertexData();
  19512. vertexData.set(data, kind);
  19513. var scene = this.getScene();
  19514. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19515. }
  19516. else {
  19517. this._geometry.setVerticesData(kind, data, updatable, stride);
  19518. }
  19519. };
  19520. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19521. if (!this._geometry) {
  19522. var scene = this.getScene();
  19523. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19524. }
  19525. this._geometry.setVerticesBuffer(buffer);
  19526. };
  19527. /**
  19528. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19529. * If the mesh has no geometry, it is simply returned as it is.
  19530. * The `data` are either a numeric array either a Float32Array.
  19531. * No new underlying VertexBuffer object is created.
  19532. * 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.
  19533. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19534. *
  19535. * Possible `kind` values :
  19536. * - BABYLON.VertexBuffer.PositionKind
  19537. * - BABYLON.VertexBuffer.UVKind
  19538. * - BABYLON.VertexBuffer.UV2Kind
  19539. * - BABYLON.VertexBuffer.UV3Kind
  19540. * - BABYLON.VertexBuffer.UV4Kind
  19541. * - BABYLON.VertexBuffer.UV5Kind
  19542. * - BABYLON.VertexBuffer.UV6Kind
  19543. * - BABYLON.VertexBuffer.ColorKind
  19544. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19545. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19546. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19547. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19548. */
  19549. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19550. if (!this._geometry) {
  19551. return;
  19552. }
  19553. if (!makeItUnique) {
  19554. this._geometry.updateVerticesData(kind, data, updateExtends);
  19555. }
  19556. else {
  19557. this.makeGeometryUnique();
  19558. this.updateVerticesData(kind, data, updateExtends, false);
  19559. }
  19560. };
  19561. /**
  19562. * Deprecated since BabylonJS v2.3
  19563. */
  19564. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19565. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19566. if (!this._geometry) {
  19567. return;
  19568. }
  19569. if (!makeItUnique) {
  19570. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19571. }
  19572. else {
  19573. this.makeGeometryUnique();
  19574. this.updateVerticesDataDirectly(kind, data, offset, false);
  19575. }
  19576. };
  19577. /**
  19578. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19579. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19580. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19581. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19582. */
  19583. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19584. if (computeNormals === void 0) { computeNormals = true; }
  19585. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19586. positionFunction(positions);
  19587. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19588. if (computeNormals) {
  19589. var indices = this.getIndices();
  19590. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19591. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19592. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19593. }
  19594. };
  19595. Mesh.prototype.makeGeometryUnique = function () {
  19596. if (!this._geometry) {
  19597. return;
  19598. }
  19599. var oldGeometry = this._geometry;
  19600. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19601. oldGeometry.releaseForMesh(this, true);
  19602. geometry.applyToMesh(this);
  19603. };
  19604. /**
  19605. * Sets the mesh indices.
  19606. * Expects an array populated with integers or a Int32Array.
  19607. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19608. * This method creates a new index buffer each call.
  19609. */
  19610. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19611. if (!this._geometry) {
  19612. var vertexData = new BABYLON.VertexData();
  19613. vertexData.indices = indices;
  19614. var scene = this.getScene();
  19615. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19616. }
  19617. else {
  19618. this._geometry.setIndices(indices, totalVertices);
  19619. }
  19620. };
  19621. /**
  19622. * Invert the geometry to move from a right handed system to a left handed one.
  19623. */
  19624. Mesh.prototype.toLeftHanded = function () {
  19625. if (!this._geometry) {
  19626. return;
  19627. }
  19628. this._geometry.toLeftHanded();
  19629. };
  19630. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19631. var engine = this.getScene().getEngine();
  19632. // Wireframe
  19633. var indexToBind;
  19634. if (this._unIndexed) {
  19635. indexToBind = null;
  19636. }
  19637. else {
  19638. switch (fillMode) {
  19639. case BABYLON.Material.PointFillMode:
  19640. indexToBind = null;
  19641. break;
  19642. case BABYLON.Material.WireFrameFillMode:
  19643. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19644. break;
  19645. default:
  19646. case BABYLON.Material.TriangleFillMode:
  19647. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19648. break;
  19649. }
  19650. }
  19651. // VBOs
  19652. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19653. };
  19654. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19655. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19656. return;
  19657. }
  19658. this.onBeforeDrawObservable.notifyObservers(this);
  19659. var engine = this.getScene().getEngine();
  19660. // Draw order
  19661. switch (fillMode) {
  19662. case BABYLON.Material.PointFillMode:
  19663. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19664. break;
  19665. case BABYLON.Material.WireFrameFillMode:
  19666. if (this._unIndexed) {
  19667. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19668. }
  19669. else {
  19670. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19671. }
  19672. break;
  19673. default:
  19674. if (this._unIndexed) {
  19675. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19676. }
  19677. else {
  19678. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19679. }
  19680. }
  19681. };
  19682. /**
  19683. * Registers for this mesh a javascript function called just before the rendering process.
  19684. * This function is passed the current mesh and doesn't return anything.
  19685. */
  19686. Mesh.prototype.registerBeforeRender = function (func) {
  19687. this.onBeforeRenderObservable.add(func);
  19688. };
  19689. /**
  19690. * Disposes a previously registered javascript function called before the rendering.
  19691. * This function is passed the current mesh and doesn't return anything.
  19692. */
  19693. Mesh.prototype.unregisterBeforeRender = function (func) {
  19694. this.onBeforeRenderObservable.removeCallback(func);
  19695. };
  19696. /**
  19697. * Registers for this mesh a javascript function called just after the rendering is complete.
  19698. * This function is passed the current mesh and doesn't return anything.
  19699. */
  19700. Mesh.prototype.registerAfterRender = function (func) {
  19701. this.onAfterRenderObservable.add(func);
  19702. };
  19703. /**
  19704. * Disposes a previously registered javascript function called after the rendering.
  19705. * This function is passed the current mesh and doesn't return anything.
  19706. */
  19707. Mesh.prototype.unregisterAfterRender = function (func) {
  19708. this.onAfterRenderObservable.removeCallback(func);
  19709. };
  19710. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19711. var scene = this.getScene();
  19712. this._batchCache.mustReturn = false;
  19713. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19714. this._batchCache.visibleInstances[subMeshId] = null;
  19715. if (this._visibleInstances) {
  19716. var currentRenderId = scene.getRenderId();
  19717. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19718. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19719. var selfRenderId = this._renderId;
  19720. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19721. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19722. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19723. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19724. }
  19725. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19726. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19727. this._batchCache.mustReturn = true;
  19728. return this._batchCache;
  19729. }
  19730. if (currentRenderId !== selfRenderId) {
  19731. this._batchCache.renderSelf[subMeshId] = false;
  19732. }
  19733. }
  19734. this._renderIdForInstances[subMeshId] = currentRenderId;
  19735. }
  19736. return this._batchCache;
  19737. };
  19738. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19739. var visibleInstances = batch.visibleInstances[subMesh._id];
  19740. var matricesCount = visibleInstances.length + 1;
  19741. var bufferSize = matricesCount * 16 * 4;
  19742. var currentInstancesBufferSize = this._instancesBufferSize;
  19743. var instancesBuffer = this._instancesBuffer;
  19744. while (this._instancesBufferSize < bufferSize) {
  19745. this._instancesBufferSize *= 2;
  19746. }
  19747. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19748. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19749. }
  19750. var offset = 0;
  19751. var instancesCount = 0;
  19752. var world = this.getWorldMatrix();
  19753. if (batch.renderSelf[subMesh._id]) {
  19754. world.copyToArray(this._instancesData, offset);
  19755. offset += 16;
  19756. instancesCount++;
  19757. }
  19758. if (visibleInstances) {
  19759. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19760. var instance = visibleInstances[instanceIndex];
  19761. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19762. offset += 16;
  19763. instancesCount++;
  19764. }
  19765. }
  19766. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19767. if (instancesBuffer) {
  19768. instancesBuffer.dispose();
  19769. }
  19770. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19771. this._instancesBuffer = instancesBuffer;
  19772. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19773. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19774. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19775. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19776. }
  19777. else {
  19778. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19779. }
  19780. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19781. this._draw(subMesh, fillMode, instancesCount);
  19782. engine.unbindInstanceAttributes();
  19783. };
  19784. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19785. var scene = this.getScene();
  19786. var engine = scene.getEngine();
  19787. if (hardwareInstancedRendering) {
  19788. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19789. }
  19790. else {
  19791. if (batch.renderSelf[subMesh._id]) {
  19792. // Draw
  19793. if (onBeforeDraw) {
  19794. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19795. }
  19796. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19797. }
  19798. if (batch.visibleInstances[subMesh._id]) {
  19799. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19800. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19801. // World
  19802. var world = instance.getWorldMatrix();
  19803. if (onBeforeDraw) {
  19804. onBeforeDraw(true, world, effectiveMaterial);
  19805. }
  19806. // Draw
  19807. this._draw(subMesh, fillMode);
  19808. }
  19809. }
  19810. }
  19811. };
  19812. /**
  19813. * Triggers the draw call for the mesh.
  19814. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19815. */
  19816. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19817. var scene = this.getScene();
  19818. // Managing instances
  19819. var batch = this._getInstancesRenderList(subMesh._id);
  19820. if (batch.mustReturn) {
  19821. return;
  19822. }
  19823. // Checking geometry state
  19824. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19825. return;
  19826. }
  19827. var callbackIndex;
  19828. this.onBeforeRenderObservable.notifyObservers(this);
  19829. var engine = scene.getEngine();
  19830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19831. // Material
  19832. var effectiveMaterial = subMesh.getMaterial();
  19833. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19834. return;
  19835. }
  19836. // Outline - step 1
  19837. var savedDepthWrite = engine.getDepthWrite();
  19838. if (this.renderOutline) {
  19839. engine.setDepthWrite(false);
  19840. scene.getOutlineRenderer().render(subMesh, batch);
  19841. engine.setDepthWrite(savedDepthWrite);
  19842. }
  19843. effectiveMaterial._preBind();
  19844. var effect = effectiveMaterial.getEffect();
  19845. // Bind
  19846. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19847. this._bind(subMesh, effect, fillMode);
  19848. var world = this.getWorldMatrix();
  19849. effectiveMaterial.bind(world, this);
  19850. // Alpha mode
  19851. if (enableAlphaMode) {
  19852. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19853. }
  19854. // Draw
  19855. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19856. // Unbind
  19857. effectiveMaterial.unbind();
  19858. // Outline - step 2
  19859. if (this.renderOutline && savedDepthWrite) {
  19860. engine.setDepthWrite(true);
  19861. engine.setColorWrite(false);
  19862. scene.getOutlineRenderer().render(subMesh, batch);
  19863. engine.setColorWrite(true);
  19864. }
  19865. // Overlay
  19866. if (this.renderOverlay) {
  19867. var currentMode = engine.getAlphaMode();
  19868. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19869. scene.getOutlineRenderer().render(subMesh, batch, true);
  19870. engine.setAlphaMode(currentMode);
  19871. }
  19872. this.onAfterRenderObservable.notifyObservers(this);
  19873. };
  19874. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19875. if (isInstance) {
  19876. effectiveMaterial.bindOnlyWorldMatrix(world);
  19877. }
  19878. };
  19879. /**
  19880. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19881. */
  19882. Mesh.prototype.getEmittedParticleSystems = function () {
  19883. var results = new Array();
  19884. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19885. var particleSystem = this.getScene().particleSystems[index];
  19886. if (particleSystem.emitter === this) {
  19887. results.push(particleSystem);
  19888. }
  19889. }
  19890. return results;
  19891. };
  19892. /**
  19893. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19894. */
  19895. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19896. var results = new Array();
  19897. var descendants = this.getDescendants();
  19898. descendants.push(this);
  19899. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19900. var particleSystem = this.getScene().particleSystems[index];
  19901. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19902. results.push(particleSystem);
  19903. }
  19904. }
  19905. return results;
  19906. };
  19907. Mesh.prototype._checkDelayState = function () {
  19908. var scene = this.getScene();
  19909. if (this._geometry) {
  19910. this._geometry.load(scene);
  19911. }
  19912. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19914. this._queueLoad(this, scene);
  19915. }
  19916. };
  19917. Mesh.prototype._queueLoad = function (mesh, scene) {
  19918. var _this = this;
  19919. scene._addPendingData(mesh);
  19920. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19921. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19922. if (data instanceof ArrayBuffer) {
  19923. _this._delayLoadingFunction(data, _this);
  19924. }
  19925. else {
  19926. _this._delayLoadingFunction(JSON.parse(data), _this);
  19927. }
  19928. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19929. scene._removePendingData(_this);
  19930. }, function () { }, scene.database, getBinaryData);
  19931. };
  19932. /**
  19933. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19934. */
  19935. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19936. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19937. return false;
  19938. }
  19939. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19940. return false;
  19941. }
  19942. this._checkDelayState();
  19943. return true;
  19944. };
  19945. /**
  19946. * Sets the mesh material by the material or multiMaterial `id` property.
  19947. * The material `id` is a string identifying the material or the multiMaterial.
  19948. * This method returns nothing.
  19949. */
  19950. Mesh.prototype.setMaterialByID = function (id) {
  19951. var materials = this.getScene().materials;
  19952. var index;
  19953. for (index = 0; index < materials.length; index++) {
  19954. if (materials[index].id === id) {
  19955. this.material = materials[index];
  19956. return;
  19957. }
  19958. }
  19959. // Multi
  19960. var multiMaterials = this.getScene().multiMaterials;
  19961. for (index = 0; index < multiMaterials.length; index++) {
  19962. if (multiMaterials[index].id === id) {
  19963. this.material = multiMaterials[index];
  19964. return;
  19965. }
  19966. }
  19967. };
  19968. /**
  19969. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19970. */
  19971. Mesh.prototype.getAnimatables = function () {
  19972. var results = [];
  19973. if (this.material) {
  19974. results.push(this.material);
  19975. }
  19976. if (this.skeleton) {
  19977. results.push(this.skeleton);
  19978. }
  19979. return results;
  19980. };
  19981. /**
  19982. * Modifies the mesh geometry according to the passed transformation matrix.
  19983. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19984. * The mesh normals are modified accordingly the same transformation.
  19985. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19986. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19987. */
  19988. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19989. // Position
  19990. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19991. return;
  19992. }
  19993. var submeshes = this.subMeshes.splice(0);
  19994. this._resetPointsArrayCache();
  19995. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19996. var temp = [];
  19997. var index;
  19998. for (index = 0; index < data.length; index += 3) {
  19999. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20000. }
  20001. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20002. // Normals
  20003. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20004. return;
  20005. }
  20006. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20007. temp = [];
  20008. for (index = 0; index < data.length; index += 3) {
  20009. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20010. }
  20011. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20012. // flip faces?
  20013. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20014. this.flipFaces();
  20015. }
  20016. // Restore submeshes
  20017. this.releaseSubMeshes();
  20018. this.subMeshes = submeshes;
  20019. };
  20020. /**
  20021. * Modifies the mesh geometry according to its own current World Matrix.
  20022. * The mesh World Matrix is then reset.
  20023. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20024. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20025. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20026. */
  20027. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20028. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20029. this.scaling.copyFromFloats(1, 1, 1);
  20030. this.position.copyFromFloats(0, 0, 0);
  20031. this.rotation.copyFromFloats(0, 0, 0);
  20032. //only if quaternion is already set
  20033. if (this.rotationQuaternion) {
  20034. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20035. }
  20036. this._worldMatrix = BABYLON.Matrix.Identity();
  20037. };
  20038. // Cache
  20039. Mesh.prototype._resetPointsArrayCache = function () {
  20040. this._positions = null;
  20041. };
  20042. Mesh.prototype._generatePointsArray = function () {
  20043. if (this._positions)
  20044. return true;
  20045. this._positions = [];
  20046. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20047. if (!data) {
  20048. return false;
  20049. }
  20050. for (var index = 0; index < data.length; index += 3) {
  20051. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20052. }
  20053. return true;
  20054. };
  20055. /**
  20056. * Returns a new Mesh object generated from the current mesh properties.
  20057. * This method must not get confused with createInstance().
  20058. * The parameter `name` is a string, the name given to the new mesh.
  20059. * The optional parameter `newParent` can be any Node object (default `null`).
  20060. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20061. * 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.
  20062. */
  20063. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20064. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20065. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20066. };
  20067. /**
  20068. * Disposes the mesh.
  20069. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20070. */
  20071. Mesh.prototype.dispose = function (doNotRecurse) {
  20072. if (this._geometry) {
  20073. this._geometry.releaseForMesh(this, true);
  20074. }
  20075. // Instances
  20076. if (this._instancesBuffer) {
  20077. this._instancesBuffer.dispose();
  20078. this._instancesBuffer = null;
  20079. }
  20080. while (this.instances.length) {
  20081. this.instances[0].dispose();
  20082. }
  20083. // Highlight layers.
  20084. var highlightLayers = this.getScene().highlightLayers;
  20085. for (var i = 0; i < highlightLayers.length; i++) {
  20086. var highlightLayer = highlightLayers[i];
  20087. if (highlightLayer) {
  20088. highlightLayer.removeMesh(this);
  20089. }
  20090. }
  20091. _super.prototype.dispose.call(this, doNotRecurse);
  20092. };
  20093. /**
  20094. * Modifies the mesh geometry according to a displacement map.
  20095. * 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.
  20096. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20097. * This method returns nothing.
  20098. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20099. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20100. * 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.
  20101. */
  20102. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20103. var _this = this;
  20104. var scene = this.getScene();
  20105. var onload = function (img) {
  20106. // Getting height map data
  20107. var canvas = document.createElement("canvas");
  20108. var context = canvas.getContext("2d");
  20109. var heightMapWidth = img.width;
  20110. var heightMapHeight = img.height;
  20111. canvas.width = heightMapWidth;
  20112. canvas.height = heightMapHeight;
  20113. context.drawImage(img, 0, 0);
  20114. // Create VertexData from map data
  20115. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20116. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20117. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20118. //execute success callback, if set
  20119. if (onSuccess) {
  20120. onSuccess(_this);
  20121. }
  20122. };
  20123. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20124. };
  20125. /**
  20126. * Modifies the mesh geometry according to a displacementMap buffer.
  20127. * 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.
  20128. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20129. * This method returns nothing.
  20130. * 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.
  20131. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20132. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20133. */
  20134. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20135. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20136. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20137. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20138. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20139. return;
  20140. }
  20141. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20142. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20143. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20144. var position = BABYLON.Vector3.Zero();
  20145. var normal = BABYLON.Vector3.Zero();
  20146. var uv = BABYLON.Vector2.Zero();
  20147. for (var index = 0; index < positions.length; index += 3) {
  20148. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20149. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20150. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20151. // Compute height
  20152. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20153. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20154. var pos = (u + v * heightMapWidth) * 4;
  20155. var r = buffer[pos] / 255.0;
  20156. var g = buffer[pos + 1] / 255.0;
  20157. var b = buffer[pos + 2] / 255.0;
  20158. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20159. normal.normalize();
  20160. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20161. position = position.add(normal);
  20162. position.toArray(positions, index);
  20163. }
  20164. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20165. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20166. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20167. };
  20168. /**
  20169. * Modify the mesh to get a flat shading rendering.
  20170. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20171. * This method returns nothing.
  20172. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20173. */
  20174. Mesh.prototype.convertToFlatShadedMesh = function () {
  20175. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20176. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20177. var kinds = this.getVerticesDataKinds();
  20178. var vbs = [];
  20179. var data = [];
  20180. var newdata = [];
  20181. var updatableNormals = false;
  20182. var kindIndex;
  20183. var kind;
  20184. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20185. kind = kinds[kindIndex];
  20186. var vertexBuffer = this.getVertexBuffer(kind);
  20187. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20188. updatableNormals = vertexBuffer.isUpdatable();
  20189. kinds.splice(kindIndex, 1);
  20190. kindIndex--;
  20191. continue;
  20192. }
  20193. vbs[kind] = vertexBuffer;
  20194. data[kind] = vbs[kind].getData();
  20195. newdata[kind] = [];
  20196. }
  20197. // Save previous submeshes
  20198. var previousSubmeshes = this.subMeshes.slice(0);
  20199. var indices = this.getIndices();
  20200. var totalIndices = this.getTotalIndices();
  20201. // Generating unique vertices per face
  20202. var index;
  20203. for (index = 0; index < totalIndices; index++) {
  20204. var vertexIndex = indices[index];
  20205. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20206. kind = kinds[kindIndex];
  20207. var stride = vbs[kind].getStrideSize();
  20208. for (var offset = 0; offset < stride; offset++) {
  20209. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20210. }
  20211. }
  20212. }
  20213. // Updating faces & normal
  20214. var normals = [];
  20215. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20216. for (index = 0; index < totalIndices; index += 3) {
  20217. indices[index] = index;
  20218. indices[index + 1] = index + 1;
  20219. indices[index + 2] = index + 2;
  20220. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20221. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20222. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20223. var p1p2 = p1.subtract(p2);
  20224. var p3p2 = p3.subtract(p2);
  20225. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20226. // Store same normals for every vertex
  20227. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20228. normals.push(normal.x);
  20229. normals.push(normal.y);
  20230. normals.push(normal.z);
  20231. }
  20232. }
  20233. this.setIndices(indices);
  20234. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20235. // Updating vertex buffers
  20236. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20237. kind = kinds[kindIndex];
  20238. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20239. }
  20240. // Updating submeshes
  20241. this.releaseSubMeshes();
  20242. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20243. var previousOne = previousSubmeshes[submeshIndex];
  20244. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20245. }
  20246. this.synchronizeInstances();
  20247. };
  20248. /**
  20249. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20250. * In other words, more vertices, no more indices and a single bigger VBO.
  20251. * This method returns nothing.
  20252. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20253. *
  20254. */
  20255. Mesh.prototype.convertToUnIndexedMesh = function () {
  20256. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20257. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20258. var kinds = this.getVerticesDataKinds();
  20259. var vbs = [];
  20260. var data = [];
  20261. var newdata = [];
  20262. var updatableNormals = false;
  20263. var kindIndex;
  20264. var kind;
  20265. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20266. kind = kinds[kindIndex];
  20267. var vertexBuffer = this.getVertexBuffer(kind);
  20268. vbs[kind] = vertexBuffer;
  20269. data[kind] = vbs[kind].getData();
  20270. newdata[kind] = [];
  20271. }
  20272. // Save previous submeshes
  20273. var previousSubmeshes = this.subMeshes.slice(0);
  20274. var indices = this.getIndices();
  20275. var totalIndices = this.getTotalIndices();
  20276. // Generating unique vertices per face
  20277. var index;
  20278. for (index = 0; index < totalIndices; index++) {
  20279. var vertexIndex = indices[index];
  20280. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20281. kind = kinds[kindIndex];
  20282. var stride = vbs[kind].getStrideSize();
  20283. for (var offset = 0; offset < stride; offset++) {
  20284. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20285. }
  20286. }
  20287. }
  20288. // Updating indices
  20289. for (index = 0; index < totalIndices; index += 3) {
  20290. indices[index] = index;
  20291. indices[index + 1] = index + 1;
  20292. indices[index + 2] = index + 2;
  20293. }
  20294. this.setIndices(indices);
  20295. // Updating vertex buffers
  20296. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20297. kind = kinds[kindIndex];
  20298. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20299. }
  20300. // Updating submeshes
  20301. this.releaseSubMeshes();
  20302. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20303. var previousOne = previousSubmeshes[submeshIndex];
  20304. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20305. }
  20306. this._unIndexed = true;
  20307. this.synchronizeInstances();
  20308. };
  20309. /**
  20310. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20311. * This method returns nothing.
  20312. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20313. */
  20314. Mesh.prototype.flipFaces = function (flipNormals) {
  20315. if (flipNormals === void 0) { flipNormals = false; }
  20316. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20317. var i;
  20318. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20319. for (i = 0; i < vertex_data.normals.length; i++) {
  20320. vertex_data.normals[i] *= -1;
  20321. }
  20322. }
  20323. var temp;
  20324. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20325. // reassign indices
  20326. temp = vertex_data.indices[i + 1];
  20327. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20328. vertex_data.indices[i + 2] = temp;
  20329. }
  20330. vertex_data.applyToMesh(this);
  20331. };
  20332. // Instances
  20333. /**
  20334. * Creates a new InstancedMesh object from the mesh model.
  20335. * An instance shares the same properties and the same material than its model.
  20336. * Only these properties of each instance can then be set individually :
  20337. * - position
  20338. * - rotation
  20339. * - rotationQuaternion
  20340. * - setPivotMatrix
  20341. * - scaling
  20342. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20343. * Warning : this method is not supported for Line mesh and LineSystem
  20344. */
  20345. Mesh.prototype.createInstance = function (name) {
  20346. return new BABYLON.InstancedMesh(name, this);
  20347. };
  20348. /**
  20349. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20350. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20351. * This method returns nothing.
  20352. */
  20353. Mesh.prototype.synchronizeInstances = function () {
  20354. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20355. var instance = this.instances[instanceIndex];
  20356. instance._syncSubMeshes();
  20357. }
  20358. };
  20359. /**
  20360. * Simplify the mesh according to the given array of settings.
  20361. * Function will return immediately and will simplify async. It returns nothing.
  20362. * @param settings a collection of simplification settings.
  20363. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20364. * @param type the type of simplification to run.
  20365. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20366. */
  20367. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20368. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20369. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20370. this.getScene().simplificationQueue.addTask({
  20371. settings: settings,
  20372. parallelProcessing: parallelProcessing,
  20373. mesh: this,
  20374. simplificationType: simplificationType,
  20375. successCallback: successCallback
  20376. });
  20377. };
  20378. /**
  20379. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20380. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20381. * This should be used together with the simplification to avoid disappearing triangles.
  20382. * @param successCallback an optional success callback to be called after the optimization finished.
  20383. */
  20384. Mesh.prototype.optimizeIndices = function (successCallback) {
  20385. var _this = this;
  20386. var indices = this.getIndices();
  20387. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20388. var vectorPositions = [];
  20389. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20390. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20391. }
  20392. var dupes = [];
  20393. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20394. var realPos = vectorPositions.length - 1 - iteration;
  20395. var testedPosition = vectorPositions[realPos];
  20396. for (var j = 0; j < realPos; ++j) {
  20397. var againstPosition = vectorPositions[j];
  20398. if (testedPosition.equals(againstPosition)) {
  20399. dupes[realPos] = j;
  20400. break;
  20401. }
  20402. }
  20403. }, function () {
  20404. for (var i = 0; i < indices.length; ++i) {
  20405. indices[i] = dupes[indices[i]] || indices[i];
  20406. }
  20407. //indices are now reordered
  20408. var originalSubMeshes = _this.subMeshes.slice(0);
  20409. _this.setIndices(indices);
  20410. _this.subMeshes = originalSubMeshes;
  20411. if (successCallback) {
  20412. successCallback(_this);
  20413. }
  20414. });
  20415. };
  20416. // Statics
  20417. /**
  20418. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20419. * The parameter `parsedMesh` is the mesh to be copied.
  20420. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20421. */
  20422. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20423. var mesh = new Mesh(parsedMesh.name, scene);
  20424. mesh.id = parsedMesh.id;
  20425. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20426. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20427. if (parsedMesh.rotationQuaternion) {
  20428. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20429. }
  20430. else if (parsedMesh.rotation) {
  20431. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20432. }
  20433. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20434. if (parsedMesh.localMatrix) {
  20435. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20436. }
  20437. else if (parsedMesh.pivotMatrix) {
  20438. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20439. }
  20440. mesh.setEnabled(parsedMesh.isEnabled);
  20441. mesh.isVisible = parsedMesh.isVisible;
  20442. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20443. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20444. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20445. if (parsedMesh.applyFog !== undefined) {
  20446. mesh.applyFog = parsedMesh.applyFog;
  20447. }
  20448. if (parsedMesh.pickable !== undefined) {
  20449. mesh.isPickable = parsedMesh.pickable;
  20450. }
  20451. if (parsedMesh.alphaIndex !== undefined) {
  20452. mesh.alphaIndex = parsedMesh.alphaIndex;
  20453. }
  20454. mesh.receiveShadows = parsedMesh.receiveShadows;
  20455. mesh.billboardMode = parsedMesh.billboardMode;
  20456. if (parsedMesh.visibility !== undefined) {
  20457. mesh.visibility = parsedMesh.visibility;
  20458. }
  20459. mesh.checkCollisions = parsedMesh.checkCollisions;
  20460. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20461. // freezeWorldMatrix
  20462. if (parsedMesh.freezeWorldMatrix) {
  20463. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20464. }
  20465. // Parent
  20466. if (parsedMesh.parentId) {
  20467. mesh._waitingParentId = parsedMesh.parentId;
  20468. }
  20469. // Actions
  20470. if (parsedMesh.actions !== undefined) {
  20471. mesh._waitingActions = parsedMesh.actions;
  20472. }
  20473. // Geometry
  20474. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20475. if (parsedMesh.delayLoadingFile) {
  20476. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20477. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20478. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20479. if (parsedMesh._binaryInfo) {
  20480. mesh._binaryInfo = parsedMesh._binaryInfo;
  20481. }
  20482. mesh._delayInfo = [];
  20483. if (parsedMesh.hasUVs) {
  20484. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20485. }
  20486. if (parsedMesh.hasUVs2) {
  20487. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20488. }
  20489. if (parsedMesh.hasUVs3) {
  20490. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20491. }
  20492. if (parsedMesh.hasUVs4) {
  20493. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20494. }
  20495. if (parsedMesh.hasUVs5) {
  20496. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20497. }
  20498. if (parsedMesh.hasUVs6) {
  20499. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20500. }
  20501. if (parsedMesh.hasColors) {
  20502. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20503. }
  20504. if (parsedMesh.hasMatricesIndices) {
  20505. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20506. }
  20507. if (parsedMesh.hasMatricesWeights) {
  20508. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20509. }
  20510. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20511. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20512. mesh._checkDelayState();
  20513. }
  20514. }
  20515. else {
  20516. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20517. }
  20518. // Material
  20519. if (parsedMesh.materialId) {
  20520. mesh.setMaterialByID(parsedMesh.materialId);
  20521. }
  20522. else {
  20523. mesh.material = null;
  20524. }
  20525. // Skeleton
  20526. if (parsedMesh.skeletonId > -1) {
  20527. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20528. if (parsedMesh.numBoneInfluencers) {
  20529. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20530. }
  20531. }
  20532. // Animations
  20533. if (parsedMesh.animations) {
  20534. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20535. var parsedAnimation = parsedMesh.animations[animationIndex];
  20536. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20537. }
  20538. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20539. }
  20540. if (parsedMesh.autoAnimate) {
  20541. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20542. }
  20543. // Layer Mask
  20544. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20545. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20546. }
  20547. else {
  20548. mesh.layerMask = 0x0FFFFFFF;
  20549. }
  20550. //(Deprecated) physics
  20551. if (parsedMesh.physicsImpostor) {
  20552. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20553. mass: parsedMesh.physicsMass,
  20554. friction: parsedMesh.physicsFriction,
  20555. restitution: parsedMesh.physicsRestitution
  20556. }, scene);
  20557. }
  20558. // Instances
  20559. if (parsedMesh.instances) {
  20560. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20561. var parsedInstance = parsedMesh.instances[index];
  20562. var instance = mesh.createInstance(parsedInstance.name);
  20563. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20564. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20565. if (parsedInstance.parentId) {
  20566. instance._waitingParentId = parsedInstance.parentId;
  20567. }
  20568. if (parsedInstance.rotationQuaternion) {
  20569. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20570. }
  20571. else if (parsedInstance.rotation) {
  20572. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20573. }
  20574. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20575. instance.checkCollisions = mesh.checkCollisions;
  20576. if (parsedMesh.animations) {
  20577. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20578. parsedAnimation = parsedMesh.animations[animationIndex];
  20579. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20580. }
  20581. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20582. }
  20583. }
  20584. }
  20585. return mesh;
  20586. };
  20587. /**
  20588. * Creates a ribbon mesh.
  20589. * Please consider using the same method from the MeshBuilder class instead.
  20590. * 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.
  20591. *
  20592. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20593. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20594. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20595. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20596. * 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.
  20597. * 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.
  20598. * 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
  20599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20600. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20602. */
  20603. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20604. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20605. pathArray: pathArray,
  20606. closeArray: closeArray,
  20607. closePath: closePath,
  20608. offset: offset,
  20609. updatable: updatable,
  20610. sideOrientation: sideOrientation,
  20611. instance: instance
  20612. }, scene);
  20613. };
  20614. /**
  20615. * Creates a plane polygonal mesh. By default, this is a disc.
  20616. * Please consider using the same method from the MeshBuilder class instead.
  20617. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20618. * 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.
  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. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20624. var options = {
  20625. radius: radius,
  20626. tessellation: tessellation,
  20627. sideOrientation: sideOrientation,
  20628. updatable: updatable
  20629. };
  20630. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20631. };
  20632. /**
  20633. * Creates a box mesh.
  20634. * Please consider using the same method from the MeshBuilder class instead.
  20635. * The parameter `size` sets the size (float) of each box side (default 1).
  20636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20639. */
  20640. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20641. var options = {
  20642. size: size,
  20643. sideOrientation: sideOrientation,
  20644. updatable: updatable
  20645. };
  20646. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20647. };
  20648. /**
  20649. * Creates a sphere mesh.
  20650. * Please consider using the same method from the MeshBuilder class instead.
  20651. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20652. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20654. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20656. */
  20657. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20658. var options = {
  20659. segments: segments,
  20660. diameterX: diameter,
  20661. diameterY: diameter,
  20662. diameterZ: diameter,
  20663. sideOrientation: sideOrientation,
  20664. updatable: updatable
  20665. };
  20666. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20667. };
  20668. /**
  20669. * Creates a cylinder or a cone mesh.
  20670. * Please consider using the same method from the MeshBuilder class instead.
  20671. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20672. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20673. * 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.
  20674. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20675. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20679. */
  20680. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20681. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20682. if (scene !== undefined) {
  20683. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20684. updatable = scene;
  20685. }
  20686. scene = subdivisions;
  20687. subdivisions = 1;
  20688. }
  20689. var options = {
  20690. height: height,
  20691. diameterTop: diameterTop,
  20692. diameterBottom: diameterBottom,
  20693. tessellation: tessellation,
  20694. subdivisions: subdivisions,
  20695. sideOrientation: sideOrientation,
  20696. updatable: updatable
  20697. };
  20698. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20699. };
  20700. // Torus (Code from SharpDX.org)
  20701. /**
  20702. * Creates a torus mesh.
  20703. * Please consider using the same method from the MeshBuilder class instead.
  20704. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20705. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20706. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20710. */
  20711. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20712. var options = {
  20713. diameter: diameter,
  20714. thickness: thickness,
  20715. tessellation: tessellation,
  20716. sideOrientation: sideOrientation,
  20717. updatable: updatable
  20718. };
  20719. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20720. };
  20721. /**
  20722. * Creates a torus knot mesh.
  20723. * Please consider using the same method from the MeshBuilder class instead.
  20724. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20725. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20726. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20727. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20731. */
  20732. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20733. var options = {
  20734. radius: radius,
  20735. tube: tube,
  20736. radialSegments: radialSegments,
  20737. tubularSegments: tubularSegments,
  20738. p: p,
  20739. q: q,
  20740. sideOrientation: sideOrientation,
  20741. updatable: updatable
  20742. };
  20743. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20744. };
  20745. /**
  20746. * Creates a line mesh.
  20747. * Please consider using the same method from the MeshBuilder class instead.
  20748. * 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.
  20749. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20750. * The parameter `points` is an array successive Vector3.
  20751. * 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
  20752. * When updating an instance, remember that only point positions can change, not the number of points.
  20753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20754. */
  20755. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20756. var options = {
  20757. points: points,
  20758. updatable: updatable,
  20759. instance: instance
  20760. };
  20761. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20762. };
  20763. /**
  20764. * Creates a dashed line mesh.
  20765. * Please consider using the same method from the MeshBuilder class instead.
  20766. * 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.
  20767. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20768. * The parameter `points` is an array successive Vector3.
  20769. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20770. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20771. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20772. * 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
  20773. * When updating an instance, remember that only point positions can change, not the number of points.
  20774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20775. */
  20776. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20777. var options = {
  20778. points: points,
  20779. dashSize: dashSize,
  20780. gapSize: gapSize,
  20781. dashNb: dashNb,
  20782. updatable: updatable,
  20783. instance: instance
  20784. };
  20785. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20786. };
  20787. /**
  20788. * Creates an extruded shape mesh.
  20789. * 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.
  20790. * Please consider using the same method from the MeshBuilder class instead.
  20791. *
  20792. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20793. * 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
  20794. * extruded along the Z axis.
  20795. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20796. * 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.
  20797. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20798. * 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
  20799. * 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
  20800. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20802. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20804. */
  20805. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20806. var options = {
  20807. shape: shape,
  20808. path: path,
  20809. scale: scale,
  20810. rotation: rotation,
  20811. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20812. sideOrientation: sideOrientation,
  20813. instance: instance,
  20814. updatable: updatable
  20815. };
  20816. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20817. };
  20818. /**
  20819. * Creates an custom extruded shape mesh.
  20820. * 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.
  20821. * Please consider using the same method from the MeshBuilder class instead.
  20822. *
  20823. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20824. * 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
  20825. * extruded along the Z axis.
  20826. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20827. * 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
  20828. * and the distance of this point from the begining of the path :
  20829. * ```javascript
  20830. * var rotationFunction = function(i, distance) {
  20831. * // do things
  20832. * return rotationValue; }
  20833. * ```
  20834. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20835. * 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
  20836. * and the distance of this point from the begining of the path :
  20837. * ```javascript
  20838. * var scaleFunction = function(i, distance) {
  20839. * // do things
  20840. * return scaleValue;}
  20841. * ```
  20842. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20843. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20844. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20845. * 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
  20846. * 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
  20847. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20851. */
  20852. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20853. var options = {
  20854. shape: shape,
  20855. path: path,
  20856. scaleFunction: scaleFunction,
  20857. rotationFunction: rotationFunction,
  20858. ribbonCloseArray: ribbonCloseArray,
  20859. ribbonClosePath: ribbonClosePath,
  20860. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20861. sideOrientation: sideOrientation,
  20862. instance: instance,
  20863. updatable: updatable
  20864. };
  20865. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20866. };
  20867. /**
  20868. * Creates lathe mesh.
  20869. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20870. * Please consider using the same method from the MeshBuilder class instead.
  20871. * 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
  20872. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20873. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20874. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20878. */
  20879. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20880. var options = {
  20881. shape: shape,
  20882. radius: radius,
  20883. tessellation: tessellation,
  20884. sideOrientation: sideOrientation,
  20885. updatable: updatable
  20886. };
  20887. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20888. };
  20889. /**
  20890. * Creates a plane mesh.
  20891. * Please consider using the same method from the MeshBuilder class instead.
  20892. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  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. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20898. var options = {
  20899. size: size,
  20900. width: size,
  20901. height: size,
  20902. sideOrientation: sideOrientation,
  20903. updatable: updatable
  20904. };
  20905. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20906. };
  20907. /**
  20908. * Creates a ground mesh.
  20909. * Please consider using the same method from the MeshBuilder class instead.
  20910. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20911. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20913. */
  20914. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20915. var options = {
  20916. width: width,
  20917. height: height,
  20918. subdivisions: subdivisions,
  20919. updatable: updatable
  20920. };
  20921. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20922. };
  20923. /**
  20924. * Creates a tiled ground mesh.
  20925. * Please consider using the same method from the MeshBuilder class instead.
  20926. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20927. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20928. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20929. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20930. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20931. * numbers of subdivisions on the ground width and height of each tile.
  20932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20933. */
  20934. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20935. var options = {
  20936. xmin: xmin,
  20937. zmin: zmin,
  20938. xmax: xmax,
  20939. zmax: zmax,
  20940. subdivisions: subdivisions,
  20941. precision: precision,
  20942. updatable: updatable
  20943. };
  20944. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20945. };
  20946. /**
  20947. * Creates a ground mesh from a height map.
  20948. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20949. * Please consider using the same method from the MeshBuilder class instead.
  20950. * The parameter `url` sets the URL of the height map image resource.
  20951. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20952. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20953. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20954. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20955. * 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).
  20956. * This function is passed the newly built mesh :
  20957. * ```javascript
  20958. * function(mesh) { // do things
  20959. * return; }
  20960. * ```
  20961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20962. */
  20963. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20964. var options = {
  20965. width: width,
  20966. height: height,
  20967. subdivisions: subdivisions,
  20968. minHeight: minHeight,
  20969. maxHeight: maxHeight,
  20970. updatable: updatable,
  20971. onReady: onReady
  20972. };
  20973. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20974. };
  20975. /**
  20976. * Creates a tube mesh.
  20977. * 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.
  20978. * Please consider using the same method from the MeshBuilder class instead.
  20979. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20980. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20981. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20982. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20983. * 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.
  20984. * It must return a radius value (positive float) :
  20985. * ```javascript
  20986. * var radiusFunction = function(i, distance) {
  20987. * // do things
  20988. * return radius; }
  20989. * ```
  20990. * 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
  20991. * 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
  20992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20993. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20995. */
  20996. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20997. var options = {
  20998. path: path,
  20999. radius: radius,
  21000. tessellation: tessellation,
  21001. radiusFunction: radiusFunction,
  21002. arc: 1,
  21003. cap: cap,
  21004. updatable: updatable,
  21005. sideOrientation: sideOrientation,
  21006. instance: instance
  21007. };
  21008. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21009. };
  21010. /**
  21011. * Creates a polyhedron mesh.
  21012. * Please consider using the same method from the MeshBuilder class instead.
  21013. * 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
  21014. * to choose the wanted type.
  21015. * The parameter `size` (positive float, default 1) sets the polygon size.
  21016. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21017. * 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`.
  21018. * 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
  21019. * 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)`).
  21020. * 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
  21021. * 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.
  21022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21023. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21025. */
  21026. Mesh.CreatePolyhedron = function (name, options, scene) {
  21027. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21028. };
  21029. /**
  21030. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21031. * Please consider using the same method from the MeshBuilder class instead.
  21032. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21033. * 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`).
  21034. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21035. * 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.
  21036. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21039. */
  21040. Mesh.CreateIcoSphere = function (name, options, scene) {
  21041. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21042. };
  21043. /**
  21044. * Creates a decal mesh.
  21045. * Please consider using the same method from the MeshBuilder class instead.
  21046. * 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.
  21047. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21048. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21049. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21050. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21051. */
  21052. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21053. var options = {
  21054. position: position,
  21055. normal: normal,
  21056. size: size,
  21057. angle: angle
  21058. };
  21059. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21060. };
  21061. // Skeletons
  21062. /**
  21063. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21064. */
  21065. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21066. var source;
  21067. if (!this._sourcePositions) {
  21068. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21069. this._sourcePositions = new Float32Array(source);
  21070. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21071. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21072. }
  21073. }
  21074. return this._sourcePositions;
  21075. };
  21076. /**
  21077. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21078. */
  21079. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21080. var source;
  21081. if (!this._sourceNormals) {
  21082. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21083. this._sourceNormals = new Float32Array(source);
  21084. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21085. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21086. }
  21087. }
  21088. return this._sourceNormals;
  21089. };
  21090. /**
  21091. * Update the vertex buffers by applying transformation from the bones
  21092. * @param {skeleton} skeleton to apply
  21093. */
  21094. Mesh.prototype.applySkeleton = function (skeleton) {
  21095. if (!this.geometry) {
  21096. return;
  21097. }
  21098. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21099. return;
  21100. }
  21101. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21102. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21103. return this;
  21104. }
  21105. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21106. return this;
  21107. }
  21108. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21109. return this;
  21110. }
  21111. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21112. return this;
  21113. }
  21114. if (!this._sourcePositions) {
  21115. this.setPositionsForCPUSkinning();
  21116. }
  21117. if (!this._sourceNormals) {
  21118. this.setNormalsForCPUSkinning();
  21119. }
  21120. // positionsData checks for not being Float32Array will only pass at most once
  21121. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21122. if (!(positionsData instanceof Float32Array)) {
  21123. positionsData = new Float32Array(positionsData);
  21124. }
  21125. // normalsData checks for not being Float32Array will only pass at most once
  21126. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21127. if (!(normalsData instanceof Float32Array)) {
  21128. normalsData = new Float32Array(normalsData);
  21129. }
  21130. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21131. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21132. var needExtras = this.numBoneInfluencers > 4;
  21133. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21134. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21135. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21136. var tempVector3 = BABYLON.Vector3.Zero();
  21137. var finalMatrix = new BABYLON.Matrix();
  21138. var tempMatrix = new BABYLON.Matrix();
  21139. var matWeightIdx = 0;
  21140. var inf;
  21141. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21142. var weight;
  21143. for (inf = 0; inf < 4; inf++) {
  21144. weight = matricesWeightsData[matWeightIdx + inf];
  21145. if (weight > 0) {
  21146. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21147. finalMatrix.addToSelf(tempMatrix);
  21148. }
  21149. else
  21150. break;
  21151. }
  21152. if (needExtras) {
  21153. for (inf = 0; inf < 4; inf++) {
  21154. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21155. if (weight > 0) {
  21156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21157. finalMatrix.addToSelf(tempMatrix);
  21158. }
  21159. else
  21160. break;
  21161. }
  21162. }
  21163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21164. tempVector3.toArray(positionsData, index);
  21165. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21166. tempVector3.toArray(normalsData, index);
  21167. finalMatrix.reset();
  21168. }
  21169. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21170. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21171. return this;
  21172. };
  21173. // Tools
  21174. /**
  21175. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21176. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21177. */
  21178. Mesh.MinMax = function (meshes) {
  21179. var minVector = null;
  21180. var maxVector = null;
  21181. for (var i in meshes) {
  21182. var mesh = meshes[i];
  21183. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21184. if (!minVector) {
  21185. minVector = boundingBox.minimumWorld;
  21186. maxVector = boundingBox.maximumWorld;
  21187. continue;
  21188. }
  21189. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21190. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21191. }
  21192. return {
  21193. min: minVector,
  21194. max: maxVector
  21195. };
  21196. };
  21197. /**
  21198. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21199. */
  21200. Mesh.Center = function (meshesOrMinMaxVector) {
  21201. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  21202. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21203. };
  21204. /**
  21205. * Merge the array of meshes into a single mesh for performance reasons.
  21206. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21207. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21208. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21209. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21210. */
  21211. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21212. if (disposeSource === void 0) { disposeSource = true; }
  21213. var index;
  21214. if (!allow32BitsIndices) {
  21215. var totalVertices = 0;
  21216. // Counting vertices
  21217. for (index = 0; index < meshes.length; index++) {
  21218. if (meshes[index]) {
  21219. totalVertices += meshes[index].getTotalVertices();
  21220. if (totalVertices > 65536) {
  21221. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21222. return null;
  21223. }
  21224. }
  21225. }
  21226. }
  21227. // Merge
  21228. var vertexData;
  21229. var otherVertexData;
  21230. var source;
  21231. for (index = 0; index < meshes.length; index++) {
  21232. if (meshes[index]) {
  21233. meshes[index].computeWorldMatrix(true);
  21234. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21235. otherVertexData.transform(meshes[index].getWorldMatrix());
  21236. if (vertexData) {
  21237. vertexData.merge(otherVertexData);
  21238. }
  21239. else {
  21240. vertexData = otherVertexData;
  21241. source = meshes[index];
  21242. }
  21243. }
  21244. }
  21245. if (!meshSubclass) {
  21246. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21247. }
  21248. vertexData.applyToMesh(meshSubclass);
  21249. // Setting properties
  21250. meshSubclass.material = source.material;
  21251. meshSubclass.checkCollisions = source.checkCollisions;
  21252. // Cleaning
  21253. if (disposeSource) {
  21254. for (index = 0; index < meshes.length; index++) {
  21255. if (meshes[index]) {
  21256. meshes[index].dispose();
  21257. }
  21258. }
  21259. }
  21260. return meshSubclass;
  21261. };
  21262. // Consts
  21263. Mesh._FRONTSIDE = 0;
  21264. Mesh._BACKSIDE = 1;
  21265. Mesh._DOUBLESIDE = 2;
  21266. Mesh._DEFAULTSIDE = 0;
  21267. Mesh._NO_CAP = 0;
  21268. Mesh._CAP_START = 1;
  21269. Mesh._CAP_END = 2;
  21270. Mesh._CAP_ALL = 3;
  21271. return Mesh;
  21272. }(BABYLON.AbstractMesh));
  21273. BABYLON.Mesh = Mesh;
  21274. })(BABYLON || (BABYLON = {}));
  21275. var BABYLON;
  21276. (function (BABYLON) {
  21277. var SubMesh = (function () {
  21278. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21279. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21280. this.materialIndex = materialIndex;
  21281. this.verticesStart = verticesStart;
  21282. this.verticesCount = verticesCount;
  21283. this.indexStart = indexStart;
  21284. this.indexCount = indexCount;
  21285. this._renderId = 0;
  21286. this._mesh = mesh;
  21287. this._renderingMesh = renderingMesh || mesh;
  21288. mesh.subMeshes.push(this);
  21289. this._trianglePlanes = [];
  21290. this._id = mesh.subMeshes.length - 1;
  21291. if (createBoundingBox) {
  21292. this.refreshBoundingInfo();
  21293. mesh.computeWorldMatrix(true);
  21294. }
  21295. }
  21296. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21297. get: function () {
  21298. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21299. },
  21300. enumerable: true,
  21301. configurable: true
  21302. });
  21303. SubMesh.prototype.getBoundingInfo = function () {
  21304. if (this.IsGlobal) {
  21305. return this._mesh.getBoundingInfo();
  21306. }
  21307. return this._boundingInfo;
  21308. };
  21309. SubMesh.prototype.getMesh = function () {
  21310. return this._mesh;
  21311. };
  21312. SubMesh.prototype.getRenderingMesh = function () {
  21313. return this._renderingMesh;
  21314. };
  21315. SubMesh.prototype.getMaterial = function () {
  21316. var rootMaterial = this._renderingMesh.material;
  21317. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21318. var multiMaterial = rootMaterial;
  21319. return multiMaterial.getSubMaterial(this.materialIndex);
  21320. }
  21321. if (!rootMaterial) {
  21322. return this._mesh.getScene().defaultMaterial;
  21323. }
  21324. return rootMaterial;
  21325. };
  21326. // Methods
  21327. SubMesh.prototype.refreshBoundingInfo = function () {
  21328. this._lastColliderWorldVertices = null;
  21329. if (this.IsGlobal) {
  21330. return;
  21331. }
  21332. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21333. if (!data) {
  21334. this._boundingInfo = this._mesh._boundingInfo;
  21335. return;
  21336. }
  21337. var indices = this._renderingMesh.getIndices();
  21338. var extend;
  21339. //is this the only submesh?
  21340. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21341. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21342. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21343. }
  21344. else {
  21345. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21346. }
  21347. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21348. };
  21349. SubMesh.prototype._checkCollision = function (collider) {
  21350. return this.getBoundingInfo()._checkCollision(collider);
  21351. };
  21352. SubMesh.prototype.updateBoundingInfo = function (world) {
  21353. if (!this.getBoundingInfo()) {
  21354. this.refreshBoundingInfo();
  21355. }
  21356. this.getBoundingInfo().update(world);
  21357. };
  21358. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21359. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21360. };
  21361. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21362. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21363. };
  21364. SubMesh.prototype.render = function (enableAlphaMode) {
  21365. this._renderingMesh.render(this, enableAlphaMode);
  21366. };
  21367. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21368. if (!this._linesIndexBuffer) {
  21369. var linesIndices = [];
  21370. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21371. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21372. }
  21373. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21374. this.linesIndexCount = linesIndices.length;
  21375. }
  21376. return this._linesIndexBuffer;
  21377. };
  21378. SubMesh.prototype.canIntersects = function (ray) {
  21379. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21380. };
  21381. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21382. var intersectInfo = null;
  21383. // LineMesh first as it's also a Mesh...
  21384. if (this._mesh instanceof BABYLON.LinesMesh) {
  21385. var lineMesh = this._mesh;
  21386. // Line test
  21387. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21388. var p0 = positions[indices[index]];
  21389. var p1 = positions[indices[index + 1]];
  21390. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21391. if (length < 0) {
  21392. continue;
  21393. }
  21394. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21395. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21396. if (fastCheck) {
  21397. break;
  21398. }
  21399. }
  21400. }
  21401. }
  21402. else {
  21403. // Triangles test
  21404. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21405. var p0 = positions[indices[index]];
  21406. var p1 = positions[indices[index + 1]];
  21407. var p2 = positions[indices[index + 2]];
  21408. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21409. if (currentIntersectInfo) {
  21410. if (currentIntersectInfo.distance < 0) {
  21411. continue;
  21412. }
  21413. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21414. intersectInfo = currentIntersectInfo;
  21415. intersectInfo.faceId = index / 3;
  21416. if (fastCheck) {
  21417. break;
  21418. }
  21419. }
  21420. }
  21421. }
  21422. }
  21423. return intersectInfo;
  21424. };
  21425. // Clone
  21426. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21427. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21428. if (!this.IsGlobal) {
  21429. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21430. }
  21431. return result;
  21432. };
  21433. // Dispose
  21434. SubMesh.prototype.dispose = function () {
  21435. if (this._linesIndexBuffer) {
  21436. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21437. this._linesIndexBuffer = null;
  21438. }
  21439. // Remove from mesh
  21440. var index = this._mesh.subMeshes.indexOf(this);
  21441. this._mesh.subMeshes.splice(index, 1);
  21442. };
  21443. // Statics
  21444. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21445. var minVertexIndex = Number.MAX_VALUE;
  21446. var maxVertexIndex = -Number.MAX_VALUE;
  21447. renderingMesh = renderingMesh || mesh;
  21448. var indices = renderingMesh.getIndices();
  21449. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21450. var vertexIndex = indices[index];
  21451. if (vertexIndex < minVertexIndex)
  21452. minVertexIndex = vertexIndex;
  21453. if (vertexIndex > maxVertexIndex)
  21454. maxVertexIndex = vertexIndex;
  21455. }
  21456. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21457. };
  21458. return SubMesh;
  21459. }());
  21460. BABYLON.SubMesh = SubMesh;
  21461. })(BABYLON || (BABYLON = {}));
  21462. var BABYLON;
  21463. (function (BABYLON) {
  21464. var MeshBuilder = (function () {
  21465. function MeshBuilder() {
  21466. }
  21467. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21468. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21469. return BABYLON.Mesh.DOUBLESIDE;
  21470. }
  21471. if (orientation === undefined || orientation === null) {
  21472. return BABYLON.Mesh.FRONTSIDE;
  21473. }
  21474. return orientation;
  21475. };
  21476. /**
  21477. * Creates a box mesh.
  21478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21479. * The parameter `size` sets the size (float) of each box side (default 1).
  21480. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21481. * 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).
  21482. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21486. */
  21487. MeshBuilder.CreateBox = function (name, options, scene) {
  21488. var box = new BABYLON.Mesh(name, scene);
  21489. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21490. var vertexData = BABYLON.VertexData.CreateBox(options);
  21491. vertexData.applyToMesh(box, options.updatable);
  21492. return box;
  21493. };
  21494. /**
  21495. * Creates a sphere mesh.
  21496. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21497. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21498. * 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`).
  21499. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21500. * 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
  21501. * 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).
  21502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21505. */
  21506. MeshBuilder.CreateSphere = function (name, options, scene) {
  21507. var sphere = new BABYLON.Mesh(name, scene);
  21508. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21509. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21510. vertexData.applyToMesh(sphere, options.updatable);
  21511. return sphere;
  21512. };
  21513. /**
  21514. * Creates a plane polygonal mesh. By default, this is a disc.
  21515. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21516. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21517. * 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.
  21518. * 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
  21519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21522. */
  21523. MeshBuilder.CreateDisc = function (name, options, scene) {
  21524. var disc = new BABYLON.Mesh(name, scene);
  21525. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21526. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21527. vertexData.applyToMesh(disc, options.updatable);
  21528. return disc;
  21529. };
  21530. /**
  21531. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21533. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21534. * 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`).
  21535. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21536. * 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.
  21537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21540. */
  21541. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21542. var sphere = new BABYLON.Mesh(name, scene);
  21543. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21544. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21545. vertexData.applyToMesh(sphere, options.updatable);
  21546. return sphere;
  21547. };
  21548. ;
  21549. /**
  21550. * Creates a ribbon mesh.
  21551. * 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.
  21552. *
  21553. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21554. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21555. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21556. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21557. * 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.
  21558. * 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.
  21559. * 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
  21560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21562. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21564. */
  21565. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21566. var pathArray = options.pathArray;
  21567. var closeArray = options.closeArray;
  21568. var closePath = options.closePath;
  21569. var offset = options.offset;
  21570. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21571. var instance = options.instance;
  21572. var updatable = options.updatable;
  21573. if (instance) {
  21574. // positionFunction : ribbon case
  21575. // only pathArray and sideOrientation parameters are taken into account for positions update
  21576. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21577. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21578. var positionFunction = function (positions) {
  21579. var minlg = pathArray[0].length;
  21580. var i = 0;
  21581. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21582. for (var si = 1; si <= ns; si++) {
  21583. for (var p = 0; p < pathArray.length; p++) {
  21584. var path = pathArray[p];
  21585. var l = path.length;
  21586. minlg = (minlg < l) ? minlg : l;
  21587. var j = 0;
  21588. while (j < minlg) {
  21589. positions[i] = path[j].x;
  21590. positions[i + 1] = path[j].y;
  21591. positions[i + 2] = path[j].z;
  21592. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21593. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21594. }
  21595. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21596. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21597. }
  21598. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21599. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21600. }
  21601. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21602. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21603. }
  21604. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21605. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21606. }
  21607. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21608. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21609. }
  21610. j++;
  21611. i += 3;
  21612. }
  21613. if (instance._closePath) {
  21614. positions[i] = path[0].x;
  21615. positions[i + 1] = path[0].y;
  21616. positions[i + 2] = path[0].z;
  21617. i += 3;
  21618. }
  21619. }
  21620. }
  21621. };
  21622. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21623. positionFunction(positions);
  21624. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21625. instance._boundingInfo.update(instance._worldMatrix);
  21626. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21627. if (!(instance.areNormalsFrozen)) {
  21628. var indices = instance.getIndices();
  21629. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21630. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21631. if (instance._closePath) {
  21632. var indexFirst = 0;
  21633. var indexLast = 0;
  21634. for (var p = 0; p < pathArray.length; p++) {
  21635. indexFirst = instance._idx[p] * 3;
  21636. if (p + 1 < pathArray.length) {
  21637. indexLast = (instance._idx[p + 1] - 1) * 3;
  21638. }
  21639. else {
  21640. indexLast = normals.length - 3;
  21641. }
  21642. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21643. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21644. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21645. normals[indexLast] = normals[indexFirst];
  21646. normals[indexLast + 1] = normals[indexFirst + 1];
  21647. normals[indexLast + 2] = normals[indexFirst + 2];
  21648. }
  21649. }
  21650. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21651. }
  21652. return instance;
  21653. }
  21654. else {
  21655. var ribbon = new BABYLON.Mesh(name, scene);
  21656. ribbon.sideOrientation = sideOrientation;
  21657. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21658. if (closePath) {
  21659. ribbon._idx = vertexData._idx;
  21660. }
  21661. ribbon._closePath = closePath;
  21662. ribbon._closeArray = closeArray;
  21663. vertexData.applyToMesh(ribbon, updatable);
  21664. return ribbon;
  21665. }
  21666. };
  21667. /**
  21668. * Creates a cylinder or a cone mesh.
  21669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21670. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21671. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21672. * 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.
  21673. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21674. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21675. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21676. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21677. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21678. * 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).
  21679. * 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
  21680. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21681. * 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
  21682. * 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.
  21683. * If `enclose` is false, a ring surface is one element.
  21684. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21685. * 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
  21686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21689. */
  21690. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21691. var cylinder = new BABYLON.Mesh(name, scene);
  21692. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21693. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21694. vertexData.applyToMesh(cylinder, options.updatable);
  21695. return cylinder;
  21696. };
  21697. /**
  21698. * Creates a torus mesh.
  21699. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21700. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21701. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21702. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21703. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21704. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21706. */
  21707. MeshBuilder.CreateTorus = function (name, options, scene) {
  21708. var torus = new BABYLON.Mesh(name, scene);
  21709. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21710. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21711. vertexData.applyToMesh(torus, options.updatable);
  21712. return torus;
  21713. };
  21714. /**
  21715. * Creates a torus knot mesh.
  21716. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21717. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21718. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21719. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21720. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21724. */
  21725. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21726. var torusKnot = new BABYLON.Mesh(name, scene);
  21727. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21728. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21729. vertexData.applyToMesh(torusKnot, options.updatable);
  21730. return torusKnot;
  21731. };
  21732. /**
  21733. * Creates a line system mesh.
  21734. * A line system is a pool of many lines gathered in a single mesh.
  21735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21736. * 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.
  21737. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21738. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21739. * 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
  21740. * 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
  21741. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21743. */
  21744. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21745. var instance = options.instance;
  21746. var lines = options.lines;
  21747. if (instance) {
  21748. var positionFunction = function (positions) {
  21749. var i = 0;
  21750. for (var l = 0; l < lines.length; l++) {
  21751. var points = lines[l];
  21752. for (var p = 0; p < points.length; p++) {
  21753. positions[i] = points[p].x;
  21754. positions[i + 1] = points[p].y;
  21755. positions[i + 2] = points[p].z;
  21756. i += 3;
  21757. }
  21758. }
  21759. };
  21760. instance.updateMeshPositions(positionFunction, false);
  21761. return instance;
  21762. }
  21763. // line system creation
  21764. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21765. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21766. vertexData.applyToMesh(lineSystem, options.updatable);
  21767. return lineSystem;
  21768. };
  21769. /**
  21770. * Creates a line mesh.
  21771. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21772. * 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.
  21773. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21774. * The parameter `points` is an array successive Vector3.
  21775. * 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
  21776. * When updating an instance, remember that only point positions can change, not the number of points.
  21777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21778. */
  21779. MeshBuilder.CreateLines = function (name, options, scene) {
  21780. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21781. return lines;
  21782. };
  21783. /**
  21784. * Creates a dashed line mesh.
  21785. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21786. * 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.
  21787. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21788. * The parameter `points` is an array successive Vector3.
  21789. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21790. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21791. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21792. * 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
  21793. * When updating an instance, remember that only point positions can change, not the number of points.
  21794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21795. */
  21796. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21797. var points = options.points;
  21798. var instance = options.instance;
  21799. var gapSize = options.gapSize;
  21800. var dashNb = options.dashNb;
  21801. var dashSize = options.dashSize;
  21802. if (instance) {
  21803. var positionFunction = function (positions) {
  21804. var curvect = BABYLON.Vector3.Zero();
  21805. var nbSeg = positions.length / 6;
  21806. var lg = 0;
  21807. var nb = 0;
  21808. var shft = 0;
  21809. var dashshft = 0;
  21810. var curshft = 0;
  21811. var p = 0;
  21812. var i = 0;
  21813. var j = 0;
  21814. for (i = 0; i < points.length - 1; i++) {
  21815. points[i + 1].subtractToRef(points[i], curvect);
  21816. lg += curvect.length();
  21817. }
  21818. shft = lg / nbSeg;
  21819. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21820. for (i = 0; i < points.length - 1; i++) {
  21821. points[i + 1].subtractToRef(points[i], curvect);
  21822. nb = Math.floor(curvect.length() / shft);
  21823. curvect.normalize();
  21824. j = 0;
  21825. while (j < nb && p < positions.length) {
  21826. curshft = shft * j;
  21827. positions[p] = points[i].x + curshft * curvect.x;
  21828. positions[p + 1] = points[i].y + curshft * curvect.y;
  21829. positions[p + 2] = points[i].z + curshft * curvect.z;
  21830. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21831. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21832. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21833. p += 6;
  21834. j++;
  21835. }
  21836. }
  21837. while (p < positions.length) {
  21838. positions[p] = points[i].x;
  21839. positions[p + 1] = points[i].y;
  21840. positions[p + 2] = points[i].z;
  21841. p += 3;
  21842. }
  21843. };
  21844. instance.updateMeshPositions(positionFunction, false);
  21845. return instance;
  21846. }
  21847. // dashed lines creation
  21848. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21849. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21850. vertexData.applyToMesh(dashedLines, options.updatable);
  21851. dashedLines.dashSize = dashSize;
  21852. dashedLines.gapSize = gapSize;
  21853. return dashedLines;
  21854. };
  21855. /**
  21856. * Creates an extruded shape mesh.
  21857. * 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.
  21858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21859. *
  21860. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21861. * 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
  21862. * extruded along the Z axis.
  21863. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21864. * 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.
  21865. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21866. * 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
  21867. * 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
  21868. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21871. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21873. */
  21874. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21875. var path = options.path;
  21876. var shape = options.shape;
  21877. var scale = options.scale || 1;
  21878. var rotation = options.rotation || 0;
  21879. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21880. var updatable = options.updatable;
  21881. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21882. var instance = options.instance;
  21883. var invertUV = options.invertUV || false;
  21884. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21885. };
  21886. /**
  21887. * Creates an custom extruded shape mesh.
  21888. * 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.
  21889. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21890. *
  21891. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21892. * 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
  21893. * extruded along the Z axis.
  21894. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21895. * 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
  21896. * and the distance of this point from the begining of the path :
  21897. * ```javascript
  21898. * var rotationFunction = function(i, distance) {
  21899. * // do things
  21900. * return rotationValue; }
  21901. * ```
  21902. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21903. * 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
  21904. * and the distance of this point from the begining of the path :
  21905. * ```javascript
  21906. * var scaleFunction = function(i, distance) {
  21907. * // do things
  21908. * return scaleValue;}
  21909. * ```
  21910. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21911. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21912. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21913. * 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
  21914. * 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
  21915. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21917. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21918. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21920. */
  21921. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21922. var path = options.path;
  21923. var shape = options.shape;
  21924. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21925. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21926. var ribbonCloseArray = options.ribbonCloseArray || false;
  21927. var ribbonClosePath = options.ribbonClosePath || false;
  21928. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21929. var updatable = options.updatable;
  21930. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21931. var instance = options.instance;
  21932. var invertUV = options.invertUV || false;
  21933. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21934. };
  21935. /**
  21936. * Creates lathe mesh.
  21937. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21938. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21939. *
  21940. * 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
  21941. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21942. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21943. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21944. * 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.
  21945. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21946. * 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
  21947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21949. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21950. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21951. */
  21952. MeshBuilder.CreateLathe = function (name, options, scene) {
  21953. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21954. var closed = (options.closed === undefined) ? true : options.closed;
  21955. var shape = options.shape;
  21956. var radius = options.radius || 1;
  21957. var tessellation = options.tessellation || 64;
  21958. var updatable = options.updatable;
  21959. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21960. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21961. var pi2 = Math.PI * 2;
  21962. var paths = new Array();
  21963. var invertUV = options.invertUV || false;
  21964. var i = 0;
  21965. var p = 0;
  21966. var step = pi2 / tessellation * arc;
  21967. var rotated;
  21968. var path = new Array();
  21969. ;
  21970. for (i = 0; i <= tessellation; i++) {
  21971. var path = [];
  21972. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21973. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21974. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21975. }
  21976. for (p = 0; p < shape.length; p++) {
  21977. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21978. path.push(rotated);
  21979. }
  21980. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21981. 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));
  21982. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21983. }
  21984. paths.push(path);
  21985. }
  21986. // lathe ribbon
  21987. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21988. return lathe;
  21989. };
  21990. /**
  21991. * Creates a plane mesh.
  21992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21993. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21994. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21995. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21999. */
  22000. MeshBuilder.CreatePlane = function (name, options, scene) {
  22001. var plane = new BABYLON.Mesh(name, scene);
  22002. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22003. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22004. vertexData.applyToMesh(plane, options.updatable);
  22005. if (options.sourcePlane) {
  22006. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22007. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22008. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22009. plane.rotate(vectorProduct, product);
  22010. }
  22011. return plane;
  22012. };
  22013. /**
  22014. * Creates a ground mesh.
  22015. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22016. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22017. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22019. */
  22020. MeshBuilder.CreateGround = function (name, options, scene) {
  22021. var ground = new BABYLON.GroundMesh(name, scene);
  22022. ground._setReady(false);
  22023. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22024. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22025. ground._width = options.width || 1;
  22026. ground._height = options.height || 1;
  22027. ground._maxX = ground._width / 2;
  22028. ground._maxZ = ground._height / 2;
  22029. ground._minX = -ground._maxX;
  22030. ground._minZ = -ground._maxZ;
  22031. var vertexData = BABYLON.VertexData.CreateGround(options);
  22032. vertexData.applyToMesh(ground, options.updatable);
  22033. ground._setReady(true);
  22034. return ground;
  22035. };
  22036. /**
  22037. * Creates a tiled ground mesh.
  22038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22039. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22040. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22041. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22042. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22043. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22044. * numbers of subdivisions on the ground width and height of each tile.
  22045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22046. */
  22047. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22048. var tiledGround = new BABYLON.Mesh(name, scene);
  22049. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22050. vertexData.applyToMesh(tiledGround, options.updatable);
  22051. return tiledGround;
  22052. };
  22053. /**
  22054. * Creates a ground mesh from a height map.
  22055. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22056. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22057. * The parameter `url` sets the URL of the height map image resource.
  22058. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22059. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22060. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22061. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22062. * 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).
  22063. * This function is passed the newly built mesh :
  22064. * ```javascript
  22065. * function(mesh) { // do things
  22066. * return; }
  22067. * ```
  22068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22069. */
  22070. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22071. var width = options.width || 10.0;
  22072. var height = options.height || 10.0;
  22073. var subdivisions = options.subdivisions || 1 | 0;
  22074. var minHeight = options.minHeight || 0.0;
  22075. var maxHeight = options.maxHeight || 10.0;
  22076. var updatable = options.updatable;
  22077. var onReady = options.onReady;
  22078. var ground = new BABYLON.GroundMesh(name, scene);
  22079. ground._subdivisionsX = subdivisions;
  22080. ground._subdivisionsY = subdivisions;
  22081. ground._width = width;
  22082. ground._height = height;
  22083. ground._maxX = ground._width / 2.0;
  22084. ground._maxZ = ground._height / 2.0;
  22085. ground._minX = -ground._maxX;
  22086. ground._minZ = -ground._maxZ;
  22087. ground._setReady(false);
  22088. var onload = function (img) {
  22089. // Getting height map data
  22090. var canvas = document.createElement("canvas");
  22091. var context = canvas.getContext("2d");
  22092. var bufferWidth = img.width;
  22093. var bufferHeight = img.height;
  22094. canvas.width = bufferWidth;
  22095. canvas.height = bufferHeight;
  22096. context.drawImage(img, 0, 0);
  22097. // Create VertexData from map data
  22098. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22099. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22100. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22101. width: width, height: height,
  22102. subdivisions: subdivisions,
  22103. minHeight: minHeight, maxHeight: maxHeight,
  22104. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22105. });
  22106. vertexData.applyToMesh(ground, updatable);
  22107. ground._setReady(true);
  22108. //execute ready callback, if set
  22109. if (onReady) {
  22110. onReady(ground);
  22111. }
  22112. };
  22113. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22114. return ground;
  22115. };
  22116. /**
  22117. * Creates a tube mesh.
  22118. * 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.
  22119. *
  22120. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22121. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22122. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22123. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22124. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22125. * 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.
  22126. * It must return a radius value (positive float) :
  22127. * ```javascript
  22128. * var radiusFunction = function(i, distance) {
  22129. * // do things
  22130. * return radius; }
  22131. * ```
  22132. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22133. * 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
  22134. * 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
  22135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22137. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22139. */
  22140. MeshBuilder.CreateTube = function (name, options, scene) {
  22141. var path = options.path;
  22142. var radius = options.radius || 1.0;
  22143. var tessellation = options.tessellation || 64 | 0;
  22144. var radiusFunction = options.radiusFunction;
  22145. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22146. var invertUV = options.invertUV || false;
  22147. var updatable = options.updatable;
  22148. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22149. var instance = options.instance;
  22150. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22151. // tube geometry
  22152. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22153. var tangents = path3D.getTangents();
  22154. var normals = path3D.getNormals();
  22155. var distances = path3D.getDistances();
  22156. var pi2 = Math.PI * 2;
  22157. var step = pi2 / tessellation * arc;
  22158. var returnRadius = function () { return radius; };
  22159. var radiusFunctionFinal = radiusFunction || returnRadius;
  22160. var circlePath;
  22161. var rad;
  22162. var normal;
  22163. var rotated;
  22164. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22165. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22166. for (var i = 0; i < path.length; i++) {
  22167. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22168. circlePath = Array(); // current circle array
  22169. normal = normals[i]; // current normal
  22170. for (var t = 0; t < tessellation; t++) {
  22171. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22172. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22173. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22174. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22175. circlePath[t] = rotated;
  22176. }
  22177. circlePaths[index] = circlePath;
  22178. index++;
  22179. }
  22180. // cap
  22181. var capPath = function (nbPoints, pathIndex) {
  22182. var pointCap = Array();
  22183. for (var i = 0; i < nbPoints; i++) {
  22184. pointCap.push(path[pathIndex]);
  22185. }
  22186. return pointCap;
  22187. };
  22188. switch (cap) {
  22189. case BABYLON.Mesh.NO_CAP:
  22190. break;
  22191. case BABYLON.Mesh.CAP_START:
  22192. circlePaths[0] = capPath(tessellation, 0);
  22193. circlePaths[1] = circlePaths[2].slice(0);
  22194. break;
  22195. case BABYLON.Mesh.CAP_END:
  22196. circlePaths[index] = circlePaths[index - 1].slice(0);
  22197. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22198. break;
  22199. case BABYLON.Mesh.CAP_ALL:
  22200. circlePaths[0] = capPath(tessellation, 0);
  22201. circlePaths[1] = circlePaths[2].slice(0);
  22202. circlePaths[index] = circlePaths[index - 1].slice(0);
  22203. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22204. break;
  22205. default:
  22206. break;
  22207. }
  22208. return circlePaths;
  22209. };
  22210. var path3D;
  22211. var pathArray;
  22212. if (instance) {
  22213. var arc = options.arc || instance.arc;
  22214. path3D = (instance.path3D).update(path);
  22215. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22216. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22217. instance.path3D = path3D;
  22218. instance.pathArray = pathArray;
  22219. instance.arc = arc;
  22220. return instance;
  22221. }
  22222. // tube creation
  22223. path3D = new BABYLON.Path3D(path);
  22224. var newPathArray = new Array();
  22225. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22226. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22227. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22228. tube.pathArray = pathArray;
  22229. tube.path3D = path3D;
  22230. tube.tessellation = tessellation;
  22231. tube.cap = cap;
  22232. tube.arc = options.arc;
  22233. return tube;
  22234. };
  22235. /**
  22236. * Creates a polyhedron mesh.
  22237. *
  22238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22239. * 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
  22240. * to choose the wanted type.
  22241. * The parameter `size` (positive float, default 1) sets the polygon size.
  22242. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22243. * 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`.
  22244. * 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
  22245. * 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)`).
  22246. * 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
  22247. * 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.
  22248. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22249. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22251. */
  22252. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22253. var polyhedron = new BABYLON.Mesh(name, scene);
  22254. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22255. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22256. vertexData.applyToMesh(polyhedron, options.updatable);
  22257. return polyhedron;
  22258. };
  22259. /**
  22260. * Creates a decal mesh.
  22261. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22262. * 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.
  22263. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22264. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22265. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22266. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22267. */
  22268. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22269. var indices = sourceMesh.getIndices();
  22270. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22271. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22272. var position = options.position || BABYLON.Vector3.Zero();
  22273. var normal = options.normal || BABYLON.Vector3.Up();
  22274. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22275. var angle = options.angle || 0;
  22276. // Getting correct rotation
  22277. if (!normal) {
  22278. var target = new BABYLON.Vector3(0, 0, 1);
  22279. var camera = sourceMesh.getScene().activeCamera;
  22280. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22281. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22282. }
  22283. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22284. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22285. var pitch = Math.atan2(normal.y, len);
  22286. // Matrix
  22287. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22288. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22289. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22290. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22291. var vertexData = new BABYLON.VertexData();
  22292. vertexData.indices = [];
  22293. vertexData.positions = [];
  22294. vertexData.normals = [];
  22295. vertexData.uvs = [];
  22296. var currentVertexDataIndex = 0;
  22297. var extractDecalVector3 = function (indexId) {
  22298. var vertexId = indices[indexId];
  22299. var result = new BABYLON.PositionNormalVertex();
  22300. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22301. // Send vector to decal local world
  22302. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22303. // Get normal
  22304. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22305. return result;
  22306. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22307. var clip = function (vertices, axis) {
  22308. if (vertices.length === 0) {
  22309. return vertices;
  22310. }
  22311. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22312. var clipVertices = function (v0, v1) {
  22313. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22314. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22315. };
  22316. var result = new Array();
  22317. for (var index = 0; index < vertices.length; index += 3) {
  22318. var v1Out;
  22319. var v2Out;
  22320. var v3Out;
  22321. var total = 0;
  22322. var nV1, nV2, nV3, nV4;
  22323. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22324. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22325. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22326. v1Out = d1 > 0;
  22327. v2Out = d2 > 0;
  22328. v3Out = d3 > 0;
  22329. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22330. switch (total) {
  22331. case 0:
  22332. result.push(vertices[index]);
  22333. result.push(vertices[index + 1]);
  22334. result.push(vertices[index + 2]);
  22335. break;
  22336. case 1:
  22337. if (v1Out) {
  22338. nV1 = vertices[index + 1];
  22339. nV2 = vertices[index + 2];
  22340. nV3 = clipVertices(vertices[index], nV1);
  22341. nV4 = clipVertices(vertices[index], nV2);
  22342. }
  22343. if (v2Out) {
  22344. nV1 = vertices[index];
  22345. nV2 = vertices[index + 2];
  22346. nV3 = clipVertices(vertices[index + 1], nV1);
  22347. nV4 = clipVertices(vertices[index + 1], nV2);
  22348. result.push(nV3);
  22349. result.push(nV2.clone());
  22350. result.push(nV1.clone());
  22351. result.push(nV2.clone());
  22352. result.push(nV3.clone());
  22353. result.push(nV4);
  22354. break;
  22355. }
  22356. if (v3Out) {
  22357. nV1 = vertices[index];
  22358. nV2 = vertices[index + 1];
  22359. nV3 = clipVertices(vertices[index + 2], nV1);
  22360. nV4 = clipVertices(vertices[index + 2], nV2);
  22361. }
  22362. result.push(nV1.clone());
  22363. result.push(nV2.clone());
  22364. result.push(nV3);
  22365. result.push(nV4);
  22366. result.push(nV3.clone());
  22367. result.push(nV2.clone());
  22368. break;
  22369. case 2:
  22370. if (!v1Out) {
  22371. nV1 = vertices[index].clone();
  22372. nV2 = clipVertices(nV1, vertices[index + 1]);
  22373. nV3 = clipVertices(nV1, vertices[index + 2]);
  22374. result.push(nV1);
  22375. result.push(nV2);
  22376. result.push(nV3);
  22377. }
  22378. if (!v2Out) {
  22379. nV1 = vertices[index + 1].clone();
  22380. nV2 = clipVertices(nV1, vertices[index + 2]);
  22381. nV3 = clipVertices(nV1, vertices[index]);
  22382. result.push(nV1);
  22383. result.push(nV2);
  22384. result.push(nV3);
  22385. }
  22386. if (!v3Out) {
  22387. nV1 = vertices[index + 2].clone();
  22388. nV2 = clipVertices(nV1, vertices[index]);
  22389. nV3 = clipVertices(nV1, vertices[index + 1]);
  22390. result.push(nV1);
  22391. result.push(nV2);
  22392. result.push(nV3);
  22393. }
  22394. break;
  22395. case 3:
  22396. break;
  22397. }
  22398. }
  22399. return result;
  22400. };
  22401. for (var index = 0; index < indices.length; index += 3) {
  22402. var faceVertices = new Array();
  22403. faceVertices.push(extractDecalVector3(index));
  22404. faceVertices.push(extractDecalVector3(index + 1));
  22405. faceVertices.push(extractDecalVector3(index + 2));
  22406. // Clip
  22407. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22408. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22409. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22410. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22411. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22412. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22413. if (faceVertices.length === 0) {
  22414. continue;
  22415. }
  22416. // Add UVs and get back to world
  22417. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22418. var vertex = faceVertices[vIndex];
  22419. //TODO check for Int32Array
  22420. vertexData.indices.push(currentVertexDataIndex);
  22421. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22422. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22423. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22424. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22425. currentVertexDataIndex++;
  22426. }
  22427. }
  22428. // Return mesh
  22429. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22430. vertexData.applyToMesh(decal);
  22431. decal.position = position.clone();
  22432. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22433. return decal;
  22434. };
  22435. // Privates
  22436. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22437. // extrusion geometry
  22438. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22439. var tangents = path3D.getTangents();
  22440. var normals = path3D.getNormals();
  22441. var binormals = path3D.getBinormals();
  22442. var distances = path3D.getDistances();
  22443. var angle = 0;
  22444. var returnScale = function () { return scale; };
  22445. var returnRotation = function () { return rotation; };
  22446. var rotate = custom ? rotateFunction : returnRotation;
  22447. var scl = custom ? scaleFunction : returnScale;
  22448. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22449. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22450. for (var i = 0; i < curve.length; i++) {
  22451. var shapePath = new Array();
  22452. var angleStep = rotate(i, distances[i]);
  22453. var scaleRatio = scl(i, distances[i]);
  22454. for (var p = 0; p < shape.length; p++) {
  22455. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22456. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22457. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22458. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22459. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22460. shapePath[p] = rotated;
  22461. }
  22462. shapePaths[index] = shapePath;
  22463. angle += angleStep;
  22464. index++;
  22465. }
  22466. // cap
  22467. var capPath = function (shapePath) {
  22468. var pointCap = Array();
  22469. var barycenter = BABYLON.Vector3.Zero();
  22470. var i;
  22471. for (i = 0; i < shapePath.length; i++) {
  22472. barycenter.addInPlace(shapePath[i]);
  22473. }
  22474. barycenter.scaleInPlace(1 / shapePath.length);
  22475. for (i = 0; i < shapePath.length; i++) {
  22476. pointCap.push(barycenter);
  22477. }
  22478. return pointCap;
  22479. };
  22480. switch (cap) {
  22481. case BABYLON.Mesh.NO_CAP:
  22482. break;
  22483. case BABYLON.Mesh.CAP_START:
  22484. shapePaths[0] = capPath(shapePaths[2]);
  22485. shapePaths[1] = shapePaths[2].slice(0);
  22486. break;
  22487. case BABYLON.Mesh.CAP_END:
  22488. shapePaths[index] = shapePaths[index - 1];
  22489. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22490. break;
  22491. case BABYLON.Mesh.CAP_ALL:
  22492. shapePaths[0] = capPath(shapePaths[2]);
  22493. shapePaths[1] = shapePaths[2].slice(0);
  22494. shapePaths[index] = shapePaths[index - 1];
  22495. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22496. break;
  22497. default:
  22498. break;
  22499. }
  22500. return shapePaths;
  22501. };
  22502. var path3D;
  22503. var pathArray;
  22504. if (instance) {
  22505. path3D = (instance.path3D).update(curve);
  22506. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22507. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22508. return instance;
  22509. }
  22510. // extruded shape creation
  22511. path3D = new BABYLON.Path3D(curve);
  22512. var newShapePaths = new Array();
  22513. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22514. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22515. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22516. extrudedGeneric.pathArray = pathArray;
  22517. extrudedGeneric.path3D = path3D;
  22518. extrudedGeneric.cap = cap;
  22519. return extrudedGeneric;
  22520. };
  22521. return MeshBuilder;
  22522. }());
  22523. BABYLON.MeshBuilder = MeshBuilder;
  22524. })(BABYLON || (BABYLON = {}));
  22525. var BABYLON;
  22526. (function (BABYLON) {
  22527. var BaseTexture = (function () {
  22528. function BaseTexture(scene) {
  22529. this.hasAlpha = false;
  22530. this.getAlphaFromRGB = false;
  22531. this.level = 1;
  22532. this.coordinatesIndex = 0;
  22533. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22534. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22535. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22536. this.anisotropicFilteringLevel = 4;
  22537. this.isCube = false;
  22538. this.isRenderTarget = false;
  22539. this.animations = new Array();
  22540. /**
  22541. * An event triggered when the texture is disposed.
  22542. * @type {BABYLON.Observable}
  22543. */
  22544. this.onDisposeObservable = new BABYLON.Observable();
  22545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22546. this._scene = scene;
  22547. this._scene.textures.push(this);
  22548. }
  22549. BaseTexture.prototype.toString = function () {
  22550. return this.name;
  22551. };
  22552. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22553. set: function (callback) {
  22554. if (this._onDisposeObserver) {
  22555. this.onDisposeObservable.remove(this._onDisposeObserver);
  22556. }
  22557. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22558. },
  22559. enumerable: true,
  22560. configurable: true
  22561. });
  22562. BaseTexture.prototype.getScene = function () {
  22563. return this._scene;
  22564. };
  22565. BaseTexture.prototype.getTextureMatrix = function () {
  22566. return null;
  22567. };
  22568. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22569. return null;
  22570. };
  22571. BaseTexture.prototype.getInternalTexture = function () {
  22572. return this._texture;
  22573. };
  22574. BaseTexture.prototype.isReady = function () {
  22575. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22576. return true;
  22577. }
  22578. if (this._texture) {
  22579. return this._texture.isReady;
  22580. }
  22581. return false;
  22582. };
  22583. BaseTexture.prototype.getSize = function () {
  22584. if (this._texture._width) {
  22585. return new BABYLON.Size(this._texture._width, this._texture._height);
  22586. }
  22587. if (this._texture._size) {
  22588. return new BABYLON.Size(this._texture._size, this._texture._size);
  22589. }
  22590. return BABYLON.Size.Zero();
  22591. };
  22592. BaseTexture.prototype.getBaseSize = function () {
  22593. if (!this.isReady() || !this._texture)
  22594. return BABYLON.Size.Zero();
  22595. if (this._texture._size) {
  22596. return new BABYLON.Size(this._texture._size, this._texture._size);
  22597. }
  22598. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22599. };
  22600. BaseTexture.prototype.scale = function (ratio) {
  22601. };
  22602. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22603. get: function () {
  22604. return false;
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22610. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22611. for (var index = 0; index < texturesCache.length; index++) {
  22612. var texturesCacheEntry = texturesCache[index];
  22613. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22614. texturesCache.splice(index, 1);
  22615. return;
  22616. }
  22617. }
  22618. };
  22619. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22620. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22621. for (var index = 0; index < texturesCache.length; index++) {
  22622. var texturesCacheEntry = texturesCache[index];
  22623. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22624. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22625. texturesCacheEntry.references++;
  22626. return texturesCacheEntry;
  22627. }
  22628. }
  22629. }
  22630. return null;
  22631. };
  22632. BaseTexture.prototype.delayLoad = function () {
  22633. };
  22634. BaseTexture.prototype.clone = function () {
  22635. return null;
  22636. };
  22637. BaseTexture.prototype.releaseInternalTexture = function () {
  22638. if (this._texture) {
  22639. this._scene.getEngine().releaseInternalTexture(this._texture);
  22640. delete this._texture;
  22641. }
  22642. };
  22643. BaseTexture.prototype.dispose = function () {
  22644. // Animations
  22645. this.getScene().stopAnimation(this);
  22646. // Remove from scene
  22647. var index = this._scene.textures.indexOf(this);
  22648. if (index >= 0) {
  22649. this._scene.textures.splice(index, 1);
  22650. }
  22651. if (this._texture === undefined) {
  22652. return;
  22653. }
  22654. // Release
  22655. this.releaseInternalTexture();
  22656. // Callback
  22657. this.onDisposeObservable.notifyObservers(this);
  22658. this.onDisposeObservable.clear();
  22659. };
  22660. BaseTexture.prototype.serialize = function () {
  22661. if (!this.name) {
  22662. return null;
  22663. }
  22664. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22665. // Animations
  22666. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22667. return serializationObject;
  22668. };
  22669. __decorate([
  22670. BABYLON.serialize()
  22671. ], BaseTexture.prototype, "name", void 0);
  22672. __decorate([
  22673. BABYLON.serialize()
  22674. ], BaseTexture.prototype, "hasAlpha", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], BaseTexture.prototype, "level", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22684. __decorate([
  22685. BABYLON.serialize()
  22686. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22687. __decorate([
  22688. BABYLON.serialize()
  22689. ], BaseTexture.prototype, "wrapU", void 0);
  22690. __decorate([
  22691. BABYLON.serialize()
  22692. ], BaseTexture.prototype, "wrapV", void 0);
  22693. __decorate([
  22694. BABYLON.serialize()
  22695. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22696. __decorate([
  22697. BABYLON.serialize()
  22698. ], BaseTexture.prototype, "isCube", void 0);
  22699. __decorate([
  22700. BABYLON.serialize()
  22701. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22702. return BaseTexture;
  22703. }());
  22704. BABYLON.BaseTexture = BaseTexture;
  22705. })(BABYLON || (BABYLON = {}));
  22706. var BABYLON;
  22707. (function (BABYLON) {
  22708. var Texture = (function (_super) {
  22709. __extends(Texture, _super);
  22710. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22711. var _this = this;
  22712. if (noMipmap === void 0) { noMipmap = false; }
  22713. if (invertY === void 0) { invertY = true; }
  22714. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22715. if (onLoad === void 0) { onLoad = null; }
  22716. if (onError === void 0) { onError = null; }
  22717. if (buffer === void 0) { buffer = null; }
  22718. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22719. _super.call(this, scene);
  22720. this.uOffset = 0;
  22721. this.vOffset = 0;
  22722. this.uScale = 1.0;
  22723. this.vScale = 1.0;
  22724. this.uAng = 0;
  22725. this.vAng = 0;
  22726. this.wAng = 0;
  22727. this.name = url;
  22728. this.url = url;
  22729. this._noMipmap = noMipmap;
  22730. this._invertY = invertY;
  22731. this._samplingMode = samplingMode;
  22732. this._buffer = buffer;
  22733. this._deleteBuffer = deleteBuffer;
  22734. if (!url) {
  22735. return;
  22736. }
  22737. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22738. var load = function () {
  22739. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22740. _this.onLoadObservable.notifyObservers(true);
  22741. }
  22742. if (onLoad) {
  22743. onLoad();
  22744. }
  22745. };
  22746. if (!this._texture) {
  22747. if (!scene.useDelayedTextureLoading) {
  22748. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22749. if (deleteBuffer) {
  22750. delete this._buffer;
  22751. }
  22752. }
  22753. else {
  22754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22755. this._delayedOnLoad = load;
  22756. this._delayedOnError = onError;
  22757. }
  22758. }
  22759. else {
  22760. if (this._texture.isReady) {
  22761. BABYLON.Tools.SetImmediate(function () { return load(); });
  22762. }
  22763. else {
  22764. this._texture.onLoadedCallbacks.push(load);
  22765. }
  22766. }
  22767. }
  22768. Object.defineProperty(Texture.prototype, "noMipmap", {
  22769. get: function () {
  22770. return this._noMipmap;
  22771. },
  22772. enumerable: true,
  22773. configurable: true
  22774. });
  22775. Texture.prototype.delayLoad = function () {
  22776. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22777. return;
  22778. }
  22779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22780. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22781. if (!this._texture) {
  22782. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22783. if (this._deleteBuffer) {
  22784. delete this._buffer;
  22785. }
  22786. }
  22787. };
  22788. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22789. if (!this._texture) {
  22790. return;
  22791. }
  22792. this._samplingMode = samplingMode;
  22793. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22794. };
  22795. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22796. x *= this.uScale;
  22797. y *= this.vScale;
  22798. x -= 0.5 * this.uScale;
  22799. y -= 0.5 * this.vScale;
  22800. z -= 0.5;
  22801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22802. t.x += 0.5 * this.uScale + this.uOffset;
  22803. t.y += 0.5 * this.vScale + this.vOffset;
  22804. t.z += 0.5;
  22805. };
  22806. Texture.prototype.getTextureMatrix = function () {
  22807. if (this.uOffset === this._cachedUOffset &&
  22808. this.vOffset === this._cachedVOffset &&
  22809. this.uScale === this._cachedUScale &&
  22810. this.vScale === this._cachedVScale &&
  22811. this.uAng === this._cachedUAng &&
  22812. this.vAng === this._cachedVAng &&
  22813. this.wAng === this._cachedWAng) {
  22814. return this._cachedTextureMatrix;
  22815. }
  22816. this._cachedUOffset = this.uOffset;
  22817. this._cachedVOffset = this.vOffset;
  22818. this._cachedUScale = this.uScale;
  22819. this._cachedVScale = this.vScale;
  22820. this._cachedUAng = this.uAng;
  22821. this._cachedVAng = this.vAng;
  22822. this._cachedWAng = this.wAng;
  22823. if (!this._cachedTextureMatrix) {
  22824. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22825. this._rowGenerationMatrix = new BABYLON.Matrix();
  22826. this._t0 = BABYLON.Vector3.Zero();
  22827. this._t1 = BABYLON.Vector3.Zero();
  22828. this._t2 = BABYLON.Vector3.Zero();
  22829. }
  22830. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22831. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22832. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22833. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22834. this._t1.subtractInPlace(this._t0);
  22835. this._t2.subtractInPlace(this._t0);
  22836. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22837. this._cachedTextureMatrix.m[0] = this._t1.x;
  22838. this._cachedTextureMatrix.m[1] = this._t1.y;
  22839. this._cachedTextureMatrix.m[2] = this._t1.z;
  22840. this._cachedTextureMatrix.m[4] = this._t2.x;
  22841. this._cachedTextureMatrix.m[5] = this._t2.y;
  22842. this._cachedTextureMatrix.m[6] = this._t2.z;
  22843. this._cachedTextureMatrix.m[8] = this._t0.x;
  22844. this._cachedTextureMatrix.m[9] = this._t0.y;
  22845. this._cachedTextureMatrix.m[10] = this._t0.z;
  22846. return this._cachedTextureMatrix;
  22847. };
  22848. Texture.prototype.getReflectionTextureMatrix = function () {
  22849. if (this.uOffset === this._cachedUOffset &&
  22850. this.vOffset === this._cachedVOffset &&
  22851. this.uScale === this._cachedUScale &&
  22852. this.vScale === this._cachedVScale &&
  22853. this.coordinatesMode === this._cachedCoordinatesMode) {
  22854. return this._cachedTextureMatrix;
  22855. }
  22856. if (!this._cachedTextureMatrix) {
  22857. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22858. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22859. }
  22860. this._cachedCoordinatesMode = this.coordinatesMode;
  22861. switch (this.coordinatesMode) {
  22862. case Texture.PLANAR_MODE:
  22863. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22864. this._cachedTextureMatrix[0] = this.uScale;
  22865. this._cachedTextureMatrix[5] = this.vScale;
  22866. this._cachedTextureMatrix[12] = this.uOffset;
  22867. this._cachedTextureMatrix[13] = this.vOffset;
  22868. break;
  22869. case Texture.PROJECTION_MODE:
  22870. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22871. this._projectionModeMatrix.m[0] = 0.5;
  22872. this._projectionModeMatrix.m[5] = -0.5;
  22873. this._projectionModeMatrix.m[10] = 0.0;
  22874. this._projectionModeMatrix.m[12] = 0.5;
  22875. this._projectionModeMatrix.m[13] = 0.5;
  22876. this._projectionModeMatrix.m[14] = 1.0;
  22877. this._projectionModeMatrix.m[15] = 1.0;
  22878. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22879. break;
  22880. default:
  22881. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22882. break;
  22883. }
  22884. return this._cachedTextureMatrix;
  22885. };
  22886. Texture.prototype.clone = function () {
  22887. var _this = this;
  22888. return BABYLON.SerializationHelper.Clone(function () {
  22889. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22890. }, this);
  22891. };
  22892. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22893. get: function () {
  22894. if (!this._onLoadObservarble) {
  22895. this._onLoadObservarble = new BABYLON.Observable();
  22896. }
  22897. return this._onLoadObservarble;
  22898. },
  22899. enumerable: true,
  22900. configurable: true
  22901. });
  22902. // Statics
  22903. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22904. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22905. if (onLoad === void 0) { onLoad = null; }
  22906. if (onError === void 0) { onError = null; }
  22907. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22908. };
  22909. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22910. if (parsedTexture.isCube) {
  22911. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22912. }
  22913. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22914. return null;
  22915. }
  22916. var texture = BABYLON.SerializationHelper.Parse(function () {
  22917. if (parsedTexture.customType) {
  22918. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22919. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22920. }
  22921. else if (parsedTexture.mirrorPlane) {
  22922. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22923. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22924. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22925. return mirrorTexture;
  22926. }
  22927. else if (parsedTexture.isRenderTarget) {
  22928. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22929. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22930. return renderTargetTexture;
  22931. }
  22932. else {
  22933. var texture;
  22934. if (parsedTexture.base64String) {
  22935. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22936. }
  22937. else {
  22938. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22939. }
  22940. return texture;
  22941. }
  22942. }, parsedTexture, scene);
  22943. // Animations
  22944. if (parsedTexture.animations) {
  22945. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22946. var parsedAnimation = parsedTexture.animations[animationIndex];
  22947. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22948. }
  22949. }
  22950. return texture;
  22951. };
  22952. // Constants
  22953. Texture.NEAREST_SAMPLINGMODE = 1;
  22954. Texture.BILINEAR_SAMPLINGMODE = 2;
  22955. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22956. Texture.EXPLICIT_MODE = 0;
  22957. Texture.SPHERICAL_MODE = 1;
  22958. Texture.PLANAR_MODE = 2;
  22959. Texture.CUBIC_MODE = 3;
  22960. Texture.PROJECTION_MODE = 4;
  22961. Texture.SKYBOX_MODE = 5;
  22962. Texture.INVCUBIC_MODE = 6;
  22963. Texture.EQUIRECTANGULAR_MODE = 7;
  22964. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22965. Texture.CLAMP_ADDRESSMODE = 0;
  22966. Texture.WRAP_ADDRESSMODE = 1;
  22967. Texture.MIRROR_ADDRESSMODE = 2;
  22968. __decorate([
  22969. BABYLON.serialize()
  22970. ], Texture.prototype, "url", void 0);
  22971. __decorate([
  22972. BABYLON.serialize()
  22973. ], Texture.prototype, "uOffset", void 0);
  22974. __decorate([
  22975. BABYLON.serialize()
  22976. ], Texture.prototype, "vOffset", void 0);
  22977. __decorate([
  22978. BABYLON.serialize()
  22979. ], Texture.prototype, "uScale", void 0);
  22980. __decorate([
  22981. BABYLON.serialize()
  22982. ], Texture.prototype, "vScale", void 0);
  22983. __decorate([
  22984. BABYLON.serialize()
  22985. ], Texture.prototype, "uAng", void 0);
  22986. __decorate([
  22987. BABYLON.serialize()
  22988. ], Texture.prototype, "vAng", void 0);
  22989. __decorate([
  22990. BABYLON.serialize()
  22991. ], Texture.prototype, "wAng", void 0);
  22992. return Texture;
  22993. }(BABYLON.BaseTexture));
  22994. BABYLON.Texture = Texture;
  22995. })(BABYLON || (BABYLON = {}));
  22996. var BABYLON;
  22997. (function (BABYLON) {
  22998. var CubeTexture = (function (_super) {
  22999. __extends(CubeTexture, _super);
  23000. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23001. if (onLoad === void 0) { onLoad = null; }
  23002. if (onError === void 0) { onError = null; }
  23003. _super.call(this, scene);
  23004. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23005. this.name = rootUrl;
  23006. this.url = rootUrl;
  23007. this._noMipmap = noMipmap;
  23008. this.hasAlpha = false;
  23009. if (!rootUrl && !files) {
  23010. return;
  23011. }
  23012. this._texture = this._getFromCache(rootUrl, noMipmap);
  23013. if (!files) {
  23014. if (!extensions) {
  23015. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23016. }
  23017. files = [];
  23018. for (var index = 0; index < extensions.length; index++) {
  23019. files.push(rootUrl + extensions[index]);
  23020. }
  23021. this._extensions = extensions;
  23022. }
  23023. this._files = files;
  23024. if (!this._texture) {
  23025. if (!scene.useDelayedTextureLoading) {
  23026. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23027. }
  23028. else {
  23029. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23030. }
  23031. }
  23032. else {
  23033. if (this._texture.isReady) {
  23034. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23035. }
  23036. else {
  23037. this._texture.onLoadedCallbacks.push(onLoad);
  23038. }
  23039. }
  23040. this.isCube = true;
  23041. this._textureMatrix = BABYLON.Matrix.Identity();
  23042. }
  23043. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23044. return new CubeTexture("", scene, null, noMipmap, files);
  23045. };
  23046. // Methods
  23047. CubeTexture.prototype.delayLoad = function () {
  23048. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23049. return;
  23050. }
  23051. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23052. this._texture = this._getFromCache(this.url, this._noMipmap);
  23053. if (!this._texture) {
  23054. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23055. }
  23056. };
  23057. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23058. return this._textureMatrix;
  23059. };
  23060. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23061. var texture = BABYLON.SerializationHelper.Parse(function () {
  23062. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23063. }, parsedTexture, scene);
  23064. // Animations
  23065. if (parsedTexture.animations) {
  23066. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23067. var parsedAnimation = parsedTexture.animations[animationIndex];
  23068. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23069. }
  23070. }
  23071. return texture;
  23072. };
  23073. CubeTexture.prototype.clone = function () {
  23074. var _this = this;
  23075. return BABYLON.SerializationHelper.Clone(function () {
  23076. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23077. }, this);
  23078. };
  23079. return CubeTexture;
  23080. }(BABYLON.BaseTexture));
  23081. BABYLON.CubeTexture = CubeTexture;
  23082. })(BABYLON || (BABYLON = {}));
  23083. var BABYLON;
  23084. (function (BABYLON) {
  23085. var RenderTargetTexture = (function (_super) {
  23086. __extends(RenderTargetTexture, _super);
  23087. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23088. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23089. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23090. if (isCube === void 0) { isCube = false; }
  23091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23092. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23093. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23094. _super.call(this, null, scene, !generateMipMaps);
  23095. this.isCube = isCube;
  23096. /**
  23097. * Use this list to define the list of mesh you want to render.
  23098. */
  23099. this.renderList = new Array();
  23100. this.renderParticles = true;
  23101. this.renderSprites = false;
  23102. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23103. // Events
  23104. /**
  23105. * An event triggered when the texture is unbind.
  23106. * @type {BABYLON.Observable}
  23107. */
  23108. this.onAfterUnbindObservable = new BABYLON.Observable();
  23109. /**
  23110. * An event triggered before rendering the texture
  23111. * @type {BABYLON.Observable}
  23112. */
  23113. this.onBeforeRenderObservable = new BABYLON.Observable();
  23114. /**
  23115. * An event triggered after rendering the texture
  23116. * @type {BABYLON.Observable}
  23117. */
  23118. this.onAfterRenderObservable = new BABYLON.Observable();
  23119. /**
  23120. * An event triggered after the texture clear
  23121. * @type {BABYLON.Observable}
  23122. */
  23123. this.onClearObservable = new BABYLON.Observable();
  23124. this._currentRefreshId = -1;
  23125. this._refreshRate = 1;
  23126. this.name = name;
  23127. this.isRenderTarget = true;
  23128. this._size = size;
  23129. this._generateMipMaps = generateMipMaps;
  23130. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23131. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23132. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23133. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23134. }
  23135. if (isCube) {
  23136. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23137. generateMipMaps: generateMipMaps,
  23138. samplingMode: samplingMode,
  23139. generateDepthBuffer: generateDepthBuffer,
  23140. generateStencilBuffer: generateStencilBuffer
  23141. });
  23142. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23143. this._textureMatrix = BABYLON.Matrix.Identity();
  23144. }
  23145. else {
  23146. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23147. generateMipMaps: generateMipMaps,
  23148. type: type,
  23149. samplingMode: samplingMode,
  23150. generateDepthBuffer: generateDepthBuffer,
  23151. generateStencilBuffer: generateStencilBuffer
  23152. });
  23153. }
  23154. // Rendering groups
  23155. this._renderingManager = new BABYLON.RenderingManager(scene);
  23156. }
  23157. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23158. get: function () {
  23159. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23160. },
  23161. enumerable: true,
  23162. configurable: true
  23163. });
  23164. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23165. get: function () {
  23166. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23167. },
  23168. enumerable: true,
  23169. configurable: true
  23170. });
  23171. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23172. get: function () {
  23173. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23174. },
  23175. enumerable: true,
  23176. configurable: true
  23177. });
  23178. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23179. set: function (callback) {
  23180. if (this._onAfterUnbindObserver) {
  23181. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23182. }
  23183. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23184. },
  23185. enumerable: true,
  23186. configurable: true
  23187. });
  23188. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23189. set: function (callback) {
  23190. if (this._onBeforeRenderObserver) {
  23191. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23192. }
  23193. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23194. },
  23195. enumerable: true,
  23196. configurable: true
  23197. });
  23198. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23199. set: function (callback) {
  23200. if (this._onAfterRenderObserver) {
  23201. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23202. }
  23203. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23204. },
  23205. enumerable: true,
  23206. configurable: true
  23207. });
  23208. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23209. set: function (callback) {
  23210. if (this._onClearObserver) {
  23211. this.onClearObservable.remove(this._onClearObserver);
  23212. }
  23213. this._onClearObserver = this.onClearObservable.add(callback);
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23219. this._currentRefreshId = -1;
  23220. };
  23221. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23222. get: function () {
  23223. return this._refreshRate;
  23224. },
  23225. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23226. set: function (value) {
  23227. this._refreshRate = value;
  23228. this.resetRefreshCounter();
  23229. },
  23230. enumerable: true,
  23231. configurable: true
  23232. });
  23233. RenderTargetTexture.prototype._shouldRender = function () {
  23234. if (this._currentRefreshId === -1) {
  23235. this._currentRefreshId = 1;
  23236. return true;
  23237. }
  23238. if (this.refreshRate === this._currentRefreshId) {
  23239. this._currentRefreshId = 1;
  23240. return true;
  23241. }
  23242. this._currentRefreshId++;
  23243. return false;
  23244. };
  23245. RenderTargetTexture.prototype.isReady = function () {
  23246. if (!this.getScene().renderTargetsEnabled) {
  23247. return false;
  23248. }
  23249. return _super.prototype.isReady.call(this);
  23250. };
  23251. RenderTargetTexture.prototype.getRenderSize = function () {
  23252. return this._size;
  23253. };
  23254. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23255. get: function () {
  23256. return true;
  23257. },
  23258. enumerable: true,
  23259. configurable: true
  23260. });
  23261. RenderTargetTexture.prototype.scale = function (ratio) {
  23262. var newSize = this._size * ratio;
  23263. this.resize(newSize, this._generateMipMaps);
  23264. };
  23265. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23266. if (this.isCube) {
  23267. return this._textureMatrix;
  23268. }
  23269. return _super.prototype.getReflectionTextureMatrix.call(this);
  23270. };
  23271. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23272. this.releaseInternalTexture();
  23273. if (this.isCube) {
  23274. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23275. }
  23276. else {
  23277. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23278. }
  23279. };
  23280. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23281. var scene = this.getScene();
  23282. if (this.useCameraPostProcesses !== undefined) {
  23283. useCameraPostProcess = this.useCameraPostProcesses;
  23284. }
  23285. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23286. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23287. }
  23288. if (this._waitingRenderList) {
  23289. this.renderList = [];
  23290. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23291. var id = this._waitingRenderList[index];
  23292. this.renderList.push(scene.getMeshByID(id));
  23293. }
  23294. delete this._waitingRenderList;
  23295. }
  23296. // Is predicate defined?
  23297. if (this.renderListPredicate) {
  23298. this.renderList.splice(0); // Clear previous renderList
  23299. var sceneMeshes = this.getScene().meshes;
  23300. for (var index = 0; index < sceneMeshes.length; index++) {
  23301. var mesh = sceneMeshes[index];
  23302. if (this.renderListPredicate(mesh)) {
  23303. this.renderList.push(mesh);
  23304. }
  23305. }
  23306. }
  23307. if (this.renderList && this.renderList.length === 0) {
  23308. return;
  23309. }
  23310. // Prepare renderingManager
  23311. this._renderingManager.reset();
  23312. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23313. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23314. var sceneRenderId = scene.getRenderId();
  23315. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23316. var mesh = currentRenderList[meshIndex];
  23317. if (mesh) {
  23318. if (!mesh.isReady()) {
  23319. // Reset _currentRefreshId
  23320. this.resetRefreshCounter();
  23321. continue;
  23322. }
  23323. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23324. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23325. mesh._activate(sceneRenderId);
  23326. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23327. var subMesh = mesh.subMeshes[subIndex];
  23328. scene._activeIndices.addCount(subMesh.indexCount, false);
  23329. this._renderingManager.dispatch(subMesh);
  23330. }
  23331. }
  23332. }
  23333. }
  23334. if (this.isCube) {
  23335. for (var face = 0; face < 6; face++) {
  23336. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23337. scene.incrementRenderId();
  23338. scene.resetCachedMaterial();
  23339. }
  23340. }
  23341. else {
  23342. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23343. }
  23344. this.onAfterUnbindObservable.notifyObservers(this);
  23345. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23346. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23347. }
  23348. scene.resetCachedMaterial();
  23349. };
  23350. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23351. var scene = this.getScene();
  23352. var engine = scene.getEngine();
  23353. // Bind
  23354. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23355. if (this.isCube) {
  23356. engine.bindFramebuffer(this._texture, faceIndex);
  23357. }
  23358. else {
  23359. engine.bindFramebuffer(this._texture);
  23360. }
  23361. }
  23362. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23363. // Clear
  23364. if (this.onClearObservable.hasObservers()) {
  23365. this.onClearObservable.notifyObservers(engine);
  23366. }
  23367. else {
  23368. engine.clear(scene.clearColor, true, true, true);
  23369. }
  23370. if (!this._doNotChangeAspectRatio) {
  23371. scene.updateTransformMatrix(true);
  23372. }
  23373. // Render
  23374. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23375. if (useCameraPostProcess) {
  23376. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23377. }
  23378. if (!this._doNotChangeAspectRatio) {
  23379. scene.updateTransformMatrix(true);
  23380. }
  23381. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23382. // Dump ?
  23383. if (dumpForDebug) {
  23384. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23385. }
  23386. // Unbind
  23387. if (!this.isCube || faceIndex === 5) {
  23388. if (this.isCube) {
  23389. if (faceIndex === 5) {
  23390. engine.generateMipMapsForCubemap(this._texture);
  23391. }
  23392. }
  23393. engine.unBindFramebuffer(this._texture, this.isCube);
  23394. }
  23395. };
  23396. /**
  23397. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23398. * This allowed control for front to back rendering or reversly depending of the special needs.
  23399. *
  23400. * @param renderingGroupId The rendering group id corresponding to its index
  23401. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23402. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23403. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23404. */
  23405. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23406. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23407. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23408. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23409. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23410. };
  23411. /**
  23412. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23413. *
  23414. * @param renderingGroupId The rendering group id corresponding to its index
  23415. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23416. */
  23417. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23418. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23419. };
  23420. RenderTargetTexture.prototype.clone = function () {
  23421. var textureSize = this.getSize();
  23422. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23423. // Base texture
  23424. newTexture.hasAlpha = this.hasAlpha;
  23425. newTexture.level = this.level;
  23426. // RenderTarget Texture
  23427. newTexture.coordinatesMode = this.coordinatesMode;
  23428. newTexture.renderList = this.renderList.slice(0);
  23429. return newTexture;
  23430. };
  23431. RenderTargetTexture.prototype.serialize = function () {
  23432. if (!this.name) {
  23433. return null;
  23434. }
  23435. var serializationObject = _super.prototype.serialize.call(this);
  23436. serializationObject.renderTargetSize = this.getRenderSize();
  23437. serializationObject.renderList = [];
  23438. for (var index = 0; index < this.renderList.length; index++) {
  23439. serializationObject.renderList.push(this.renderList[index].id);
  23440. }
  23441. return serializationObject;
  23442. };
  23443. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23444. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23445. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23446. return RenderTargetTexture;
  23447. }(BABYLON.Texture));
  23448. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23449. })(BABYLON || (BABYLON = {}));
  23450. var BABYLON;
  23451. (function (BABYLON) {
  23452. var ProceduralTexture = (function (_super) {
  23453. __extends(ProceduralTexture, _super);
  23454. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23455. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23456. if (isCube === void 0) { isCube = false; }
  23457. _super.call(this, null, scene, !generateMipMaps);
  23458. this.isCube = isCube;
  23459. this.isEnabled = true;
  23460. this._currentRefreshId = -1;
  23461. this._refreshRate = 1;
  23462. this._vertexBuffers = {};
  23463. this._uniforms = new Array();
  23464. this._samplers = new Array();
  23465. this._textures = new Array();
  23466. this._floats = new Array();
  23467. this._floatsArrays = {};
  23468. this._colors3 = new Array();
  23469. this._colors4 = new Array();
  23470. this._vectors2 = new Array();
  23471. this._vectors3 = new Array();
  23472. this._matrices = new Array();
  23473. this._fallbackTextureUsed = false;
  23474. scene._proceduralTextures.push(this);
  23475. this.name = name;
  23476. this.isRenderTarget = true;
  23477. this._size = size;
  23478. this._generateMipMaps = generateMipMaps;
  23479. this.setFragment(fragment);
  23480. this._fallbackTexture = fallbackTexture;
  23481. var engine = scene.getEngine();
  23482. if (isCube) {
  23483. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23484. this.setFloat("face", 0);
  23485. }
  23486. else {
  23487. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23488. }
  23489. // VBO
  23490. var vertices = [];
  23491. vertices.push(1, 1);
  23492. vertices.push(-1, 1);
  23493. vertices.push(-1, -1);
  23494. vertices.push(1, -1);
  23495. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23496. // Indices
  23497. var indices = [];
  23498. indices.push(0);
  23499. indices.push(1);
  23500. indices.push(2);
  23501. indices.push(0);
  23502. indices.push(2);
  23503. indices.push(3);
  23504. this._indexBuffer = engine.createIndexBuffer(indices);
  23505. }
  23506. ProceduralTexture.prototype.reset = function () {
  23507. if (this._effect === undefined) {
  23508. return;
  23509. }
  23510. var engine = this.getScene().getEngine();
  23511. engine._releaseEffect(this._effect);
  23512. };
  23513. ProceduralTexture.prototype.isReady = function () {
  23514. var _this = this;
  23515. var engine = this.getScene().getEngine();
  23516. var shaders;
  23517. if (!this._fragment) {
  23518. return false;
  23519. }
  23520. if (this._fallbackTextureUsed) {
  23521. return true;
  23522. }
  23523. if (this._fragment.fragmentElement !== undefined) {
  23524. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23525. }
  23526. else {
  23527. shaders = { vertex: "procedural", fragment: this._fragment };
  23528. }
  23529. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23530. _this.releaseInternalTexture();
  23531. if (_this._fallbackTexture) {
  23532. _this._texture = _this._fallbackTexture._texture;
  23533. _this._texture.references++;
  23534. }
  23535. _this._fallbackTextureUsed = true;
  23536. });
  23537. return this._effect.isReady();
  23538. };
  23539. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23540. this._currentRefreshId = -1;
  23541. };
  23542. ProceduralTexture.prototype.setFragment = function (fragment) {
  23543. this._fragment = fragment;
  23544. };
  23545. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23546. get: function () {
  23547. return this._refreshRate;
  23548. },
  23549. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23550. set: function (value) {
  23551. this._refreshRate = value;
  23552. this.resetRefreshCounter();
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. ProceduralTexture.prototype._shouldRender = function () {
  23558. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23559. return false;
  23560. }
  23561. if (this._fallbackTextureUsed) {
  23562. return false;
  23563. }
  23564. if (this._currentRefreshId === -1) {
  23565. this._currentRefreshId = 1;
  23566. return true;
  23567. }
  23568. if (this.refreshRate === this._currentRefreshId) {
  23569. this._currentRefreshId = 1;
  23570. return true;
  23571. }
  23572. this._currentRefreshId++;
  23573. return false;
  23574. };
  23575. ProceduralTexture.prototype.getRenderSize = function () {
  23576. return this._size;
  23577. };
  23578. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23579. if (this._fallbackTextureUsed) {
  23580. return;
  23581. }
  23582. this.releaseInternalTexture();
  23583. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23584. };
  23585. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23586. if (this._uniforms.indexOf(uniformName) === -1) {
  23587. this._uniforms.push(uniformName);
  23588. }
  23589. };
  23590. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23591. if (this._samplers.indexOf(name) === -1) {
  23592. this._samplers.push(name);
  23593. }
  23594. this._textures[name] = texture;
  23595. return this;
  23596. };
  23597. ProceduralTexture.prototype.setFloat = function (name, value) {
  23598. this._checkUniform(name);
  23599. this._floats[name] = value;
  23600. return this;
  23601. };
  23602. ProceduralTexture.prototype.setFloats = function (name, value) {
  23603. this._checkUniform(name);
  23604. this._floatsArrays[name] = value;
  23605. return this;
  23606. };
  23607. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23608. this._checkUniform(name);
  23609. this._colors3[name] = value;
  23610. return this;
  23611. };
  23612. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23613. this._checkUniform(name);
  23614. this._colors4[name] = value;
  23615. return this;
  23616. };
  23617. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23618. this._checkUniform(name);
  23619. this._vectors2[name] = value;
  23620. return this;
  23621. };
  23622. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23623. this._checkUniform(name);
  23624. this._vectors3[name] = value;
  23625. return this;
  23626. };
  23627. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23628. this._checkUniform(name);
  23629. this._matrices[name] = value;
  23630. return this;
  23631. };
  23632. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23633. var scene = this.getScene();
  23634. var engine = scene.getEngine();
  23635. // Render
  23636. engine.enableEffect(this._effect);
  23637. engine.setState(false);
  23638. // Texture
  23639. for (var name in this._textures) {
  23640. this._effect.setTexture(name, this._textures[name]);
  23641. }
  23642. // Float
  23643. for (name in this._floats) {
  23644. this._effect.setFloat(name, this._floats[name]);
  23645. }
  23646. // Floats
  23647. for (name in this._floatsArrays) {
  23648. this._effect.setArray(name, this._floatsArrays[name]);
  23649. }
  23650. // Color3
  23651. for (name in this._colors3) {
  23652. this._effect.setColor3(name, this._colors3[name]);
  23653. }
  23654. // Color4
  23655. for (name in this._colors4) {
  23656. var color = this._colors4[name];
  23657. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23658. }
  23659. // Vector2
  23660. for (name in this._vectors2) {
  23661. this._effect.setVector2(name, this._vectors2[name]);
  23662. }
  23663. // Vector3
  23664. for (name in this._vectors3) {
  23665. this._effect.setVector3(name, this._vectors3[name]);
  23666. }
  23667. // Matrix
  23668. for (name in this._matrices) {
  23669. this._effect.setMatrix(name, this._matrices[name]);
  23670. }
  23671. // VBOs
  23672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23673. if (this.isCube) {
  23674. for (var face = 0; face < 6; face++) {
  23675. engine.bindFramebuffer(this._texture, face);
  23676. this._effect.setFloat("face", face);
  23677. // Clear
  23678. engine.clear(scene.clearColor, true, true, true);
  23679. // Draw order
  23680. engine.draw(true, 0, 6);
  23681. // Mipmaps
  23682. if (face === 5) {
  23683. engine.generateMipMapsForCubemap(this._texture);
  23684. }
  23685. }
  23686. }
  23687. else {
  23688. engine.bindFramebuffer(this._texture);
  23689. // Clear
  23690. engine.clear(scene.clearColor, true, true, true);
  23691. // Draw order
  23692. engine.draw(true, 0, 6);
  23693. }
  23694. // Unbind
  23695. engine.unBindFramebuffer(this._texture, this.isCube);
  23696. if (this.onGenerated) {
  23697. this.onGenerated();
  23698. }
  23699. };
  23700. ProceduralTexture.prototype.clone = function () {
  23701. var textureSize = this.getSize();
  23702. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23703. // Base texture
  23704. newTexture.hasAlpha = this.hasAlpha;
  23705. newTexture.level = this.level;
  23706. // RenderTarget Texture
  23707. newTexture.coordinatesMode = this.coordinatesMode;
  23708. return newTexture;
  23709. };
  23710. ProceduralTexture.prototype.dispose = function () {
  23711. var index = this.getScene()._proceduralTextures.indexOf(this);
  23712. if (index >= 0) {
  23713. this.getScene()._proceduralTextures.splice(index, 1);
  23714. }
  23715. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23716. if (vertexBuffer) {
  23717. vertexBuffer.dispose();
  23718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23719. }
  23720. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23721. this._indexBuffer = null;
  23722. }
  23723. _super.prototype.dispose.call(this);
  23724. };
  23725. return ProceduralTexture;
  23726. }(BABYLON.Texture));
  23727. BABYLON.ProceduralTexture = ProceduralTexture;
  23728. })(BABYLON || (BABYLON = {}));
  23729. var BABYLON;
  23730. (function (BABYLON) {
  23731. var MirrorTexture = (function (_super) {
  23732. __extends(MirrorTexture, _super);
  23733. function MirrorTexture(name, size, scene, generateMipMaps) {
  23734. var _this = this;
  23735. _super.call(this, name, size, scene, generateMipMaps, true);
  23736. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23737. this._transformMatrix = BABYLON.Matrix.Zero();
  23738. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23739. this.onBeforeRenderObservable.add(function () {
  23740. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23741. _this._savedViewMatrix = scene.getViewMatrix();
  23742. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23743. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23744. scene.clipPlane = _this.mirrorPlane;
  23745. scene.getEngine().cullBackFaces = false;
  23746. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23747. });
  23748. this.onAfterRenderObservable.add(function () {
  23749. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23750. scene.getEngine().cullBackFaces = true;
  23751. scene._mirroredCameraPosition = null;
  23752. delete scene.clipPlane;
  23753. });
  23754. }
  23755. MirrorTexture.prototype.clone = function () {
  23756. var textureSize = this.getSize();
  23757. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23758. // Base texture
  23759. newTexture.hasAlpha = this.hasAlpha;
  23760. newTexture.level = this.level;
  23761. // Mirror Texture
  23762. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23763. newTexture.renderList = this.renderList.slice(0);
  23764. return newTexture;
  23765. };
  23766. MirrorTexture.prototype.serialize = function () {
  23767. if (!this.name) {
  23768. return null;
  23769. }
  23770. var serializationObject = _super.prototype.serialize.call(this);
  23771. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23772. return serializationObject;
  23773. };
  23774. return MirrorTexture;
  23775. }(BABYLON.RenderTargetTexture));
  23776. BABYLON.MirrorTexture = MirrorTexture;
  23777. })(BABYLON || (BABYLON = {}));
  23778. var BABYLON;
  23779. (function (BABYLON) {
  23780. /**
  23781. * Creates a refraction texture used by refraction channel of the standard material.
  23782. * @param name the texture name
  23783. * @param size size of the underlying texture
  23784. * @param scene root scene
  23785. */
  23786. var RefractionTexture = (function (_super) {
  23787. __extends(RefractionTexture, _super);
  23788. function RefractionTexture(name, size, scene, generateMipMaps) {
  23789. var _this = this;
  23790. _super.call(this, name, size, scene, generateMipMaps, true);
  23791. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23792. this.depth = 2.0;
  23793. this.onBeforeRenderObservable.add(function () {
  23794. scene.clipPlane = _this.refractionPlane;
  23795. });
  23796. this.onAfterRenderObservable.add(function () {
  23797. delete scene.clipPlane;
  23798. });
  23799. }
  23800. RefractionTexture.prototype.clone = function () {
  23801. var textureSize = this.getSize();
  23802. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23803. // Base texture
  23804. newTexture.hasAlpha = this.hasAlpha;
  23805. newTexture.level = this.level;
  23806. // Refraction Texture
  23807. newTexture.refractionPlane = this.refractionPlane.clone();
  23808. newTexture.renderList = this.renderList.slice(0);
  23809. newTexture.depth = this.depth;
  23810. return newTexture;
  23811. };
  23812. RefractionTexture.prototype.serialize = function () {
  23813. if (!this.name) {
  23814. return null;
  23815. }
  23816. var serializationObject = _super.prototype.serialize.call(this);
  23817. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23818. serializationObject.depth = this.depth;
  23819. return serializationObject;
  23820. };
  23821. return RefractionTexture;
  23822. }(BABYLON.RenderTargetTexture));
  23823. BABYLON.RefractionTexture = RefractionTexture;
  23824. })(BABYLON || (BABYLON = {}));
  23825. var BABYLON;
  23826. (function (BABYLON) {
  23827. var DynamicTexture = (function (_super) {
  23828. __extends(DynamicTexture, _super);
  23829. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23831. _super.call(this, null, scene, !generateMipMaps);
  23832. this.name = name;
  23833. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23834. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23835. this._generateMipMaps = generateMipMaps;
  23836. if (options.getContext) {
  23837. this._canvas = options;
  23838. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23839. }
  23840. else {
  23841. this._canvas = document.createElement("canvas");
  23842. if (options.width) {
  23843. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23844. }
  23845. else {
  23846. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23847. }
  23848. }
  23849. var textureSize = this.getSize();
  23850. this._canvas.width = textureSize.width;
  23851. this._canvas.height = textureSize.height;
  23852. this._context = this._canvas.getContext("2d");
  23853. }
  23854. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23855. get: function () {
  23856. return true;
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. DynamicTexture.prototype.scale = function (ratio) {
  23862. var textureSize = this.getSize();
  23863. textureSize.width *= ratio;
  23864. textureSize.height *= ratio;
  23865. this._canvas.width = textureSize.width;
  23866. this._canvas.height = textureSize.height;
  23867. this.releaseInternalTexture();
  23868. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23869. };
  23870. DynamicTexture.prototype.getContext = function () {
  23871. return this._context;
  23872. };
  23873. DynamicTexture.prototype.clear = function () {
  23874. var size = this.getSize();
  23875. this._context.fillRect(0, 0, size.width, size.height);
  23876. };
  23877. DynamicTexture.prototype.update = function (invertY) {
  23878. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23879. };
  23880. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23881. if (update === void 0) { update = true; }
  23882. var size = this.getSize();
  23883. if (clearColor) {
  23884. this._context.fillStyle = clearColor;
  23885. this._context.fillRect(0, 0, size.width, size.height);
  23886. }
  23887. this._context.font = font;
  23888. if (x === null) {
  23889. var textSize = this._context.measureText(text);
  23890. x = (size.width - textSize.width) / 2;
  23891. }
  23892. this._context.fillStyle = color;
  23893. this._context.fillText(text, x, y);
  23894. if (update) {
  23895. this.update(invertY);
  23896. }
  23897. };
  23898. DynamicTexture.prototype.clone = function () {
  23899. var textureSize = this.getSize();
  23900. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23901. // Base texture
  23902. newTexture.hasAlpha = this.hasAlpha;
  23903. newTexture.level = this.level;
  23904. // Dynamic Texture
  23905. newTexture.wrapU = this.wrapU;
  23906. newTexture.wrapV = this.wrapV;
  23907. return newTexture;
  23908. };
  23909. return DynamicTexture;
  23910. }(BABYLON.Texture));
  23911. BABYLON.DynamicTexture = DynamicTexture;
  23912. })(BABYLON || (BABYLON = {}));
  23913. var BABYLON;
  23914. (function (BABYLON) {
  23915. var VideoTexture = (function (_super) {
  23916. __extends(VideoTexture, _super);
  23917. /**
  23918. * Creates a video texture.
  23919. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23920. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23921. * @param {BABYLON.Scene} scene is obviously the current scene.
  23922. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23923. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23924. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23925. */
  23926. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23927. var _this = this;
  23928. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23929. if (invertY === void 0) { invertY = false; }
  23930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23931. _super.call(this, null, scene, !generateMipMaps, invertY);
  23932. this._autoLaunch = true;
  23933. var urls;
  23934. this.name = name;
  23935. if (urlsOrVideo instanceof HTMLVideoElement) {
  23936. this.video = urlsOrVideo;
  23937. }
  23938. else {
  23939. urls = urlsOrVideo;
  23940. this.video = document.createElement("video");
  23941. this.video.autoplay = false;
  23942. this.video.loop = true;
  23943. }
  23944. this._generateMipMaps = generateMipMaps;
  23945. this._samplingMode = samplingMode;
  23946. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23947. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23948. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23949. }
  23950. else {
  23951. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23952. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23953. this._generateMipMaps = false;
  23954. }
  23955. if (urls) {
  23956. this.video.addEventListener("canplaythrough", function () {
  23957. _this._createTexture();
  23958. });
  23959. urls.forEach(function (url) {
  23960. var source = document.createElement("source");
  23961. source.src = url;
  23962. _this.video.appendChild(source);
  23963. });
  23964. }
  23965. else {
  23966. this._createTexture();
  23967. }
  23968. this._lastUpdate = BABYLON.Tools.Now;
  23969. }
  23970. VideoTexture.prototype._createTexture = function () {
  23971. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23972. this._texture.isReady = true;
  23973. };
  23974. VideoTexture.prototype.update = function () {
  23975. if (this._autoLaunch) {
  23976. this._autoLaunch = false;
  23977. this.video.play();
  23978. }
  23979. var now = BABYLON.Tools.Now;
  23980. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23981. return false;
  23982. }
  23983. this._lastUpdate = now;
  23984. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23985. return true;
  23986. };
  23987. return VideoTexture;
  23988. }(BABYLON.Texture));
  23989. BABYLON.VideoTexture = VideoTexture;
  23990. })(BABYLON || (BABYLON = {}));
  23991. var BABYLON;
  23992. (function (BABYLON) {
  23993. var CustomProceduralTexture = (function (_super) {
  23994. __extends(CustomProceduralTexture, _super);
  23995. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23996. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23997. this._animate = true;
  23998. this._time = 0;
  23999. this._texturePath = texturePath;
  24000. //Try to load json
  24001. this.loadJson(texturePath);
  24002. this.refreshRate = 1;
  24003. }
  24004. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24005. var _this = this;
  24006. var that = this;
  24007. function noConfigFile() {
  24008. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24009. try {
  24010. that.setFragment(that._texturePath);
  24011. }
  24012. catch (ex) {
  24013. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24014. }
  24015. }
  24016. var configFileUrl = jsonUrl + "/config.json";
  24017. var xhr = new XMLHttpRequest();
  24018. xhr.open("GET", configFileUrl, true);
  24019. xhr.addEventListener("load", function () {
  24020. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24021. try {
  24022. _this._config = JSON.parse(xhr.response);
  24023. _this.updateShaderUniforms();
  24024. _this.updateTextures();
  24025. _this.setFragment(_this._texturePath + "/custom");
  24026. _this._animate = _this._config.animate;
  24027. _this.refreshRate = _this._config.refreshrate;
  24028. }
  24029. catch (ex) {
  24030. noConfigFile();
  24031. }
  24032. }
  24033. else {
  24034. noConfigFile();
  24035. }
  24036. }, false);
  24037. xhr.addEventListener("error", function () {
  24038. noConfigFile();
  24039. }, false);
  24040. try {
  24041. xhr.send();
  24042. }
  24043. catch (ex) {
  24044. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24045. }
  24046. };
  24047. CustomProceduralTexture.prototype.isReady = function () {
  24048. if (!_super.prototype.isReady.call(this)) {
  24049. return false;
  24050. }
  24051. for (var name in this._textures) {
  24052. var texture = this._textures[name];
  24053. if (!texture.isReady()) {
  24054. return false;
  24055. }
  24056. }
  24057. return true;
  24058. };
  24059. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24060. if (this._animate) {
  24061. this._time += this.getScene().getAnimationRatio() * 0.03;
  24062. this.updateShaderUniforms();
  24063. }
  24064. _super.prototype.render.call(this, useCameraPostProcess);
  24065. };
  24066. CustomProceduralTexture.prototype.updateTextures = function () {
  24067. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24068. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24069. }
  24070. };
  24071. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24072. if (this._config) {
  24073. for (var j = 0; j < this._config.uniforms.length; j++) {
  24074. var uniform = this._config.uniforms[j];
  24075. switch (uniform.type) {
  24076. case "float":
  24077. this.setFloat(uniform.name, uniform.value);
  24078. break;
  24079. case "color3":
  24080. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24081. break;
  24082. case "color4":
  24083. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24084. break;
  24085. case "vector2":
  24086. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24087. break;
  24088. case "vector3":
  24089. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24090. break;
  24091. }
  24092. }
  24093. }
  24094. this.setFloat("time", this._time);
  24095. };
  24096. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24097. get: function () {
  24098. return this._animate;
  24099. },
  24100. set: function (value) {
  24101. this._animate = value;
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. return CustomProceduralTexture;
  24107. }(BABYLON.ProceduralTexture));
  24108. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24109. })(BABYLON || (BABYLON = {}));
  24110. var BABYLON;
  24111. (function (BABYLON) {
  24112. var EffectFallbacks = (function () {
  24113. function EffectFallbacks() {
  24114. this._defines = {};
  24115. this._currentRank = 32;
  24116. this._maxRank = -1;
  24117. }
  24118. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24119. if (!this._defines[rank]) {
  24120. if (rank < this._currentRank) {
  24121. this._currentRank = rank;
  24122. }
  24123. if (rank > this._maxRank) {
  24124. this._maxRank = rank;
  24125. }
  24126. this._defines[rank] = new Array();
  24127. }
  24128. this._defines[rank].push(define);
  24129. };
  24130. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24131. this._meshRank = rank;
  24132. this._mesh = mesh;
  24133. if (rank > this._maxRank) {
  24134. this._maxRank = rank;
  24135. }
  24136. };
  24137. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24138. get: function () {
  24139. return this._currentRank <= this._maxRank;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24145. var currentFallbacks = this._defines[this._currentRank];
  24146. for (var index = 0; index < currentFallbacks.length; index++) {
  24147. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24148. }
  24149. if (this._mesh && this._currentRank === this._meshRank) {
  24150. this._mesh.computeBonesUsingShaders = false;
  24151. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24152. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24153. }
  24154. this._currentRank++;
  24155. return currentDefines;
  24156. };
  24157. return EffectFallbacks;
  24158. }());
  24159. BABYLON.EffectFallbacks = EffectFallbacks;
  24160. var Effect = (function () {
  24161. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24162. var _this = this;
  24163. this._isReady = false;
  24164. this._compilationError = "";
  24165. this._valueCache = {};
  24166. this._engine = engine;
  24167. this.name = baseName;
  24168. this.defines = defines;
  24169. this._uniformsNames = uniformsNames.concat(samplers);
  24170. this._samplers = samplers;
  24171. this._attributesNames = attributesNames;
  24172. this.onError = onError;
  24173. this.onCompiled = onCompiled;
  24174. this._indexParameters = indexParameters;
  24175. var vertexSource;
  24176. var fragmentSource;
  24177. if (baseName.vertexElement) {
  24178. vertexSource = document.getElementById(baseName.vertexElement);
  24179. if (!vertexSource) {
  24180. vertexSource = baseName.vertexElement;
  24181. }
  24182. }
  24183. else {
  24184. vertexSource = baseName.vertex || baseName;
  24185. }
  24186. if (baseName.fragmentElement) {
  24187. fragmentSource = document.getElementById(baseName.fragmentElement);
  24188. if (!fragmentSource) {
  24189. fragmentSource = baseName.fragmentElement;
  24190. }
  24191. }
  24192. else {
  24193. fragmentSource = baseName.fragment || baseName;
  24194. }
  24195. this._loadVertexShader(vertexSource, function (vertexCode) {
  24196. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24197. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24198. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24199. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24200. });
  24201. });
  24202. });
  24203. });
  24204. }
  24205. // Properties
  24206. Effect.prototype.isReady = function () {
  24207. return this._isReady;
  24208. };
  24209. Effect.prototype.getProgram = function () {
  24210. return this._program;
  24211. };
  24212. Effect.prototype.getAttributesNames = function () {
  24213. return this._attributesNames;
  24214. };
  24215. Effect.prototype.getAttributeLocation = function (index) {
  24216. return this._attributes[index];
  24217. };
  24218. Effect.prototype.getAttributeLocationByName = function (name) {
  24219. var index = this._attributesNames.indexOf(name);
  24220. return this._attributes[index];
  24221. };
  24222. Effect.prototype.getAttributesCount = function () {
  24223. return this._attributes.length;
  24224. };
  24225. Effect.prototype.getUniformIndex = function (uniformName) {
  24226. return this._uniformsNames.indexOf(uniformName);
  24227. };
  24228. Effect.prototype.getUniform = function (uniformName) {
  24229. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24230. };
  24231. Effect.prototype.getSamplers = function () {
  24232. return this._samplers;
  24233. };
  24234. Effect.prototype.getCompilationError = function () {
  24235. return this._compilationError;
  24236. };
  24237. // Methods
  24238. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24239. // DOM element ?
  24240. if (vertex instanceof HTMLElement) {
  24241. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24242. callback(vertexCode);
  24243. return;
  24244. }
  24245. // Is in local store ?
  24246. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24247. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24248. return;
  24249. }
  24250. var vertexShaderUrl;
  24251. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24252. vertexShaderUrl = vertex;
  24253. }
  24254. else {
  24255. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24256. }
  24257. // Vertex shader
  24258. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24259. };
  24260. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24261. // DOM element ?
  24262. if (fragment instanceof HTMLElement) {
  24263. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24264. callback(fragmentCode);
  24265. return;
  24266. }
  24267. // Is in local store ?
  24268. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24269. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24270. return;
  24271. }
  24272. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24273. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24274. return;
  24275. }
  24276. var fragmentShaderUrl;
  24277. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24278. fragmentShaderUrl = fragment;
  24279. }
  24280. else {
  24281. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24282. }
  24283. // Fragment shader
  24284. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24285. };
  24286. Effect.prototype._dumpShadersName = function () {
  24287. if (this.name.vertexElement) {
  24288. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24289. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24290. }
  24291. else if (this.name.vertex) {
  24292. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24293. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24294. }
  24295. else {
  24296. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24297. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24298. }
  24299. };
  24300. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24301. var _this = this;
  24302. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24303. var match = regex.exec(sourceCode);
  24304. var returnValue = new String(sourceCode);
  24305. while (match != null) {
  24306. var includeFile = match[1];
  24307. if (Effect.IncludesShadersStore[includeFile]) {
  24308. // Substitution
  24309. var includeContent = Effect.IncludesShadersStore[includeFile];
  24310. if (match[2]) {
  24311. var splits = match[3].split(",");
  24312. for (var index = 0; index < splits.length; index += 2) {
  24313. var source = new RegExp(splits[index], "g");
  24314. var dest = splits[index + 1];
  24315. includeContent = includeContent.replace(source, dest);
  24316. }
  24317. }
  24318. if (match[4]) {
  24319. var indexString = match[5];
  24320. if (indexString.indexOf("..") !== -1) {
  24321. var indexSplits = indexString.split("..");
  24322. var minIndex = parseInt(indexSplits[0]);
  24323. var maxIndex = parseInt(indexSplits[1]);
  24324. var sourceIncludeContent = includeContent.slice(0);
  24325. includeContent = "";
  24326. if (isNaN(maxIndex)) {
  24327. maxIndex = this._indexParameters[indexSplits[1]];
  24328. }
  24329. for (var i = minIndex; i <= maxIndex; i++) {
  24330. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24331. }
  24332. }
  24333. else {
  24334. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24335. }
  24336. }
  24337. // Replace
  24338. returnValue = returnValue.replace(match[0], includeContent);
  24339. }
  24340. else {
  24341. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24342. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24343. Effect.IncludesShadersStore[includeFile] = fileContent;
  24344. _this._processIncludes(returnValue, callback);
  24345. });
  24346. return;
  24347. }
  24348. match = regex.exec(sourceCode);
  24349. }
  24350. callback(returnValue);
  24351. };
  24352. Effect.prototype._processPrecision = function (source) {
  24353. if (source.indexOf("precision highp float") === -1) {
  24354. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24355. source = "precision mediump float;\n" + source;
  24356. }
  24357. else {
  24358. source = "precision highp float;\n" + source;
  24359. }
  24360. }
  24361. else {
  24362. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24363. source = source.replace("precision highp float", "precision mediump float");
  24364. }
  24365. }
  24366. return source;
  24367. };
  24368. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24369. try {
  24370. var engine = this._engine;
  24371. // Precision
  24372. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24373. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24374. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24375. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24376. this._attributes = engine.getAttributes(this._program, attributesNames);
  24377. var index;
  24378. for (index = 0; index < this._samplers.length; index++) {
  24379. var sampler = this.getUniform(this._samplers[index]);
  24380. if (sampler == null) {
  24381. this._samplers.splice(index, 1);
  24382. index--;
  24383. }
  24384. }
  24385. engine.bindSamplers(this);
  24386. this._isReady = true;
  24387. if (this.onCompiled) {
  24388. this.onCompiled(this);
  24389. }
  24390. }
  24391. catch (e) {
  24392. // Let's go through fallbacks then
  24393. if (fallbacks && fallbacks.isMoreFallbacks) {
  24394. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24395. this._dumpShadersName();
  24396. defines = fallbacks.reduce(defines);
  24397. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24398. }
  24399. else {
  24400. BABYLON.Tools.Error("Unable to compile effect: ");
  24401. this._dumpShadersName();
  24402. BABYLON.Tools.Error("Defines: " + defines);
  24403. BABYLON.Tools.Error("Error: " + e.message);
  24404. this._compilationError = e.message;
  24405. if (this.onError) {
  24406. this.onError(this, this._compilationError);
  24407. }
  24408. }
  24409. }
  24410. };
  24411. Object.defineProperty(Effect.prototype, "isSupported", {
  24412. get: function () {
  24413. return this._compilationError === "";
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. Effect.prototype._bindTexture = function (channel, texture) {
  24419. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24420. };
  24421. Effect.prototype.setTexture = function (channel, texture) {
  24422. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24423. };
  24424. Effect.prototype.setTextureArray = function (channel, textures) {
  24425. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24426. var initialPos = this._samplers.indexOf(channel);
  24427. for (var index = 1; index < textures.length; index++) {
  24428. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24429. }
  24430. }
  24431. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24432. };
  24433. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24434. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24435. };
  24436. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24437. var changed = false;
  24438. var cache = this._valueCache[uniformName];
  24439. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24440. changed = true;
  24441. cache = new BABYLON.Matrix();
  24442. }
  24443. var tm = cache.m;
  24444. var om = matrix.m;
  24445. for (var index = 0; index < 16; index++) {
  24446. if (tm[index] !== om[index]) {
  24447. tm[index] = om[index];
  24448. changed = true;
  24449. }
  24450. }
  24451. this._valueCache[uniformName] = cache;
  24452. return changed;
  24453. };
  24454. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24455. var cache = this._valueCache[uniformName];
  24456. if (!cache) {
  24457. cache = [x, y];
  24458. this._valueCache[uniformName] = cache;
  24459. return true;
  24460. }
  24461. var changed = false;
  24462. if (cache[0] !== x) {
  24463. cache[0] = x;
  24464. changed = true;
  24465. }
  24466. if (cache[1] !== y) {
  24467. cache[1] = y;
  24468. changed = true;
  24469. }
  24470. return changed;
  24471. };
  24472. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24473. var cache = this._valueCache[uniformName];
  24474. if (!cache) {
  24475. cache = [x, y, z];
  24476. this._valueCache[uniformName] = cache;
  24477. return true;
  24478. }
  24479. var changed = false;
  24480. if (cache[0] !== x) {
  24481. cache[0] = x;
  24482. changed = true;
  24483. }
  24484. if (cache[1] !== y) {
  24485. cache[1] = y;
  24486. changed = true;
  24487. }
  24488. if (cache[2] !== z) {
  24489. cache[2] = z;
  24490. changed = true;
  24491. }
  24492. return changed;
  24493. };
  24494. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24495. var cache = this._valueCache[uniformName];
  24496. if (!cache) {
  24497. cache = [x, y, z, w];
  24498. this._valueCache[uniformName] = cache;
  24499. return true;
  24500. }
  24501. var changed = false;
  24502. if (cache[0] !== x) {
  24503. cache[0] = x;
  24504. changed = true;
  24505. }
  24506. if (cache[1] !== y) {
  24507. cache[1] = y;
  24508. changed = true;
  24509. }
  24510. if (cache[2] !== z) {
  24511. cache[2] = z;
  24512. changed = true;
  24513. }
  24514. if (cache[3] !== w) {
  24515. cache[3] = w;
  24516. changed = true;
  24517. }
  24518. return changed;
  24519. };
  24520. Effect.prototype.setIntArray = function (uniformName, array) {
  24521. this._valueCache[uniformName] = null;
  24522. this._engine.setIntArray(this.getUniform(uniformName), array);
  24523. return this;
  24524. };
  24525. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24526. this._valueCache[uniformName] = null;
  24527. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24528. return this;
  24529. };
  24530. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24531. this._valueCache[uniformName] = null;
  24532. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24533. return this;
  24534. };
  24535. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24536. this._valueCache[uniformName] = null;
  24537. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24538. return this;
  24539. };
  24540. Effect.prototype.setFloatArray = function (uniformName, array) {
  24541. this._valueCache[uniformName] = null;
  24542. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24543. return this;
  24544. };
  24545. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24546. this._valueCache[uniformName] = null;
  24547. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24548. return this;
  24549. };
  24550. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24551. this._valueCache[uniformName] = null;
  24552. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24553. return this;
  24554. };
  24555. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24556. this._valueCache[uniformName] = null;
  24557. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24558. return this;
  24559. };
  24560. Effect.prototype.setArray = function (uniformName, array) {
  24561. this._valueCache[uniformName] = null;
  24562. this._engine.setArray(this.getUniform(uniformName), array);
  24563. return this;
  24564. };
  24565. Effect.prototype.setArray2 = function (uniformName, array) {
  24566. this._valueCache[uniformName] = null;
  24567. this._engine.setArray2(this.getUniform(uniformName), array);
  24568. return this;
  24569. };
  24570. Effect.prototype.setArray3 = function (uniformName, array) {
  24571. this._valueCache[uniformName] = null;
  24572. this._engine.setArray3(this.getUniform(uniformName), array);
  24573. return this;
  24574. };
  24575. Effect.prototype.setArray4 = function (uniformName, array) {
  24576. this._valueCache[uniformName] = null;
  24577. this._engine.setArray4(this.getUniform(uniformName), array);
  24578. return this;
  24579. };
  24580. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24581. this._valueCache[uniformName] = null;
  24582. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24583. return this;
  24584. };
  24585. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24586. if (this._cacheMatrix(uniformName, matrix)) {
  24587. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24588. }
  24589. return this;
  24590. };
  24591. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24592. this._valueCache[uniformName] = null;
  24593. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24594. return this;
  24595. };
  24596. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24597. this._valueCache[uniformName] = null;
  24598. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24599. return this;
  24600. };
  24601. Effect.prototype.setFloat = function (uniformName, value) {
  24602. var cache = this._valueCache[uniformName];
  24603. if (cache !== undefined && cache === value)
  24604. return this;
  24605. this._valueCache[uniformName] = value;
  24606. this._engine.setFloat(this.getUniform(uniformName), value);
  24607. return this;
  24608. };
  24609. Effect.prototype.setBool = function (uniformName, bool) {
  24610. var cache = this._valueCache[uniformName];
  24611. if (cache !== undefined && cache === bool)
  24612. return this;
  24613. this._valueCache[uniformName] = bool;
  24614. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24615. return this;
  24616. };
  24617. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24618. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24619. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24620. }
  24621. return this;
  24622. };
  24623. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24624. if (this._cacheFloat2(uniformName, x, y)) {
  24625. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24626. }
  24627. return this;
  24628. };
  24629. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24630. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24631. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24632. }
  24633. return this;
  24634. };
  24635. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24636. if (this._cacheFloat3(uniformName, x, y, z)) {
  24637. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24638. }
  24639. return this;
  24640. };
  24641. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24642. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24643. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24644. }
  24645. return this;
  24646. };
  24647. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24648. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24649. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24650. }
  24651. return this;
  24652. };
  24653. Effect.prototype.setColor3 = function (uniformName, color3) {
  24654. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24655. this._engine.setColor3(this.getUniform(uniformName), color3);
  24656. }
  24657. return this;
  24658. };
  24659. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24660. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24661. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24662. }
  24663. return this;
  24664. };
  24665. // Statics
  24666. Effect.ShadersStore = {};
  24667. Effect.IncludesShadersStore = {};
  24668. return Effect;
  24669. }());
  24670. BABYLON.Effect = Effect;
  24671. })(BABYLON || (BABYLON = {}));
  24672. var BABYLON;
  24673. (function (BABYLON) {
  24674. var MaterialHelper = (function () {
  24675. function MaterialHelper() {
  24676. }
  24677. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24678. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24679. var lightIndex = 0;
  24680. var needNormals = false;
  24681. var needRebuild = false;
  24682. var needShadows = false;
  24683. var lightmapMode = false;
  24684. for (var index = 0; index < scene.lights.length; index++) {
  24685. var light = scene.lights[index];
  24686. if (!light.isEnabled()) {
  24687. continue;
  24688. }
  24689. // Excluded check
  24690. if (light._excludedMeshesIds.length > 0) {
  24691. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24692. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24693. if (excludedMesh) {
  24694. light.excludedMeshes.push(excludedMesh);
  24695. }
  24696. }
  24697. light._excludedMeshesIds = [];
  24698. }
  24699. // Included check
  24700. if (light._includedOnlyMeshesIds.length > 0) {
  24701. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24702. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24703. if (includedOnlyMesh) {
  24704. light.includedOnlyMeshes.push(includedOnlyMesh);
  24705. }
  24706. }
  24707. light._includedOnlyMeshesIds = [];
  24708. }
  24709. if (!light.canAffectMesh(mesh)) {
  24710. continue;
  24711. }
  24712. needNormals = true;
  24713. if (defines["LIGHT" + lightIndex] === undefined) {
  24714. needRebuild = true;
  24715. }
  24716. defines["LIGHT" + lightIndex] = true;
  24717. var type;
  24718. if (light instanceof BABYLON.SpotLight) {
  24719. type = "SPOTLIGHT" + lightIndex;
  24720. }
  24721. else if (light instanceof BABYLON.HemisphericLight) {
  24722. type = "HEMILIGHT" + lightIndex;
  24723. }
  24724. else if (light instanceof BABYLON.PointLight) {
  24725. type = "POINTLIGHT" + lightIndex;
  24726. }
  24727. else {
  24728. type = "DIRLIGHT" + lightIndex;
  24729. }
  24730. if (defines[type] === undefined) {
  24731. needRebuild = true;
  24732. }
  24733. defines[type] = true;
  24734. // Specular
  24735. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24736. defines["SPECULARTERM"] = true;
  24737. }
  24738. // Shadows
  24739. if (scene.shadowsEnabled) {
  24740. var shadowGenerator = light.getShadowGenerator();
  24741. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24742. if (defines["SHADOW" + lightIndex] === undefined) {
  24743. needRebuild = true;
  24744. }
  24745. defines["SHADOW" + lightIndex] = true;
  24746. defines["SHADOWS"] = true;
  24747. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24748. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24749. needRebuild = true;
  24750. }
  24751. defines["SHADOWVSM" + lightIndex] = true;
  24752. }
  24753. if (shadowGenerator.usePoissonSampling) {
  24754. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24755. needRebuild = true;
  24756. }
  24757. defines["SHADOWPCF" + lightIndex] = true;
  24758. }
  24759. needShadows = true;
  24760. }
  24761. }
  24762. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24763. lightmapMode = true;
  24764. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24765. needRebuild = true;
  24766. }
  24767. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24768. needRebuild = true;
  24769. }
  24770. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24771. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24772. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24773. }
  24774. }
  24775. lightIndex++;
  24776. if (lightIndex === maxSimultaneousLights)
  24777. break;
  24778. }
  24779. var caps = scene.getEngine().getCaps();
  24780. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24781. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24782. needRebuild = true;
  24783. }
  24784. defines["SHADOWFULLFLOAT"] = true;
  24785. }
  24786. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24787. needRebuild = true;
  24788. }
  24789. if (lightmapMode) {
  24790. defines["LIGHTMAPEXCLUDED"] = true;
  24791. }
  24792. if (needRebuild) {
  24793. defines.rebuild();
  24794. }
  24795. return needNormals;
  24796. };
  24797. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24798. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24799. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24800. if (!defines["LIGHT" + lightIndex]) {
  24801. break;
  24802. }
  24803. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24804. samplersList.push("shadowSampler" + lightIndex);
  24805. }
  24806. };
  24807. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24808. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24809. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24810. if (!defines["LIGHT" + lightIndex]) {
  24811. break;
  24812. }
  24813. if (lightIndex > 0) {
  24814. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24815. }
  24816. if (defines["SHADOW" + lightIndex]) {
  24817. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24818. }
  24819. if (defines["SHADOWPCF" + lightIndex]) {
  24820. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24821. }
  24822. if (defines["SHADOWVSM" + lightIndex]) {
  24823. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24824. }
  24825. }
  24826. };
  24827. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24828. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24829. fallbacks.addCPUSkinningFallback(0, mesh);
  24830. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24831. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24832. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24833. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24834. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24835. }
  24836. }
  24837. };
  24838. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24839. if (defines["INSTANCES"]) {
  24840. attribs.push("world0");
  24841. attribs.push("world1");
  24842. attribs.push("world2");
  24843. attribs.push("world3");
  24844. }
  24845. };
  24846. // Bindings
  24847. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24848. var shadowGenerator = light.getShadowGenerator();
  24849. if (mesh.receiveShadows && shadowGenerator) {
  24850. if (!light.needCube()) {
  24851. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24852. }
  24853. else {
  24854. if (!depthValuesAlreadySet) {
  24855. depthValuesAlreadySet = true;
  24856. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24857. }
  24858. }
  24859. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24860. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24861. }
  24862. return depthValuesAlreadySet;
  24863. };
  24864. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24865. if (light instanceof BABYLON.PointLight) {
  24866. // Point Light
  24867. light.transferToEffect(effect, "vLightData" + lightIndex);
  24868. }
  24869. else if (light instanceof BABYLON.DirectionalLight) {
  24870. // Directional Light
  24871. light.transferToEffect(effect, "vLightData" + lightIndex);
  24872. }
  24873. else if (light instanceof BABYLON.SpotLight) {
  24874. // Spot Light
  24875. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24876. }
  24877. else if (light instanceof BABYLON.HemisphericLight) {
  24878. // Hemispheric Light
  24879. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24880. }
  24881. };
  24882. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24883. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24884. var lightIndex = 0;
  24885. var depthValuesAlreadySet = false;
  24886. for (var index = 0; index < scene.lights.length; index++) {
  24887. var light = scene.lights[index];
  24888. if (!light.isEnabled()) {
  24889. continue;
  24890. }
  24891. if (!light.canAffectMesh(mesh)) {
  24892. continue;
  24893. }
  24894. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24895. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24896. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24897. if (defines["SPECULARTERM"]) {
  24898. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24899. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24900. }
  24901. // Shadows
  24902. if (scene.shadowsEnabled) {
  24903. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24904. }
  24905. lightIndex++;
  24906. if (lightIndex === maxSimultaneousLights)
  24907. break;
  24908. }
  24909. };
  24910. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24911. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24912. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24913. effect.setColor3("vFogColor", scene.fogColor);
  24914. }
  24915. };
  24916. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24917. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24918. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24919. }
  24920. };
  24921. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24922. if (defines["LOGARITHMICDEPTH"]) {
  24923. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24924. }
  24925. };
  24926. MaterialHelper.BindClipPlane = function (effect, scene) {
  24927. if (scene.clipPlane) {
  24928. var clipPlane = scene.clipPlane;
  24929. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24930. }
  24931. };
  24932. return MaterialHelper;
  24933. }());
  24934. BABYLON.MaterialHelper = MaterialHelper;
  24935. })(BABYLON || (BABYLON = {}));
  24936. var BABYLON;
  24937. (function (BABYLON) {
  24938. var FresnelParameters = (function () {
  24939. function FresnelParameters() {
  24940. this.isEnabled = true;
  24941. this.leftColor = BABYLON.Color3.White();
  24942. this.rightColor = BABYLON.Color3.Black();
  24943. this.bias = 0;
  24944. this.power = 1;
  24945. }
  24946. FresnelParameters.prototype.clone = function () {
  24947. var newFresnelParameters = new FresnelParameters();
  24948. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24949. return new FresnelParameters;
  24950. };
  24951. FresnelParameters.prototype.serialize = function () {
  24952. var serializationObject = {};
  24953. serializationObject.isEnabled = this.isEnabled;
  24954. serializationObject.leftColor = this.leftColor;
  24955. serializationObject.rightColor = this.rightColor;
  24956. serializationObject.bias = this.bias;
  24957. serializationObject.power = this.power;
  24958. return serializationObject;
  24959. };
  24960. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24961. var fresnelParameters = new FresnelParameters();
  24962. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24963. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24964. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24965. fresnelParameters.bias = parsedFresnelParameters.bias;
  24966. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24967. return fresnelParameters;
  24968. };
  24969. return FresnelParameters;
  24970. }());
  24971. BABYLON.FresnelParameters = FresnelParameters;
  24972. })(BABYLON || (BABYLON = {}));
  24973. var BABYLON;
  24974. (function (BABYLON) {
  24975. var MaterialDefines = (function () {
  24976. function MaterialDefines() {
  24977. }
  24978. MaterialDefines.prototype.rebuild = function () {
  24979. if (this._keys) {
  24980. delete this._keys;
  24981. }
  24982. this._keys = Object.keys(this);
  24983. };
  24984. MaterialDefines.prototype.isEqual = function (other) {
  24985. if (this._keys.length !== other._keys.length) {
  24986. return false;
  24987. }
  24988. for (var index = 0; index < this._keys.length; index++) {
  24989. var prop = this._keys[index];
  24990. if (this[prop] !== other[prop]) {
  24991. return false;
  24992. }
  24993. }
  24994. return true;
  24995. };
  24996. MaterialDefines.prototype.cloneTo = function (other) {
  24997. if (this._keys.length !== other._keys.length) {
  24998. other._keys = this._keys.slice(0);
  24999. }
  25000. for (var index = 0; index < this._keys.length; index++) {
  25001. var prop = this._keys[index];
  25002. other[prop] = this[prop];
  25003. }
  25004. };
  25005. MaterialDefines.prototype.reset = function () {
  25006. for (var index = 0; index < this._keys.length; index++) {
  25007. var prop = this._keys[index];
  25008. if (typeof (this[prop]) === "number") {
  25009. this[prop] = 0;
  25010. }
  25011. else {
  25012. this[prop] = false;
  25013. }
  25014. }
  25015. };
  25016. MaterialDefines.prototype.toString = function () {
  25017. var result = "";
  25018. for (var index = 0; index < this._keys.length; index++) {
  25019. var prop = this._keys[index];
  25020. if (typeof (this[prop]) === "number") {
  25021. result += "#define " + prop + " " + this[prop] + "\n";
  25022. }
  25023. else if (this[prop]) {
  25024. result += "#define " + prop + "\n";
  25025. }
  25026. }
  25027. return result;
  25028. };
  25029. return MaterialDefines;
  25030. }());
  25031. BABYLON.MaterialDefines = MaterialDefines;
  25032. var Material = (function () {
  25033. function Material(name, scene, doNotAdd) {
  25034. this.name = name;
  25035. this.checkReadyOnEveryCall = false;
  25036. this.checkReadyOnlyOnce = false;
  25037. this.state = "";
  25038. this.alpha = 1.0;
  25039. this.backFaceCulling = true;
  25040. /**
  25041. * An event triggered when the material is disposed.
  25042. * @type {BABYLON.Observable}
  25043. */
  25044. this.onDisposeObservable = new BABYLON.Observable();
  25045. /**
  25046. * An event triggered when the material is bound.
  25047. * @type {BABYLON.Observable}
  25048. */
  25049. this.onBindObservable = new BABYLON.Observable();
  25050. /**
  25051. * An event triggered when the material is unbound.
  25052. * @type {BABYLON.Observable}
  25053. */
  25054. this.onUnBindObservable = new BABYLON.Observable();
  25055. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25056. this.disableDepthWrite = false;
  25057. this.fogEnabled = true;
  25058. this.pointSize = 1.0;
  25059. this.zOffset = 0;
  25060. this._wasPreviouslyReady = false;
  25061. this._fillMode = Material.TriangleFillMode;
  25062. this.id = name;
  25063. this._scene = scene;
  25064. if (scene.useRightHandedSystem) {
  25065. this.sideOrientation = Material.ClockWiseSideOrientation;
  25066. }
  25067. else {
  25068. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25069. }
  25070. if (!doNotAdd) {
  25071. scene.materials.push(this);
  25072. }
  25073. }
  25074. Object.defineProperty(Material, "TriangleFillMode", {
  25075. get: function () {
  25076. return Material._TriangleFillMode;
  25077. },
  25078. enumerable: true,
  25079. configurable: true
  25080. });
  25081. Object.defineProperty(Material, "WireFrameFillMode", {
  25082. get: function () {
  25083. return Material._WireFrameFillMode;
  25084. },
  25085. enumerable: true,
  25086. configurable: true
  25087. });
  25088. Object.defineProperty(Material, "PointFillMode", {
  25089. get: function () {
  25090. return Material._PointFillMode;
  25091. },
  25092. enumerable: true,
  25093. configurable: true
  25094. });
  25095. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25096. get: function () {
  25097. return Material._ClockWiseSideOrientation;
  25098. },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25103. get: function () {
  25104. return Material._CounterClockWiseSideOrientation;
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. Object.defineProperty(Material.prototype, "onDispose", {
  25110. set: function (callback) {
  25111. if (this._onDisposeObserver) {
  25112. this.onDisposeObservable.remove(this._onDisposeObserver);
  25113. }
  25114. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. Object.defineProperty(Material.prototype, "onBind", {
  25120. set: function (callback) {
  25121. if (this._onBindObserver) {
  25122. this.onBindObservable.remove(this._onBindObserver);
  25123. }
  25124. this._onBindObserver = this.onBindObservable.add(callback);
  25125. },
  25126. enumerable: true,
  25127. configurable: true
  25128. });
  25129. Object.defineProperty(Material.prototype, "wireframe", {
  25130. get: function () {
  25131. return this._fillMode === Material.WireFrameFillMode;
  25132. },
  25133. set: function (value) {
  25134. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. Object.defineProperty(Material.prototype, "pointsCloud", {
  25140. get: function () {
  25141. return this._fillMode === Material.PointFillMode;
  25142. },
  25143. set: function (value) {
  25144. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25145. },
  25146. enumerable: true,
  25147. configurable: true
  25148. });
  25149. Object.defineProperty(Material.prototype, "fillMode", {
  25150. get: function () {
  25151. return this._fillMode;
  25152. },
  25153. set: function (value) {
  25154. this._fillMode = value;
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. /**
  25160. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25161. * subclasses should override adding information pertainent to themselves
  25162. */
  25163. Material.prototype.toString = function (fullDetails) {
  25164. var ret = "Name: " + this.name;
  25165. if (fullDetails) {
  25166. }
  25167. return ret;
  25168. };
  25169. Object.defineProperty(Material.prototype, "isFrozen", {
  25170. get: function () {
  25171. return this.checkReadyOnlyOnce;
  25172. },
  25173. enumerable: true,
  25174. configurable: true
  25175. });
  25176. Material.prototype.freeze = function () {
  25177. this.checkReadyOnlyOnce = true;
  25178. };
  25179. Material.prototype.unfreeze = function () {
  25180. this.checkReadyOnlyOnce = false;
  25181. };
  25182. Material.prototype.isReady = function (mesh, useInstances) {
  25183. return true;
  25184. };
  25185. Material.prototype.getEffect = function () {
  25186. return this._effect;
  25187. };
  25188. Material.prototype.getScene = function () {
  25189. return this._scene;
  25190. };
  25191. Material.prototype.needAlphaBlending = function () {
  25192. return (this.alpha < 1.0);
  25193. };
  25194. Material.prototype.needAlphaTesting = function () {
  25195. return false;
  25196. };
  25197. Material.prototype.getAlphaTestTexture = function () {
  25198. return null;
  25199. };
  25200. Material.prototype.markDirty = function () {
  25201. this._wasPreviouslyReady = false;
  25202. };
  25203. Material.prototype._preBind = function () {
  25204. var engine = this._scene.getEngine();
  25205. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25206. engine.enableEffect(this._effect);
  25207. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25208. };
  25209. Material.prototype.bind = function (world, mesh) {
  25210. this._scene._cachedMaterial = this;
  25211. this.onBindObservable.notifyObservers(mesh);
  25212. if (this.disableDepthWrite) {
  25213. var engine = this._scene.getEngine();
  25214. this._cachedDepthWriteState = engine.getDepthWrite();
  25215. engine.setDepthWrite(false);
  25216. }
  25217. };
  25218. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25219. };
  25220. Material.prototype.unbind = function () {
  25221. this.onUnBindObservable.notifyObservers(this);
  25222. if (this.disableDepthWrite) {
  25223. var engine = this._scene.getEngine();
  25224. engine.setDepthWrite(this._cachedDepthWriteState);
  25225. }
  25226. };
  25227. Material.prototype.clone = function (name) {
  25228. return null;
  25229. };
  25230. Material.prototype.getBindedMeshes = function () {
  25231. var result = new Array();
  25232. for (var index = 0; index < this._scene.meshes.length; index++) {
  25233. var mesh = this._scene.meshes[index];
  25234. if (mesh.material === this) {
  25235. result.push(mesh);
  25236. }
  25237. }
  25238. return result;
  25239. };
  25240. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25241. // Animations
  25242. this.getScene().stopAnimation(this);
  25243. // Remove from scene
  25244. var index = this._scene.materials.indexOf(this);
  25245. if (index >= 0) {
  25246. this._scene.materials.splice(index, 1);
  25247. }
  25248. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25249. if (forceDisposeEffect && this._effect) {
  25250. this._scene.getEngine()._releaseEffect(this._effect);
  25251. this._effect = null;
  25252. }
  25253. // Remove from meshes
  25254. for (index = 0; index < this._scene.meshes.length; index++) {
  25255. var mesh = this._scene.meshes[index];
  25256. if (mesh.material === this) {
  25257. mesh.material = null;
  25258. }
  25259. }
  25260. // Callback
  25261. this.onDisposeObservable.notifyObservers(this);
  25262. this.onDisposeObservable.clear();
  25263. this.onBindObservable.clear();
  25264. this.onUnBindObservable.clear();
  25265. };
  25266. Material.prototype.serialize = function () {
  25267. return BABYLON.SerializationHelper.Serialize(this);
  25268. };
  25269. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25270. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25271. multiMaterial.id = parsedMultiMaterial.id;
  25272. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25273. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25274. var subMatId = parsedMultiMaterial.materials[matIndex];
  25275. if (subMatId) {
  25276. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25277. }
  25278. else {
  25279. multiMaterial.subMaterials.push(null);
  25280. }
  25281. }
  25282. return multiMaterial;
  25283. };
  25284. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25285. if (!parsedMaterial.customType) {
  25286. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25287. }
  25288. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25289. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25290. ;
  25291. };
  25292. Material._TriangleFillMode = 0;
  25293. Material._WireFrameFillMode = 1;
  25294. Material._PointFillMode = 2;
  25295. Material._ClockWiseSideOrientation = 0;
  25296. Material._CounterClockWiseSideOrientation = 1;
  25297. __decorate([
  25298. BABYLON.serialize()
  25299. ], Material.prototype, "id", void 0);
  25300. __decorate([
  25301. BABYLON.serialize()
  25302. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25303. __decorate([
  25304. BABYLON.serialize()
  25305. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25306. __decorate([
  25307. BABYLON.serialize()
  25308. ], Material.prototype, "state", void 0);
  25309. __decorate([
  25310. BABYLON.serialize()
  25311. ], Material.prototype, "alpha", void 0);
  25312. __decorate([
  25313. BABYLON.serialize()
  25314. ], Material.prototype, "backFaceCulling", void 0);
  25315. __decorate([
  25316. BABYLON.serialize()
  25317. ], Material.prototype, "sideOrientation", void 0);
  25318. __decorate([
  25319. BABYLON.serialize()
  25320. ], Material.prototype, "alphaMode", void 0);
  25321. __decorate([
  25322. BABYLON.serialize()
  25323. ], Material.prototype, "disableDepthWrite", void 0);
  25324. __decorate([
  25325. BABYLON.serialize()
  25326. ], Material.prototype, "fogEnabled", void 0);
  25327. __decorate([
  25328. BABYLON.serialize()
  25329. ], Material.prototype, "pointSize", void 0);
  25330. __decorate([
  25331. BABYLON.serialize()
  25332. ], Material.prototype, "zOffset", void 0);
  25333. __decorate([
  25334. BABYLON.serialize()
  25335. ], Material.prototype, "wireframe", null);
  25336. __decorate([
  25337. BABYLON.serialize()
  25338. ], Material.prototype, "pointsCloud", null);
  25339. __decorate([
  25340. BABYLON.serialize()
  25341. ], Material.prototype, "fillMode", null);
  25342. return Material;
  25343. }());
  25344. BABYLON.Material = Material;
  25345. })(BABYLON || (BABYLON = {}));
  25346. var BABYLON;
  25347. (function (BABYLON) {
  25348. var StandardMaterialDefines = (function (_super) {
  25349. __extends(StandardMaterialDefines, _super);
  25350. function StandardMaterialDefines() {
  25351. _super.call(this);
  25352. this.DIFFUSE = false;
  25353. this.AMBIENT = false;
  25354. this.OPACITY = false;
  25355. this.OPACITYRGB = false;
  25356. this.REFLECTION = false;
  25357. this.EMISSIVE = false;
  25358. this.SPECULAR = false;
  25359. this.BUMP = false;
  25360. this.PARALLAX = false;
  25361. this.PARALLAXOCCLUSION = false;
  25362. this.SPECULAROVERALPHA = false;
  25363. this.CLIPPLANE = false;
  25364. this.ALPHATEST = false;
  25365. this.ALPHAFROMDIFFUSE = false;
  25366. this.POINTSIZE = false;
  25367. this.FOG = false;
  25368. this.SPECULARTERM = false;
  25369. this.DIFFUSEFRESNEL = false;
  25370. this.OPACITYFRESNEL = false;
  25371. this.REFLECTIONFRESNEL = false;
  25372. this.REFRACTIONFRESNEL = false;
  25373. this.EMISSIVEFRESNEL = false;
  25374. this.FRESNEL = false;
  25375. this.NORMAL = false;
  25376. this.UV1 = false;
  25377. this.UV2 = false;
  25378. this.VERTEXCOLOR = false;
  25379. this.VERTEXALPHA = false;
  25380. this.NUM_BONE_INFLUENCERS = 0;
  25381. this.BonesPerMesh = 0;
  25382. this.INSTANCES = false;
  25383. this.GLOSSINESS = false;
  25384. this.ROUGHNESS = false;
  25385. this.EMISSIVEASILLUMINATION = false;
  25386. this.LINKEMISSIVEWITHDIFFUSE = false;
  25387. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25388. this.LIGHTMAP = false;
  25389. this.USELIGHTMAPASSHADOWMAP = false;
  25390. this.REFLECTIONMAP_3D = false;
  25391. this.REFLECTIONMAP_SPHERICAL = false;
  25392. this.REFLECTIONMAP_PLANAR = false;
  25393. this.REFLECTIONMAP_CUBIC = false;
  25394. this.REFLECTIONMAP_PROJECTION = false;
  25395. this.REFLECTIONMAP_SKYBOX = false;
  25396. this.REFLECTIONMAP_EXPLICIT = false;
  25397. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25398. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25399. this.INVERTCUBICMAP = false;
  25400. this.LOGARITHMICDEPTH = false;
  25401. this.REFRACTION = false;
  25402. this.REFRACTIONMAP_3D = false;
  25403. this.REFLECTIONOVERALPHA = false;
  25404. this.INVERTNORMALMAPX = false;
  25405. this.INVERTNORMALMAPY = false;
  25406. this.SHADOWFULLFLOAT = false;
  25407. this.CAMERACOLORGRADING = false;
  25408. this.CAMERACOLORCURVES = false;
  25409. this.rebuild();
  25410. }
  25411. return StandardMaterialDefines;
  25412. }(BABYLON.MaterialDefines));
  25413. var StandardMaterial = (function (_super) {
  25414. __extends(StandardMaterial, _super);
  25415. function StandardMaterial(name, scene) {
  25416. var _this = this;
  25417. _super.call(this, name, scene);
  25418. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25419. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25420. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25421. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25422. this.specularPower = 64;
  25423. this.useAlphaFromDiffuseTexture = false;
  25424. this.useEmissiveAsIllumination = false;
  25425. this.linkEmissiveWithDiffuse = false;
  25426. this.useReflectionFresnelFromSpecular = false;
  25427. this.useSpecularOverAlpha = false;
  25428. this.useReflectionOverAlpha = false;
  25429. this.disableLighting = false;
  25430. this.useParallax = false;
  25431. this.useParallaxOcclusion = false;
  25432. this.parallaxScaleBias = 0.05;
  25433. this.roughness = 0;
  25434. this.indexOfRefraction = 0.98;
  25435. this.invertRefractionY = true;
  25436. this.useLightmapAsShadowmap = false;
  25437. this.useGlossinessFromSpecularMapAlpha = false;
  25438. this.maxSimultaneousLights = 4;
  25439. /**
  25440. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25441. */
  25442. this.invertNormalMapX = false;
  25443. /**
  25444. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25445. */
  25446. this.invertNormalMapY = false;
  25447. /**
  25448. * Color Grading 2D Lookup Texture.
  25449. * This allows special effects like sepia, black and white to sixties rendering style.
  25450. */
  25451. this.cameraColorGradingTexture = null;
  25452. /**
  25453. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25454. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25455. * 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;
  25456. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25457. */
  25458. this.cameraColorCurves = null;
  25459. this._renderTargets = new BABYLON.SmartArray(16);
  25460. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25461. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25462. this._defines = new StandardMaterialDefines();
  25463. this._cachedDefines = new StandardMaterialDefines();
  25464. this._cachedDefines.BonesPerMesh = -1;
  25465. this.getRenderTargetTextures = function () {
  25466. _this._renderTargets.reset();
  25467. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25468. _this._renderTargets.push(_this.reflectionTexture);
  25469. }
  25470. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25471. _this._renderTargets.push(_this.refractionTexture);
  25472. }
  25473. return _this._renderTargets;
  25474. };
  25475. }
  25476. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25477. get: function () {
  25478. return this._useLogarithmicDepth;
  25479. },
  25480. set: function (value) {
  25481. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25482. },
  25483. enumerable: true,
  25484. configurable: true
  25485. });
  25486. StandardMaterial.prototype.needAlphaBlending = function () {
  25487. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25488. };
  25489. StandardMaterial.prototype.needAlphaTesting = function () {
  25490. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25491. };
  25492. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25493. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25494. };
  25495. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25496. return this.diffuseTexture;
  25497. };
  25498. // Methods
  25499. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25500. if (!mesh) {
  25501. return true;
  25502. }
  25503. if (this._defines.INSTANCES !== useInstances) {
  25504. return false;
  25505. }
  25506. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25507. return true;
  25508. }
  25509. return false;
  25510. };
  25511. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25512. if (this.isFrozen) {
  25513. if (this._wasPreviouslyReady) {
  25514. return true;
  25515. }
  25516. }
  25517. var scene = this.getScene();
  25518. if (!this.checkReadyOnEveryCall) {
  25519. if (this._renderId === scene.getRenderId()) {
  25520. if (this._checkCache(scene, mesh, useInstances)) {
  25521. return true;
  25522. }
  25523. }
  25524. }
  25525. var engine = scene.getEngine();
  25526. var needNormals = false;
  25527. var needUVs = false;
  25528. this._defines.reset();
  25529. // Textures
  25530. if (scene.texturesEnabled) {
  25531. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25532. if (!this.diffuseTexture.isReady()) {
  25533. return false;
  25534. }
  25535. else {
  25536. needUVs = true;
  25537. this._defines.DIFFUSE = true;
  25538. }
  25539. }
  25540. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25541. if (!this.ambientTexture.isReady()) {
  25542. return false;
  25543. }
  25544. else {
  25545. needUVs = true;
  25546. this._defines.AMBIENT = true;
  25547. }
  25548. }
  25549. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25550. if (!this.opacityTexture.isReady()) {
  25551. return false;
  25552. }
  25553. else {
  25554. needUVs = true;
  25555. this._defines.OPACITY = true;
  25556. if (this.opacityTexture.getAlphaFromRGB) {
  25557. this._defines.OPACITYRGB = true;
  25558. }
  25559. }
  25560. }
  25561. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25562. if (!this.reflectionTexture.isReady()) {
  25563. return false;
  25564. }
  25565. else {
  25566. needNormals = true;
  25567. this._defines.REFLECTION = true;
  25568. if (this.roughness > 0) {
  25569. this._defines.ROUGHNESS = true;
  25570. }
  25571. if (this.useReflectionOverAlpha) {
  25572. this._defines.REFLECTIONOVERALPHA = true;
  25573. }
  25574. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25575. this._defines.INVERTCUBICMAP = true;
  25576. }
  25577. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25578. switch (this.reflectionTexture.coordinatesMode) {
  25579. case BABYLON.Texture.CUBIC_MODE:
  25580. case BABYLON.Texture.INVCUBIC_MODE:
  25581. this._defines.REFLECTIONMAP_CUBIC = true;
  25582. break;
  25583. case BABYLON.Texture.EXPLICIT_MODE:
  25584. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25585. break;
  25586. case BABYLON.Texture.PLANAR_MODE:
  25587. this._defines.REFLECTIONMAP_PLANAR = true;
  25588. break;
  25589. case BABYLON.Texture.PROJECTION_MODE:
  25590. this._defines.REFLECTIONMAP_PROJECTION = true;
  25591. break;
  25592. case BABYLON.Texture.SKYBOX_MODE:
  25593. this._defines.REFLECTIONMAP_SKYBOX = true;
  25594. break;
  25595. case BABYLON.Texture.SPHERICAL_MODE:
  25596. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25597. break;
  25598. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25599. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25600. break;
  25601. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25602. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25603. break;
  25604. }
  25605. }
  25606. }
  25607. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25608. if (!this.emissiveTexture.isReady()) {
  25609. return false;
  25610. }
  25611. else {
  25612. needUVs = true;
  25613. this._defines.EMISSIVE = true;
  25614. }
  25615. }
  25616. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25617. if (!this.lightmapTexture.isReady()) {
  25618. return false;
  25619. }
  25620. else {
  25621. needUVs = true;
  25622. this._defines.LIGHTMAP = true;
  25623. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25624. }
  25625. }
  25626. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25627. if (!this.specularTexture.isReady()) {
  25628. return false;
  25629. }
  25630. else {
  25631. needUVs = true;
  25632. this._defines.SPECULAR = true;
  25633. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25634. }
  25635. }
  25636. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25637. if (!this.bumpTexture.isReady()) {
  25638. return false;
  25639. }
  25640. else {
  25641. needUVs = true;
  25642. this._defines.BUMP = true;
  25643. if (this.useParallax) {
  25644. this._defines.PARALLAX = true;
  25645. if (this.useParallaxOcclusion) {
  25646. this._defines.PARALLAXOCCLUSION = true;
  25647. }
  25648. }
  25649. if (this.invertNormalMapX) {
  25650. this._defines.INVERTNORMALMAPX = true;
  25651. }
  25652. if (this.invertNormalMapY) {
  25653. this._defines.INVERTNORMALMAPY = true;
  25654. }
  25655. }
  25656. }
  25657. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25658. if (!this.refractionTexture.isReady()) {
  25659. return false;
  25660. }
  25661. else {
  25662. needUVs = true;
  25663. this._defines.REFRACTION = true;
  25664. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25665. }
  25666. }
  25667. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25668. if (!this.cameraColorGradingTexture.isReady()) {
  25669. return false;
  25670. }
  25671. else {
  25672. this._defines.CAMERACOLORGRADING = true;
  25673. }
  25674. }
  25675. }
  25676. // Effect
  25677. if (scene.clipPlane) {
  25678. this._defines.CLIPPLANE = true;
  25679. }
  25680. if (engine.getAlphaTesting()) {
  25681. this._defines.ALPHATEST = true;
  25682. }
  25683. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25684. this._defines.ALPHAFROMDIFFUSE = true;
  25685. }
  25686. if (this.useEmissiveAsIllumination) {
  25687. this._defines.EMISSIVEASILLUMINATION = true;
  25688. }
  25689. if (this.linkEmissiveWithDiffuse) {
  25690. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25691. }
  25692. if (this.useLogarithmicDepth) {
  25693. this._defines.LOGARITHMICDEPTH = true;
  25694. }
  25695. if (this.cameraColorCurves) {
  25696. this._defines.CAMERACOLORCURVES = true;
  25697. }
  25698. // Point size
  25699. if (this.pointsCloud || scene.forcePointsCloud) {
  25700. this._defines.POINTSIZE = true;
  25701. }
  25702. // Fog
  25703. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25704. this._defines.FOG = true;
  25705. }
  25706. if (scene.lightsEnabled && !this.disableLighting) {
  25707. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25708. }
  25709. if (StandardMaterial.FresnelEnabled) {
  25710. // Fresnel
  25711. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25712. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25713. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25714. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25715. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25716. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25717. this._defines.DIFFUSEFRESNEL = true;
  25718. }
  25719. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25720. this._defines.OPACITYFRESNEL = true;
  25721. }
  25722. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25723. this._defines.REFLECTIONFRESNEL = true;
  25724. if (this.useReflectionFresnelFromSpecular) {
  25725. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25726. }
  25727. }
  25728. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25729. this._defines.REFRACTIONFRESNEL = true;
  25730. }
  25731. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25732. this._defines.EMISSIVEFRESNEL = true;
  25733. }
  25734. needNormals = true;
  25735. this._defines.FRESNEL = true;
  25736. }
  25737. }
  25738. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25739. this._defines.SPECULAROVERALPHA = true;
  25740. }
  25741. // Attribs
  25742. if (mesh) {
  25743. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25744. this._defines.NORMAL = true;
  25745. }
  25746. if (needUVs) {
  25747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25748. this._defines.UV1 = true;
  25749. }
  25750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25751. this._defines.UV2 = true;
  25752. }
  25753. }
  25754. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25755. this._defines.VERTEXCOLOR = true;
  25756. if (mesh.hasVertexAlpha) {
  25757. this._defines.VERTEXALPHA = true;
  25758. }
  25759. }
  25760. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25761. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25762. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25763. }
  25764. // Instances
  25765. if (useInstances) {
  25766. this._defines.INSTANCES = true;
  25767. }
  25768. }
  25769. // Get correct effect
  25770. if (!this._defines.isEqual(this._cachedDefines)) {
  25771. this._defines.cloneTo(this._cachedDefines);
  25772. scene.resetCachedMaterial();
  25773. // Fallbacks
  25774. var fallbacks = new BABYLON.EffectFallbacks();
  25775. if (this._defines.REFLECTION) {
  25776. fallbacks.addFallback(0, "REFLECTION");
  25777. }
  25778. if (this._defines.SPECULAR) {
  25779. fallbacks.addFallback(0, "SPECULAR");
  25780. }
  25781. if (this._defines.BUMP) {
  25782. fallbacks.addFallback(0, "BUMP");
  25783. }
  25784. if (this._defines.PARALLAX) {
  25785. fallbacks.addFallback(1, "PARALLAX");
  25786. }
  25787. if (this._defines.PARALLAXOCCLUSION) {
  25788. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25789. }
  25790. if (this._defines.SPECULAROVERALPHA) {
  25791. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25792. }
  25793. if (this._defines.FOG) {
  25794. fallbacks.addFallback(1, "FOG");
  25795. }
  25796. if (this._defines.POINTSIZE) {
  25797. fallbacks.addFallback(0, "POINTSIZE");
  25798. }
  25799. if (this._defines.LOGARITHMICDEPTH) {
  25800. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25801. }
  25802. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25803. if (this._defines.SPECULARTERM) {
  25804. fallbacks.addFallback(0, "SPECULARTERM");
  25805. }
  25806. if (this._defines.DIFFUSEFRESNEL) {
  25807. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25808. }
  25809. if (this._defines.OPACITYFRESNEL) {
  25810. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25811. }
  25812. if (this._defines.REFLECTIONFRESNEL) {
  25813. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25814. }
  25815. if (this._defines.EMISSIVEFRESNEL) {
  25816. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25817. }
  25818. if (this._defines.FRESNEL) {
  25819. fallbacks.addFallback(4, "FRESNEL");
  25820. }
  25821. //Attributes
  25822. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25823. if (this._defines.NORMAL) {
  25824. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25825. }
  25826. if (this._defines.UV1) {
  25827. attribs.push(BABYLON.VertexBuffer.UVKind);
  25828. }
  25829. if (this._defines.UV2) {
  25830. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25831. }
  25832. if (this._defines.VERTEXCOLOR) {
  25833. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25834. }
  25835. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25836. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25837. var shaderName = "default";
  25838. var join = this._defines.toString();
  25839. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25840. "vFogInfos", "vFogColor", "pointSize",
  25841. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25842. "mBones",
  25843. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25844. "depthValues",
  25845. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25846. "logarithmicDepthConstant"
  25847. ];
  25848. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25849. if (this._defines.CAMERACOLORCURVES) {
  25850. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25851. }
  25852. if (this._defines.CAMERACOLORGRADING) {
  25853. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25854. }
  25855. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25856. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25857. }
  25858. if (!this._effect.isReady()) {
  25859. return false;
  25860. }
  25861. this._renderId = scene.getRenderId();
  25862. this._wasPreviouslyReady = true;
  25863. if (mesh) {
  25864. if (!mesh._materialDefines) {
  25865. mesh._materialDefines = new StandardMaterialDefines();
  25866. }
  25867. this._defines.cloneTo(mesh._materialDefines);
  25868. }
  25869. return true;
  25870. };
  25871. StandardMaterial.prototype.unbind = function () {
  25872. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25873. this._effect.setTexture("reflection2DSampler", null);
  25874. }
  25875. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25876. this._effect.setTexture("refraction2DSampler", null);
  25877. }
  25878. _super.prototype.unbind.call(this);
  25879. };
  25880. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25881. this._effect.setMatrix("world", world);
  25882. };
  25883. StandardMaterial.prototype.bind = function (world, mesh) {
  25884. var scene = this.getScene();
  25885. // Matrices
  25886. this.bindOnlyWorldMatrix(world);
  25887. // Bones
  25888. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25889. if (scene.getCachedMaterial() !== this) {
  25890. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25891. if (StandardMaterial.FresnelEnabled) {
  25892. // Fresnel
  25893. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25894. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25895. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25896. }
  25897. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25898. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25899. }
  25900. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25901. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25902. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25903. }
  25904. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25905. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25906. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25907. }
  25908. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25909. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25910. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25911. }
  25912. }
  25913. // Textures
  25914. if (scene.texturesEnabled) {
  25915. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25916. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25917. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25918. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25919. }
  25920. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25921. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25922. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25923. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25924. }
  25925. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25926. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25927. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25928. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25929. }
  25930. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25931. if (this.reflectionTexture.isCube) {
  25932. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25933. }
  25934. else {
  25935. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25936. }
  25937. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25938. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25939. }
  25940. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25941. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25942. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25943. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25944. }
  25945. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25946. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25947. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25948. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25949. }
  25950. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25951. this._effect.setTexture("specularSampler", this.specularTexture);
  25952. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25953. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25954. }
  25955. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25956. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25957. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25958. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25959. }
  25960. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25961. var depth = 1.0;
  25962. if (this.refractionTexture.isCube) {
  25963. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25964. }
  25965. else {
  25966. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25967. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25968. if (this.refractionTexture.depth) {
  25969. depth = this.refractionTexture.depth;
  25970. }
  25971. }
  25972. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25973. }
  25974. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25975. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25976. }
  25977. }
  25978. // Clip plane
  25979. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25980. // Point size
  25981. if (this.pointsCloud) {
  25982. this._effect.setFloat("pointSize", this.pointSize);
  25983. }
  25984. // Colors
  25985. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25986. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25987. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25988. if (this._defines.SPECULARTERM) {
  25989. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25990. }
  25991. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25992. }
  25993. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25994. // Diffuse
  25995. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25996. // Lights
  25997. if (scene.lightsEnabled && !this.disableLighting) {
  25998. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25999. }
  26000. // View
  26001. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26002. this._effect.setMatrix("view", scene.getViewMatrix());
  26003. }
  26004. // Fog
  26005. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26006. // Log. depth
  26007. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26008. // Color Curves
  26009. if (this.cameraColorCurves) {
  26010. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26011. }
  26012. }
  26013. _super.prototype.bind.call(this, world, mesh);
  26014. };
  26015. StandardMaterial.prototype.getAnimatables = function () {
  26016. var results = [];
  26017. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26018. results.push(this.diffuseTexture);
  26019. }
  26020. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26021. results.push(this.ambientTexture);
  26022. }
  26023. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26024. results.push(this.opacityTexture);
  26025. }
  26026. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26027. results.push(this.reflectionTexture);
  26028. }
  26029. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26030. results.push(this.emissiveTexture);
  26031. }
  26032. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26033. results.push(this.specularTexture);
  26034. }
  26035. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26036. results.push(this.bumpTexture);
  26037. }
  26038. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26039. results.push(this.lightmapTexture);
  26040. }
  26041. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26042. results.push(this.refractionTexture);
  26043. }
  26044. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26045. results.push(this.cameraColorGradingTexture);
  26046. }
  26047. return results;
  26048. };
  26049. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26050. if (forceDisposeTextures) {
  26051. if (this.diffuseTexture) {
  26052. this.diffuseTexture.dispose();
  26053. }
  26054. if (this.ambientTexture) {
  26055. this.ambientTexture.dispose();
  26056. }
  26057. if (this.opacityTexture) {
  26058. this.opacityTexture.dispose();
  26059. }
  26060. if (this.reflectionTexture) {
  26061. this.reflectionTexture.dispose();
  26062. }
  26063. if (this.emissiveTexture) {
  26064. this.emissiveTexture.dispose();
  26065. }
  26066. if (this.specularTexture) {
  26067. this.specularTexture.dispose();
  26068. }
  26069. if (this.bumpTexture) {
  26070. this.bumpTexture.dispose();
  26071. }
  26072. if (this.lightmapTexture) {
  26073. this.lightmapTexture.dispose();
  26074. }
  26075. if (this.refractionTexture) {
  26076. this.refractionTexture.dispose();
  26077. }
  26078. if (this.cameraColorGradingTexture) {
  26079. this.cameraColorGradingTexture.dispose();
  26080. }
  26081. }
  26082. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26083. };
  26084. StandardMaterial.prototype.clone = function (name) {
  26085. var _this = this;
  26086. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26087. };
  26088. StandardMaterial.prototype.serialize = function () {
  26089. return BABYLON.SerializationHelper.Serialize(this);
  26090. };
  26091. // Statics
  26092. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26093. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26094. };
  26095. // Flags used to enable or disable a type of texture for all Standard Materials
  26096. StandardMaterial.DiffuseTextureEnabled = true;
  26097. StandardMaterial.AmbientTextureEnabled = true;
  26098. StandardMaterial.OpacityTextureEnabled = true;
  26099. StandardMaterial.ReflectionTextureEnabled = true;
  26100. StandardMaterial.EmissiveTextureEnabled = true;
  26101. StandardMaterial.SpecularTextureEnabled = true;
  26102. StandardMaterial.BumpTextureEnabled = true;
  26103. StandardMaterial.FresnelEnabled = true;
  26104. StandardMaterial.LightmapTextureEnabled = true;
  26105. StandardMaterial.RefractionTextureEnabled = true;
  26106. StandardMaterial.ColorGradingTextureEnabled = true;
  26107. __decorate([
  26108. BABYLON.serializeAsTexture()
  26109. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26110. __decorate([
  26111. BABYLON.serializeAsTexture()
  26112. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26113. __decorate([
  26114. BABYLON.serializeAsTexture()
  26115. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26116. __decorate([
  26117. BABYLON.serializeAsTexture()
  26118. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26119. __decorate([
  26120. BABYLON.serializeAsTexture()
  26121. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26122. __decorate([
  26123. BABYLON.serializeAsTexture()
  26124. ], StandardMaterial.prototype, "specularTexture", void 0);
  26125. __decorate([
  26126. BABYLON.serializeAsTexture()
  26127. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26128. __decorate([
  26129. BABYLON.serializeAsTexture()
  26130. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26131. __decorate([
  26132. BABYLON.serializeAsTexture()
  26133. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26134. __decorate([
  26135. BABYLON.serializeAsColor3("ambient")
  26136. ], StandardMaterial.prototype, "ambientColor", void 0);
  26137. __decorate([
  26138. BABYLON.serializeAsColor3("diffuse")
  26139. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26140. __decorate([
  26141. BABYLON.serializeAsColor3("specular")
  26142. ], StandardMaterial.prototype, "specularColor", void 0);
  26143. __decorate([
  26144. BABYLON.serializeAsColor3("emissive")
  26145. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26146. __decorate([
  26147. BABYLON.serialize()
  26148. ], StandardMaterial.prototype, "specularPower", void 0);
  26149. __decorate([
  26150. BABYLON.serialize()
  26151. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26152. __decorate([
  26153. BABYLON.serialize()
  26154. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26155. __decorate([
  26156. BABYLON.serialize()
  26157. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26158. __decorate([
  26159. BABYLON.serialize()
  26160. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26161. __decorate([
  26162. BABYLON.serialize()
  26163. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26164. __decorate([
  26165. BABYLON.serialize()
  26166. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26167. __decorate([
  26168. BABYLON.serialize()
  26169. ], StandardMaterial.prototype, "disableLighting", void 0);
  26170. __decorate([
  26171. BABYLON.serialize()
  26172. ], StandardMaterial.prototype, "useParallax", void 0);
  26173. __decorate([
  26174. BABYLON.serialize()
  26175. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26176. __decorate([
  26177. BABYLON.serialize()
  26178. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26179. __decorate([
  26180. BABYLON.serialize()
  26181. ], StandardMaterial.prototype, "roughness", void 0);
  26182. __decorate([
  26183. BABYLON.serialize()
  26184. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26185. __decorate([
  26186. BABYLON.serialize()
  26187. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26188. __decorate([
  26189. BABYLON.serialize()
  26190. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26191. __decorate([
  26192. BABYLON.serializeAsFresnelParameters()
  26193. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26194. __decorate([
  26195. BABYLON.serializeAsFresnelParameters()
  26196. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26197. __decorate([
  26198. BABYLON.serializeAsFresnelParameters()
  26199. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26200. __decorate([
  26201. BABYLON.serializeAsFresnelParameters()
  26202. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26203. __decorate([
  26204. BABYLON.serializeAsFresnelParameters()
  26205. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26206. __decorate([
  26207. BABYLON.serialize()
  26208. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26209. __decorate([
  26210. BABYLON.serialize()
  26211. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26212. __decorate([
  26213. BABYLON.serialize()
  26214. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26215. __decorate([
  26216. BABYLON.serialize()
  26217. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26218. __decorate([
  26219. BABYLON.serializeAsTexture()
  26220. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26221. __decorate([
  26222. BABYLON.serializeAsColorCurves()
  26223. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26224. __decorate([
  26225. BABYLON.serialize()
  26226. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26227. return StandardMaterial;
  26228. }(BABYLON.Material));
  26229. BABYLON.StandardMaterial = StandardMaterial;
  26230. })(BABYLON || (BABYLON = {}));
  26231. var BABYLON;
  26232. (function (BABYLON) {
  26233. var MultiMaterial = (function (_super) {
  26234. __extends(MultiMaterial, _super);
  26235. function MultiMaterial(name, scene) {
  26236. _super.call(this, name, scene, true);
  26237. this.subMaterials = new Array();
  26238. scene.multiMaterials.push(this);
  26239. }
  26240. // Properties
  26241. MultiMaterial.prototype.getSubMaterial = function (index) {
  26242. if (index < 0 || index >= this.subMaterials.length) {
  26243. return this.getScene().defaultMaterial;
  26244. }
  26245. return this.subMaterials[index];
  26246. };
  26247. // Methods
  26248. MultiMaterial.prototype.isReady = function (mesh) {
  26249. for (var index = 0; index < this.subMaterials.length; index++) {
  26250. var subMaterial = this.subMaterials[index];
  26251. if (subMaterial) {
  26252. if (!this.subMaterials[index].isReady(mesh)) {
  26253. return false;
  26254. }
  26255. }
  26256. }
  26257. return true;
  26258. };
  26259. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26260. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26261. for (var index = 0; index < this.subMaterials.length; index++) {
  26262. var subMaterial = null;
  26263. if (cloneChildren) {
  26264. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26265. }
  26266. else {
  26267. subMaterial = this.subMaterials[index];
  26268. }
  26269. newMultiMaterial.subMaterials.push(subMaterial);
  26270. }
  26271. return newMultiMaterial;
  26272. };
  26273. MultiMaterial.prototype.serialize = function () {
  26274. var serializationObject = {};
  26275. serializationObject.name = this.name;
  26276. serializationObject.id = this.id;
  26277. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26278. serializationObject.materials = [];
  26279. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26280. var subMat = this.subMaterials[matIndex];
  26281. if (subMat) {
  26282. serializationObject.materials.push(subMat.id);
  26283. }
  26284. else {
  26285. serializationObject.materials.push(null);
  26286. }
  26287. }
  26288. return serializationObject;
  26289. };
  26290. return MultiMaterial;
  26291. }(BABYLON.Material));
  26292. BABYLON.MultiMaterial = MultiMaterial;
  26293. })(BABYLON || (BABYLON = {}));
  26294. var BABYLON;
  26295. (function (BABYLON) {
  26296. var SceneLoader = (function () {
  26297. function SceneLoader() {
  26298. }
  26299. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26300. get: function () {
  26301. return 0;
  26302. },
  26303. enumerable: true,
  26304. configurable: true
  26305. });
  26306. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26307. get: function () {
  26308. return 1;
  26309. },
  26310. enumerable: true,
  26311. configurable: true
  26312. });
  26313. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26314. get: function () {
  26315. return 2;
  26316. },
  26317. enumerable: true,
  26318. configurable: true
  26319. });
  26320. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26321. get: function () {
  26322. return 3;
  26323. },
  26324. enumerable: true,
  26325. configurable: true
  26326. });
  26327. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26328. get: function () {
  26329. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26330. },
  26331. set: function (value) {
  26332. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26333. },
  26334. enumerable: true,
  26335. configurable: true
  26336. });
  26337. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26338. get: function () {
  26339. return SceneLoader._ShowLoadingScreen;
  26340. },
  26341. set: function (value) {
  26342. SceneLoader._ShowLoadingScreen = value;
  26343. },
  26344. enumerable: true,
  26345. configurable: true
  26346. });
  26347. Object.defineProperty(SceneLoader, "loggingLevel", {
  26348. get: function () {
  26349. return SceneLoader._loggingLevel;
  26350. },
  26351. set: function (value) {
  26352. SceneLoader._loggingLevel = value;
  26353. },
  26354. enumerable: true,
  26355. configurable: true
  26356. });
  26357. SceneLoader._getDefaultPlugin = function () {
  26358. return SceneLoader._registeredPlugins[".babylon"];
  26359. };
  26360. SceneLoader._getPluginForExtension = function (extension) {
  26361. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26362. if (registeredPlugin) {
  26363. return registeredPlugin;
  26364. }
  26365. return SceneLoader._getDefaultPlugin();
  26366. };
  26367. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26368. if (sceneFilename.name) {
  26369. sceneFilename = sceneFilename.name;
  26370. }
  26371. var dotPosition = sceneFilename.lastIndexOf(".");
  26372. var queryStringPosition = sceneFilename.indexOf("?");
  26373. if (queryStringPosition === -1) {
  26374. queryStringPosition = sceneFilename.length;
  26375. }
  26376. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26377. return SceneLoader._getPluginForExtension(extension);
  26378. };
  26379. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26380. SceneLoader._getDirectLoad = function (sceneFilename) {
  26381. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26382. return sceneFilename.substr(5);
  26383. }
  26384. return null;
  26385. };
  26386. // Public functions
  26387. SceneLoader.GetPluginForExtension = function (extension) {
  26388. return SceneLoader._getPluginForExtension(extension).plugin;
  26389. };
  26390. SceneLoader.RegisterPlugin = function (plugin) {
  26391. if (typeof plugin.extensions === "string") {
  26392. var extension = plugin.extensions;
  26393. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26394. plugin: plugin,
  26395. isBinary: false
  26396. };
  26397. }
  26398. else {
  26399. var extensions = plugin.extensions;
  26400. Object.keys(extensions).forEach(function (extension) {
  26401. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26402. plugin: plugin,
  26403. isBinary: extensions[extension].isBinary
  26404. };
  26405. });
  26406. }
  26407. };
  26408. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26409. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26410. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26411. return;
  26412. }
  26413. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26414. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26415. return;
  26416. }
  26417. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26418. var loadingToken = {};
  26419. scene._addPendingData(loadingToken);
  26420. var manifestChecked = function (success) {
  26421. scene.database = database;
  26422. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26423. var plugin = registeredPlugin.plugin;
  26424. var useArrayBuffer = registeredPlugin.isBinary;
  26425. var importMeshFromData = function (data) {
  26426. var meshes = [];
  26427. var particleSystems = [];
  26428. var skeletons = [];
  26429. try {
  26430. if (plugin.importMesh) {
  26431. var syncedPlugin = plugin;
  26432. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26433. if (onerror) {
  26434. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26435. }
  26436. scene._removePendingData(loadingToken);
  26437. return;
  26438. }
  26439. if (onsuccess) {
  26440. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26441. onsuccess(meshes, particleSystems, skeletons);
  26442. scene._removePendingData(loadingToken);
  26443. }
  26444. }
  26445. else {
  26446. var asyncedPlugin = plugin;
  26447. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26448. if (onsuccess) {
  26449. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26450. onsuccess(meshes, particleSystems, skeletons);
  26451. scene._removePendingData(loadingToken);
  26452. }
  26453. }, function () {
  26454. if (onerror) {
  26455. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26456. }
  26457. scene._removePendingData(loadingToken);
  26458. });
  26459. }
  26460. }
  26461. catch (e) {
  26462. if (onerror) {
  26463. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26464. }
  26465. scene._removePendingData(loadingToken);
  26466. }
  26467. };
  26468. if (directLoad) {
  26469. importMeshFromData(directLoad);
  26470. return;
  26471. }
  26472. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26473. importMeshFromData(data);
  26474. }, progressCallBack, database, useArrayBuffer);
  26475. };
  26476. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26477. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26478. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26479. }
  26480. else {
  26481. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26482. manifestChecked(true);
  26483. }
  26484. };
  26485. /**
  26486. * Load a scene
  26487. * @param rootUrl a string that defines the root url for scene and resources
  26488. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26489. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26490. */
  26491. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26492. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26493. };
  26494. /**
  26495. * Append a scene
  26496. * @param rootUrl a string that defines the root url for scene and resources
  26497. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26498. * @param scene is the instance of BABYLON.Scene to append to
  26499. */
  26500. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26501. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26502. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26503. return;
  26504. }
  26505. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26506. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26507. var plugin = registeredPlugin.plugin;
  26508. var useArrayBuffer = registeredPlugin.isBinary;
  26509. var database;
  26510. var loadingToken = {};
  26511. scene._addPendingData(loadingToken);
  26512. if (SceneLoader.ShowLoadingScreen) {
  26513. scene.getEngine().displayLoadingUI();
  26514. }
  26515. var loadSceneFromData = function (data) {
  26516. scene.database = database;
  26517. if (plugin.load) {
  26518. var syncedPlugin = plugin;
  26519. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26520. if (onerror) {
  26521. onerror(scene);
  26522. }
  26523. scene._removePendingData(loadingToken);
  26524. scene.getEngine().hideLoadingUI();
  26525. return;
  26526. }
  26527. if (onsuccess) {
  26528. onsuccess(scene);
  26529. }
  26530. scene._removePendingData(loadingToken);
  26531. }
  26532. else {
  26533. var asyncedPlugin = plugin;
  26534. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26535. if (onsuccess) {
  26536. onsuccess(scene);
  26537. }
  26538. scene._removePendingData(loadingToken);
  26539. }, function () {
  26540. if (onerror) {
  26541. onerror(scene);
  26542. }
  26543. scene._removePendingData(loadingToken);
  26544. scene.getEngine().hideLoadingUI();
  26545. });
  26546. }
  26547. if (SceneLoader.ShowLoadingScreen) {
  26548. scene.executeWhenReady(function () {
  26549. scene.getEngine().hideLoadingUI();
  26550. });
  26551. }
  26552. };
  26553. var manifestChecked = function (success) {
  26554. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26555. };
  26556. if (directLoad) {
  26557. loadSceneFromData(directLoad);
  26558. return;
  26559. }
  26560. if (rootUrl.indexOf("file:") === -1) {
  26561. if (scene.getEngine().enableOfflineSupport) {
  26562. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26563. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26564. }
  26565. else {
  26566. manifestChecked(true);
  26567. }
  26568. }
  26569. else {
  26570. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26571. }
  26572. };
  26573. // Flags
  26574. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26575. SceneLoader._ShowLoadingScreen = true;
  26576. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26577. // Members
  26578. SceneLoader._registeredPlugins = {};
  26579. return SceneLoader;
  26580. }());
  26581. BABYLON.SceneLoader = SceneLoader;
  26582. ;
  26583. })(BABYLON || (BABYLON = {}));
  26584. var BABYLON;
  26585. (function (BABYLON) {
  26586. var Internals;
  26587. (function (Internals) {
  26588. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26589. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26590. var parsedMaterial = parsedData.materials[index];
  26591. if (parsedMaterial.id === id) {
  26592. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26593. }
  26594. }
  26595. return null;
  26596. };
  26597. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26598. names = (names instanceof Array) ? names : [names];
  26599. for (var i in names) {
  26600. if (mesh.name === names[i]) {
  26601. hierarchyIds.push(mesh.id);
  26602. return true;
  26603. }
  26604. }
  26605. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26606. hierarchyIds.push(mesh.id);
  26607. return true;
  26608. }
  26609. return false;
  26610. };
  26611. var logOperation = function (operation, producer) {
  26612. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26613. };
  26614. BABYLON.SceneLoader.RegisterPlugin({
  26615. extensions: ".babylon",
  26616. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26617. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26618. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26619. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26620. // and avoid problems with multiple concurrent .babylon loads.
  26621. var log = "importMesh has failed JSON parse";
  26622. try {
  26623. var parsedData = JSON.parse(data);
  26624. log = "";
  26625. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26626. var loadedSkeletonsIds = [];
  26627. var loadedMaterialsIds = [];
  26628. var hierarchyIds = [];
  26629. var index;
  26630. var cache;
  26631. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26632. var parsedMesh = parsedData.meshes[index];
  26633. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26634. if (meshesNames instanceof Array) {
  26635. // Remove found mesh name from list.
  26636. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26637. }
  26638. //Geometry?
  26639. if (parsedMesh.geometryId) {
  26640. //does the file contain geometries?
  26641. if (parsedData.geometries) {
  26642. //find the correct geometry and add it to the scene
  26643. var found = false;
  26644. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26645. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26646. return;
  26647. }
  26648. else {
  26649. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26650. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26651. switch (geometryType) {
  26652. case "boxes":
  26653. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26654. break;
  26655. case "spheres":
  26656. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26657. break;
  26658. case "cylinders":
  26659. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26660. break;
  26661. case "toruses":
  26662. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26663. break;
  26664. case "grounds":
  26665. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26666. break;
  26667. case "planes":
  26668. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26669. break;
  26670. case "torusKnots":
  26671. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26672. break;
  26673. case "vertexData":
  26674. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26675. break;
  26676. }
  26677. found = true;
  26678. }
  26679. });
  26680. }
  26681. });
  26682. if (!found) {
  26683. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26684. }
  26685. }
  26686. }
  26687. // Material ?
  26688. if (parsedMesh.materialId) {
  26689. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26690. if (!materialFound && parsedData.multiMaterials) {
  26691. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26692. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26693. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26694. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26695. var subMatId = parsedMultiMaterial.materials[matIndex];
  26696. loadedMaterialsIds.push(subMatId);
  26697. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26698. log += "\n\tMaterial " + mat.toString(fullDetails);
  26699. }
  26700. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26701. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26702. materialFound = true;
  26703. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26704. break;
  26705. }
  26706. }
  26707. }
  26708. if (!materialFound) {
  26709. loadedMaterialsIds.push(parsedMesh.materialId);
  26710. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26711. if (!mat) {
  26712. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26713. }
  26714. else {
  26715. log += "\n\tMaterial " + mat.toString(fullDetails);
  26716. }
  26717. }
  26718. }
  26719. // Skeleton ?
  26720. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26721. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26722. if (!skeletonAlreadyLoaded) {
  26723. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26724. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26725. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26726. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26727. skeletons.push(skeleton);
  26728. loadedSkeletonsIds.push(parsedSkeleton.id);
  26729. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26730. }
  26731. }
  26732. }
  26733. }
  26734. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26735. meshes.push(mesh);
  26736. log += "\n\tMesh " + mesh.toString(fullDetails);
  26737. }
  26738. }
  26739. // Connecting parents
  26740. var currentMesh;
  26741. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26742. currentMesh = scene.meshes[index];
  26743. if (currentMesh._waitingParentId) {
  26744. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26745. currentMesh._waitingParentId = undefined;
  26746. }
  26747. }
  26748. // freeze and compute world matrix application
  26749. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26750. currentMesh = scene.meshes[index];
  26751. if (currentMesh._waitingFreezeWorldMatrix) {
  26752. currentMesh.freezeWorldMatrix();
  26753. currentMesh._waitingFreezeWorldMatrix = undefined;
  26754. }
  26755. else {
  26756. currentMesh.computeWorldMatrix(true);
  26757. }
  26758. }
  26759. // Particles
  26760. if (parsedData.particleSystems) {
  26761. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26762. var parsedParticleSystem = parsedData.particleSystems[index];
  26763. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26764. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26765. }
  26766. }
  26767. }
  26768. return true;
  26769. }
  26770. catch (err) {
  26771. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26772. log = null;
  26773. throw err;
  26774. }
  26775. finally {
  26776. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26777. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26778. }
  26779. }
  26780. },
  26781. load: function (scene, data, rootUrl) {
  26782. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26783. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26784. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26785. // and avoid problems with multiple concurrent .babylon loads.
  26786. var log = "importScene has failed JSON parse";
  26787. try {
  26788. var parsedData = JSON.parse(data);
  26789. log = "";
  26790. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26791. // Scene
  26792. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26793. scene.autoClear = parsedData.autoClear;
  26794. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26795. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26796. if (parsedData.gravity) {
  26797. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26798. }
  26799. // Fog
  26800. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26801. scene.fogMode = parsedData.fogMode;
  26802. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26803. scene.fogStart = parsedData.fogStart;
  26804. scene.fogEnd = parsedData.fogEnd;
  26805. scene.fogDensity = parsedData.fogDensity;
  26806. log += "\tFog mode for scene: ";
  26807. switch (scene.fogMode) {
  26808. // getters not compiling, so using hardcoded
  26809. case 1:
  26810. log += "exp\n";
  26811. break;
  26812. case 2:
  26813. log += "exp2\n";
  26814. break;
  26815. case 3:
  26816. log += "linear\n";
  26817. break;
  26818. }
  26819. }
  26820. //Physics
  26821. if (parsedData.physicsEnabled) {
  26822. var physicsPlugin;
  26823. if (parsedData.physicsEngine === "cannon") {
  26824. physicsPlugin = new BABYLON.CannonJSPlugin();
  26825. }
  26826. else if (parsedData.physicsEngine === "oimo") {
  26827. physicsPlugin = new BABYLON.OimoJSPlugin();
  26828. }
  26829. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26830. //else - default engine, which is currently oimo
  26831. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26832. scene.enablePhysics(physicsGravity, physicsPlugin);
  26833. }
  26834. //collisions, if defined. otherwise, default is true
  26835. if (parsedData.collisionsEnabled != undefined) {
  26836. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26837. }
  26838. scene.workerCollisions = !!parsedData.workerCollisions;
  26839. var index;
  26840. var cache;
  26841. // Lights
  26842. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26843. var parsedLight = parsedData.lights[index];
  26844. var light = BABYLON.Light.Parse(parsedLight, scene);
  26845. log += (index === 0 ? "\n\tLights:" : "");
  26846. log += "\n\t\t" + light.toString(fullDetails);
  26847. }
  26848. // Animations
  26849. if (parsedData.animations) {
  26850. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26851. var parsedAnimation = parsedData.animations[index];
  26852. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26853. scene.animations.push(animation);
  26854. log += (index === 0 ? "\n\tAnimations:" : "");
  26855. log += "\n\t\t" + animation.toString(fullDetails);
  26856. }
  26857. }
  26858. if (parsedData.autoAnimate) {
  26859. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26860. }
  26861. // Materials
  26862. if (parsedData.materials) {
  26863. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26864. var parsedMaterial = parsedData.materials[index];
  26865. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26866. log += (index === 0 ? "\n\tMaterials:" : "");
  26867. log += "\n\t\t" + mat.toString(fullDetails);
  26868. }
  26869. }
  26870. if (parsedData.multiMaterials) {
  26871. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26872. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26873. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26874. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26875. log += "\n\t\t" + mmat.toString(fullDetails);
  26876. }
  26877. }
  26878. // Skeletons
  26879. if (parsedData.skeletons) {
  26880. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26881. var parsedSkeleton = parsedData.skeletons[index];
  26882. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26883. log += (index === 0 ? "\n\tSkeletons:" : "");
  26884. log += "\n\t\t" + skeleton.toString(fullDetails);
  26885. }
  26886. }
  26887. // Geometries
  26888. var geometries = parsedData.geometries;
  26889. if (geometries) {
  26890. // Boxes
  26891. var boxes = geometries.boxes;
  26892. if (boxes) {
  26893. for (index = 0, cache = boxes.length; index < cache; index++) {
  26894. var parsedBox = boxes[index];
  26895. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26896. }
  26897. }
  26898. // Spheres
  26899. var spheres = geometries.spheres;
  26900. if (spheres) {
  26901. for (index = 0, cache = spheres.length; index < cache; index++) {
  26902. var parsedSphere = spheres[index];
  26903. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26904. }
  26905. }
  26906. // Cylinders
  26907. var cylinders = geometries.cylinders;
  26908. if (cylinders) {
  26909. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26910. var parsedCylinder = cylinders[index];
  26911. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26912. }
  26913. }
  26914. // Toruses
  26915. var toruses = geometries.toruses;
  26916. if (toruses) {
  26917. for (index = 0, cache = toruses.length; index < cache; index++) {
  26918. var parsedTorus = toruses[index];
  26919. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26920. }
  26921. }
  26922. // Grounds
  26923. var grounds = geometries.grounds;
  26924. if (grounds) {
  26925. for (index = 0, cache = grounds.length; index < cache; index++) {
  26926. var parsedGround = grounds[index];
  26927. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26928. }
  26929. }
  26930. // Planes
  26931. var planes = geometries.planes;
  26932. if (planes) {
  26933. for (index = 0, cache = planes.length; index < cache; index++) {
  26934. var parsedPlane = planes[index];
  26935. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26936. }
  26937. }
  26938. // TorusKnots
  26939. var torusKnots = geometries.torusKnots;
  26940. if (torusKnots) {
  26941. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26942. var parsedTorusKnot = torusKnots[index];
  26943. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26944. }
  26945. }
  26946. // VertexData
  26947. var vertexData = geometries.vertexData;
  26948. if (vertexData) {
  26949. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26950. var parsedVertexData = vertexData[index];
  26951. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26952. }
  26953. }
  26954. }
  26955. // Meshes
  26956. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26957. var parsedMesh = parsedData.meshes[index];
  26958. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26959. log += (index === 0 ? "\n\tMeshes:" : "");
  26960. log += "\n\t\t" + mesh.toString(fullDetails);
  26961. }
  26962. // Cameras
  26963. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26964. var parsedCamera = parsedData.cameras[index];
  26965. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26966. log += (index === 0 ? "\n\tCameras:" : "");
  26967. log += "\n\t\t" + camera.toString(fullDetails);
  26968. }
  26969. if (parsedData.activeCameraID) {
  26970. scene.setActiveCameraByID(parsedData.activeCameraID);
  26971. }
  26972. // Browsing all the graph to connect the dots
  26973. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26974. var camera = scene.cameras[index];
  26975. if (camera._waitingParentId) {
  26976. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26977. camera._waitingParentId = undefined;
  26978. }
  26979. }
  26980. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26981. var light = scene.lights[index];
  26982. if (light._waitingParentId) {
  26983. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26984. light._waitingParentId = undefined;
  26985. }
  26986. }
  26987. // Sounds
  26988. var loadedSounds = [];
  26989. var loadedSound;
  26990. if (BABYLON.AudioEngine && parsedData.sounds) {
  26991. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26992. var parsedSound = parsedData.sounds[index];
  26993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26994. if (!parsedSound.url)
  26995. parsedSound.url = parsedSound.name;
  26996. if (!loadedSounds[parsedSound.url]) {
  26997. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26998. loadedSounds[parsedSound.url] = loadedSound;
  26999. }
  27000. else {
  27001. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27002. }
  27003. }
  27004. else {
  27005. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27006. }
  27007. }
  27008. }
  27009. loadedSounds = [];
  27010. // Connect parents & children and parse actions
  27011. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27012. var mesh = scene.meshes[index];
  27013. if (mesh._waitingParentId) {
  27014. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27015. mesh._waitingParentId = undefined;
  27016. }
  27017. if (mesh._waitingActions) {
  27018. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27019. mesh._waitingActions = undefined;
  27020. }
  27021. }
  27022. // freeze world matrix application
  27023. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27024. var currentMesh = scene.meshes[index];
  27025. if (currentMesh._waitingFreezeWorldMatrix) {
  27026. currentMesh.freezeWorldMatrix();
  27027. currentMesh._waitingFreezeWorldMatrix = undefined;
  27028. }
  27029. else {
  27030. currentMesh.computeWorldMatrix(true);
  27031. }
  27032. }
  27033. // Particles Systems
  27034. if (parsedData.particleSystems) {
  27035. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27036. var parsedParticleSystem = parsedData.particleSystems[index];
  27037. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27038. }
  27039. }
  27040. // Lens flares
  27041. if (parsedData.lensFlareSystems) {
  27042. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27043. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27044. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27045. }
  27046. }
  27047. // Shadows
  27048. if (parsedData.shadowGenerators) {
  27049. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27050. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27051. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27052. }
  27053. }
  27054. // Actions (scene)
  27055. if (parsedData.actions) {
  27056. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27057. }
  27058. // Finish
  27059. return true;
  27060. }
  27061. catch (err) {
  27062. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27063. log = null;
  27064. throw err;
  27065. }
  27066. finally {
  27067. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27068. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27069. }
  27070. }
  27071. }
  27072. });
  27073. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27074. })(BABYLON || (BABYLON = {}));
  27075. var BABYLON;
  27076. (function (BABYLON) {
  27077. var SpriteManager = (function () {
  27078. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27080. this.name = name;
  27081. this.sprites = new Array();
  27082. this.renderingGroupId = 0;
  27083. this.layerMask = 0x0FFFFFFF;
  27084. this.fogEnabled = true;
  27085. this.isPickable = false;
  27086. /**
  27087. * An event triggered when the manager is disposed.
  27088. * @type {BABYLON.Observable}
  27089. */
  27090. this.onDisposeObservable = new BABYLON.Observable();
  27091. this._vertexBuffers = {};
  27092. this._capacity = capacity;
  27093. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27094. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27095. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27096. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  27097. if (cellSize.width) {
  27098. this.cellWidth = cellSize.width;
  27099. this.cellHeight = cellSize.height;
  27100. }
  27101. else {
  27102. this.cellWidth = cellSize;
  27103. this.cellHeight = cellSize;
  27104. }
  27105. this._scene = scene;
  27106. this._scene.spriteManagers.push(this);
  27107. var indices = [];
  27108. var index = 0;
  27109. for (var count = 0; count < capacity; count++) {
  27110. indices.push(index);
  27111. indices.push(index + 1);
  27112. indices.push(index + 2);
  27113. indices.push(index);
  27114. indices.push(index + 2);
  27115. indices.push(index + 3);
  27116. index += 4;
  27117. }
  27118. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27119. // VBO
  27120. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27121. this._vertexData = new Float32Array(capacity * 16 * 4);
  27122. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27123. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27124. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27125. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27126. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27127. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27128. this._vertexBuffers["options"] = options;
  27129. this._vertexBuffers["cellInfo"] = cellInfo;
  27130. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27131. // Effects
  27132. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27133. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27134. }
  27135. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27136. set: function (callback) {
  27137. if (this._onDisposeObserver) {
  27138. this.onDisposeObservable.remove(this._onDisposeObserver);
  27139. }
  27140. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27141. },
  27142. enumerable: true,
  27143. configurable: true
  27144. });
  27145. Object.defineProperty(SpriteManager.prototype, "texture", {
  27146. get: function () {
  27147. return this._spriteTexture;
  27148. },
  27149. set: function (value) {
  27150. this._spriteTexture = value;
  27151. },
  27152. enumerable: true,
  27153. configurable: true
  27154. });
  27155. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27156. var arrayOffset = index * 16;
  27157. if (offsetX === 0)
  27158. offsetX = this._epsilon;
  27159. else if (offsetX === 1)
  27160. offsetX = 1 - this._epsilon;
  27161. if (offsetY === 0)
  27162. offsetY = this._epsilon;
  27163. else if (offsetY === 1)
  27164. offsetY = 1 - this._epsilon;
  27165. this._vertexData[arrayOffset] = sprite.position.x;
  27166. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27167. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27168. this._vertexData[arrayOffset + 3] = sprite.angle;
  27169. this._vertexData[arrayOffset + 4] = sprite.width;
  27170. this._vertexData[arrayOffset + 5] = sprite.height;
  27171. this._vertexData[arrayOffset + 6] = offsetX;
  27172. this._vertexData[arrayOffset + 7] = offsetY;
  27173. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27174. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27175. var offset = (sprite.cellIndex / rowSize) >> 0;
  27176. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27177. this._vertexData[arrayOffset + 11] = offset;
  27178. // Color
  27179. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27180. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27181. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27182. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27183. };
  27184. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27185. var count = Math.min(this._capacity, this.sprites.length);
  27186. var min = BABYLON.Vector3.Zero();
  27187. var max = BABYLON.Vector3.Zero();
  27188. var distance = Number.MAX_VALUE;
  27189. var currentSprite;
  27190. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27191. var cameraView = camera.getViewMatrix();
  27192. for (var index = 0; index < count; index++) {
  27193. var sprite = this.sprites[index];
  27194. if (!sprite) {
  27195. continue;
  27196. }
  27197. if (predicate) {
  27198. if (!predicate(sprite)) {
  27199. continue;
  27200. }
  27201. }
  27202. else if (!sprite.isPickable) {
  27203. continue;
  27204. }
  27205. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27206. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27207. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27208. if (ray.intersectsBoxMinMax(min, max)) {
  27209. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27210. if (distance > currentDistance) {
  27211. distance = currentDistance;
  27212. currentSprite = sprite;
  27213. if (fastCheck) {
  27214. break;
  27215. }
  27216. }
  27217. }
  27218. }
  27219. if (currentSprite) {
  27220. var result = new BABYLON.PickingInfo();
  27221. result.hit = true;
  27222. result.pickedSprite = currentSprite;
  27223. result.distance = distance;
  27224. return result;
  27225. }
  27226. return null;
  27227. };
  27228. SpriteManager.prototype.render = function () {
  27229. // Check
  27230. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27231. return;
  27232. var engine = this._scene.getEngine();
  27233. var baseSize = this._spriteTexture.getBaseSize();
  27234. // Sprites
  27235. var deltaTime = engine.getDeltaTime();
  27236. var max = Math.min(this._capacity, this.sprites.length);
  27237. var rowSize = baseSize.width / this.cellWidth;
  27238. var offset = 0;
  27239. for (var index = 0; index < max; index++) {
  27240. var sprite = this.sprites[index];
  27241. if (!sprite) {
  27242. continue;
  27243. }
  27244. sprite._animate(deltaTime);
  27245. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27246. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27247. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27248. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27249. }
  27250. this._buffer.update(this._vertexData);
  27251. // Render
  27252. var effect = this._effectBase;
  27253. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27254. effect = this._effectFog;
  27255. }
  27256. engine.enableEffect(effect);
  27257. var viewMatrix = this._scene.getViewMatrix();
  27258. effect.setTexture("diffuseSampler", this._spriteTexture);
  27259. effect.setMatrix("view", viewMatrix);
  27260. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27261. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27262. // Fog
  27263. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27264. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27265. effect.setColor3("vFogColor", this._scene.fogColor);
  27266. }
  27267. // VBOs
  27268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27269. // Draw order
  27270. engine.setDepthFunctionToLessOrEqual();
  27271. effect.setBool("alphaTest", true);
  27272. engine.setColorWrite(false);
  27273. engine.draw(true, 0, max * 6);
  27274. engine.setColorWrite(true);
  27275. effect.setBool("alphaTest", false);
  27276. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27277. engine.draw(true, 0, max * 6);
  27278. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27279. };
  27280. SpriteManager.prototype.dispose = function () {
  27281. if (this._buffer) {
  27282. this._buffer.dispose();
  27283. this._buffer = null;
  27284. }
  27285. if (this._indexBuffer) {
  27286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27287. this._indexBuffer = null;
  27288. }
  27289. if (this._spriteTexture) {
  27290. this._spriteTexture.dispose();
  27291. this._spriteTexture = null;
  27292. }
  27293. // Remove from scene
  27294. var index = this._scene.spriteManagers.indexOf(this);
  27295. this._scene.spriteManagers.splice(index, 1);
  27296. // Callback
  27297. this.onDisposeObservable.notifyObservers(this);
  27298. this.onDisposeObservable.clear();
  27299. };
  27300. return SpriteManager;
  27301. }());
  27302. BABYLON.SpriteManager = SpriteManager;
  27303. })(BABYLON || (BABYLON = {}));
  27304. var BABYLON;
  27305. (function (BABYLON) {
  27306. var Sprite = (function () {
  27307. function Sprite(name, manager) {
  27308. this.name = name;
  27309. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27310. this.width = 1.0;
  27311. this.height = 1.0;
  27312. this.angle = 0;
  27313. this.cellIndex = 0;
  27314. this.invertU = 0;
  27315. this.invertV = 0;
  27316. this.animations = new Array();
  27317. this.isPickable = false;
  27318. this._animationStarted = false;
  27319. this._loopAnimation = false;
  27320. this._fromIndex = 0;
  27321. this._toIndex = 0;
  27322. this._delay = 0;
  27323. this._direction = 1;
  27324. this._frameCount = 0;
  27325. this._time = 0;
  27326. this._manager = manager;
  27327. this._manager.sprites.push(this);
  27328. this.position = BABYLON.Vector3.Zero();
  27329. }
  27330. Object.defineProperty(Sprite.prototype, "size", {
  27331. get: function () {
  27332. return this.width;
  27333. },
  27334. set: function (value) {
  27335. this.width = value;
  27336. this.height = value;
  27337. },
  27338. enumerable: true,
  27339. configurable: true
  27340. });
  27341. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27342. this._fromIndex = from;
  27343. this._toIndex = to;
  27344. this._loopAnimation = loop;
  27345. this._delay = delay;
  27346. this._animationStarted = true;
  27347. this._direction = from < to ? 1 : -1;
  27348. this.cellIndex = from;
  27349. this._time = 0;
  27350. this._onAnimationEnd = onAnimationEnd;
  27351. };
  27352. Sprite.prototype.stopAnimation = function () {
  27353. this._animationStarted = false;
  27354. };
  27355. Sprite.prototype._animate = function (deltaTime) {
  27356. if (!this._animationStarted)
  27357. return;
  27358. this._time += deltaTime;
  27359. if (this._time > this._delay) {
  27360. this._time = this._time % this._delay;
  27361. this.cellIndex += this._direction;
  27362. if (this.cellIndex === this._toIndex) {
  27363. if (this._loopAnimation) {
  27364. this.cellIndex = this._fromIndex;
  27365. }
  27366. else {
  27367. this._animationStarted = false;
  27368. if (this._onAnimationEnd) {
  27369. this._onAnimationEnd();
  27370. }
  27371. if (this.disposeWhenFinishedAnimating) {
  27372. this.dispose();
  27373. }
  27374. }
  27375. }
  27376. }
  27377. };
  27378. Sprite.prototype.dispose = function () {
  27379. for (var i = 0; i < this._manager.sprites.length; i++) {
  27380. if (this._manager.sprites[i] == this) {
  27381. this._manager.sprites.splice(i, 1);
  27382. }
  27383. }
  27384. };
  27385. return Sprite;
  27386. }());
  27387. BABYLON.Sprite = Sprite;
  27388. })(BABYLON || (BABYLON = {}));
  27389. var BABYLON;
  27390. (function (BABYLON) {
  27391. var Layer = (function () {
  27392. function Layer(name, imgUrl, scene, isBackground, color) {
  27393. this.name = name;
  27394. this.scale = new BABYLON.Vector2(1, 1);
  27395. this.offset = new BABYLON.Vector2(0, 0);
  27396. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27397. this._vertexBuffers = {};
  27398. // Events
  27399. /**
  27400. * An event triggered when the layer is disposed.
  27401. * @type {BABYLON.Observable}
  27402. */
  27403. this.onDisposeObservable = new BABYLON.Observable();
  27404. /**
  27405. * An event triggered before rendering the scene
  27406. * @type {BABYLON.Observable}
  27407. */
  27408. this.onBeforeRenderObservable = new BABYLON.Observable();
  27409. /**
  27410. * An event triggered after rendering the scene
  27411. * @type {BABYLON.Observable}
  27412. */
  27413. this.onAfterRenderObservable = new BABYLON.Observable();
  27414. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27415. this.isBackground = isBackground === undefined ? true : isBackground;
  27416. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27417. this._scene = scene;
  27418. this._scene.layers.push(this);
  27419. var engine = scene.getEngine();
  27420. // VBO
  27421. var vertices = [];
  27422. vertices.push(1, 1);
  27423. vertices.push(-1, 1);
  27424. vertices.push(-1, -1);
  27425. vertices.push(1, -1);
  27426. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27427. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27428. // Indices
  27429. var indices = [];
  27430. indices.push(0);
  27431. indices.push(1);
  27432. indices.push(2);
  27433. indices.push(0);
  27434. indices.push(2);
  27435. indices.push(3);
  27436. this._indexBuffer = engine.createIndexBuffer(indices);
  27437. // Effects
  27438. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27439. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27440. }
  27441. Object.defineProperty(Layer.prototype, "onDispose", {
  27442. set: function (callback) {
  27443. if (this._onDisposeObserver) {
  27444. this.onDisposeObservable.remove(this._onDisposeObserver);
  27445. }
  27446. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27447. },
  27448. enumerable: true,
  27449. configurable: true
  27450. });
  27451. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27452. set: function (callback) {
  27453. if (this._onBeforeRenderObserver) {
  27454. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27455. }
  27456. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27457. },
  27458. enumerable: true,
  27459. configurable: true
  27460. });
  27461. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27462. set: function (callback) {
  27463. if (this._onAfterRenderObserver) {
  27464. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27465. }
  27466. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27467. },
  27468. enumerable: true,
  27469. configurable: true
  27470. });
  27471. Layer.prototype.render = function () {
  27472. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27473. // Check
  27474. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27475. return;
  27476. var engine = this._scene.getEngine();
  27477. this.onBeforeRenderObservable.notifyObservers(this);
  27478. // Render
  27479. engine.enableEffect(currentEffect);
  27480. engine.setState(false);
  27481. // Texture
  27482. currentEffect.setTexture("textureSampler", this.texture);
  27483. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27484. // Color
  27485. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27486. // Scale / offset
  27487. currentEffect.setVector2("offset", this.offset);
  27488. currentEffect.setVector2("scale", this.scale);
  27489. // VBOs
  27490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27491. // Draw order
  27492. if (!this.alphaTest) {
  27493. engine.setAlphaMode(this.alphaBlendingMode);
  27494. engine.draw(true, 0, 6);
  27495. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27496. }
  27497. else {
  27498. engine.draw(true, 0, 6);
  27499. }
  27500. this.onAfterRenderObservable.notifyObservers(this);
  27501. };
  27502. Layer.prototype.dispose = function () {
  27503. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27504. if (vertexBuffer) {
  27505. vertexBuffer.dispose();
  27506. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27507. }
  27508. if (this._indexBuffer) {
  27509. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27510. this._indexBuffer = null;
  27511. }
  27512. if (this.texture) {
  27513. this.texture.dispose();
  27514. this.texture = null;
  27515. }
  27516. // Remove from scene
  27517. var index = this._scene.layers.indexOf(this);
  27518. this._scene.layers.splice(index, 1);
  27519. // Callback
  27520. this.onDisposeObservable.notifyObservers(this);
  27521. this.onDisposeObservable.clear();
  27522. this.onAfterRenderObservable.clear();
  27523. this.onBeforeRenderObservable.clear();
  27524. };
  27525. return Layer;
  27526. }());
  27527. BABYLON.Layer = Layer;
  27528. })(BABYLON || (BABYLON = {}));
  27529. var BABYLON;
  27530. (function (BABYLON) {
  27531. var Particle = (function () {
  27532. function Particle() {
  27533. this.position = BABYLON.Vector3.Zero();
  27534. this.direction = BABYLON.Vector3.Zero();
  27535. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27536. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27537. this.lifeTime = 1.0;
  27538. this.age = 0;
  27539. this.size = 0;
  27540. this.angle = 0;
  27541. this.angularSpeed = 0;
  27542. }
  27543. Particle.prototype.copyTo = function (other) {
  27544. other.position.copyFrom(this.position);
  27545. other.direction.copyFrom(this.direction);
  27546. other.color.copyFrom(this.color);
  27547. other.colorStep.copyFrom(this.colorStep);
  27548. other.lifeTime = this.lifeTime;
  27549. other.age = this.age;
  27550. other.size = this.size;
  27551. other.angle = this.angle;
  27552. other.angularSpeed = this.angularSpeed;
  27553. };
  27554. return Particle;
  27555. }());
  27556. BABYLON.Particle = Particle;
  27557. })(BABYLON || (BABYLON = {}));
  27558. var BABYLON;
  27559. (function (BABYLON) {
  27560. var randomNumber = function (min, max) {
  27561. if (min === max) {
  27562. return (min);
  27563. }
  27564. var random = Math.random();
  27565. return ((random * (max - min)) + min);
  27566. };
  27567. var ParticleSystem = (function () {
  27568. function ParticleSystem(name, capacity, scene, customEffect) {
  27569. var _this = this;
  27570. this.name = name;
  27571. // Members
  27572. this.animations = [];
  27573. this.renderingGroupId = 0;
  27574. this.emitter = null;
  27575. this.emitRate = 10;
  27576. this.manualEmitCount = -1;
  27577. this.updateSpeed = 0.01;
  27578. this.targetStopDuration = 0;
  27579. this.disposeOnStop = false;
  27580. this.minEmitPower = 1;
  27581. this.maxEmitPower = 1;
  27582. this.minLifeTime = 1;
  27583. this.maxLifeTime = 1;
  27584. this.minSize = 1;
  27585. this.maxSize = 1;
  27586. this.minAngularSpeed = 0;
  27587. this.maxAngularSpeed = 0;
  27588. this.layerMask = 0x0FFFFFFF;
  27589. /**
  27590. * An event triggered when the system is disposed.
  27591. * @type {BABYLON.Observable}
  27592. */
  27593. this.onDisposeObservable = new BABYLON.Observable();
  27594. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27595. this.forceDepthWrite = false;
  27596. this.gravity = BABYLON.Vector3.Zero();
  27597. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27598. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27599. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27600. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27601. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27602. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27603. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27604. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27605. this.particles = new Array();
  27606. this._stockParticles = new Array();
  27607. this._newPartsExcess = 0;
  27608. this._vertexBuffers = {};
  27609. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27610. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27611. this._scaledDirection = BABYLON.Vector3.Zero();
  27612. this._scaledGravity = BABYLON.Vector3.Zero();
  27613. this._currentRenderId = -1;
  27614. this._started = false;
  27615. this._stopped = false;
  27616. this._actualFrame = 0;
  27617. this.id = name;
  27618. this._capacity = capacity;
  27619. this._scene = scene;
  27620. this._customEffect = customEffect;
  27621. scene.particleSystems.push(this);
  27622. var indices = [];
  27623. var index = 0;
  27624. for (var count = 0; count < capacity; count++) {
  27625. indices.push(index);
  27626. indices.push(index + 1);
  27627. indices.push(index + 2);
  27628. indices.push(index);
  27629. indices.push(index + 2);
  27630. indices.push(index + 3);
  27631. index += 4;
  27632. }
  27633. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27634. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27635. this._vertexData = new Float32Array(capacity * 11 * 4);
  27636. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27637. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27638. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27639. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27640. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27641. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27642. this._vertexBuffers["options"] = options;
  27643. // Default behaviors
  27644. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27645. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27646. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27647. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27648. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27649. };
  27650. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27651. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27652. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27653. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27654. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27655. };
  27656. this.updateFunction = function (particles) {
  27657. for (var index = 0; index < particles.length; index++) {
  27658. var particle = particles[index];
  27659. particle.age += _this._scaledUpdateSpeed;
  27660. if (particle.age >= particle.lifeTime) {
  27661. _this.recycleParticle(particle);
  27662. index--;
  27663. continue;
  27664. }
  27665. else {
  27666. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27667. particle.color.addInPlace(_this._scaledColorStep);
  27668. if (particle.color.a < 0)
  27669. particle.color.a = 0;
  27670. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27671. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27672. particle.position.addInPlace(_this._scaledDirection);
  27673. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27674. particle.direction.addInPlace(_this._scaledGravity);
  27675. }
  27676. }
  27677. };
  27678. }
  27679. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27680. set: function (callback) {
  27681. if (this._onDisposeObserver) {
  27682. this.onDisposeObservable.remove(this._onDisposeObserver);
  27683. }
  27684. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27685. },
  27686. enumerable: true,
  27687. configurable: true
  27688. });
  27689. ParticleSystem.prototype.recycleParticle = function (particle) {
  27690. var lastParticle = this.particles.pop();
  27691. if (lastParticle !== particle) {
  27692. lastParticle.copyTo(particle);
  27693. this._stockParticles.push(lastParticle);
  27694. }
  27695. };
  27696. ParticleSystem.prototype.getCapacity = function () {
  27697. return this._capacity;
  27698. };
  27699. ParticleSystem.prototype.isAlive = function () {
  27700. return this._alive;
  27701. };
  27702. ParticleSystem.prototype.isStarted = function () {
  27703. return this._started;
  27704. };
  27705. ParticleSystem.prototype.start = function () {
  27706. this._started = true;
  27707. this._stopped = false;
  27708. this._actualFrame = 0;
  27709. };
  27710. ParticleSystem.prototype.stop = function () {
  27711. this._stopped = true;
  27712. };
  27713. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27714. var offset = index * 11;
  27715. this._vertexData[offset] = particle.position.x;
  27716. this._vertexData[offset + 1] = particle.position.y;
  27717. this._vertexData[offset + 2] = particle.position.z;
  27718. this._vertexData[offset + 3] = particle.color.r;
  27719. this._vertexData[offset + 4] = particle.color.g;
  27720. this._vertexData[offset + 5] = particle.color.b;
  27721. this._vertexData[offset + 6] = particle.color.a;
  27722. this._vertexData[offset + 7] = particle.angle;
  27723. this._vertexData[offset + 8] = particle.size;
  27724. this._vertexData[offset + 9] = offsetX;
  27725. this._vertexData[offset + 10] = offsetY;
  27726. };
  27727. ParticleSystem.prototype._update = function (newParticles) {
  27728. // Update current
  27729. this._alive = this.particles.length > 0;
  27730. this.updateFunction(this.particles);
  27731. // Add new ones
  27732. var worldMatrix;
  27733. if (this.emitter.position) {
  27734. worldMatrix = this.emitter.getWorldMatrix();
  27735. }
  27736. else {
  27737. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27738. }
  27739. var particle;
  27740. for (var index = 0; index < newParticles; index++) {
  27741. if (this.particles.length === this._capacity) {
  27742. break;
  27743. }
  27744. if (this._stockParticles.length !== 0) {
  27745. particle = this._stockParticles.pop();
  27746. particle.age = 0;
  27747. }
  27748. else {
  27749. particle = new BABYLON.Particle();
  27750. }
  27751. this.particles.push(particle);
  27752. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27753. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27754. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27755. particle.size = randomNumber(this.minSize, this.maxSize);
  27756. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27757. this.startPositionFunction(worldMatrix, particle.position, particle);
  27758. var step = randomNumber(0, 1.0);
  27759. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27760. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27761. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27762. }
  27763. };
  27764. ParticleSystem.prototype._getEffect = function () {
  27765. if (this._customEffect) {
  27766. return this._customEffect;
  27767. }
  27768. ;
  27769. var defines = [];
  27770. if (this._scene.clipPlane) {
  27771. defines.push("#define CLIPPLANE");
  27772. }
  27773. // Effect
  27774. var join = defines.join("\n");
  27775. if (this._cachedDefines !== join) {
  27776. this._cachedDefines = join;
  27777. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27778. }
  27779. return this._effect;
  27780. };
  27781. ParticleSystem.prototype.animate = function () {
  27782. if (!this._started)
  27783. return;
  27784. var effect = this._getEffect();
  27785. // Check
  27786. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27787. return;
  27788. if (this._currentRenderId === this._scene.getRenderId()) {
  27789. return;
  27790. }
  27791. this._currentRenderId = this._scene.getRenderId();
  27792. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27793. // determine the number of particles we need to create
  27794. var newParticles;
  27795. if (this.manualEmitCount > -1) {
  27796. newParticles = this.manualEmitCount;
  27797. this._newPartsExcess = 0;
  27798. this.manualEmitCount = 0;
  27799. }
  27800. else {
  27801. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27802. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27803. }
  27804. if (this._newPartsExcess > 1.0) {
  27805. newParticles += this._newPartsExcess >> 0;
  27806. this._newPartsExcess -= this._newPartsExcess >> 0;
  27807. }
  27808. this._alive = false;
  27809. if (!this._stopped) {
  27810. this._actualFrame += this._scaledUpdateSpeed;
  27811. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27812. this.stop();
  27813. }
  27814. else {
  27815. newParticles = 0;
  27816. }
  27817. this._update(newParticles);
  27818. // Stopped?
  27819. if (this._stopped) {
  27820. if (!this._alive) {
  27821. this._started = false;
  27822. if (this.disposeOnStop) {
  27823. this._scene._toBeDisposed.push(this);
  27824. }
  27825. }
  27826. }
  27827. // Update VBO
  27828. var offset = 0;
  27829. for (var index = 0; index < this.particles.length; index++) {
  27830. var particle = this.particles[index];
  27831. this._appendParticleVertex(offset++, particle, 0, 0);
  27832. this._appendParticleVertex(offset++, particle, 1, 0);
  27833. this._appendParticleVertex(offset++, particle, 1, 1);
  27834. this._appendParticleVertex(offset++, particle, 0, 1);
  27835. }
  27836. this._vertexBuffer.update(this._vertexData);
  27837. };
  27838. ParticleSystem.prototype.render = function () {
  27839. var effect = this._getEffect();
  27840. // Check
  27841. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27842. return 0;
  27843. var engine = this._scene.getEngine();
  27844. // Render
  27845. engine.enableEffect(effect);
  27846. engine.setState(false);
  27847. var viewMatrix = this._scene.getViewMatrix();
  27848. effect.setTexture("diffuseSampler", this.particleTexture);
  27849. effect.setMatrix("view", viewMatrix);
  27850. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27851. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27852. if (this._scene.clipPlane) {
  27853. var clipPlane = this._scene.clipPlane;
  27854. var invView = viewMatrix.clone();
  27855. invView.invert();
  27856. effect.setMatrix("invView", invView);
  27857. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27858. }
  27859. // VBOs
  27860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27861. // Draw order
  27862. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27863. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27864. }
  27865. else {
  27866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27867. }
  27868. if (this.forceDepthWrite) {
  27869. engine.setDepthWrite(true);
  27870. }
  27871. engine.draw(true, 0, this.particles.length * 6);
  27872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27873. return this.particles.length;
  27874. };
  27875. ParticleSystem.prototype.dispose = function () {
  27876. if (this._vertexBuffer) {
  27877. this._vertexBuffer.dispose();
  27878. this._vertexBuffer = null;
  27879. }
  27880. if (this._indexBuffer) {
  27881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27882. this._indexBuffer = null;
  27883. }
  27884. if (this.particleTexture) {
  27885. this.particleTexture.dispose();
  27886. this.particleTexture = null;
  27887. }
  27888. // Remove from scene
  27889. var index = this._scene.particleSystems.indexOf(this);
  27890. this._scene.particleSystems.splice(index, 1);
  27891. // Callback
  27892. this.onDisposeObservable.notifyObservers(this);
  27893. this.onDisposeObservable.clear();
  27894. };
  27895. // Clone
  27896. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27897. var result = new ParticleSystem(name, this._capacity, this._scene);
  27898. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27899. if (newEmitter === undefined) {
  27900. newEmitter = this.emitter;
  27901. }
  27902. result.emitter = newEmitter;
  27903. if (this.particleTexture) {
  27904. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27905. }
  27906. result.start();
  27907. return result;
  27908. };
  27909. ParticleSystem.prototype.serialize = function () {
  27910. var serializationObject = {};
  27911. serializationObject.name = this.name;
  27912. serializationObject.id = this.id;
  27913. // Emitter
  27914. if (this.emitter.position) {
  27915. serializationObject.emitterId = this.emitter.id;
  27916. }
  27917. else {
  27918. serializationObject.emitter = this.emitter.asArray();
  27919. }
  27920. serializationObject.capacity = this.getCapacity();
  27921. if (this.particleTexture) {
  27922. serializationObject.textureName = this.particleTexture.name;
  27923. }
  27924. // Animations
  27925. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27926. // Particle system
  27927. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27928. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27929. serializationObject.minSize = this.minSize;
  27930. serializationObject.maxSize = this.maxSize;
  27931. serializationObject.minEmitPower = this.minEmitPower;
  27932. serializationObject.maxEmitPower = this.maxEmitPower;
  27933. serializationObject.minLifeTime = this.minLifeTime;
  27934. serializationObject.maxLifeTime = this.maxLifeTime;
  27935. serializationObject.emitRate = this.emitRate;
  27936. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27937. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27938. serializationObject.gravity = this.gravity.asArray();
  27939. serializationObject.direction1 = this.direction1.asArray();
  27940. serializationObject.direction2 = this.direction2.asArray();
  27941. serializationObject.color1 = this.color1.asArray();
  27942. serializationObject.color2 = this.color2.asArray();
  27943. serializationObject.colorDead = this.colorDead.asArray();
  27944. serializationObject.updateSpeed = this.updateSpeed;
  27945. serializationObject.targetStopDuration = this.targetStopDuration;
  27946. serializationObject.textureMask = this.textureMask.asArray();
  27947. serializationObject.blendMode = this.blendMode;
  27948. return serializationObject;
  27949. };
  27950. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27951. var name = parsedParticleSystem.name;
  27952. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27953. if (parsedParticleSystem.id) {
  27954. particleSystem.id = parsedParticleSystem.id;
  27955. }
  27956. // Texture
  27957. if (parsedParticleSystem.textureName) {
  27958. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27959. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27960. }
  27961. // Emitter
  27962. if (parsedParticleSystem.emitterId) {
  27963. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27964. }
  27965. else {
  27966. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27967. }
  27968. // Animations
  27969. if (parsedParticleSystem.animations) {
  27970. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27971. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27972. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27973. }
  27974. }
  27975. if (parsedParticleSystem.autoAnimate) {
  27976. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27977. }
  27978. // Particle system
  27979. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27980. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27981. particleSystem.minSize = parsedParticleSystem.minSize;
  27982. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27983. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27984. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27985. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27986. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27987. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27988. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27989. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27990. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27991. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27992. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27993. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27994. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27995. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27996. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27997. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27998. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27999. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28000. if (!parsedParticleSystem.preventAutoStart) {
  28001. particleSystem.start();
  28002. }
  28003. return particleSystem;
  28004. };
  28005. // Statics
  28006. ParticleSystem.BLENDMODE_ONEONE = 0;
  28007. ParticleSystem.BLENDMODE_STANDARD = 1;
  28008. return ParticleSystem;
  28009. }());
  28010. BABYLON.ParticleSystem = ParticleSystem;
  28011. })(BABYLON || (BABYLON = {}));
  28012. var BABYLON;
  28013. (function (BABYLON) {
  28014. var AnimationRange = (function () {
  28015. function AnimationRange(name, from, to) {
  28016. this.name = name;
  28017. this.from = from;
  28018. this.to = to;
  28019. }
  28020. AnimationRange.prototype.clone = function () {
  28021. return new AnimationRange(this.name, this.from, this.to);
  28022. };
  28023. return AnimationRange;
  28024. }());
  28025. BABYLON.AnimationRange = AnimationRange;
  28026. /**
  28027. * Composed of a frame, and an action function
  28028. */
  28029. var AnimationEvent = (function () {
  28030. function AnimationEvent(frame, action, onlyOnce) {
  28031. this.frame = frame;
  28032. this.action = action;
  28033. this.onlyOnce = onlyOnce;
  28034. this.isDone = false;
  28035. }
  28036. return AnimationEvent;
  28037. }());
  28038. BABYLON.AnimationEvent = AnimationEvent;
  28039. var PathCursor = (function () {
  28040. function PathCursor(path) {
  28041. this.path = path;
  28042. this._onchange = new Array();
  28043. this.value = 0;
  28044. this.animations = new Array();
  28045. }
  28046. PathCursor.prototype.getPoint = function () {
  28047. var point = this.path.getPointAtLengthPosition(this.value);
  28048. return new BABYLON.Vector3(point.x, 0, point.y);
  28049. };
  28050. PathCursor.prototype.moveAhead = function (step) {
  28051. if (step === void 0) { step = 0.002; }
  28052. this.move(step);
  28053. return this;
  28054. };
  28055. PathCursor.prototype.moveBack = function (step) {
  28056. if (step === void 0) { step = 0.002; }
  28057. this.move(-step);
  28058. return this;
  28059. };
  28060. PathCursor.prototype.move = function (step) {
  28061. if (Math.abs(step) > 1) {
  28062. throw "step size should be less than 1.";
  28063. }
  28064. this.value += step;
  28065. this.ensureLimits();
  28066. this.raiseOnChange();
  28067. return this;
  28068. };
  28069. PathCursor.prototype.ensureLimits = function () {
  28070. while (this.value > 1) {
  28071. this.value -= 1;
  28072. }
  28073. while (this.value < 0) {
  28074. this.value += 1;
  28075. }
  28076. return this;
  28077. };
  28078. // used by animation engine
  28079. PathCursor.prototype.markAsDirty = function (propertyName) {
  28080. this.ensureLimits();
  28081. this.raiseOnChange();
  28082. return this;
  28083. };
  28084. PathCursor.prototype.raiseOnChange = function () {
  28085. var _this = this;
  28086. this._onchange.forEach(function (f) { return f(_this); });
  28087. return this;
  28088. };
  28089. PathCursor.prototype.onchange = function (f) {
  28090. this._onchange.push(f);
  28091. return this;
  28092. };
  28093. return PathCursor;
  28094. }());
  28095. BABYLON.PathCursor = PathCursor;
  28096. var Animation = (function () {
  28097. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28098. this.name = name;
  28099. this.targetProperty = targetProperty;
  28100. this.framePerSecond = framePerSecond;
  28101. this.dataType = dataType;
  28102. this.loopMode = loopMode;
  28103. this.enableBlending = enableBlending;
  28104. this._offsetsCache = {};
  28105. this._highLimitsCache = {};
  28106. this._stopped = false;
  28107. this._blendingFactor = 0;
  28108. // The set of event that will be linked to this animation
  28109. this._events = new Array();
  28110. this.allowMatricesInterpolation = false;
  28111. this.blendingSpeed = 0.01;
  28112. this._ranges = {};
  28113. this.targetPropertyPath = targetProperty.split(".");
  28114. this.dataType = dataType;
  28115. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28116. }
  28117. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28118. var dataType = undefined;
  28119. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28120. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28121. }
  28122. else if (from instanceof BABYLON.Quaternion) {
  28123. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28124. }
  28125. else if (from instanceof BABYLON.Vector3) {
  28126. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28127. }
  28128. else if (from instanceof BABYLON.Vector2) {
  28129. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28130. }
  28131. else if (from instanceof BABYLON.Color3) {
  28132. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28133. }
  28134. else if (from instanceof BABYLON.Size) {
  28135. dataType = Animation.ANIMATIONTYPE_SIZE;
  28136. }
  28137. if (dataType == undefined) {
  28138. return null;
  28139. }
  28140. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28141. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28142. animation.setKeys(keys);
  28143. if (easingFunction !== undefined) {
  28144. animation.setEasingFunction(easingFunction);
  28145. }
  28146. return animation;
  28147. };
  28148. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28149. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28150. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28151. };
  28152. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28153. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28154. node.animations.push(animation);
  28155. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28156. };
  28157. // Methods
  28158. /**
  28159. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28160. */
  28161. Animation.prototype.toString = function (fullDetails) {
  28162. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28163. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28164. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28165. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28166. if (fullDetails) {
  28167. ret += ", Ranges: {";
  28168. var first = true;
  28169. for (var name in this._ranges) {
  28170. if (first) {
  28171. ret += ", ";
  28172. first = false;
  28173. }
  28174. ret += name;
  28175. }
  28176. ret += "}";
  28177. }
  28178. return ret;
  28179. };
  28180. /**
  28181. * Add an event to this animation.
  28182. */
  28183. Animation.prototype.addEvent = function (event) {
  28184. this._events.push(event);
  28185. };
  28186. /**
  28187. * Remove all events found at the given frame
  28188. * @param frame
  28189. */
  28190. Animation.prototype.removeEvents = function (frame) {
  28191. for (var index = 0; index < this._events.length; index++) {
  28192. if (this._events[index].frame === frame) {
  28193. this._events.splice(index, 1);
  28194. index--;
  28195. }
  28196. }
  28197. };
  28198. Animation.prototype.createRange = function (name, from, to) {
  28199. // check name not already in use; could happen for bones after serialized
  28200. if (!this._ranges[name]) {
  28201. this._ranges[name] = new AnimationRange(name, from, to);
  28202. }
  28203. };
  28204. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28205. if (deleteFrames === void 0) { deleteFrames = true; }
  28206. if (this._ranges[name]) {
  28207. if (deleteFrames) {
  28208. var from = this._ranges[name].from;
  28209. var to = this._ranges[name].to;
  28210. // this loop MUST go high to low for multiple splices to work
  28211. for (var key = this._keys.length - 1; key >= 0; key--) {
  28212. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28213. this._keys.splice(key, 1);
  28214. }
  28215. }
  28216. }
  28217. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28218. }
  28219. };
  28220. Animation.prototype.getRange = function (name) {
  28221. return this._ranges[name];
  28222. };
  28223. Animation.prototype.reset = function () {
  28224. this._offsetsCache = {};
  28225. this._highLimitsCache = {};
  28226. this.currentFrame = 0;
  28227. this._blendingFactor = 0;
  28228. this._originalBlendValue = null;
  28229. };
  28230. Animation.prototype.isStopped = function () {
  28231. return this._stopped;
  28232. };
  28233. Animation.prototype.getKeys = function () {
  28234. return this._keys;
  28235. };
  28236. Animation.prototype.getHighestFrame = function () {
  28237. var ret = 0;
  28238. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28239. if (ret < this._keys[key].frame) {
  28240. ret = this._keys[key].frame;
  28241. }
  28242. }
  28243. return ret;
  28244. };
  28245. Animation.prototype.getEasingFunction = function () {
  28246. return this._easingFunction;
  28247. };
  28248. Animation.prototype.setEasingFunction = function (easingFunction) {
  28249. this._easingFunction = easingFunction;
  28250. };
  28251. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28252. return startValue + (endValue - startValue) * gradient;
  28253. };
  28254. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28255. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28256. };
  28257. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28258. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28259. };
  28260. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28261. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28262. };
  28263. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28264. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28265. };
  28266. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28267. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28268. };
  28269. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28270. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28271. };
  28272. Animation.prototype.clone = function () {
  28273. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28274. if (this._keys) {
  28275. clone.setKeys(this._keys);
  28276. }
  28277. if (this._ranges) {
  28278. clone._ranges = {};
  28279. for (var name in this._ranges) {
  28280. clone._ranges[name] = this._ranges[name].clone();
  28281. }
  28282. }
  28283. return clone;
  28284. };
  28285. Animation.prototype.setKeys = function (values) {
  28286. this._keys = values.slice(0);
  28287. this._offsetsCache = {};
  28288. this._highLimitsCache = {};
  28289. };
  28290. Animation.prototype._getKeyValue = function (value) {
  28291. if (typeof value === "function") {
  28292. return value();
  28293. }
  28294. return value;
  28295. };
  28296. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28297. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28298. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28299. }
  28300. this.currentFrame = currentFrame;
  28301. // Try to get a hash to find the right key
  28302. 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));
  28303. if (this._keys[startKey].frame >= currentFrame) {
  28304. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28305. startKey--;
  28306. }
  28307. }
  28308. for (var key = startKey; key < this._keys.length; key++) {
  28309. if (this._keys[key + 1].frame >= currentFrame) {
  28310. var startValue = this._getKeyValue(this._keys[key].value);
  28311. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28312. // gradient : percent of currentFrame between the frame inf and the frame sup
  28313. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28314. // check for easingFunction and correction of gradient
  28315. if (this._easingFunction != null) {
  28316. gradient = this._easingFunction.ease(gradient);
  28317. }
  28318. switch (this.dataType) {
  28319. // Float
  28320. case Animation.ANIMATIONTYPE_FLOAT:
  28321. switch (loopMode) {
  28322. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28323. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28324. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28325. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28326. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28327. }
  28328. break;
  28329. // Quaternion
  28330. case Animation.ANIMATIONTYPE_QUATERNION:
  28331. var quaternion = null;
  28332. switch (loopMode) {
  28333. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28334. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28335. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28336. break;
  28337. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28338. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28339. break;
  28340. }
  28341. return quaternion;
  28342. // Vector3
  28343. case Animation.ANIMATIONTYPE_VECTOR3:
  28344. switch (loopMode) {
  28345. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28346. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28347. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28348. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28349. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28350. }
  28351. // Vector2
  28352. case Animation.ANIMATIONTYPE_VECTOR2:
  28353. switch (loopMode) {
  28354. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28355. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28356. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28357. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28358. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28359. }
  28360. // Size
  28361. case Animation.ANIMATIONTYPE_SIZE:
  28362. switch (loopMode) {
  28363. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28364. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28365. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28366. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28367. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28368. }
  28369. // Color3
  28370. case Animation.ANIMATIONTYPE_COLOR3:
  28371. switch (loopMode) {
  28372. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28373. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28374. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28375. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28376. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28377. }
  28378. // Matrix
  28379. case Animation.ANIMATIONTYPE_MATRIX:
  28380. switch (loopMode) {
  28381. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28382. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28383. if (this.allowMatricesInterpolation) {
  28384. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28385. }
  28386. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28387. return startValue;
  28388. }
  28389. default:
  28390. break;
  28391. }
  28392. break;
  28393. }
  28394. }
  28395. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28396. };
  28397. Animation.prototype.setValue = function (currentValue, blend) {
  28398. if (blend === void 0) { blend = false; }
  28399. // Set value
  28400. var path;
  28401. var destination;
  28402. if (this.targetPropertyPath.length > 1) {
  28403. var property = this._target[this.targetPropertyPath[0]];
  28404. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28405. property = property[this.targetPropertyPath[index]];
  28406. }
  28407. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28408. destination = property;
  28409. }
  28410. else {
  28411. path = this.targetPropertyPath[0];
  28412. destination = this._target;
  28413. }
  28414. // Blending
  28415. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28416. if (!this._originalBlendValue) {
  28417. if (destination[path].clone) {
  28418. this._originalBlendValue = destination[path].clone();
  28419. }
  28420. else {
  28421. this._originalBlendValue = destination[path];
  28422. }
  28423. }
  28424. if (this._originalBlendValue.prototype) {
  28425. if (this._originalBlendValue.prototype.Lerp) {
  28426. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28427. }
  28428. else {
  28429. destination[path] = currentValue;
  28430. }
  28431. }
  28432. else if (this._originalBlendValue.m) {
  28433. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28434. }
  28435. else {
  28436. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28437. }
  28438. this._blendingFactor += this.blendingSpeed;
  28439. }
  28440. else {
  28441. destination[path] = currentValue;
  28442. }
  28443. if (this._target.markAsDirty) {
  28444. this._target.markAsDirty(this.targetProperty);
  28445. }
  28446. };
  28447. Animation.prototype.goToFrame = function (frame) {
  28448. if (frame < this._keys[0].frame) {
  28449. frame = this._keys[0].frame;
  28450. }
  28451. else if (frame > this._keys[this._keys.length - 1].frame) {
  28452. frame = this._keys[this._keys.length - 1].frame;
  28453. }
  28454. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28455. this.setValue(currentValue);
  28456. };
  28457. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28458. if (blend === void 0) { blend = false; }
  28459. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28460. this._stopped = true;
  28461. return false;
  28462. }
  28463. var returnValue = true;
  28464. // Adding a start key at frame 0 if missing
  28465. if (this._keys[0].frame !== 0) {
  28466. var newKey = { frame: 0, value: this._keys[0].value };
  28467. this._keys.splice(0, 0, newKey);
  28468. }
  28469. // Check limits
  28470. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28471. from = this._keys[0].frame;
  28472. }
  28473. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28474. to = this._keys[this._keys.length - 1].frame;
  28475. }
  28476. // Compute ratio
  28477. var range = to - from;
  28478. var offsetValue;
  28479. // ratio represents the frame delta between from and to
  28480. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28481. var highLimitValue = 0;
  28482. if (ratio > range && !loop) {
  28483. returnValue = false;
  28484. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28485. }
  28486. else {
  28487. // Get max value if required
  28488. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28489. var keyOffset = to.toString() + from.toString();
  28490. if (!this._offsetsCache[keyOffset]) {
  28491. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28492. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28493. switch (this.dataType) {
  28494. // Float
  28495. case Animation.ANIMATIONTYPE_FLOAT:
  28496. this._offsetsCache[keyOffset] = toValue - fromValue;
  28497. break;
  28498. // Quaternion
  28499. case Animation.ANIMATIONTYPE_QUATERNION:
  28500. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28501. break;
  28502. // Vector3
  28503. case Animation.ANIMATIONTYPE_VECTOR3:
  28504. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28505. // Vector2
  28506. case Animation.ANIMATIONTYPE_VECTOR2:
  28507. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28508. // Size
  28509. case Animation.ANIMATIONTYPE_SIZE:
  28510. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28511. // Color3
  28512. case Animation.ANIMATIONTYPE_COLOR3:
  28513. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28514. default:
  28515. break;
  28516. }
  28517. this._highLimitsCache[keyOffset] = toValue;
  28518. }
  28519. highLimitValue = this._highLimitsCache[keyOffset];
  28520. offsetValue = this._offsetsCache[keyOffset];
  28521. }
  28522. }
  28523. if (offsetValue === undefined) {
  28524. switch (this.dataType) {
  28525. // Float
  28526. case Animation.ANIMATIONTYPE_FLOAT:
  28527. offsetValue = 0;
  28528. break;
  28529. // Quaternion
  28530. case Animation.ANIMATIONTYPE_QUATERNION:
  28531. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28532. break;
  28533. // Vector3
  28534. case Animation.ANIMATIONTYPE_VECTOR3:
  28535. offsetValue = BABYLON.Vector3.Zero();
  28536. break;
  28537. // Vector2
  28538. case Animation.ANIMATIONTYPE_VECTOR2:
  28539. offsetValue = BABYLON.Vector2.Zero();
  28540. break;
  28541. // Size
  28542. case Animation.ANIMATIONTYPE_SIZE:
  28543. offsetValue = BABYLON.Size.Zero();
  28544. break;
  28545. // Color3
  28546. case Animation.ANIMATIONTYPE_COLOR3:
  28547. offsetValue = BABYLON.Color3.Black();
  28548. }
  28549. }
  28550. // Compute value
  28551. var repeatCount = (ratio / range) >> 0;
  28552. var currentFrame = returnValue ? from + ratio % range : to;
  28553. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28554. // Set value
  28555. this.setValue(currentValue);
  28556. // Check events
  28557. for (var index = 0; index < this._events.length; index++) {
  28558. if (currentFrame >= this._events[index].frame) {
  28559. var event = this._events[index];
  28560. if (!event.isDone) {
  28561. // If event should be done only once, remove it.
  28562. if (event.onlyOnce) {
  28563. this._events.splice(index, 1);
  28564. index--;
  28565. }
  28566. event.isDone = true;
  28567. event.action();
  28568. } // Don't do anything if the event has already be done.
  28569. }
  28570. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28571. // reset event, the animation is looping
  28572. this._events[index].isDone = false;
  28573. }
  28574. }
  28575. if (!returnValue) {
  28576. this._stopped = true;
  28577. }
  28578. return returnValue;
  28579. };
  28580. Animation.prototype.serialize = function () {
  28581. var serializationObject = {};
  28582. serializationObject.name = this.name;
  28583. serializationObject.property = this.targetProperty;
  28584. serializationObject.framePerSecond = this.framePerSecond;
  28585. serializationObject.dataType = this.dataType;
  28586. serializationObject.loopBehavior = this.loopMode;
  28587. var dataType = this.dataType;
  28588. serializationObject.keys = [];
  28589. var keys = this.getKeys();
  28590. for (var index = 0; index < keys.length; index++) {
  28591. var animationKey = keys[index];
  28592. var key = {};
  28593. key.frame = animationKey.frame;
  28594. switch (dataType) {
  28595. case Animation.ANIMATIONTYPE_FLOAT:
  28596. key.values = [animationKey.value];
  28597. break;
  28598. case Animation.ANIMATIONTYPE_QUATERNION:
  28599. case Animation.ANIMATIONTYPE_MATRIX:
  28600. case Animation.ANIMATIONTYPE_VECTOR3:
  28601. case Animation.ANIMATIONTYPE_COLOR3:
  28602. key.values = animationKey.value.asArray();
  28603. break;
  28604. }
  28605. serializationObject.keys.push(key);
  28606. }
  28607. serializationObject.ranges = [];
  28608. for (var name in this._ranges) {
  28609. var range = {};
  28610. range.name = name;
  28611. range.from = this._ranges[name].from;
  28612. range.to = this._ranges[name].to;
  28613. serializationObject.ranges.push(range);
  28614. }
  28615. return serializationObject;
  28616. };
  28617. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28618. get: function () {
  28619. return Animation._ANIMATIONTYPE_FLOAT;
  28620. },
  28621. enumerable: true,
  28622. configurable: true
  28623. });
  28624. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28625. get: function () {
  28626. return Animation._ANIMATIONTYPE_VECTOR3;
  28627. },
  28628. enumerable: true,
  28629. configurable: true
  28630. });
  28631. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28632. get: function () {
  28633. return Animation._ANIMATIONTYPE_VECTOR2;
  28634. },
  28635. enumerable: true,
  28636. configurable: true
  28637. });
  28638. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28639. get: function () {
  28640. return Animation._ANIMATIONTYPE_SIZE;
  28641. },
  28642. enumerable: true,
  28643. configurable: true
  28644. });
  28645. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28646. get: function () {
  28647. return Animation._ANIMATIONTYPE_QUATERNION;
  28648. },
  28649. enumerable: true,
  28650. configurable: true
  28651. });
  28652. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28653. get: function () {
  28654. return Animation._ANIMATIONTYPE_MATRIX;
  28655. },
  28656. enumerable: true,
  28657. configurable: true
  28658. });
  28659. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28660. get: function () {
  28661. return Animation._ANIMATIONTYPE_COLOR3;
  28662. },
  28663. enumerable: true,
  28664. configurable: true
  28665. });
  28666. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28667. get: function () {
  28668. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28669. },
  28670. enumerable: true,
  28671. configurable: true
  28672. });
  28673. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28674. get: function () {
  28675. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28676. },
  28677. enumerable: true,
  28678. configurable: true
  28679. });
  28680. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28681. get: function () {
  28682. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28683. },
  28684. enumerable: true,
  28685. configurable: true
  28686. });
  28687. Animation.Parse = function (parsedAnimation) {
  28688. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28689. var dataType = parsedAnimation.dataType;
  28690. var keys = [];
  28691. var data;
  28692. var index;
  28693. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28694. var key = parsedAnimation.keys[index];
  28695. switch (dataType) {
  28696. case Animation.ANIMATIONTYPE_FLOAT:
  28697. data = key.values[0];
  28698. break;
  28699. case Animation.ANIMATIONTYPE_QUATERNION:
  28700. data = BABYLON.Quaternion.FromArray(key.values);
  28701. break;
  28702. case Animation.ANIMATIONTYPE_MATRIX:
  28703. data = BABYLON.Matrix.FromArray(key.values);
  28704. break;
  28705. case Animation.ANIMATIONTYPE_COLOR3:
  28706. data = BABYLON.Color3.FromArray(key.values);
  28707. break;
  28708. case Animation.ANIMATIONTYPE_VECTOR3:
  28709. default:
  28710. data = BABYLON.Vector3.FromArray(key.values);
  28711. break;
  28712. }
  28713. keys.push({
  28714. frame: key.frame,
  28715. value: data
  28716. });
  28717. }
  28718. animation.setKeys(keys);
  28719. if (parsedAnimation.ranges) {
  28720. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28721. data = parsedAnimation.ranges[index];
  28722. animation.createRange(data.name, data.from, data.to);
  28723. }
  28724. }
  28725. return animation;
  28726. };
  28727. Animation.AppendSerializedAnimations = function (source, destination) {
  28728. if (source.animations) {
  28729. destination.animations = [];
  28730. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28731. var animation = source.animations[animationIndex];
  28732. destination.animations.push(animation.serialize());
  28733. }
  28734. }
  28735. };
  28736. // Statics
  28737. Animation._ANIMATIONTYPE_FLOAT = 0;
  28738. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28739. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28740. Animation._ANIMATIONTYPE_MATRIX = 3;
  28741. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28742. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28743. Animation._ANIMATIONTYPE_SIZE = 6;
  28744. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28745. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28746. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28747. return Animation;
  28748. }());
  28749. BABYLON.Animation = Animation;
  28750. })(BABYLON || (BABYLON = {}));
  28751. var BABYLON;
  28752. (function (BABYLON) {
  28753. var Animatable = (function () {
  28754. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28755. if (fromFrame === void 0) { fromFrame = 0; }
  28756. if (toFrame === void 0) { toFrame = 100; }
  28757. if (loopAnimation === void 0) { loopAnimation = false; }
  28758. if (speedRatio === void 0) { speedRatio = 1.0; }
  28759. this.target = target;
  28760. this.fromFrame = fromFrame;
  28761. this.toFrame = toFrame;
  28762. this.loopAnimation = loopAnimation;
  28763. this.speedRatio = speedRatio;
  28764. this.onAnimationEnd = onAnimationEnd;
  28765. this._animations = new Array();
  28766. this._paused = false;
  28767. this.animationStarted = false;
  28768. if (animations) {
  28769. this.appendAnimations(target, animations);
  28770. }
  28771. this._scene = scene;
  28772. scene._activeAnimatables.push(this);
  28773. }
  28774. // Methods
  28775. Animatable.prototype.getAnimations = function () {
  28776. return this._animations;
  28777. };
  28778. Animatable.prototype.appendAnimations = function (target, animations) {
  28779. for (var index = 0; index < animations.length; index++) {
  28780. var animation = animations[index];
  28781. animation._target = target;
  28782. this._animations.push(animation);
  28783. }
  28784. };
  28785. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28786. var animations = this._animations;
  28787. for (var index = 0; index < animations.length; index++) {
  28788. if (animations[index].targetProperty === property) {
  28789. return animations[index];
  28790. }
  28791. }
  28792. return null;
  28793. };
  28794. Animatable.prototype.reset = function () {
  28795. var animations = this._animations;
  28796. for (var index = 0; index < animations.length; index++) {
  28797. animations[index].reset();
  28798. }
  28799. this._localDelayOffset = null;
  28800. this._pausedDelay = null;
  28801. };
  28802. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28803. var animations = this._animations;
  28804. for (var index = 0; index < animations.length; index++) {
  28805. animations[index].enableBlending = true;
  28806. animations[index].blendingSpeed = blendingSpeed;
  28807. }
  28808. };
  28809. Animatable.prototype.disableBlending = function () {
  28810. var animations = this._animations;
  28811. for (var index = 0; index < animations.length; index++) {
  28812. animations[index].enableBlending = false;
  28813. }
  28814. };
  28815. Animatable.prototype.goToFrame = function (frame) {
  28816. var animations = this._animations;
  28817. for (var index = 0; index < animations.length; index++) {
  28818. animations[index].goToFrame(frame);
  28819. }
  28820. };
  28821. Animatable.prototype.pause = function () {
  28822. if (this._paused) {
  28823. return;
  28824. }
  28825. this._paused = true;
  28826. };
  28827. Animatable.prototype.restart = function () {
  28828. this._paused = false;
  28829. };
  28830. Animatable.prototype.stop = function () {
  28831. var index = this._scene._activeAnimatables.indexOf(this);
  28832. if (index > -1) {
  28833. this._scene._activeAnimatables.splice(index, 1);
  28834. var animations = this._animations;
  28835. for (var index = 0; index < animations.length; index++) {
  28836. animations[index].reset();
  28837. }
  28838. if (this.onAnimationEnd) {
  28839. this.onAnimationEnd();
  28840. }
  28841. }
  28842. };
  28843. Animatable.prototype._animate = function (delay) {
  28844. if (this._paused) {
  28845. this.animationStarted = false;
  28846. if (!this._pausedDelay) {
  28847. this._pausedDelay = delay;
  28848. }
  28849. return true;
  28850. }
  28851. if (!this._localDelayOffset) {
  28852. this._localDelayOffset = delay;
  28853. }
  28854. else if (this._pausedDelay) {
  28855. this._localDelayOffset += delay - this._pausedDelay;
  28856. this._pausedDelay = null;
  28857. }
  28858. // Animating
  28859. var running = false;
  28860. var animations = this._animations;
  28861. var index;
  28862. for (index = 0; index < animations.length; index++) {
  28863. var animation = animations[index];
  28864. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28865. running = running || isRunning;
  28866. }
  28867. this.animationStarted = running;
  28868. if (!running) {
  28869. // Remove from active animatables
  28870. index = this._scene._activeAnimatables.indexOf(this);
  28871. this._scene._activeAnimatables.splice(index, 1);
  28872. }
  28873. if (!running && this.onAnimationEnd) {
  28874. this.onAnimationEnd();
  28875. this.onAnimationEnd = null;
  28876. }
  28877. return running;
  28878. };
  28879. return Animatable;
  28880. }());
  28881. BABYLON.Animatable = Animatable;
  28882. })(BABYLON || (BABYLON = {}));
  28883. var BABYLON;
  28884. (function (BABYLON) {
  28885. var EasingFunction = (function () {
  28886. function EasingFunction() {
  28887. // Properties
  28888. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28889. }
  28890. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28891. get: function () {
  28892. return EasingFunction._EASINGMODE_EASEIN;
  28893. },
  28894. enumerable: true,
  28895. configurable: true
  28896. });
  28897. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28898. get: function () {
  28899. return EasingFunction._EASINGMODE_EASEOUT;
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28905. get: function () {
  28906. return EasingFunction._EASINGMODE_EASEINOUT;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28912. var n = Math.min(Math.max(easingMode, 0), 2);
  28913. this._easingMode = n;
  28914. };
  28915. EasingFunction.prototype.getEasingMode = function () {
  28916. return this._easingMode;
  28917. };
  28918. EasingFunction.prototype.easeInCore = function (gradient) {
  28919. throw new Error('You must implement this method');
  28920. };
  28921. EasingFunction.prototype.ease = function (gradient) {
  28922. switch (this._easingMode) {
  28923. case EasingFunction.EASINGMODE_EASEIN:
  28924. return this.easeInCore(gradient);
  28925. case EasingFunction.EASINGMODE_EASEOUT:
  28926. return (1 - this.easeInCore(1 - gradient));
  28927. }
  28928. if (gradient >= 0.5) {
  28929. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28930. }
  28931. return (this.easeInCore(gradient * 2) * 0.5);
  28932. };
  28933. //Statics
  28934. EasingFunction._EASINGMODE_EASEIN = 0;
  28935. EasingFunction._EASINGMODE_EASEOUT = 1;
  28936. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28937. return EasingFunction;
  28938. }());
  28939. BABYLON.EasingFunction = EasingFunction;
  28940. var CircleEase = (function (_super) {
  28941. __extends(CircleEase, _super);
  28942. function CircleEase() {
  28943. _super.apply(this, arguments);
  28944. }
  28945. CircleEase.prototype.easeInCore = function (gradient) {
  28946. gradient = Math.max(0, Math.min(1, gradient));
  28947. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28948. };
  28949. return CircleEase;
  28950. }(EasingFunction));
  28951. BABYLON.CircleEase = CircleEase;
  28952. var BackEase = (function (_super) {
  28953. __extends(BackEase, _super);
  28954. function BackEase(amplitude) {
  28955. if (amplitude === void 0) { amplitude = 1; }
  28956. _super.call(this);
  28957. this.amplitude = amplitude;
  28958. }
  28959. BackEase.prototype.easeInCore = function (gradient) {
  28960. var num = Math.max(0, this.amplitude);
  28961. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28962. };
  28963. return BackEase;
  28964. }(EasingFunction));
  28965. BABYLON.BackEase = BackEase;
  28966. var BounceEase = (function (_super) {
  28967. __extends(BounceEase, _super);
  28968. function BounceEase(bounces, bounciness) {
  28969. if (bounces === void 0) { bounces = 3; }
  28970. if (bounciness === void 0) { bounciness = 2; }
  28971. _super.call(this);
  28972. this.bounces = bounces;
  28973. this.bounciness = bounciness;
  28974. }
  28975. BounceEase.prototype.easeInCore = function (gradient) {
  28976. var y = Math.max(0.0, this.bounces);
  28977. var bounciness = this.bounciness;
  28978. if (bounciness <= 1.0) {
  28979. bounciness = 1.001;
  28980. }
  28981. var num9 = Math.pow(bounciness, y);
  28982. var num5 = 1.0 - bounciness;
  28983. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28984. var num15 = gradient * num4;
  28985. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28986. var num3 = Math.floor(num65);
  28987. var num13 = num3 + 1.0;
  28988. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28989. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28990. var num7 = (num8 + num12) * 0.5;
  28991. var num6 = gradient - num7;
  28992. var num2 = num7 - num8;
  28993. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28994. };
  28995. return BounceEase;
  28996. }(EasingFunction));
  28997. BABYLON.BounceEase = BounceEase;
  28998. var CubicEase = (function (_super) {
  28999. __extends(CubicEase, _super);
  29000. function CubicEase() {
  29001. _super.apply(this, arguments);
  29002. }
  29003. CubicEase.prototype.easeInCore = function (gradient) {
  29004. return (gradient * gradient * gradient);
  29005. };
  29006. return CubicEase;
  29007. }(EasingFunction));
  29008. BABYLON.CubicEase = CubicEase;
  29009. var ElasticEase = (function (_super) {
  29010. __extends(ElasticEase, _super);
  29011. function ElasticEase(oscillations, springiness) {
  29012. if (oscillations === void 0) { oscillations = 3; }
  29013. if (springiness === void 0) { springiness = 3; }
  29014. _super.call(this);
  29015. this.oscillations = oscillations;
  29016. this.springiness = springiness;
  29017. }
  29018. ElasticEase.prototype.easeInCore = function (gradient) {
  29019. var num2;
  29020. var num3 = Math.max(0.0, this.oscillations);
  29021. var num = Math.max(0.0, this.springiness);
  29022. if (num == 0) {
  29023. num2 = gradient;
  29024. }
  29025. else {
  29026. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29027. }
  29028. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29029. };
  29030. return ElasticEase;
  29031. }(EasingFunction));
  29032. BABYLON.ElasticEase = ElasticEase;
  29033. var ExponentialEase = (function (_super) {
  29034. __extends(ExponentialEase, _super);
  29035. function ExponentialEase(exponent) {
  29036. if (exponent === void 0) { exponent = 2; }
  29037. _super.call(this);
  29038. this.exponent = exponent;
  29039. }
  29040. ExponentialEase.prototype.easeInCore = function (gradient) {
  29041. if (this.exponent <= 0) {
  29042. return gradient;
  29043. }
  29044. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29045. };
  29046. return ExponentialEase;
  29047. }(EasingFunction));
  29048. BABYLON.ExponentialEase = ExponentialEase;
  29049. var PowerEase = (function (_super) {
  29050. __extends(PowerEase, _super);
  29051. function PowerEase(power) {
  29052. if (power === void 0) { power = 2; }
  29053. _super.call(this);
  29054. this.power = power;
  29055. }
  29056. PowerEase.prototype.easeInCore = function (gradient) {
  29057. var y = Math.max(0.0, this.power);
  29058. return Math.pow(gradient, y);
  29059. };
  29060. return PowerEase;
  29061. }(EasingFunction));
  29062. BABYLON.PowerEase = PowerEase;
  29063. var QuadraticEase = (function (_super) {
  29064. __extends(QuadraticEase, _super);
  29065. function QuadraticEase() {
  29066. _super.apply(this, arguments);
  29067. }
  29068. QuadraticEase.prototype.easeInCore = function (gradient) {
  29069. return (gradient * gradient);
  29070. };
  29071. return QuadraticEase;
  29072. }(EasingFunction));
  29073. BABYLON.QuadraticEase = QuadraticEase;
  29074. var QuarticEase = (function (_super) {
  29075. __extends(QuarticEase, _super);
  29076. function QuarticEase() {
  29077. _super.apply(this, arguments);
  29078. }
  29079. QuarticEase.prototype.easeInCore = function (gradient) {
  29080. return (gradient * gradient * gradient * gradient);
  29081. };
  29082. return QuarticEase;
  29083. }(EasingFunction));
  29084. BABYLON.QuarticEase = QuarticEase;
  29085. var QuinticEase = (function (_super) {
  29086. __extends(QuinticEase, _super);
  29087. function QuinticEase() {
  29088. _super.apply(this, arguments);
  29089. }
  29090. QuinticEase.prototype.easeInCore = function (gradient) {
  29091. return (gradient * gradient * gradient * gradient * gradient);
  29092. };
  29093. return QuinticEase;
  29094. }(EasingFunction));
  29095. BABYLON.QuinticEase = QuinticEase;
  29096. var SineEase = (function (_super) {
  29097. __extends(SineEase, _super);
  29098. function SineEase() {
  29099. _super.apply(this, arguments);
  29100. }
  29101. SineEase.prototype.easeInCore = function (gradient) {
  29102. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29103. };
  29104. return SineEase;
  29105. }(EasingFunction));
  29106. BABYLON.SineEase = SineEase;
  29107. var BezierCurveEase = (function (_super) {
  29108. __extends(BezierCurveEase, _super);
  29109. function BezierCurveEase(x1, y1, x2, y2) {
  29110. if (x1 === void 0) { x1 = 0; }
  29111. if (y1 === void 0) { y1 = 0; }
  29112. if (x2 === void 0) { x2 = 1; }
  29113. if (y2 === void 0) { y2 = 1; }
  29114. _super.call(this);
  29115. this.x1 = x1;
  29116. this.y1 = y1;
  29117. this.x2 = x2;
  29118. this.y2 = y2;
  29119. }
  29120. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29121. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29122. };
  29123. return BezierCurveEase;
  29124. }(EasingFunction));
  29125. BABYLON.BezierCurveEase = BezierCurveEase;
  29126. })(BABYLON || (BABYLON = {}));
  29127. var BABYLON;
  29128. (function (BABYLON) {
  29129. var Bone = (function (_super) {
  29130. __extends(Bone, _super);
  29131. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29132. _super.call(this, name, skeleton.getScene());
  29133. this.name = name;
  29134. this.children = new Array();
  29135. this.animations = new Array();
  29136. this._worldTransform = new BABYLON.Matrix();
  29137. this._absoluteTransform = new BABYLON.Matrix();
  29138. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29139. this._skeleton = skeleton;
  29140. this._matrix = matrix;
  29141. this._baseMatrix = matrix;
  29142. this._restPose = restPose ? restPose : matrix.clone();
  29143. skeleton.bones.push(this);
  29144. if (parentBone) {
  29145. this._parent = parentBone;
  29146. parentBone.children.push(this);
  29147. }
  29148. else {
  29149. this._parent = null;
  29150. }
  29151. this._updateDifferenceMatrix();
  29152. }
  29153. // Members
  29154. Bone.prototype.getParent = function () {
  29155. return this._parent;
  29156. };
  29157. Bone.prototype.getLocalMatrix = function () {
  29158. return this._matrix;
  29159. };
  29160. Bone.prototype.getBaseMatrix = function () {
  29161. return this._baseMatrix;
  29162. };
  29163. Bone.prototype.getRestPose = function () {
  29164. return this._restPose;
  29165. };
  29166. Bone.prototype.returnToRest = function () {
  29167. this.updateMatrix(this._restPose.clone());
  29168. };
  29169. Bone.prototype.getWorldMatrix = function () {
  29170. return this._worldTransform;
  29171. };
  29172. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29173. return this._invertedAbsoluteTransform;
  29174. };
  29175. Bone.prototype.getAbsoluteTransform = function () {
  29176. return this._absoluteTransform;
  29177. };
  29178. // Methods
  29179. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29180. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29181. this._baseMatrix = matrix.clone();
  29182. this._matrix = matrix.clone();
  29183. this._skeleton._markAsDirty();
  29184. if (updateDifferenceMatrix) {
  29185. this._updateDifferenceMatrix();
  29186. }
  29187. };
  29188. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29189. if (!rootMatrix) {
  29190. rootMatrix = this._baseMatrix;
  29191. }
  29192. if (this._parent) {
  29193. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29194. }
  29195. else {
  29196. this._absoluteTransform.copyFrom(rootMatrix);
  29197. }
  29198. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29199. for (var index = 0; index < this.children.length; index++) {
  29200. this.children[index]._updateDifferenceMatrix();
  29201. }
  29202. };
  29203. Bone.prototype.markAsDirty = function () {
  29204. this._currentRenderId++;
  29205. this._skeleton._markAsDirty();
  29206. };
  29207. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29208. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29209. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29210. // all animation may be coming from a library skeleton, so may need to create animation
  29211. if (this.animations.length === 0) {
  29212. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29213. this.animations[0].setKeys([]);
  29214. }
  29215. // get animation info / verify there is such a range from the source bone
  29216. var sourceRange = source.animations[0].getRange(rangeName);
  29217. if (!sourceRange) {
  29218. return false;
  29219. }
  29220. var from = sourceRange.from;
  29221. var to = sourceRange.to;
  29222. var sourceKeys = source.animations[0].getKeys();
  29223. // rescaling prep
  29224. var sourceBoneLength = source.length;
  29225. var sourceParent = source.getParent();
  29226. var parent = this.getParent();
  29227. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29228. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29229. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29230. var destKeys = this.animations[0].getKeys();
  29231. // loop vars declaration
  29232. var orig;
  29233. var origTranslation;
  29234. var mat;
  29235. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29236. orig = sourceKeys[key];
  29237. if (orig.frame >= from && orig.frame <= to) {
  29238. if (rescaleAsRequired) {
  29239. mat = orig.value.clone();
  29240. // scale based on parent ratio, when bone has parent
  29241. if (parentScalingReqd) {
  29242. origTranslation = mat.getTranslation();
  29243. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29244. }
  29245. else if (dimensionsScalingReqd) {
  29246. origTranslation = mat.getTranslation();
  29247. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29248. }
  29249. else {
  29250. mat = orig.value;
  29251. }
  29252. }
  29253. else {
  29254. mat = orig.value;
  29255. }
  29256. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29257. }
  29258. }
  29259. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29260. return true;
  29261. };
  29262. return Bone;
  29263. }(BABYLON.Node));
  29264. BABYLON.Bone = Bone;
  29265. })(BABYLON || (BABYLON = {}));
  29266. var BABYLON;
  29267. (function (BABYLON) {
  29268. var Skeleton = (function () {
  29269. function Skeleton(name, id, scene) {
  29270. this.name = name;
  29271. this.id = id;
  29272. this.bones = new Array();
  29273. this.needInitialSkinMatrix = false;
  29274. this._isDirty = true;
  29275. this._meshesWithPoseMatrix = new Array();
  29276. this._identity = BABYLON.Matrix.Identity();
  29277. this._ranges = {};
  29278. this.bones = [];
  29279. this._scene = scene;
  29280. scene.skeletons.push(this);
  29281. //make sure it will recalculate the matrix next time prepare is called.
  29282. this._isDirty = true;
  29283. }
  29284. // Members
  29285. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29286. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29287. return mesh._bonesTransformMatrices;
  29288. }
  29289. return this._transformMatrices;
  29290. };
  29291. Skeleton.prototype.getScene = function () {
  29292. return this._scene;
  29293. };
  29294. // Methods
  29295. /**
  29296. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29297. */
  29298. Skeleton.prototype.toString = function (fullDetails) {
  29299. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29300. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29301. if (fullDetails) {
  29302. ret += ", Ranges: {";
  29303. var first = true;
  29304. for (var name_1 in this._ranges) {
  29305. if (first) {
  29306. ret += ", ";
  29307. first = false;
  29308. }
  29309. ret += name_1;
  29310. }
  29311. ret += "}";
  29312. }
  29313. return ret;
  29314. };
  29315. /**
  29316. * Get bone's index searching by name
  29317. * @param {string} name is bone's name to search for
  29318. * @return {number} Indice of the bone. Returns -1 if not found
  29319. */
  29320. Skeleton.prototype.getBoneIndexByName = function (name) {
  29321. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29322. if (this.bones[boneIndex].name === name) {
  29323. return boneIndex;
  29324. }
  29325. }
  29326. return -1;
  29327. };
  29328. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29329. // check name not already in use
  29330. if (!this._ranges[name]) {
  29331. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29332. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29333. if (this.bones[i].animations[0]) {
  29334. this.bones[i].animations[0].createRange(name, from, to);
  29335. }
  29336. }
  29337. }
  29338. };
  29339. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29340. if (deleteFrames === void 0) { deleteFrames = true; }
  29341. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29342. if (this.bones[i].animations[0]) {
  29343. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29344. }
  29345. }
  29346. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29347. };
  29348. Skeleton.prototype.getAnimationRange = function (name) {
  29349. return this._ranges[name];
  29350. };
  29351. /**
  29352. * Returns as an Array, all AnimationRanges defined on this skeleton
  29353. */
  29354. Skeleton.prototype.getAnimationRanges = function () {
  29355. var animationRanges = [];
  29356. var name;
  29357. var i = 0;
  29358. for (name in this._ranges) {
  29359. animationRanges[i] = this._ranges[name];
  29360. i++;
  29361. }
  29362. return animationRanges;
  29363. };
  29364. /**
  29365. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29366. */
  29367. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29368. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29369. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29370. return false;
  29371. }
  29372. var ret = true;
  29373. var frameOffset = this._getHighestAnimationFrame() + 1;
  29374. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29375. var boneDict = {};
  29376. var sourceBones = source.bones;
  29377. var nBones;
  29378. var i;
  29379. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29380. boneDict[sourceBones[i].name] = sourceBones[i];
  29381. }
  29382. if (this.bones.length !== sourceBones.length) {
  29383. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29384. ret = false;
  29385. }
  29386. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29387. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29388. var boneName = this.bones[i].name;
  29389. var sourceBone = boneDict[boneName];
  29390. if (sourceBone) {
  29391. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29392. }
  29393. else {
  29394. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29395. ret = false;
  29396. }
  29397. }
  29398. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29399. var range = source.getAnimationRange(name);
  29400. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29401. return ret;
  29402. };
  29403. Skeleton.prototype.returnToRest = function () {
  29404. for (var index = 0; index < this.bones.length; index++) {
  29405. this.bones[index].returnToRest();
  29406. }
  29407. };
  29408. Skeleton.prototype._getHighestAnimationFrame = function () {
  29409. var ret = 0;
  29410. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29411. if (this.bones[i].animations[0]) {
  29412. var highest = this.bones[i].animations[0].getHighestFrame();
  29413. if (ret < highest) {
  29414. ret = highest;
  29415. }
  29416. }
  29417. }
  29418. return ret;
  29419. };
  29420. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29421. var range = this.getAnimationRange(name);
  29422. if (!range) {
  29423. return null;
  29424. }
  29425. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29426. };
  29427. Skeleton.prototype._markAsDirty = function () {
  29428. this._isDirty = true;
  29429. };
  29430. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29431. this._meshesWithPoseMatrix.push(mesh);
  29432. };
  29433. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29434. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29435. if (index > -1) {
  29436. this._meshesWithPoseMatrix.splice(index, 1);
  29437. }
  29438. };
  29439. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29440. for (var index = 0; index < this.bones.length; index++) {
  29441. var bone = this.bones[index];
  29442. var parentBone = bone.getParent();
  29443. if (parentBone) {
  29444. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29445. }
  29446. else {
  29447. if (initialSkinMatrix) {
  29448. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29449. }
  29450. else {
  29451. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29452. }
  29453. }
  29454. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29455. }
  29456. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29457. };
  29458. Skeleton.prototype.prepare = function () {
  29459. if (!this._isDirty) {
  29460. return;
  29461. }
  29462. if (this.needInitialSkinMatrix) {
  29463. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29464. var mesh = this._meshesWithPoseMatrix[index];
  29465. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29466. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29467. }
  29468. var poseMatrix = mesh.getPoseMatrix();
  29469. // Prepare bones
  29470. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29471. var bone = this.bones[boneIndex];
  29472. if (!bone.getParent()) {
  29473. var matrix = bone.getBaseMatrix();
  29474. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29475. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29476. }
  29477. }
  29478. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29479. }
  29480. }
  29481. else {
  29482. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29483. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29484. }
  29485. this._computeTransformMatrices(this._transformMatrices, null);
  29486. }
  29487. this._isDirty = false;
  29488. this._scene._activeBones.addCount(this.bones.length, false);
  29489. };
  29490. Skeleton.prototype.getAnimatables = function () {
  29491. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29492. this._animatables = [];
  29493. for (var index = 0; index < this.bones.length; index++) {
  29494. this._animatables.push(this.bones[index]);
  29495. }
  29496. }
  29497. return this._animatables;
  29498. };
  29499. Skeleton.prototype.clone = function (name, id) {
  29500. var result = new Skeleton(name, id || name, this._scene);
  29501. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29502. for (var index = 0; index < this.bones.length; index++) {
  29503. var source = this.bones[index];
  29504. var parentBone = null;
  29505. if (source.getParent()) {
  29506. var parentIndex = this.bones.indexOf(source.getParent());
  29507. parentBone = result.bones[parentIndex];
  29508. }
  29509. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29510. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29511. }
  29512. if (this._ranges) {
  29513. result._ranges = {};
  29514. for (var rangeName in this._ranges) {
  29515. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29516. }
  29517. }
  29518. this._isDirty = true;
  29519. return result;
  29520. };
  29521. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29522. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29523. this.bones.forEach(function (bone) {
  29524. bone.animations.forEach(function (animation) {
  29525. animation.enableBlending = true;
  29526. animation.blendingSpeed = blendingSpeed;
  29527. });
  29528. });
  29529. };
  29530. Skeleton.prototype.dispose = function () {
  29531. this._meshesWithPoseMatrix = [];
  29532. // Animations
  29533. this.getScene().stopAnimation(this);
  29534. // Remove from scene
  29535. this.getScene().removeSkeleton(this);
  29536. };
  29537. Skeleton.prototype.serialize = function () {
  29538. var serializationObject = {};
  29539. serializationObject.name = this.name;
  29540. serializationObject.id = this.id;
  29541. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29542. serializationObject.bones = [];
  29543. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29544. for (var index = 0; index < this.bones.length; index++) {
  29545. var bone = this.bones[index];
  29546. var serializedBone = {
  29547. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29548. name: bone.name,
  29549. matrix: bone.getLocalMatrix().toArray(),
  29550. rest: bone.getRestPose().toArray()
  29551. };
  29552. serializationObject.bones.push(serializedBone);
  29553. if (bone.length) {
  29554. serializedBone.length = bone.length;
  29555. }
  29556. if (bone.animations && bone.animations.length > 0) {
  29557. serializedBone.animation = bone.animations[0].serialize();
  29558. }
  29559. serializationObject.ranges = [];
  29560. for (var name in this._ranges) {
  29561. var range = {};
  29562. range.name = name;
  29563. range.from = this._ranges[name].from;
  29564. range.to = this._ranges[name].to;
  29565. serializationObject.ranges.push(range);
  29566. }
  29567. }
  29568. return serializationObject;
  29569. };
  29570. Skeleton.Parse = function (parsedSkeleton, scene) {
  29571. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29572. if (parsedSkeleton.dimensionsAtRest) {
  29573. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29574. }
  29575. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29576. var index;
  29577. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29578. var parsedBone = parsedSkeleton.bones[index];
  29579. var parentBone = null;
  29580. if (parsedBone.parentBoneIndex > -1) {
  29581. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29582. }
  29583. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29584. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29585. if (parsedBone.length) {
  29586. bone.length = parsedBone.length;
  29587. }
  29588. if (parsedBone.animation) {
  29589. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29590. }
  29591. }
  29592. // placed after bones, so createAnimationRange can cascade down
  29593. if (parsedSkeleton.ranges) {
  29594. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29595. var data = parsedSkeleton.ranges[index];
  29596. skeleton.createAnimationRange(data.name, data.from, data.to);
  29597. }
  29598. }
  29599. return skeleton;
  29600. };
  29601. return Skeleton;
  29602. }());
  29603. BABYLON.Skeleton = Skeleton;
  29604. })(BABYLON || (BABYLON = {}));
  29605. var BABYLON;
  29606. (function (BABYLON) {
  29607. var PostProcess = (function () {
  29608. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29610. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29611. this.name = name;
  29612. this.width = -1;
  29613. this.height = -1;
  29614. /*
  29615. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29616. Can only be used on a single postprocess or on the last one of a chain.
  29617. */
  29618. this.enablePixelPerfectMode = false;
  29619. this._reusable = false;
  29620. this._textures = new BABYLON.SmartArray(2);
  29621. this._currentRenderTextureInd = 0;
  29622. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29623. // Events
  29624. /**
  29625. * An event triggered when the postprocess is activated.
  29626. * @type {BABYLON.Observable}
  29627. */
  29628. this.onActivateObservable = new BABYLON.Observable();
  29629. /**
  29630. * An event triggered when the postprocess changes its size.
  29631. * @type {BABYLON.Observable}
  29632. */
  29633. this.onSizeChangedObservable = new BABYLON.Observable();
  29634. /**
  29635. * An event triggered when the postprocess applies its effect.
  29636. * @type {BABYLON.Observable}
  29637. */
  29638. this.onApplyObservable = new BABYLON.Observable();
  29639. /**
  29640. * An event triggered before rendering the postprocess
  29641. * @type {BABYLON.Observable}
  29642. */
  29643. this.onBeforeRenderObservable = new BABYLON.Observable();
  29644. /**
  29645. * An event triggered after rendering the postprocess
  29646. * @type {BABYLON.Observable}
  29647. */
  29648. this.onAfterRenderObservable = new BABYLON.Observable();
  29649. if (camera != null) {
  29650. this._camera = camera;
  29651. this._scene = camera.getScene();
  29652. camera.attachPostProcess(this);
  29653. this._engine = this._scene.getEngine();
  29654. }
  29655. else {
  29656. this._engine = engine;
  29657. }
  29658. this._options = options;
  29659. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29660. this._reusable = reusable || false;
  29661. this._textureType = textureType;
  29662. this._samplers = samplers || [];
  29663. this._samplers.push("textureSampler");
  29664. this._fragmentUrl = fragmentUrl;
  29665. this._parameters = parameters || [];
  29666. this._parameters.push("scale");
  29667. this.updateEffect(defines);
  29668. }
  29669. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29670. set: function (callback) {
  29671. if (this._onActivateObserver) {
  29672. this.onActivateObservable.remove(this._onActivateObserver);
  29673. }
  29674. this._onActivateObserver = this.onActivateObservable.add(callback);
  29675. },
  29676. enumerable: true,
  29677. configurable: true
  29678. });
  29679. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29680. set: function (callback) {
  29681. if (this._onSizeChangedObserver) {
  29682. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29683. }
  29684. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. Object.defineProperty(PostProcess.prototype, "onApply", {
  29690. set: function (callback) {
  29691. if (this._onApplyObserver) {
  29692. this.onApplyObservable.remove(this._onApplyObserver);
  29693. }
  29694. this._onApplyObserver = this.onApplyObservable.add(callback);
  29695. },
  29696. enumerable: true,
  29697. configurable: true
  29698. });
  29699. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29700. set: function (callback) {
  29701. if (this._onBeforeRenderObserver) {
  29702. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29703. }
  29704. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29705. },
  29706. enumerable: true,
  29707. configurable: true
  29708. });
  29709. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29710. set: function (callback) {
  29711. if (this._onAfterRenderObserver) {
  29712. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29713. }
  29714. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29715. },
  29716. enumerable: true,
  29717. configurable: true
  29718. });
  29719. PostProcess.prototype.updateEffect = function (defines) {
  29720. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29721. };
  29722. PostProcess.prototype.isReusable = function () {
  29723. return this._reusable;
  29724. };
  29725. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29726. PostProcess.prototype.markTextureDirty = function () {
  29727. this.width = -1;
  29728. };
  29729. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29730. camera = camera || this._camera;
  29731. var scene = camera.getScene();
  29732. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29733. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29734. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29735. var desiredWidth = this._options.width || requiredWidth;
  29736. var desiredHeight = this._options.height || requiredHeight;
  29737. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29738. if (!this._options.width) {
  29739. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29740. }
  29741. if (!this._options.height) {
  29742. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29743. }
  29744. }
  29745. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29746. if (this._textures.length > 0) {
  29747. for (var i = 0; i < this._textures.length; i++) {
  29748. this._engine._releaseTexture(this._textures.data[i]);
  29749. }
  29750. this._textures.reset();
  29751. }
  29752. this.width = desiredWidth;
  29753. this.height = desiredHeight;
  29754. var textureSize = { width: this.width, height: this.height };
  29755. var textureOptions = {
  29756. generateMipMaps: false,
  29757. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29758. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29759. samplingMode: this.renderTargetSamplingMode,
  29760. type: this._textureType
  29761. };
  29762. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29763. if (this._reusable) {
  29764. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29765. }
  29766. this.onSizeChangedObservable.notifyObservers(this);
  29767. }
  29768. if (this.enablePixelPerfectMode) {
  29769. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29770. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29771. }
  29772. else {
  29773. this._scaleRatio.copyFromFloats(1, 1);
  29774. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29775. }
  29776. this.onActivateObservable.notifyObservers(camera);
  29777. // Clear
  29778. if (this.clearColor) {
  29779. this._engine.clear(this.clearColor, true, true, true);
  29780. }
  29781. else {
  29782. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29783. }
  29784. if (this._reusable) {
  29785. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29786. }
  29787. };
  29788. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29789. get: function () {
  29790. return this._effect.isSupported;
  29791. },
  29792. enumerable: true,
  29793. configurable: true
  29794. });
  29795. PostProcess.prototype.apply = function () {
  29796. // Check
  29797. if (!this._effect.isReady())
  29798. return null;
  29799. // States
  29800. this._engine.enableEffect(this._effect);
  29801. this._engine.setState(false);
  29802. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29803. this._engine.setDepthBuffer(false);
  29804. this._engine.setDepthWrite(false);
  29805. // Texture
  29806. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29807. // Parameters
  29808. this._effect.setVector2("scale", this._scaleRatio);
  29809. this.onApplyObservable.notifyObservers(this._effect);
  29810. return this._effect;
  29811. };
  29812. PostProcess.prototype.dispose = function (camera) {
  29813. camera = camera || this._camera;
  29814. if (this._textures.length > 0) {
  29815. for (var i = 0; i < this._textures.length; i++) {
  29816. this._engine._releaseTexture(this._textures.data[i]);
  29817. }
  29818. this._textures.reset();
  29819. }
  29820. if (!camera) {
  29821. return;
  29822. }
  29823. camera.detachPostProcess(this);
  29824. var index = camera._postProcesses.indexOf(this);
  29825. if (index === 0 && camera._postProcesses.length > 0) {
  29826. this._camera._postProcesses[0].markTextureDirty();
  29827. }
  29828. this.onActivateObservable.clear();
  29829. this.onAfterRenderObservable.clear();
  29830. this.onApplyObservable.clear();
  29831. this.onBeforeRenderObservable.clear();
  29832. this.onSizeChangedObservable.clear();
  29833. };
  29834. return PostProcess;
  29835. }());
  29836. BABYLON.PostProcess = PostProcess;
  29837. })(BABYLON || (BABYLON = {}));
  29838. var BABYLON;
  29839. (function (BABYLON) {
  29840. var PostProcessManager = (function () {
  29841. function PostProcessManager(scene) {
  29842. this._vertexBuffers = {};
  29843. this._scene = scene;
  29844. }
  29845. PostProcessManager.prototype._prepareBuffers = function () {
  29846. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29847. return;
  29848. }
  29849. // VBO
  29850. var vertices = [];
  29851. vertices.push(1, 1);
  29852. vertices.push(-1, 1);
  29853. vertices.push(-1, -1);
  29854. vertices.push(1, -1);
  29855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29856. // Indices
  29857. var indices = [];
  29858. indices.push(0);
  29859. indices.push(1);
  29860. indices.push(2);
  29861. indices.push(0);
  29862. indices.push(2);
  29863. indices.push(3);
  29864. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29865. };
  29866. // Methods
  29867. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29868. var postProcesses = this._scene.activeCamera._postProcesses;
  29869. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29870. return false;
  29871. }
  29872. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29873. return true;
  29874. };
  29875. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29876. var engine = this._scene.getEngine();
  29877. for (var index = 0; index < postProcesses.length; index++) {
  29878. if (index < postProcesses.length - 1) {
  29879. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29880. }
  29881. else {
  29882. if (targetTexture) {
  29883. engine.bindFramebuffer(targetTexture);
  29884. }
  29885. else {
  29886. engine.restoreDefaultFramebuffer();
  29887. }
  29888. }
  29889. var pp = postProcesses[index];
  29890. var effect = pp.apply();
  29891. if (effect) {
  29892. pp.onBeforeRenderObservable.notifyObservers(effect);
  29893. // VBOs
  29894. this._prepareBuffers();
  29895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29896. // Draw order
  29897. engine.draw(true, 0, 6);
  29898. pp.onAfterRenderObservable.notifyObservers(effect);
  29899. }
  29900. }
  29901. // Restore depth buffer
  29902. engine.setDepthBuffer(true);
  29903. engine.setDepthWrite(true);
  29904. };
  29905. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29906. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29907. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29908. return;
  29909. }
  29910. var engine = this._scene.getEngine();
  29911. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29912. if (index < len - 1) {
  29913. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29914. }
  29915. else {
  29916. if (targetTexture) {
  29917. engine.bindFramebuffer(targetTexture, faceIndex);
  29918. }
  29919. else {
  29920. engine.restoreDefaultFramebuffer();
  29921. }
  29922. }
  29923. if (doNotPresent) {
  29924. break;
  29925. }
  29926. var pp = postProcesses[index];
  29927. var effect = pp.apply();
  29928. if (effect) {
  29929. pp.onBeforeRenderObservable.notifyObservers(effect);
  29930. // VBOs
  29931. this._prepareBuffers();
  29932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29933. // Draw order
  29934. engine.draw(true, 0, 6);
  29935. pp.onAfterRenderObservable.notifyObservers(effect);
  29936. }
  29937. }
  29938. // Restore depth buffer
  29939. engine.setDepthBuffer(true);
  29940. engine.setDepthWrite(true);
  29941. };
  29942. PostProcessManager.prototype.dispose = function () {
  29943. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29944. if (buffer) {
  29945. buffer.dispose();
  29946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29947. }
  29948. if (this._indexBuffer) {
  29949. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29950. this._indexBuffer = null;
  29951. }
  29952. };
  29953. return PostProcessManager;
  29954. }());
  29955. BABYLON.PostProcessManager = PostProcessManager;
  29956. })(BABYLON || (BABYLON = {}));
  29957. var BABYLON;
  29958. (function (BABYLON) {
  29959. var PassPostProcess = (function (_super) {
  29960. __extends(PassPostProcess, _super);
  29961. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29962. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29963. }
  29964. return PassPostProcess;
  29965. }(BABYLON.PostProcess));
  29966. BABYLON.PassPostProcess = PassPostProcess;
  29967. })(BABYLON || (BABYLON = {}));
  29968. var BABYLON;
  29969. (function (BABYLON) {
  29970. /**
  29971. * This is a holder class for the physics joint created by the physics plugin.
  29972. * It holds a set of functions to control the underlying joint.
  29973. */
  29974. var PhysicsJoint = (function () {
  29975. function PhysicsJoint(type, jointData) {
  29976. this.type = type;
  29977. this.jointData = jointData;
  29978. jointData.nativeParams = jointData.nativeParams || {};
  29979. }
  29980. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29981. get: function () {
  29982. return this._physicsJoint;
  29983. },
  29984. set: function (newJoint) {
  29985. if (this._physicsJoint) {
  29986. }
  29987. this._physicsJoint = newJoint;
  29988. },
  29989. enumerable: true,
  29990. configurable: true
  29991. });
  29992. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29993. set: function (physicsPlugin) {
  29994. this._physicsPlugin = physicsPlugin;
  29995. },
  29996. enumerable: true,
  29997. configurable: true
  29998. });
  29999. /**
  30000. * Execute a function that is physics-plugin specific.
  30001. * @param {Function} func the function that will be executed.
  30002. * It accepts two parameters: the physics world and the physics joint.
  30003. */
  30004. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30005. func(this._physicsPlugin.world, this._physicsJoint);
  30006. };
  30007. //TODO check if the native joints are the same
  30008. //Joint Types
  30009. PhysicsJoint.DistanceJoint = 0;
  30010. PhysicsJoint.HingeJoint = 1;
  30011. PhysicsJoint.BallAndSocketJoint = 2;
  30012. PhysicsJoint.WheelJoint = 3;
  30013. PhysicsJoint.SliderJoint = 4;
  30014. //OIMO
  30015. PhysicsJoint.PrismaticJoint = 5;
  30016. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30017. PhysicsJoint.UniversalJoint = 6;
  30018. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30019. //Cannon
  30020. //Similar to a Ball-Joint. Different in params
  30021. PhysicsJoint.PointToPointJoint = 8;
  30022. //Cannon only at the moment
  30023. PhysicsJoint.SpringJoint = 9;
  30024. PhysicsJoint.LockJoint = 10;
  30025. return PhysicsJoint;
  30026. }());
  30027. BABYLON.PhysicsJoint = PhysicsJoint;
  30028. /**
  30029. * A class representing a physics distance joint.
  30030. */
  30031. var DistanceJoint = (function (_super) {
  30032. __extends(DistanceJoint, _super);
  30033. function DistanceJoint(jointData) {
  30034. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30035. }
  30036. /**
  30037. * Update the predefined distance.
  30038. */
  30039. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30040. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30041. };
  30042. return DistanceJoint;
  30043. }(PhysicsJoint));
  30044. BABYLON.DistanceJoint = DistanceJoint;
  30045. var MotorEnabledJoint = (function (_super) {
  30046. __extends(MotorEnabledJoint, _super);
  30047. function MotorEnabledJoint(type, jointData) {
  30048. _super.call(this, type, jointData);
  30049. }
  30050. /**
  30051. * Set the motor values.
  30052. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30053. * @param {number} force the force to apply
  30054. * @param {number} maxForce max force for this motor.
  30055. */
  30056. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30057. this._physicsPlugin.setMotor(this, force, maxForce);
  30058. };
  30059. /**
  30060. * Set the motor's limits.
  30061. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30062. */
  30063. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30064. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30065. };
  30066. return MotorEnabledJoint;
  30067. }(PhysicsJoint));
  30068. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30069. /**
  30070. * This class represents a single hinge physics joint
  30071. */
  30072. var HingeJoint = (function (_super) {
  30073. __extends(HingeJoint, _super);
  30074. function HingeJoint(jointData) {
  30075. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30076. }
  30077. /**
  30078. * Set the motor values.
  30079. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30080. * @param {number} force the force to apply
  30081. * @param {number} maxForce max force for this motor.
  30082. */
  30083. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30084. this._physicsPlugin.setMotor(this, force, maxForce);
  30085. };
  30086. /**
  30087. * Set the motor's limits.
  30088. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30089. */
  30090. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30091. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30092. };
  30093. return HingeJoint;
  30094. }(MotorEnabledJoint));
  30095. BABYLON.HingeJoint = HingeJoint;
  30096. /**
  30097. * This class represents a dual hinge physics joint (same as wheel joint)
  30098. */
  30099. var Hinge2Joint = (function (_super) {
  30100. __extends(Hinge2Joint, _super);
  30101. function Hinge2Joint(jointData) {
  30102. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30103. }
  30104. /**
  30105. * Set the motor values.
  30106. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30107. * @param {number} force the force to apply
  30108. * @param {number} maxForce max force for this motor.
  30109. * @param {motorIndex} the motor's index, 0 or 1.
  30110. */
  30111. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30112. if (motorIndex === void 0) { motorIndex = 0; }
  30113. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30114. };
  30115. /**
  30116. * Set the motor limits.
  30117. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30118. * @param {number} upperLimit the upper limit
  30119. * @param {number} lowerLimit lower limit
  30120. * @param {motorIndex} the motor's index, 0 or 1.
  30121. */
  30122. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30123. if (motorIndex === void 0) { motorIndex = 0; }
  30124. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30125. };
  30126. return Hinge2Joint;
  30127. }(MotorEnabledJoint));
  30128. BABYLON.Hinge2Joint = Hinge2Joint;
  30129. })(BABYLON || (BABYLON = {}));
  30130. var BABYLON;
  30131. (function (BABYLON) {
  30132. var PhysicsImpostor = (function () {
  30133. function PhysicsImpostor(object, type, _options, _scene) {
  30134. var _this = this;
  30135. if (_options === void 0) { _options = { mass: 0 }; }
  30136. this.object = object;
  30137. this.type = type;
  30138. this._options = _options;
  30139. this._scene = _scene;
  30140. this._bodyUpdateRequired = false;
  30141. this._onBeforePhysicsStepCallbacks = new Array();
  30142. this._onAfterPhysicsStepCallbacks = new Array();
  30143. this._onPhysicsCollideCallbacks = [];
  30144. this._deltaPosition = BABYLON.Vector3.Zero();
  30145. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30146. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30147. /**
  30148. * this function is executed by the physics engine.
  30149. */
  30150. this.beforeStep = function () {
  30151. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30152. //conjugate deltaRotation
  30153. if (_this._deltaRotationConjugated) {
  30154. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30155. }
  30156. else {
  30157. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30158. }
  30159. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30160. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30161. func(_this);
  30162. });
  30163. };
  30164. /**
  30165. * this function is executed by the physics engine.
  30166. */
  30167. this.afterStep = function () {
  30168. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30169. func(_this);
  30170. });
  30171. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30172. _this.object.position.addInPlace(_this._deltaPosition);
  30173. if (_this._deltaRotation) {
  30174. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30175. }
  30176. };
  30177. //event and body object due to cannon's event-based architecture.
  30178. this.onCollide = function (e) {
  30179. if (!_this._onPhysicsCollideCallbacks.length)
  30180. return;
  30181. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30182. if (otherImpostor) {
  30183. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30184. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30185. }).forEach(function (obj) {
  30186. obj.callback(_this, otherImpostor);
  30187. });
  30188. }
  30189. };
  30190. //sanity check!
  30191. if (!this.object) {
  30192. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30193. return;
  30194. }
  30195. //legacy support for old syntax.
  30196. if (!this._scene && object.getScene) {
  30197. this._scene = object.getScene();
  30198. }
  30199. this._physicsEngine = this._scene.getPhysicsEngine();
  30200. if (!this._physicsEngine) {
  30201. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30202. }
  30203. else {
  30204. //set the object's quaternion, if not set
  30205. if (!this.object.rotationQuaternion) {
  30206. if (this.object.rotation) {
  30207. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30208. }
  30209. else {
  30210. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30211. }
  30212. }
  30213. //default options params
  30214. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30215. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30216. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30217. this._joints = [];
  30218. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30219. if (!this.object.parent) {
  30220. this._init();
  30221. }
  30222. }
  30223. }
  30224. /**
  30225. * This function will completly initialize this impostor.
  30226. * It will create a new body - but only if this mesh has no parent.
  30227. * If it has, this impostor will not be used other than to define the impostor
  30228. * of the child mesh.
  30229. */
  30230. PhysicsImpostor.prototype._init = function () {
  30231. this._physicsEngine.removeImpostor(this);
  30232. this.physicsBody = null;
  30233. this._parent = this._parent || this._getPhysicsParent();
  30234. if (!this.parent) {
  30235. this._physicsEngine.addImpostor(this);
  30236. }
  30237. };
  30238. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30239. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30240. var parentMesh = this.object.parent;
  30241. return parentMesh.physicsImpostor;
  30242. }
  30243. return;
  30244. };
  30245. /**
  30246. * Should a new body be generated.
  30247. */
  30248. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30249. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30250. };
  30251. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30252. this.forceUpdate();
  30253. };
  30254. /**
  30255. * Force a regeneration of this or the parent's impostor's body.
  30256. * Use under cautious - This will remove all joints already implemented.
  30257. */
  30258. PhysicsImpostor.prototype.forceUpdate = function () {
  30259. this._init();
  30260. if (this.parent) {
  30261. this.parent.forceUpdate();
  30262. }
  30263. };
  30264. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30265. /*public get mesh(): AbstractMesh {
  30266. return this._mesh;
  30267. }*/
  30268. /**
  30269. * Gets the body that holds this impostor. Either its own, or its parent.
  30270. */
  30271. get: function () {
  30272. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30273. },
  30274. /**
  30275. * Set the physics body. Used mainly by the physics engine/plugin
  30276. */
  30277. set: function (physicsBody) {
  30278. if (this._physicsBody) {
  30279. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30280. }
  30281. this._physicsBody = physicsBody;
  30282. this.resetUpdateFlags();
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30288. get: function () {
  30289. return this._parent;
  30290. },
  30291. set: function (value) {
  30292. this._parent = value;
  30293. },
  30294. enumerable: true,
  30295. configurable: true
  30296. });
  30297. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30298. this._bodyUpdateRequired = false;
  30299. };
  30300. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30301. if (this.object.getBoundingInfo) {
  30302. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30303. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30304. }
  30305. else {
  30306. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30307. }
  30308. };
  30309. PhysicsImpostor.prototype.getObjectCenter = function () {
  30310. if (this.object.getBoundingInfo) {
  30311. return this.object.getBoundingInfo().boundingBox.center;
  30312. }
  30313. else {
  30314. return this.object.position;
  30315. }
  30316. };
  30317. /**
  30318. * Get a specific parametes from the options parameter.
  30319. */
  30320. PhysicsImpostor.prototype.getParam = function (paramName) {
  30321. return this._options[paramName];
  30322. };
  30323. /**
  30324. * Sets a specific parameter in the options given to the physics plugin
  30325. */
  30326. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30327. this._options[paramName] = value;
  30328. this._bodyUpdateRequired = true;
  30329. };
  30330. /**
  30331. * Specifically change the body's mass option. Won't recreate the physics body object
  30332. */
  30333. PhysicsImpostor.prototype.setMass = function (mass) {
  30334. if (this.getParam("mass") !== mass) {
  30335. this.setParam("mass", mass);
  30336. }
  30337. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30338. };
  30339. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30340. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30341. };
  30342. /**
  30343. * Set the body's linear velocity.
  30344. */
  30345. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30346. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30347. };
  30348. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30349. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30350. };
  30351. /**
  30352. * Set the body's linear velocity.
  30353. */
  30354. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30355. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30356. };
  30357. /**
  30358. * Execute a function with the physics plugin native code.
  30359. * Provide a function the will have two variables - the world object and the physics body object.
  30360. */
  30361. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30362. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30363. };
  30364. /**
  30365. * Register a function that will be executed before the physics world is stepping forward.
  30366. */
  30367. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30368. this._onBeforePhysicsStepCallbacks.push(func);
  30369. };
  30370. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30371. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30372. if (index > -1) {
  30373. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30374. }
  30375. else {
  30376. BABYLON.Tools.Warn("Function to remove was not found");
  30377. }
  30378. };
  30379. /**
  30380. * Register a function that will be executed after the physics step
  30381. */
  30382. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30383. this._onAfterPhysicsStepCallbacks.push(func);
  30384. };
  30385. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30386. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30387. if (index > -1) {
  30388. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30389. }
  30390. else {
  30391. BABYLON.Tools.Warn("Function to remove was not found");
  30392. }
  30393. };
  30394. /**
  30395. * register a function that will be executed when this impostor collides against a different body.
  30396. */
  30397. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30398. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30399. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30400. };
  30401. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30402. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30403. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30404. if (index > -1) {
  30405. this._onPhysicsCollideCallbacks.splice(index, 1);
  30406. }
  30407. else {
  30408. BABYLON.Tools.Warn("Function to remove was not found");
  30409. }
  30410. };
  30411. /**
  30412. * Apply a force
  30413. */
  30414. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30415. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30416. };
  30417. /**
  30418. * Apply an impulse
  30419. */
  30420. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30421. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30422. };
  30423. /**
  30424. * A help function to create a joint.
  30425. */
  30426. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30427. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30428. this.addJoint(otherImpostor, joint);
  30429. };
  30430. /**
  30431. * Add a joint to this impostor with a different impostor.
  30432. */
  30433. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30434. this._joints.push({
  30435. otherImpostor: otherImpostor,
  30436. joint: joint
  30437. });
  30438. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30439. };
  30440. /**
  30441. * Will keep this body still, in a sleep mode.
  30442. */
  30443. PhysicsImpostor.prototype.sleep = function () {
  30444. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30445. };
  30446. /**
  30447. * Wake the body up.
  30448. */
  30449. PhysicsImpostor.prototype.wakeUp = function () {
  30450. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30451. };
  30452. PhysicsImpostor.prototype.clone = function (newObject) {
  30453. if (!newObject)
  30454. return null;
  30455. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30456. };
  30457. PhysicsImpostor.prototype.dispose = function () {
  30458. var _this = this;
  30459. //no dispose if no physics engine is available.
  30460. if (!this._physicsEngine) {
  30461. return;
  30462. }
  30463. this._joints.forEach(function (j) {
  30464. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30465. });
  30466. //dispose the physics body
  30467. this._physicsEngine.removeImpostor(this);
  30468. if (this.parent) {
  30469. this.parent.forceUpdate();
  30470. }
  30471. else {
  30472. }
  30473. };
  30474. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30475. this._deltaPosition.copyFrom(position);
  30476. };
  30477. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30478. if (!this._deltaRotation) {
  30479. this._deltaRotation = new BABYLON.Quaternion();
  30480. }
  30481. this._deltaRotation.copyFrom(rotation);
  30482. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30483. };
  30484. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30485. //Impostor types
  30486. PhysicsImpostor.NoImpostor = 0;
  30487. PhysicsImpostor.SphereImpostor = 1;
  30488. PhysicsImpostor.BoxImpostor = 2;
  30489. PhysicsImpostor.PlaneImpostor = 3;
  30490. PhysicsImpostor.MeshImpostor = 4;
  30491. PhysicsImpostor.CylinderImpostor = 7;
  30492. PhysicsImpostor.ParticleImpostor = 8;
  30493. PhysicsImpostor.HeightmapImpostor = 9;
  30494. return PhysicsImpostor;
  30495. }());
  30496. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30497. })(BABYLON || (BABYLON = {}));
  30498. var BABYLON;
  30499. (function (BABYLON) {
  30500. var PhysicsEngine = (function () {
  30501. function PhysicsEngine(gravity, _physicsPlugin) {
  30502. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30503. this._physicsPlugin = _physicsPlugin;
  30504. //new methods and parameters
  30505. this._impostors = [];
  30506. this._joints = [];
  30507. if (!this._physicsPlugin.isSupported()) {
  30508. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30509. + "Please make sure it is included.");
  30510. }
  30511. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30512. this.setGravity(gravity);
  30513. this.setTimeStep();
  30514. }
  30515. PhysicsEngine.prototype.setGravity = function (gravity) {
  30516. this.gravity = gravity;
  30517. this._physicsPlugin.setGravity(this.gravity);
  30518. };
  30519. /**
  30520. * Set the time step of the physics engine.
  30521. * default is 1/60.
  30522. * To slow it down, enter 1/600 for example.
  30523. * To speed it up, 1/30
  30524. * @param {number} newTimeStep the new timestep to apply to this world.
  30525. */
  30526. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30527. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30528. this._physicsPlugin.setTimeStep(newTimeStep);
  30529. };
  30530. PhysicsEngine.prototype.dispose = function () {
  30531. this._impostors.forEach(function (impostor) {
  30532. impostor.dispose();
  30533. });
  30534. this._physicsPlugin.dispose();
  30535. };
  30536. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30537. return this._physicsPlugin.name;
  30538. };
  30539. /**
  30540. * Adding a new impostor for the impostor tracking.
  30541. * This will be done by the impostor itself.
  30542. * @param {PhysicsImpostor} impostor the impostor to add
  30543. */
  30544. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30545. impostor.uniqueId = this._impostors.push(impostor);
  30546. //if no parent, generate the body
  30547. if (!impostor.parent) {
  30548. this._physicsPlugin.generatePhysicsBody(impostor);
  30549. }
  30550. };
  30551. /**
  30552. * Remove an impostor from the engine.
  30553. * This impostor and its mesh will not longer be updated by the physics engine.
  30554. * @param {PhysicsImpostor} impostor the impostor to remove
  30555. */
  30556. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30557. var index = this._impostors.indexOf(impostor);
  30558. if (index > -1) {
  30559. var removed = this._impostors.splice(index, 1);
  30560. //Is it needed?
  30561. if (removed.length) {
  30562. //this will also remove it from the world.
  30563. removed[0].physicsBody = null;
  30564. }
  30565. }
  30566. };
  30567. /**
  30568. * Add a joint to the physics engine
  30569. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30570. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30571. * @param {PhysicsJoint} the joint that will connect both impostors.
  30572. */
  30573. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30574. var impostorJoint = {
  30575. mainImpostor: mainImpostor,
  30576. connectedImpostor: connectedImpostor,
  30577. joint: joint
  30578. };
  30579. joint.physicsPlugin = this._physicsPlugin;
  30580. this._joints.push(impostorJoint);
  30581. this._physicsPlugin.generateJoint(impostorJoint);
  30582. };
  30583. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30584. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30585. return (impostorJoint.connectedImpostor === connectedImpostor
  30586. && impostorJoint.joint === joint
  30587. && impostorJoint.mainImpostor === mainImpostor);
  30588. });
  30589. if (matchingJoints.length) {
  30590. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30591. }
  30592. };
  30593. /**
  30594. * Called by the scene. no need to call it.
  30595. */
  30596. PhysicsEngine.prototype._step = function (delta) {
  30597. var _this = this;
  30598. //check if any mesh has no body / requires an update
  30599. this._impostors.forEach(function (impostor) {
  30600. if (impostor.isBodyInitRequired()) {
  30601. _this._physicsPlugin.generatePhysicsBody(impostor);
  30602. }
  30603. });
  30604. if (delta > 0.1) {
  30605. delta = 0.1;
  30606. }
  30607. else if (delta <= 0) {
  30608. delta = 1.0 / 60.0;
  30609. }
  30610. this._physicsPlugin.executeStep(delta, this._impostors);
  30611. };
  30612. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30613. return this._physicsPlugin;
  30614. };
  30615. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30616. for (var i = 0; i < this._impostors.length; ++i) {
  30617. if (this._impostors[i].object === object) {
  30618. return this._impostors[i];
  30619. }
  30620. }
  30621. };
  30622. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30623. for (var i = 0; i < this._impostors.length; ++i) {
  30624. if (this._impostors[i].physicsBody === body) {
  30625. return this._impostors[i];
  30626. }
  30627. }
  30628. };
  30629. // Statics, Legacy support.
  30630. /**
  30631. * @Deprecated
  30632. *
  30633. */
  30634. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30635. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30636. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30637. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30638. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30639. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30640. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30641. PhysicsEngine.CapsuleImpostor = -1;
  30642. PhysicsEngine.ConeImpostor = -1;
  30643. PhysicsEngine.ConvexHullImpostor = -1;
  30644. PhysicsEngine.Epsilon = 0.001;
  30645. return PhysicsEngine;
  30646. }());
  30647. BABYLON.PhysicsEngine = PhysicsEngine;
  30648. })(BABYLON || (BABYLON = {}));
  30649. var BABYLON;
  30650. (function (BABYLON) {
  30651. var VertexData = (function () {
  30652. function VertexData() {
  30653. }
  30654. VertexData.prototype.set = function (data, kind) {
  30655. switch (kind) {
  30656. case BABYLON.VertexBuffer.PositionKind:
  30657. this.positions = data;
  30658. break;
  30659. case BABYLON.VertexBuffer.NormalKind:
  30660. this.normals = data;
  30661. break;
  30662. case BABYLON.VertexBuffer.UVKind:
  30663. this.uvs = data;
  30664. break;
  30665. case BABYLON.VertexBuffer.UV2Kind:
  30666. this.uvs2 = data;
  30667. break;
  30668. case BABYLON.VertexBuffer.UV3Kind:
  30669. this.uvs3 = data;
  30670. break;
  30671. case BABYLON.VertexBuffer.UV4Kind:
  30672. this.uvs4 = data;
  30673. break;
  30674. case BABYLON.VertexBuffer.UV5Kind:
  30675. this.uvs5 = data;
  30676. break;
  30677. case BABYLON.VertexBuffer.UV6Kind:
  30678. this.uvs6 = data;
  30679. break;
  30680. case BABYLON.VertexBuffer.ColorKind:
  30681. this.colors = data;
  30682. break;
  30683. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30684. this.matricesIndices = data;
  30685. break;
  30686. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30687. this.matricesWeights = data;
  30688. break;
  30689. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30690. this.matricesIndicesExtra = data;
  30691. break;
  30692. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30693. this.matricesWeightsExtra = data;
  30694. break;
  30695. }
  30696. };
  30697. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30698. this._applyTo(mesh, updatable);
  30699. };
  30700. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30701. this._applyTo(geometry, updatable);
  30702. };
  30703. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30704. this._update(mesh);
  30705. };
  30706. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30707. this._update(geometry);
  30708. };
  30709. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30710. if (this.positions) {
  30711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30712. }
  30713. if (this.normals) {
  30714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30715. }
  30716. if (this.uvs) {
  30717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30718. }
  30719. if (this.uvs2) {
  30720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30721. }
  30722. if (this.uvs3) {
  30723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30724. }
  30725. if (this.uvs4) {
  30726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30727. }
  30728. if (this.uvs5) {
  30729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30730. }
  30731. if (this.uvs6) {
  30732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30733. }
  30734. if (this.colors) {
  30735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30736. }
  30737. if (this.matricesIndices) {
  30738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30739. }
  30740. if (this.matricesWeights) {
  30741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30742. }
  30743. if (this.matricesIndicesExtra) {
  30744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30745. }
  30746. if (this.matricesWeightsExtra) {
  30747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30748. }
  30749. if (this.indices) {
  30750. meshOrGeometry.setIndices(this.indices);
  30751. }
  30752. };
  30753. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30754. if (this.positions) {
  30755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30756. }
  30757. if (this.normals) {
  30758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30759. }
  30760. if (this.uvs) {
  30761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30762. }
  30763. if (this.uvs2) {
  30764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30765. }
  30766. if (this.uvs3) {
  30767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30768. }
  30769. if (this.uvs4) {
  30770. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30771. }
  30772. if (this.uvs5) {
  30773. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30774. }
  30775. if (this.uvs6) {
  30776. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30777. }
  30778. if (this.colors) {
  30779. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30780. }
  30781. if (this.matricesIndices) {
  30782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30783. }
  30784. if (this.matricesWeights) {
  30785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30786. }
  30787. if (this.matricesIndicesExtra) {
  30788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30789. }
  30790. if (this.matricesWeightsExtra) {
  30791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30792. }
  30793. if (this.indices) {
  30794. meshOrGeometry.setIndices(this.indices);
  30795. }
  30796. };
  30797. VertexData.prototype.transform = function (matrix) {
  30798. var transformed = BABYLON.Vector3.Zero();
  30799. var index;
  30800. if (this.positions) {
  30801. var position = BABYLON.Vector3.Zero();
  30802. for (index = 0; index < this.positions.length; index += 3) {
  30803. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30804. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30805. this.positions[index] = transformed.x;
  30806. this.positions[index + 1] = transformed.y;
  30807. this.positions[index + 2] = transformed.z;
  30808. }
  30809. }
  30810. if (this.normals) {
  30811. var normal = BABYLON.Vector3.Zero();
  30812. for (index = 0; index < this.normals.length; index += 3) {
  30813. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30814. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30815. this.normals[index] = transformed.x;
  30816. this.normals[index + 1] = transformed.y;
  30817. this.normals[index + 2] = transformed.z;
  30818. }
  30819. }
  30820. };
  30821. VertexData.prototype.merge = function (other) {
  30822. if (other.indices) {
  30823. if (!this.indices) {
  30824. this.indices = [];
  30825. }
  30826. var offset = this.positions ? this.positions.length / 3 : 0;
  30827. for (var index = 0; index < other.indices.length; index++) {
  30828. //TODO check type - if Int32Array!
  30829. this.indices.push(other.indices[index] + offset);
  30830. }
  30831. }
  30832. this.positions = this._mergeElement(this.positions, other.positions);
  30833. this.normals = this._mergeElement(this.normals, other.normals);
  30834. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30835. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30836. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30837. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30838. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30839. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30840. this.colors = this._mergeElement(this.colors, other.colors);
  30841. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30842. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30843. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30844. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30845. };
  30846. VertexData.prototype._mergeElement = function (source, other) {
  30847. if (!other)
  30848. return source;
  30849. if (!source)
  30850. return other;
  30851. var len = other.length + source.length;
  30852. var isSrcTypedArray = source instanceof Float32Array;
  30853. var isOthTypedArray = other instanceof Float32Array;
  30854. // use non-loop method when the source is Float32Array
  30855. if (isSrcTypedArray) {
  30856. var ret32 = new Float32Array(len);
  30857. ret32.set(source);
  30858. ret32.set(other, source.length);
  30859. return ret32;
  30860. }
  30861. else if (!isOthTypedArray) {
  30862. return source.concat(other);
  30863. }
  30864. else {
  30865. var ret = source.slice(0); // copy source to a separate array
  30866. for (var i = 0, len = other.length; i < len; i++) {
  30867. ret.push(other[i]);
  30868. }
  30869. return ret;
  30870. }
  30871. };
  30872. VertexData.prototype.serialize = function () {
  30873. var serializationObject = this.serialize();
  30874. if (this.positions) {
  30875. serializationObject.positions = this.positions;
  30876. }
  30877. if (this.normals) {
  30878. serializationObject.normals = this.normals;
  30879. }
  30880. if (this.uvs) {
  30881. serializationObject.uvs = this.uvs;
  30882. }
  30883. if (this.uvs2) {
  30884. serializationObject.uvs2 = this.uvs2;
  30885. }
  30886. if (this.uvs3) {
  30887. serializationObject.uvs3 = this.uvs3;
  30888. }
  30889. if (this.uvs4) {
  30890. serializationObject.uvs4 = this.uvs4;
  30891. }
  30892. if (this.uvs5) {
  30893. serializationObject.uvs5 = this.uvs5;
  30894. }
  30895. if (this.uvs6) {
  30896. serializationObject.uvs6 = this.uvs6;
  30897. }
  30898. if (this.colors) {
  30899. serializationObject.colors = this.colors;
  30900. }
  30901. if (this.matricesIndices) {
  30902. serializationObject.matricesIndices = this.matricesIndices;
  30903. serializationObject.matricesIndices._isExpanded = true;
  30904. }
  30905. if (this.matricesWeights) {
  30906. serializationObject.matricesWeights = this.matricesWeights;
  30907. }
  30908. if (this.matricesIndicesExtra) {
  30909. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30910. serializationObject.matricesIndicesExtra._isExpanded = true;
  30911. }
  30912. if (this.matricesWeightsExtra) {
  30913. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30914. }
  30915. serializationObject.indices = this.indices;
  30916. return serializationObject;
  30917. };
  30918. // Statics
  30919. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30920. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30921. };
  30922. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30923. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30924. };
  30925. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30926. var result = new VertexData();
  30927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30928. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30929. }
  30930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30931. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30932. }
  30933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30934. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30935. }
  30936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30937. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30938. }
  30939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30940. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30941. }
  30942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30943. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30944. }
  30945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30946. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30947. }
  30948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30949. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30950. }
  30951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30952. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30953. }
  30954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30955. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30956. }
  30957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30958. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30959. }
  30960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30961. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30962. }
  30963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30964. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30965. }
  30966. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30967. return result;
  30968. };
  30969. VertexData.CreateRibbon = function (options) {
  30970. var pathArray = options.pathArray;
  30971. var closeArray = options.closeArray || false;
  30972. var closePath = options.closePath || false;
  30973. var invertUV = options.invertUV || false;
  30974. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30975. var offset = options.offset || defaultOffset;
  30976. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30977. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30978. var positions = [];
  30979. var indices = [];
  30980. var normals = [];
  30981. var uvs = [];
  30982. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30983. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30984. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30985. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30986. var minlg; // minimal length among all paths from pathArray
  30987. var lg = []; // array of path lengths : nb of vertex per path
  30988. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30989. var p; // path iterator
  30990. var i; // point iterator
  30991. var j; // point iterator
  30992. // if single path in pathArray
  30993. if (pathArray.length < 2) {
  30994. var ar1 = [];
  30995. var ar2 = [];
  30996. for (i = 0; i < pathArray[0].length - offset; i++) {
  30997. ar1.push(pathArray[0][i]);
  30998. ar2.push(pathArray[0][i + offset]);
  30999. }
  31000. pathArray = [ar1, ar2];
  31001. }
  31002. // positions and horizontal distances (u)
  31003. var idc = 0;
  31004. var closePathCorr = (closePath) ? 1 : 0;
  31005. var path;
  31006. var l;
  31007. minlg = pathArray[0].length;
  31008. var vectlg;
  31009. var dist;
  31010. for (p = 0; p < pathArray.length; p++) {
  31011. uTotalDistance[p] = 0;
  31012. us[p] = [0];
  31013. path = pathArray[p];
  31014. l = path.length;
  31015. minlg = (minlg < l) ? minlg : l;
  31016. j = 0;
  31017. while (j < l) {
  31018. positions.push(path[j].x, path[j].y, path[j].z);
  31019. if (j > 0) {
  31020. vectlg = path[j].subtract(path[j - 1]).length();
  31021. dist = vectlg + uTotalDistance[p];
  31022. us[p].push(dist);
  31023. uTotalDistance[p] = dist;
  31024. }
  31025. j++;
  31026. }
  31027. if (closePath) {
  31028. j--;
  31029. positions.push(path[0].x, path[0].y, path[0].z);
  31030. vectlg = path[j].subtract(path[0]).length();
  31031. dist = vectlg + uTotalDistance[p];
  31032. us[p].push(dist);
  31033. uTotalDistance[p] = dist;
  31034. }
  31035. lg[p] = l + closePathCorr;
  31036. idx[p] = idc;
  31037. idc += (l + closePathCorr);
  31038. }
  31039. // vertical distances (v)
  31040. var path1;
  31041. var path2;
  31042. var vertex1;
  31043. var vertex2;
  31044. for (i = 0; i < minlg + closePathCorr; i++) {
  31045. vTotalDistance[i] = 0;
  31046. vs[i] = [0];
  31047. for (p = 0; p < pathArray.length - 1; p++) {
  31048. path1 = pathArray[p];
  31049. path2 = pathArray[p + 1];
  31050. if (i === minlg) {
  31051. vertex1 = path1[0];
  31052. vertex2 = path2[0];
  31053. }
  31054. else {
  31055. vertex1 = path1[i];
  31056. vertex2 = path2[i];
  31057. }
  31058. vectlg = vertex2.subtract(vertex1).length();
  31059. dist = vectlg + vTotalDistance[i];
  31060. vs[i].push(dist);
  31061. vTotalDistance[i] = dist;
  31062. }
  31063. if (closeArray) {
  31064. path1 = pathArray[p];
  31065. path2 = pathArray[0];
  31066. if (i === minlg) {
  31067. vertex2 = path2[0];
  31068. }
  31069. vectlg = vertex2.subtract(vertex1).length();
  31070. dist = vectlg + vTotalDistance[i];
  31071. vTotalDistance[i] = dist;
  31072. }
  31073. }
  31074. // uvs
  31075. var u;
  31076. var v;
  31077. for (p = 0; p < pathArray.length; p++) {
  31078. for (i = 0; i < minlg + closePathCorr; i++) {
  31079. u = us[p][i] / uTotalDistance[p];
  31080. v = vs[i][p] / vTotalDistance[i];
  31081. if (invertUV) {
  31082. uvs.push(v, u);
  31083. }
  31084. else {
  31085. uvs.push(u, v);
  31086. }
  31087. }
  31088. }
  31089. // indices
  31090. p = 0; // path index
  31091. var pi = 0; // positions array index
  31092. var l1 = lg[p] - 1; // path1 length
  31093. var l2 = lg[p + 1] - 1; // path2 length
  31094. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31095. var shft = idx[1] - idx[0]; // shift
  31096. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31097. while (pi <= min && p < path1nb) {
  31098. // 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
  31099. indices.push(pi, pi + shft, pi + 1);
  31100. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31101. pi += 1;
  31102. if (pi === min) {
  31103. p++;
  31104. if (p === lg.length - 1) {
  31105. shft = idx[0] - idx[p];
  31106. l1 = lg[p] - 1;
  31107. l2 = lg[0] - 1;
  31108. }
  31109. else {
  31110. shft = idx[p + 1] - idx[p];
  31111. l1 = lg[p] - 1;
  31112. l2 = lg[p + 1] - 1;
  31113. }
  31114. pi = idx[p];
  31115. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31116. }
  31117. }
  31118. // normals
  31119. VertexData.ComputeNormals(positions, indices, normals);
  31120. if (closePath) {
  31121. var indexFirst = 0;
  31122. var indexLast = 0;
  31123. for (p = 0; p < pathArray.length; p++) {
  31124. indexFirst = idx[p] * 3;
  31125. if (p + 1 < pathArray.length) {
  31126. indexLast = (idx[p + 1] - 1) * 3;
  31127. }
  31128. else {
  31129. indexLast = normals.length - 3;
  31130. }
  31131. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31132. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31133. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31134. normals[indexLast] = normals[indexFirst];
  31135. normals[indexLast + 1] = normals[indexFirst + 1];
  31136. normals[indexLast + 2] = normals[indexFirst + 2];
  31137. }
  31138. }
  31139. // sides
  31140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31141. // Result
  31142. var vertexData = new VertexData();
  31143. vertexData.indices = indices;
  31144. vertexData.positions = positions;
  31145. vertexData.normals = normals;
  31146. vertexData.uvs = uvs;
  31147. if (closePath) {
  31148. vertexData._idx = idx;
  31149. }
  31150. return vertexData;
  31151. };
  31152. VertexData.CreateBox = function (options) {
  31153. var normalsSource = [
  31154. new BABYLON.Vector3(0, 0, 1),
  31155. new BABYLON.Vector3(0, 0, -1),
  31156. new BABYLON.Vector3(1, 0, 0),
  31157. new BABYLON.Vector3(-1, 0, 0),
  31158. new BABYLON.Vector3(0, 1, 0),
  31159. new BABYLON.Vector3(0, -1, 0)
  31160. ];
  31161. var indices = [];
  31162. var positions = [];
  31163. var normals = [];
  31164. var uvs = [];
  31165. var width = options.width || options.size || 1;
  31166. var height = options.height || options.size || 1;
  31167. var depth = options.depth || options.size || 1;
  31168. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31169. var faceUV = options.faceUV || new Array(6);
  31170. var faceColors = options.faceColors;
  31171. var colors = [];
  31172. // default face colors and UV if undefined
  31173. for (var f = 0; f < 6; f++) {
  31174. if (faceUV[f] === undefined) {
  31175. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31176. }
  31177. if (faceColors && faceColors[f] === undefined) {
  31178. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31179. }
  31180. }
  31181. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31182. // Create each face in turn.
  31183. for (var index = 0; index < normalsSource.length; index++) {
  31184. var normal = normalsSource[index];
  31185. // Get two vectors perpendicular to the face normal and to each other.
  31186. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31187. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31188. // Six indices (two triangles) per face.
  31189. var verticesLength = positions.length / 3;
  31190. indices.push(verticesLength);
  31191. indices.push(verticesLength + 1);
  31192. indices.push(verticesLength + 2);
  31193. indices.push(verticesLength);
  31194. indices.push(verticesLength + 2);
  31195. indices.push(verticesLength + 3);
  31196. // Four vertices per face.
  31197. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31198. positions.push(vertex.x, vertex.y, vertex.z);
  31199. normals.push(normal.x, normal.y, normal.z);
  31200. uvs.push(faceUV[index].z, faceUV[index].w);
  31201. if (faceColors) {
  31202. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31203. }
  31204. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31205. positions.push(vertex.x, vertex.y, vertex.z);
  31206. normals.push(normal.x, normal.y, normal.z);
  31207. uvs.push(faceUV[index].x, faceUV[index].w);
  31208. if (faceColors) {
  31209. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31210. }
  31211. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31212. positions.push(vertex.x, vertex.y, vertex.z);
  31213. normals.push(normal.x, normal.y, normal.z);
  31214. uvs.push(faceUV[index].x, faceUV[index].y);
  31215. if (faceColors) {
  31216. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31217. }
  31218. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31219. positions.push(vertex.x, vertex.y, vertex.z);
  31220. normals.push(normal.x, normal.y, normal.z);
  31221. uvs.push(faceUV[index].z, faceUV[index].y);
  31222. if (faceColors) {
  31223. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31224. }
  31225. }
  31226. // sides
  31227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31228. // Result
  31229. var vertexData = new VertexData();
  31230. vertexData.indices = indices;
  31231. vertexData.positions = positions;
  31232. vertexData.normals = normals;
  31233. vertexData.uvs = uvs;
  31234. if (faceColors) {
  31235. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31236. vertexData.colors = totalColors;
  31237. }
  31238. return vertexData;
  31239. };
  31240. VertexData.CreateSphere = function (options) {
  31241. var segments = options.segments || 32;
  31242. var diameterX = options.diameterX || options.diameter || 1;
  31243. var diameterY = options.diameterY || options.diameter || 1;
  31244. var diameterZ = options.diameterZ || options.diameter || 1;
  31245. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31246. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31247. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31248. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31249. var totalZRotationSteps = 2 + segments;
  31250. var totalYRotationSteps = 2 * totalZRotationSteps;
  31251. var indices = [];
  31252. var positions = [];
  31253. var normals = [];
  31254. var uvs = [];
  31255. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31256. var normalizedZ = zRotationStep / totalZRotationSteps;
  31257. var angleZ = normalizedZ * Math.PI * slice;
  31258. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31259. var normalizedY = yRotationStep / totalYRotationSteps;
  31260. var angleY = normalizedY * Math.PI * 2 * arc;
  31261. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31262. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31263. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31264. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31265. var vertex = complete.multiply(radius);
  31266. var normal = complete.divide(radius).normalize();
  31267. positions.push(vertex.x, vertex.y, vertex.z);
  31268. normals.push(normal.x, normal.y, normal.z);
  31269. uvs.push(normalizedY, normalizedZ);
  31270. }
  31271. if (zRotationStep > 0) {
  31272. var verticesCount = positions.length / 3;
  31273. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31274. indices.push((firstIndex));
  31275. indices.push((firstIndex + 1));
  31276. indices.push(firstIndex + totalYRotationSteps + 1);
  31277. indices.push((firstIndex + totalYRotationSteps + 1));
  31278. indices.push((firstIndex + 1));
  31279. indices.push((firstIndex + totalYRotationSteps + 2));
  31280. }
  31281. }
  31282. }
  31283. // Sides
  31284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31285. // Result
  31286. var vertexData = new VertexData();
  31287. vertexData.indices = indices;
  31288. vertexData.positions = positions;
  31289. vertexData.normals = normals;
  31290. vertexData.uvs = uvs;
  31291. return vertexData;
  31292. };
  31293. // Cylinder and cone
  31294. VertexData.CreateCylinder = function (options) {
  31295. var height = options.height || 2;
  31296. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31297. var diameterBottom = options.diameterBottom || options.diameter || 1;
  31298. var tessellation = options.tessellation || 24;
  31299. var subdivisions = options.subdivisions || 1;
  31300. var hasRings = options.hasRings;
  31301. var enclose = options.enclose;
  31302. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31303. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31304. var faceUV = options.faceUV || new Array(3);
  31305. var faceColors = options.faceColors;
  31306. // default face colors and UV if undefined
  31307. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31308. var ringNb = (hasRings) ? subdivisions : 1;
  31309. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31310. var f;
  31311. for (f = 0; f < surfaceNb; f++) {
  31312. if (faceColors && faceColors[f] === undefined) {
  31313. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31314. }
  31315. }
  31316. for (f = 0; f < surfaceNb; f++) {
  31317. if (faceUV && faceUV[f] === undefined) {
  31318. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31319. }
  31320. }
  31321. var indices = [];
  31322. var positions = [];
  31323. var normals = [];
  31324. var uvs = [];
  31325. var colors = [];
  31326. var angle_step = Math.PI * 2 * arc / tessellation;
  31327. var angle;
  31328. var h;
  31329. var radius;
  31330. var tan = (diameterBottom - diameterTop) / 2 / height;
  31331. var ringVertex = BABYLON.Vector3.Zero();
  31332. var ringNormal = BABYLON.Vector3.Zero();
  31333. var ringFirstVertex = BABYLON.Vector3.Zero();
  31334. var ringFirstNormal = BABYLON.Vector3.Zero();
  31335. var quadNormal = BABYLON.Vector3.Zero();
  31336. var Y = BABYLON.Axis.Y;
  31337. // positions, normals, uvs
  31338. var i;
  31339. var j;
  31340. var r;
  31341. var ringIdx = 1;
  31342. var s = 1; // surface index
  31343. var cs = 0;
  31344. var v = 0;
  31345. for (i = 0; i <= subdivisions; i++) {
  31346. h = i / subdivisions;
  31347. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31348. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31349. for (r = 0; r < ringIdx; r++) {
  31350. if (hasRings) {
  31351. s += r;
  31352. }
  31353. if (enclose) {
  31354. s += 2 * r;
  31355. }
  31356. for (j = 0; j <= tessellation; j++) {
  31357. angle = j * angle_step;
  31358. // position
  31359. ringVertex.x = Math.cos(-angle) * radius;
  31360. ringVertex.y = -height / 2 + h * height;
  31361. ringVertex.z = Math.sin(-angle) * radius;
  31362. // normal
  31363. if (diameterTop === 0 && i === subdivisions) {
  31364. // if no top cap, reuse former normals
  31365. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31366. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31367. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31368. }
  31369. else {
  31370. ringNormal.x = ringVertex.x;
  31371. ringNormal.z = ringVertex.z;
  31372. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31373. ringNormal.normalize();
  31374. }
  31375. // keep first ring vertex values for enclose
  31376. if (j === 0) {
  31377. ringFirstVertex.copyFrom(ringVertex);
  31378. ringFirstNormal.copyFrom(ringNormal);
  31379. }
  31380. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31381. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31382. if (hasRings) {
  31383. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31384. }
  31385. else {
  31386. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31387. }
  31388. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31389. if (faceColors) {
  31390. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31391. }
  31392. }
  31393. // if enclose, add four vertices and their dedicated normals
  31394. if (arc !== 1 && enclose) {
  31395. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31396. positions.push(0, ringVertex.y, 0);
  31397. positions.push(0, ringVertex.y, 0);
  31398. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31399. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31400. quadNormal.normalize();
  31401. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31402. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31403. quadNormal.normalize();
  31404. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31405. if (hasRings) {
  31406. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31407. }
  31408. else {
  31409. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31410. }
  31411. uvs.push(faceUV[s + 1].x, v);
  31412. uvs.push(faceUV[s + 1].z, v);
  31413. if (hasRings) {
  31414. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31415. }
  31416. else {
  31417. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31418. }
  31419. uvs.push(faceUV[s + 2].x, v);
  31420. uvs.push(faceUV[s + 2].z, v);
  31421. if (faceColors) {
  31422. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31423. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31424. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31425. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31426. }
  31427. }
  31428. if (cs !== s) {
  31429. cs = s;
  31430. }
  31431. }
  31432. }
  31433. // indices
  31434. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31435. var s;
  31436. i = 0;
  31437. for (s = 0; s < subdivisions; s++) {
  31438. for (j = 0; j < tessellation; j++) {
  31439. var i0 = i * (e + 1) + j;
  31440. var i1 = (i + 1) * (e + 1) + j;
  31441. var i2 = i * (e + 1) + (j + 1);
  31442. var i3 = (i + 1) * (e + 1) + (j + 1);
  31443. indices.push(i0, i1, i2);
  31444. indices.push(i3, i2, i1);
  31445. }
  31446. if (arc !== 1 && enclose) {
  31447. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31448. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31449. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31450. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31451. }
  31452. i = (hasRings) ? (i + 2) : (i + 1);
  31453. }
  31454. // Caps
  31455. var createCylinderCap = function (isTop) {
  31456. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31457. if (radius === 0) {
  31458. return;
  31459. }
  31460. // Cap positions, normals & uvs
  31461. var angle;
  31462. var circleVector;
  31463. var i;
  31464. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31465. var c;
  31466. if (faceColors) {
  31467. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31468. }
  31469. // cap center
  31470. var vbase = positions.length / 3;
  31471. var offset = isTop ? height / 2 : -height / 2;
  31472. var center = new BABYLON.Vector3(0, offset, 0);
  31473. positions.push(center.x, center.y, center.z);
  31474. normals.push(0, isTop ? 1 : -1, 0);
  31475. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31476. if (faceColors) {
  31477. colors.push(c.r, c.g, c.b, c.a);
  31478. }
  31479. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31480. for (i = 0; i <= tessellation; i++) {
  31481. angle = Math.PI * 2 * i * arc / tessellation;
  31482. var cos = Math.cos(-angle);
  31483. var sin = Math.sin(-angle);
  31484. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31485. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31486. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31487. normals.push(0, isTop ? 1 : -1, 0);
  31488. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31489. if (faceColors) {
  31490. colors.push(c.r, c.g, c.b, c.a);
  31491. }
  31492. }
  31493. // Cap indices
  31494. for (i = 0; i < tessellation; i++) {
  31495. if (!isTop) {
  31496. indices.push(vbase);
  31497. indices.push(vbase + (i + 1));
  31498. indices.push(vbase + (i + 2));
  31499. }
  31500. else {
  31501. indices.push(vbase);
  31502. indices.push(vbase + (i + 2));
  31503. indices.push(vbase + (i + 1));
  31504. }
  31505. }
  31506. };
  31507. // add caps to geometry
  31508. createCylinderCap(false);
  31509. createCylinderCap(true);
  31510. // Sides
  31511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31512. var vertexData = new VertexData();
  31513. vertexData.indices = indices;
  31514. vertexData.positions = positions;
  31515. vertexData.normals = normals;
  31516. vertexData.uvs = uvs;
  31517. if (faceColors) {
  31518. vertexData.colors = colors;
  31519. }
  31520. return vertexData;
  31521. };
  31522. VertexData.CreateTorus = function (options) {
  31523. var indices = [];
  31524. var positions = [];
  31525. var normals = [];
  31526. var uvs = [];
  31527. var diameter = options.diameter || 1;
  31528. var thickness = options.thickness || 0.5;
  31529. var tessellation = options.tessellation || 16;
  31530. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31531. var stride = tessellation + 1;
  31532. for (var i = 0; i <= tessellation; i++) {
  31533. var u = i / tessellation;
  31534. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31535. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31536. for (var j = 0; j <= tessellation; j++) {
  31537. var v = 1 - j / tessellation;
  31538. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31539. var dx = Math.cos(innerAngle);
  31540. var dy = Math.sin(innerAngle);
  31541. // Create a vertex.
  31542. var normal = new BABYLON.Vector3(dx, dy, 0);
  31543. var position = normal.scale(thickness / 2);
  31544. var textureCoordinate = new BABYLON.Vector2(u, v);
  31545. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31546. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31547. positions.push(position.x, position.y, position.z);
  31548. normals.push(normal.x, normal.y, normal.z);
  31549. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31550. // And create indices for two triangles.
  31551. var nextI = (i + 1) % stride;
  31552. var nextJ = (j + 1) % stride;
  31553. indices.push(i * stride + j);
  31554. indices.push(i * stride + nextJ);
  31555. indices.push(nextI * stride + j);
  31556. indices.push(i * stride + nextJ);
  31557. indices.push(nextI * stride + nextJ);
  31558. indices.push(nextI * stride + j);
  31559. }
  31560. }
  31561. // Sides
  31562. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31563. // Result
  31564. var vertexData = new VertexData();
  31565. vertexData.indices = indices;
  31566. vertexData.positions = positions;
  31567. vertexData.normals = normals;
  31568. vertexData.uvs = uvs;
  31569. return vertexData;
  31570. };
  31571. VertexData.CreateLineSystem = function (options) {
  31572. var indices = [];
  31573. var positions = [];
  31574. var lines = options.lines;
  31575. var idx = 0;
  31576. for (var l = 0; l < lines.length; l++) {
  31577. var points = lines[l];
  31578. for (var index = 0; index < points.length; index++) {
  31579. positions.push(points[index].x, points[index].y, points[index].z);
  31580. if (index > 0) {
  31581. indices.push(idx - 1);
  31582. indices.push(idx);
  31583. }
  31584. idx++;
  31585. }
  31586. }
  31587. var vertexData = new VertexData();
  31588. vertexData.indices = indices;
  31589. vertexData.positions = positions;
  31590. return vertexData;
  31591. };
  31592. VertexData.CreateDashedLines = function (options) {
  31593. var dashSize = options.dashSize || 3;
  31594. var gapSize = options.gapSize || 1;
  31595. var dashNb = options.dashNb || 200;
  31596. var points = options.points;
  31597. var positions = new Array();
  31598. var indices = new Array();
  31599. var curvect = BABYLON.Vector3.Zero();
  31600. var lg = 0;
  31601. var nb = 0;
  31602. var shft = 0;
  31603. var dashshft = 0;
  31604. var curshft = 0;
  31605. var idx = 0;
  31606. var i = 0;
  31607. for (i = 0; i < points.length - 1; i++) {
  31608. points[i + 1].subtractToRef(points[i], curvect);
  31609. lg += curvect.length();
  31610. }
  31611. shft = lg / dashNb;
  31612. dashshft = dashSize * shft / (dashSize + gapSize);
  31613. for (i = 0; i < points.length - 1; i++) {
  31614. points[i + 1].subtractToRef(points[i], curvect);
  31615. nb = Math.floor(curvect.length() / shft);
  31616. curvect.normalize();
  31617. for (var j = 0; j < nb; j++) {
  31618. curshft = shft * j;
  31619. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31620. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31621. indices.push(idx, idx + 1);
  31622. idx += 2;
  31623. }
  31624. }
  31625. // Result
  31626. var vertexData = new VertexData();
  31627. vertexData.positions = positions;
  31628. vertexData.indices = indices;
  31629. return vertexData;
  31630. };
  31631. VertexData.CreateGround = function (options) {
  31632. var indices = [];
  31633. var positions = [];
  31634. var normals = [];
  31635. var uvs = [];
  31636. var row, col;
  31637. var width = options.width || 1;
  31638. var height = options.height || 1;
  31639. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31640. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31641. for (row = 0; row <= subdivisionsY; row++) {
  31642. for (col = 0; col <= subdivisionsX; col++) {
  31643. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31644. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31645. positions.push(position.x, position.y, position.z);
  31646. normals.push(normal.x, normal.y, normal.z);
  31647. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31648. }
  31649. }
  31650. for (row = 0; row < subdivisionsY; row++) {
  31651. for (col = 0; col < subdivisionsX; col++) {
  31652. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31653. indices.push(col + 1 + row * (subdivisionsX + 1));
  31654. indices.push(col + row * (subdivisionsX + 1));
  31655. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31656. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31657. indices.push(col + row * (subdivisionsX + 1));
  31658. }
  31659. }
  31660. // Result
  31661. var vertexData = new VertexData();
  31662. vertexData.indices = indices;
  31663. vertexData.positions = positions;
  31664. vertexData.normals = normals;
  31665. vertexData.uvs = uvs;
  31666. return vertexData;
  31667. };
  31668. VertexData.CreateTiledGround = function (options) {
  31669. var xmin = options.xmin || -1.0;
  31670. var zmin = options.zmin || -1.0;
  31671. var xmax = options.xmax || 1.0;
  31672. var zmax = options.zmax || 1.0;
  31673. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31674. var precision = options.precision || { w: 1, h: 1 };
  31675. var indices = [];
  31676. var positions = [];
  31677. var normals = [];
  31678. var uvs = [];
  31679. var row, col, tileRow, tileCol;
  31680. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31681. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31682. precision.w = (precision.w < 1) ? 1 : precision.w;
  31683. precision.h = (precision.h < 1) ? 1 : precision.h;
  31684. var tileSize = {
  31685. 'w': (xmax - xmin) / subdivisions.w,
  31686. 'h': (zmax - zmin) / subdivisions.h
  31687. };
  31688. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31689. // Indices
  31690. var base = positions.length / 3;
  31691. var rowLength = precision.w + 1;
  31692. for (row = 0; row < precision.h; row++) {
  31693. for (col = 0; col < precision.w; col++) {
  31694. var square = [
  31695. base + col + row * rowLength,
  31696. base + (col + 1) + row * rowLength,
  31697. base + (col + 1) + (row + 1) * rowLength,
  31698. base + col + (row + 1) * rowLength
  31699. ];
  31700. indices.push(square[1]);
  31701. indices.push(square[2]);
  31702. indices.push(square[3]);
  31703. indices.push(square[0]);
  31704. indices.push(square[1]);
  31705. indices.push(square[3]);
  31706. }
  31707. }
  31708. // Position, normals and uvs
  31709. var position = BABYLON.Vector3.Zero();
  31710. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31711. for (row = 0; row <= precision.h; row++) {
  31712. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31713. for (col = 0; col <= precision.w; col++) {
  31714. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31715. position.y = 0;
  31716. positions.push(position.x, position.y, position.z);
  31717. normals.push(normal.x, normal.y, normal.z);
  31718. uvs.push(col / precision.w, row / precision.h);
  31719. }
  31720. }
  31721. }
  31722. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31723. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31724. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31725. }
  31726. }
  31727. // Result
  31728. var vertexData = new VertexData();
  31729. vertexData.indices = indices;
  31730. vertexData.positions = positions;
  31731. vertexData.normals = normals;
  31732. vertexData.uvs = uvs;
  31733. return vertexData;
  31734. };
  31735. VertexData.CreateGroundFromHeightMap = function (options) {
  31736. var indices = [];
  31737. var positions = [];
  31738. var normals = [];
  31739. var uvs = [];
  31740. var row, col;
  31741. // Vertices
  31742. for (row = 0; row <= options.subdivisions; row++) {
  31743. for (col = 0; col <= options.subdivisions; col++) {
  31744. 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));
  31745. // Compute height
  31746. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31747. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31748. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31749. var r = options.buffer[pos] / 255.0;
  31750. var g = options.buffer[pos + 1] / 255.0;
  31751. var b = options.buffer[pos + 2] / 255.0;
  31752. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31753. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31754. // Add vertex
  31755. positions.push(position.x, position.y, position.z);
  31756. normals.push(0, 0, 0);
  31757. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31758. }
  31759. }
  31760. // Indices
  31761. for (row = 0; row < options.subdivisions; row++) {
  31762. for (col = 0; col < options.subdivisions; col++) {
  31763. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31764. indices.push(col + 1 + row * (options.subdivisions + 1));
  31765. indices.push(col + row * (options.subdivisions + 1));
  31766. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31767. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31768. indices.push(col + row * (options.subdivisions + 1));
  31769. }
  31770. }
  31771. // Normals
  31772. VertexData.ComputeNormals(positions, indices, normals);
  31773. // Result
  31774. var vertexData = new VertexData();
  31775. vertexData.indices = indices;
  31776. vertexData.positions = positions;
  31777. vertexData.normals = normals;
  31778. vertexData.uvs = uvs;
  31779. return vertexData;
  31780. };
  31781. VertexData.CreatePlane = function (options) {
  31782. var indices = [];
  31783. var positions = [];
  31784. var normals = [];
  31785. var uvs = [];
  31786. var width = options.width || options.size || 1;
  31787. var height = options.height || options.size || 1;
  31788. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31789. // Vertices
  31790. var halfWidth = width / 2.0;
  31791. var halfHeight = height / 2.0;
  31792. positions.push(-halfWidth, -halfHeight, 0);
  31793. normals.push(0, 0, -1.0);
  31794. uvs.push(0.0, 0.0);
  31795. positions.push(halfWidth, -halfHeight, 0);
  31796. normals.push(0, 0, -1.0);
  31797. uvs.push(1.0, 0.0);
  31798. positions.push(halfWidth, halfHeight, 0);
  31799. normals.push(0, 0, -1.0);
  31800. uvs.push(1.0, 1.0);
  31801. positions.push(-halfWidth, halfHeight, 0);
  31802. normals.push(0, 0, -1.0);
  31803. uvs.push(0.0, 1.0);
  31804. // Indices
  31805. indices.push(0);
  31806. indices.push(1);
  31807. indices.push(2);
  31808. indices.push(0);
  31809. indices.push(2);
  31810. indices.push(3);
  31811. // Sides
  31812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31813. // Result
  31814. var vertexData = new VertexData();
  31815. vertexData.indices = indices;
  31816. vertexData.positions = positions;
  31817. vertexData.normals = normals;
  31818. vertexData.uvs = uvs;
  31819. return vertexData;
  31820. };
  31821. VertexData.CreateDisc = function (options) {
  31822. var positions = [];
  31823. var indices = [];
  31824. var normals = [];
  31825. var uvs = [];
  31826. var radius = options.radius || 0.5;
  31827. var tessellation = options.tessellation || 64;
  31828. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31829. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31830. // positions and uvs
  31831. positions.push(0, 0, 0); // disc center first
  31832. uvs.push(0.5, 0.5);
  31833. var theta = Math.PI * 2 * arc;
  31834. var step = theta / tessellation;
  31835. for (var a = 0; a < theta; a += step) {
  31836. var x = Math.cos(a);
  31837. var y = Math.sin(a);
  31838. var u = (x + 1) / 2;
  31839. var v = (1 - y) / 2;
  31840. positions.push(radius * x, radius * y, 0);
  31841. uvs.push(u, v);
  31842. }
  31843. if (arc === 1) {
  31844. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31845. uvs.push(uvs[2], uvs[3]);
  31846. }
  31847. //indices
  31848. var vertexNb = positions.length / 3;
  31849. for (var i = 1; i < vertexNb - 1; i++) {
  31850. indices.push(i + 1, 0, i);
  31851. }
  31852. // result
  31853. VertexData.ComputeNormals(positions, indices, normals);
  31854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31855. var vertexData = new VertexData();
  31856. vertexData.indices = indices;
  31857. vertexData.positions = positions;
  31858. vertexData.normals = normals;
  31859. vertexData.uvs = uvs;
  31860. return vertexData;
  31861. };
  31862. VertexData.CreateIcoSphere = function (options) {
  31863. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31864. var radius = options.radius || 1;
  31865. var flat = (options.flat === undefined) ? true : options.flat;
  31866. var subdivisions = options.subdivisions || 4;
  31867. var radiusX = options.radiusX || radius;
  31868. var radiusY = options.radiusY || radius;
  31869. var radiusZ = options.radiusZ || radius;
  31870. var t = (1 + Math.sqrt(5)) / 2;
  31871. // 12 vertex x,y,z
  31872. var ico_vertices = [
  31873. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31874. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31875. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31876. ];
  31877. // index of 3 vertex makes a face of icopshere
  31878. var ico_indices = [
  31879. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31880. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31881. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31882. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31883. ];
  31884. // vertex for uv have aliased position, not for UV
  31885. var vertices_unalias_id = [
  31886. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31887. // vertex alias
  31888. 0,
  31889. 2,
  31890. 3,
  31891. 3,
  31892. 3,
  31893. 4,
  31894. 7,
  31895. 8,
  31896. 9,
  31897. 9,
  31898. 10,
  31899. 11 // 23: B + 12
  31900. ];
  31901. // uv as integer step (not pixels !)
  31902. var ico_vertexuv = [
  31903. 5, 1, 3, 1, 6, 4, 0, 0,
  31904. 5, 3, 4, 2, 2, 2, 4, 0,
  31905. 2, 0, 1, 1, 6, 0, 6, 2,
  31906. // vertex alias (for same vertex on different faces)
  31907. 0, 4,
  31908. 3, 3,
  31909. 4, 4,
  31910. 3, 1,
  31911. 4, 2,
  31912. 4, 4,
  31913. 0, 2,
  31914. 1, 1,
  31915. 2, 2,
  31916. 3, 3,
  31917. 1, 3,
  31918. 2, 4 // 23: B + 12
  31919. ];
  31920. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31921. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31922. // First island of uv mapping
  31923. // v = 4h 3+ 2
  31924. // v = 3h 9+ 4
  31925. // v = 2h 9+ 5 B
  31926. // v = 1h 9 1 0
  31927. // v = 0h 3 8 7 A
  31928. // u = 0 1 2 3 4 5 6 *a
  31929. // Second island of uv mapping
  31930. // v = 4h 0+ B+ 4+
  31931. // v = 3h A+ 2+
  31932. // v = 2h 7+ 6 3+
  31933. // v = 1h 8+ 3+
  31934. // v = 0h
  31935. // u = 0 1 2 3 4 5 6 *a
  31936. // Face layout on texture UV mapping
  31937. // ============
  31938. // \ 4 /\ 16 / ======
  31939. // \ / \ / /\ 11 /
  31940. // \/ 7 \/ / \ /
  31941. // ======= / 10 \/
  31942. // /\ 17 /\ =======
  31943. // / \ / \ \ 15 /\
  31944. // / 8 \/ 12 \ \ / \
  31945. // ============ \/ 6 \
  31946. // \ 18 /\ ============
  31947. // \ / \ \ 5 /\ 0 /
  31948. // \/ 13 \ \ / \ /
  31949. // ======= \/ 1 \/
  31950. // =============
  31951. // /\ 19 /\ 2 /\
  31952. // / \ / \ / \
  31953. // / 14 \/ 9 \/ 3 \
  31954. // ===================
  31955. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31956. var ustep = 138 / 1024;
  31957. var vstep = 239 / 1024;
  31958. var uoffset = 60 / 1024;
  31959. var voffset = 26 / 1024;
  31960. // Second island should have margin, not to touch the first island
  31961. // avoid any borderline artefact in pixel rounding
  31962. var island_u_offset = -40 / 1024;
  31963. var island_v_offset = +20 / 1024;
  31964. // face is either island 0 or 1 :
  31965. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31966. var island = [
  31967. 0, 0, 0, 0, 1,
  31968. 0, 0, 1, 1, 0,
  31969. 0, 0, 1, 1, 0,
  31970. 0, 1, 1, 1, 0 // 15 - 19
  31971. ];
  31972. var indices = [];
  31973. var positions = [];
  31974. var normals = [];
  31975. var uvs = [];
  31976. var current_indice = 0;
  31977. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31978. var face_vertex_pos = new Array(3);
  31979. var face_vertex_uv = new Array(3);
  31980. var v012;
  31981. for (v012 = 0; v012 < 3; v012++) {
  31982. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31983. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31984. }
  31985. // create all with normals
  31986. for (var face = 0; face < 20; face++) {
  31987. // 3 vertex per face
  31988. for (v012 = 0; v012 < 3; v012++) {
  31989. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31990. var v_id = ico_indices[3 * face + v012];
  31991. // vertex have 3D position (x,y,z)
  31992. 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]);
  31993. // Normalize to get normal, then scale to radius
  31994. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31995. // uv Coordinates from vertex ID
  31996. 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);
  31997. }
  31998. // Subdivide the face (interpolate pos, norm, uv)
  31999. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32000. // - norm is linear interpolation of vertex corner normal
  32001. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32002. // - uv is linear interpolation
  32003. //
  32004. // Topology is as below for sub-divide by 2
  32005. // vertex shown as v0,v1,v2
  32006. // interp index is i1 to progress in range [v0,v1[
  32007. // interp index is i2 to progress in range [v0,v2[
  32008. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32009. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32010. //
  32011. //
  32012. // i2 v2
  32013. // ^ ^
  32014. // / / \
  32015. // / / \
  32016. // / / \
  32017. // / / (0,1) \
  32018. // / #---------\
  32019. // / / \ (0,0)'/ \
  32020. // / / \ / \
  32021. // / / \ / \
  32022. // / / (0,0) \ / (1,0) \
  32023. // / #---------#---------\
  32024. // v0 v1
  32025. //
  32026. // --------------------> i1
  32027. //
  32028. // interp of (i1,i2):
  32029. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32030. // along i1 : lerp(x0,x1, i1/(S-i2))
  32031. //
  32032. // centroid of triangle is needed to get help normal computation
  32033. // (c1,c2) are used for centroid location
  32034. var interp_vertex = function (i1, i2, c1, c2) {
  32035. // vertex is interpolated from
  32036. // - face_vertex_pos[0..2]
  32037. // - face_vertex_uv[0..2]
  32038. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32039. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32040. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32041. pos_interp.normalize();
  32042. var vertex_normal;
  32043. if (flat) {
  32044. // in flat mode, recalculate normal as face centroid normal
  32045. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32046. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32047. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32048. }
  32049. else {
  32050. // in smooth mode, recalculate normal from each single vertex position
  32051. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32052. }
  32053. // Vertex normal need correction due to X,Y,Z radius scaling
  32054. vertex_normal.x /= radiusX;
  32055. vertex_normal.y /= radiusY;
  32056. vertex_normal.z /= radiusZ;
  32057. vertex_normal.normalize();
  32058. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32059. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32060. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32061. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32062. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32063. uvs.push(uv_interp.x, uv_interp.y);
  32064. // push each vertex has member of a face
  32065. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32066. indices.push(current_indice);
  32067. current_indice++;
  32068. };
  32069. for (var i2 = 0; i2 < subdivisions; i2++) {
  32070. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32071. // face : (i1,i2) for /\ :
  32072. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32073. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32074. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32075. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32076. if (i1 + i2 + 1 < subdivisions) {
  32077. // face : (i1,i2)' for \/ :
  32078. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32079. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32080. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32081. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32082. }
  32083. }
  32084. }
  32085. }
  32086. // Sides
  32087. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32088. // Result
  32089. var vertexData = new VertexData();
  32090. vertexData.indices = indices;
  32091. vertexData.positions = positions;
  32092. vertexData.normals = normals;
  32093. vertexData.uvs = uvs;
  32094. return vertexData;
  32095. };
  32096. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32097. VertexData.CreatePolyhedron = function (options) {
  32098. // provided polyhedron types :
  32099. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32100. // 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)
  32101. var polyhedra = [];
  32102. 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]] };
  32103. 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]] };
  32104. polyhedra[2] = {
  32105. 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]],
  32106. 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]]
  32107. };
  32108. polyhedra[3] = {
  32109. 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]],
  32110. 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]]
  32111. };
  32112. polyhedra[4] = {
  32113. 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]],
  32114. 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]]
  32115. };
  32116. 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]] };
  32117. 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]] };
  32118. 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]] };
  32119. 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]] };
  32120. 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]] };
  32121. 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]] };
  32122. 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]] };
  32123. 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]] };
  32124. 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]] };
  32125. polyhedra[14] = {
  32126. 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]],
  32127. 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]]
  32128. };
  32129. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32130. var size = options.size;
  32131. var sizeX = options.sizeX || size || 1;
  32132. var sizeY = options.sizeY || size || 1;
  32133. var sizeZ = options.sizeZ || size || 1;
  32134. var data = options.custom || polyhedra[type];
  32135. var nbfaces = data.face.length;
  32136. var faceUV = options.faceUV || new Array(nbfaces);
  32137. var faceColors = options.faceColors;
  32138. var flat = (options.flat === undefined) ? true : options.flat;
  32139. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32140. var positions = [];
  32141. var indices = [];
  32142. var normals = [];
  32143. var uvs = [];
  32144. var colors = [];
  32145. var index = 0;
  32146. var faceIdx = 0; // face cursor in the array "indexes"
  32147. var indexes = [];
  32148. var i = 0;
  32149. var f = 0;
  32150. var u, v, ang, x, y, tmp;
  32151. // default face colors and UV if undefined
  32152. if (flat) {
  32153. for (f = 0; f < nbfaces; f++) {
  32154. if (faceColors && faceColors[f] === undefined) {
  32155. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32156. }
  32157. if (faceUV && faceUV[f] === undefined) {
  32158. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32159. }
  32160. }
  32161. }
  32162. if (!flat) {
  32163. for (i = 0; i < data.vertex.length; i++) {
  32164. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32165. uvs.push(0, 0);
  32166. }
  32167. for (f = 0; f < nbfaces; f++) {
  32168. for (i = 0; i < data.face[f].length - 2; i++) {
  32169. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32170. }
  32171. }
  32172. }
  32173. else {
  32174. for (f = 0; f < nbfaces; f++) {
  32175. var fl = data.face[f].length; // number of vertices of the current face
  32176. ang = 2 * Math.PI / fl;
  32177. x = 0.5 * Math.tan(ang / 2);
  32178. y = 0.5;
  32179. // positions, uvs, colors
  32180. for (i = 0; i < fl; i++) {
  32181. // positions
  32182. 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);
  32183. indexes.push(index);
  32184. index++;
  32185. // uvs
  32186. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32187. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32188. uvs.push(u, v);
  32189. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32190. y = x * Math.sin(ang) + y * Math.cos(ang);
  32191. x = tmp;
  32192. // colors
  32193. if (faceColors) {
  32194. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32195. }
  32196. }
  32197. // indices from indexes
  32198. for (i = 0; i < fl - 2; i++) {
  32199. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32200. }
  32201. faceIdx += fl;
  32202. }
  32203. }
  32204. VertexData.ComputeNormals(positions, indices, normals);
  32205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32206. var vertexData = new VertexData();
  32207. vertexData.positions = positions;
  32208. vertexData.indices = indices;
  32209. vertexData.normals = normals;
  32210. vertexData.uvs = uvs;
  32211. if (faceColors && flat) {
  32212. vertexData.colors = colors;
  32213. }
  32214. return vertexData;
  32215. };
  32216. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32217. VertexData.CreateTorusKnot = function (options) {
  32218. var indices = [];
  32219. var positions = [];
  32220. var normals = [];
  32221. var uvs = [];
  32222. var radius = options.radius || 2;
  32223. var tube = options.tube || 0.5;
  32224. var radialSegments = options.radialSegments || 32;
  32225. var tubularSegments = options.tubularSegments || 32;
  32226. var p = options.p || 2;
  32227. var q = options.q || 3;
  32228. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32229. // Helper
  32230. var getPos = function (angle) {
  32231. var cu = Math.cos(angle);
  32232. var su = Math.sin(angle);
  32233. var quOverP = q / p * angle;
  32234. var cs = Math.cos(quOverP);
  32235. var tx = radius * (2 + cs) * 0.5 * cu;
  32236. var ty = radius * (2 + cs) * su * 0.5;
  32237. var tz = radius * Math.sin(quOverP) * 0.5;
  32238. return new BABYLON.Vector3(tx, ty, tz);
  32239. };
  32240. // Vertices
  32241. var i;
  32242. var j;
  32243. for (i = 0; i <= radialSegments; i++) {
  32244. var modI = i % radialSegments;
  32245. var u = modI / radialSegments * 2 * p * Math.PI;
  32246. var p1 = getPos(u);
  32247. var p2 = getPos(u + 0.01);
  32248. var tang = p2.subtract(p1);
  32249. var n = p2.add(p1);
  32250. var bitan = BABYLON.Vector3.Cross(tang, n);
  32251. n = BABYLON.Vector3.Cross(bitan, tang);
  32252. bitan.normalize();
  32253. n.normalize();
  32254. for (j = 0; j < tubularSegments; j++) {
  32255. var modJ = j % tubularSegments;
  32256. var v = modJ / tubularSegments * 2 * Math.PI;
  32257. var cx = -tube * Math.cos(v);
  32258. var cy = tube * Math.sin(v);
  32259. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32260. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32261. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32262. uvs.push(i / radialSegments);
  32263. uvs.push(j / tubularSegments);
  32264. }
  32265. }
  32266. for (i = 0; i < radialSegments; i++) {
  32267. for (j = 0; j < tubularSegments; j++) {
  32268. var jNext = (j + 1) % tubularSegments;
  32269. var a = i * tubularSegments + j;
  32270. var b = (i + 1) * tubularSegments + j;
  32271. var c = (i + 1) * tubularSegments + jNext;
  32272. var d = i * tubularSegments + jNext;
  32273. indices.push(d);
  32274. indices.push(b);
  32275. indices.push(a);
  32276. indices.push(d);
  32277. indices.push(c);
  32278. indices.push(b);
  32279. }
  32280. }
  32281. // Normals
  32282. VertexData.ComputeNormals(positions, indices, normals);
  32283. // Sides
  32284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32285. // Result
  32286. var vertexData = new VertexData();
  32287. vertexData.indices = indices;
  32288. vertexData.positions = positions;
  32289. vertexData.normals = normals;
  32290. vertexData.uvs = uvs;
  32291. return vertexData;
  32292. };
  32293. // Tools
  32294. /**
  32295. * @param {any} - positions (number[] or Float32Array)
  32296. * @param {any} - indices (number[] or Uint16Array)
  32297. * @param {any} - normals (number[] or Float32Array)
  32298. */
  32299. VertexData.ComputeNormals = function (positions, indices, normals) {
  32300. var index = 0;
  32301. var p1p2x = 0.0;
  32302. var p1p2y = 0.0;
  32303. var p1p2z = 0.0;
  32304. var p3p2x = 0.0;
  32305. var p3p2y = 0.0;
  32306. var p3p2z = 0.0;
  32307. var faceNormalx = 0.0;
  32308. var faceNormaly = 0.0;
  32309. var faceNormalz = 0.0;
  32310. var length = 0.0;
  32311. var i1 = 0;
  32312. var i2 = 0;
  32313. var i3 = 0;
  32314. for (index = 0; index < positions.length; index++) {
  32315. normals[index] = 0.0;
  32316. }
  32317. // indice triplet = 1 face
  32318. var nbFaces = indices.length / 3;
  32319. for (index = 0; index < nbFaces; index++) {
  32320. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32321. i2 = indices[index * 3 + 1];
  32322. i3 = indices[index * 3 + 2];
  32323. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32324. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32325. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32326. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32327. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32328. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32329. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32330. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32331. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32332. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32333. length = (length === 0) ? 1.0 : length;
  32334. faceNormalx /= length; // normalize this normal
  32335. faceNormaly /= length;
  32336. faceNormalz /= length;
  32337. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32338. normals[i1 * 3 + 1] += faceNormaly;
  32339. normals[i1 * 3 + 2] += faceNormalz;
  32340. normals[i2 * 3] += faceNormalx;
  32341. normals[i2 * 3 + 1] += faceNormaly;
  32342. normals[i2 * 3 + 2] += faceNormalz;
  32343. normals[i3 * 3] += faceNormalx;
  32344. normals[i3 * 3 + 1] += faceNormaly;
  32345. normals[i3 * 3 + 2] += faceNormalz;
  32346. }
  32347. // last normalization of each normal
  32348. for (index = 0; index < normals.length / 3; index++) {
  32349. faceNormalx = normals[index * 3];
  32350. faceNormaly = normals[index * 3 + 1];
  32351. faceNormalz = normals[index * 3 + 2];
  32352. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32353. length = (length === 0) ? 1.0 : length;
  32354. faceNormalx /= length;
  32355. faceNormaly /= length;
  32356. faceNormalz /= length;
  32357. normals[index * 3] = faceNormalx;
  32358. normals[index * 3 + 1] = faceNormaly;
  32359. normals[index * 3 + 2] = faceNormalz;
  32360. }
  32361. };
  32362. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32363. var li = indices.length;
  32364. var ln = normals.length;
  32365. var i;
  32366. var n;
  32367. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32368. switch (sideOrientation) {
  32369. case BABYLON.Mesh.FRONTSIDE:
  32370. // nothing changed
  32371. break;
  32372. case BABYLON.Mesh.BACKSIDE:
  32373. var tmp;
  32374. // indices
  32375. for (i = 0; i < li; i += 3) {
  32376. tmp = indices[i];
  32377. indices[i] = indices[i + 2];
  32378. indices[i + 2] = tmp;
  32379. }
  32380. // normals
  32381. for (n = 0; n < ln; n++) {
  32382. normals[n] = -normals[n];
  32383. }
  32384. break;
  32385. case BABYLON.Mesh.DOUBLESIDE:
  32386. // positions
  32387. var lp = positions.length;
  32388. var l = lp / 3;
  32389. for (var p = 0; p < lp; p++) {
  32390. positions[lp + p] = positions[p];
  32391. }
  32392. // indices
  32393. for (i = 0; i < li; i += 3) {
  32394. indices[i + li] = indices[i + 2] + l;
  32395. indices[i + 1 + li] = indices[i + 1] + l;
  32396. indices[i + 2 + li] = indices[i] + l;
  32397. }
  32398. // normals
  32399. for (n = 0; n < ln; n++) {
  32400. normals[ln + n] = -normals[n];
  32401. }
  32402. // uvs
  32403. var lu = uvs.length;
  32404. for (var u = 0; u < lu; u++) {
  32405. uvs[u + lu] = uvs[u];
  32406. }
  32407. break;
  32408. }
  32409. };
  32410. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32411. var vertexData = new VertexData();
  32412. // positions
  32413. var positions = parsedVertexData.positions;
  32414. if (positions) {
  32415. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32416. }
  32417. // normals
  32418. var normals = parsedVertexData.normals;
  32419. if (normals) {
  32420. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32421. }
  32422. // uvs
  32423. var uvs = parsedVertexData.uvs;
  32424. if (uvs) {
  32425. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32426. }
  32427. // uv2s
  32428. var uv2s = parsedVertexData.uv2s;
  32429. if (uv2s) {
  32430. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32431. }
  32432. // uv3s
  32433. var uv3s = parsedVertexData.uv3s;
  32434. if (uv3s) {
  32435. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32436. }
  32437. // uv4s
  32438. var uv4s = parsedVertexData.uv4s;
  32439. if (uv4s) {
  32440. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32441. }
  32442. // uv5s
  32443. var uv5s = parsedVertexData.uv5s;
  32444. if (uv5s) {
  32445. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32446. }
  32447. // uv6s
  32448. var uv6s = parsedVertexData.uv6s;
  32449. if (uv6s) {
  32450. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32451. }
  32452. // colors
  32453. var colors = parsedVertexData.colors;
  32454. if (colors) {
  32455. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32456. }
  32457. // matricesIndices
  32458. var matricesIndices = parsedVertexData.matricesIndices;
  32459. if (matricesIndices) {
  32460. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32461. }
  32462. // matricesWeights
  32463. var matricesWeights = parsedVertexData.matricesWeights;
  32464. if (matricesWeights) {
  32465. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32466. }
  32467. // indices
  32468. var indices = parsedVertexData.indices;
  32469. if (indices) {
  32470. vertexData.indices = indices;
  32471. }
  32472. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32473. };
  32474. return VertexData;
  32475. }());
  32476. BABYLON.VertexData = VertexData;
  32477. })(BABYLON || (BABYLON = {}));
  32478. var BABYLON;
  32479. (function (BABYLON) {
  32480. var Tags = (function () {
  32481. function Tags() {
  32482. }
  32483. Tags.EnableFor = function (obj) {
  32484. obj._tags = obj._tags || {};
  32485. obj.hasTags = function () {
  32486. return Tags.HasTags(obj);
  32487. };
  32488. obj.addTags = function (tagsString) {
  32489. return Tags.AddTagsTo(obj, tagsString);
  32490. };
  32491. obj.removeTags = function (tagsString) {
  32492. return Tags.RemoveTagsFrom(obj, tagsString);
  32493. };
  32494. obj.matchesTagsQuery = function (tagsQuery) {
  32495. return Tags.MatchesQuery(obj, tagsQuery);
  32496. };
  32497. };
  32498. Tags.DisableFor = function (obj) {
  32499. delete obj._tags;
  32500. delete obj.hasTags;
  32501. delete obj.addTags;
  32502. delete obj.removeTags;
  32503. delete obj.matchesTagsQuery;
  32504. };
  32505. Tags.HasTags = function (obj) {
  32506. if (!obj._tags) {
  32507. return false;
  32508. }
  32509. return !BABYLON.Tools.IsEmpty(obj._tags);
  32510. };
  32511. Tags.GetTags = function (obj, asString) {
  32512. if (asString === void 0) { asString = true; }
  32513. if (!obj._tags) {
  32514. return null;
  32515. }
  32516. if (asString) {
  32517. var tagsArray = [];
  32518. for (var tag in obj._tags) {
  32519. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32520. tagsArray.push(tag);
  32521. }
  32522. }
  32523. return tagsArray.join(" ");
  32524. }
  32525. else {
  32526. return obj._tags;
  32527. }
  32528. };
  32529. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32530. // a tag cannot start with '||', '&&', and '!'
  32531. // it cannot contain whitespaces
  32532. Tags.AddTagsTo = function (obj, tagsString) {
  32533. if (!tagsString) {
  32534. return;
  32535. }
  32536. if (typeof tagsString !== "string") {
  32537. return;
  32538. }
  32539. var tags = tagsString.split(" ");
  32540. for (var t in tags) {
  32541. Tags._AddTagTo(obj, tags[t]);
  32542. }
  32543. };
  32544. Tags._AddTagTo = function (obj, tag) {
  32545. tag = tag.trim();
  32546. if (tag === "" || tag === "true" || tag === "false") {
  32547. return;
  32548. }
  32549. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32550. return;
  32551. }
  32552. Tags.EnableFor(obj);
  32553. obj._tags[tag] = true;
  32554. };
  32555. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32556. if (!Tags.HasTags(obj)) {
  32557. return;
  32558. }
  32559. var tags = tagsString.split(" ");
  32560. for (var t in tags) {
  32561. Tags._RemoveTagFrom(obj, tags[t]);
  32562. }
  32563. };
  32564. Tags._RemoveTagFrom = function (obj, tag) {
  32565. delete obj._tags[tag];
  32566. };
  32567. Tags.MatchesQuery = function (obj, tagsQuery) {
  32568. if (tagsQuery === undefined) {
  32569. return true;
  32570. }
  32571. if (tagsQuery === "") {
  32572. return Tags.HasTags(obj);
  32573. }
  32574. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32575. };
  32576. return Tags;
  32577. }());
  32578. BABYLON.Tags = Tags;
  32579. })(BABYLON || (BABYLON = {}));
  32580. var BABYLON;
  32581. (function (BABYLON) {
  32582. var Internals;
  32583. (function (Internals) {
  32584. var AndOrNotEvaluator = (function () {
  32585. function AndOrNotEvaluator() {
  32586. }
  32587. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32588. if (!query.match(/\([^\(\)]*\)/g)) {
  32589. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32590. }
  32591. else {
  32592. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32593. // remove parenthesis
  32594. r = r.slice(1, r.length - 1);
  32595. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32596. });
  32597. }
  32598. if (query === "true") {
  32599. return true;
  32600. }
  32601. if (query === "false") {
  32602. return false;
  32603. }
  32604. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32605. };
  32606. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32607. evaluateCallback = evaluateCallback || (function (r) {
  32608. return r === "true" ? true : false;
  32609. });
  32610. var result;
  32611. var or = parenthesisContent.split("||");
  32612. for (var i in or) {
  32613. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32614. var and = ori.split("&&");
  32615. if (and.length > 1) {
  32616. for (var j = 0; j < and.length; ++j) {
  32617. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32618. if (andj !== "true" && andj !== "false") {
  32619. if (andj[0] === "!") {
  32620. result = !evaluateCallback(andj.substring(1));
  32621. }
  32622. else {
  32623. result = evaluateCallback(andj);
  32624. }
  32625. }
  32626. else {
  32627. result = andj === "true" ? true : false;
  32628. }
  32629. if (!result) {
  32630. ori = "false";
  32631. break;
  32632. }
  32633. }
  32634. }
  32635. if (result || ori === "true") {
  32636. result = true;
  32637. break;
  32638. }
  32639. // result equals false (or undefined)
  32640. if (ori !== "true" && ori !== "false") {
  32641. if (ori[0] === "!") {
  32642. result = !evaluateCallback(ori.substring(1));
  32643. }
  32644. else {
  32645. result = evaluateCallback(ori);
  32646. }
  32647. }
  32648. else {
  32649. result = ori === "true" ? true : false;
  32650. }
  32651. }
  32652. // the whole parenthesis scope is replaced by 'true' or 'false'
  32653. return result ? "true" : "false";
  32654. };
  32655. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32656. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32657. // remove whitespaces
  32658. r = r.replace(/[\s]/g, function () { return ""; });
  32659. return r.length % 2 ? "!" : "";
  32660. });
  32661. booleanString = booleanString.trim();
  32662. if (booleanString === "!true") {
  32663. booleanString = "false";
  32664. }
  32665. else if (booleanString === "!false") {
  32666. booleanString = "true";
  32667. }
  32668. return booleanString;
  32669. };
  32670. return AndOrNotEvaluator;
  32671. }());
  32672. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32673. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32674. })(BABYLON || (BABYLON = {}));
  32675. var BABYLON;
  32676. (function (BABYLON) {
  32677. var PostProcessRenderPass = (function () {
  32678. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32679. this._enabled = true;
  32680. this._refCount = 0;
  32681. this._name = name;
  32682. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32683. this.setRenderList(renderList);
  32684. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32685. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32686. this._scene = scene;
  32687. this._renderList = renderList;
  32688. }
  32689. // private
  32690. PostProcessRenderPass.prototype._incRefCount = function () {
  32691. if (this._refCount === 0) {
  32692. this._scene.customRenderTargets.push(this._renderTexture);
  32693. }
  32694. return ++this._refCount;
  32695. };
  32696. PostProcessRenderPass.prototype._decRefCount = function () {
  32697. this._refCount--;
  32698. if (this._refCount <= 0) {
  32699. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32700. }
  32701. return this._refCount;
  32702. };
  32703. PostProcessRenderPass.prototype._update = function () {
  32704. this.setRenderList(this._renderList);
  32705. };
  32706. // public
  32707. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32708. this._renderTexture.renderList = renderList;
  32709. };
  32710. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32711. return this._renderTexture;
  32712. };
  32713. return PostProcessRenderPass;
  32714. }());
  32715. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32716. })(BABYLON || (BABYLON = {}));
  32717. var BABYLON;
  32718. (function (BABYLON) {
  32719. var PostProcessRenderEffect = (function () {
  32720. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32721. this._engine = engine;
  32722. this._name = name;
  32723. this._singleInstance = singleInstance || true;
  32724. this._getPostProcess = getPostProcess;
  32725. this._cameras = [];
  32726. this._indicesForCamera = [];
  32727. this._postProcesses = {};
  32728. this._renderPasses = {};
  32729. this._renderEffectAsPasses = {};
  32730. }
  32731. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32732. get: function () {
  32733. for (var index in this._postProcesses) {
  32734. if (!this._postProcesses[index].isSupported) {
  32735. return false;
  32736. }
  32737. }
  32738. return true;
  32739. },
  32740. enumerable: true,
  32741. configurable: true
  32742. });
  32743. PostProcessRenderEffect.prototype._update = function () {
  32744. for (var renderPassName in this._renderPasses) {
  32745. this._renderPasses[renderPassName]._update();
  32746. }
  32747. };
  32748. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32749. this._renderPasses[renderPass._name] = renderPass;
  32750. this._linkParameters();
  32751. };
  32752. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32753. delete this._renderPasses[renderPass._name];
  32754. this._linkParameters();
  32755. };
  32756. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32757. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32758. this._linkParameters();
  32759. };
  32760. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32761. for (var renderPassName in this._renderPasses) {
  32762. if (renderPassName === passName) {
  32763. return this._renderPasses[passName];
  32764. }
  32765. }
  32766. };
  32767. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32768. this._renderPasses = {};
  32769. this._linkParameters();
  32770. };
  32771. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32772. var cameraKey;
  32773. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32774. for (var i = 0; i < _cam.length; i++) {
  32775. var camera = _cam[i];
  32776. var cameraName = camera.name;
  32777. if (this._singleInstance) {
  32778. cameraKey = 0;
  32779. }
  32780. else {
  32781. cameraKey = cameraName;
  32782. }
  32783. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32784. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32785. if (!this._indicesForCamera[cameraName]) {
  32786. this._indicesForCamera[cameraName] = [];
  32787. }
  32788. this._indicesForCamera[cameraName].push(index);
  32789. if (this._cameras.indexOf(camera) === -1) {
  32790. this._cameras[cameraName] = camera;
  32791. }
  32792. for (var passName in this._renderPasses) {
  32793. this._renderPasses[passName]._incRefCount();
  32794. }
  32795. }
  32796. this._linkParameters();
  32797. };
  32798. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32799. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32800. for (var i = 0; i < _cam.length; i++) {
  32801. var camera = _cam[i];
  32802. var cameraName = camera.name;
  32803. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32804. var index = this._cameras.indexOf(cameraName);
  32805. this._indicesForCamera.splice(index, 1);
  32806. this._cameras.splice(index, 1);
  32807. for (var passName in this._renderPasses) {
  32808. this._renderPasses[passName]._decRefCount();
  32809. }
  32810. }
  32811. };
  32812. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32813. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32814. for (var i = 0; i < _cam.length; i++) {
  32815. var camera = _cam[i];
  32816. var cameraName = camera.name;
  32817. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32818. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32819. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32820. }
  32821. }
  32822. for (var passName in this._renderPasses) {
  32823. this._renderPasses[passName]._incRefCount();
  32824. }
  32825. }
  32826. };
  32827. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32828. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32829. for (var i = 0; i < _cam.length; i++) {
  32830. var camera = _cam[i];
  32831. var cameraName = camera.Name;
  32832. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32833. for (var passName in this._renderPasses) {
  32834. this._renderPasses[passName]._decRefCount();
  32835. }
  32836. }
  32837. };
  32838. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32839. if (this._singleInstance) {
  32840. return this._postProcesses[0];
  32841. }
  32842. else {
  32843. return this._postProcesses[camera.name];
  32844. }
  32845. };
  32846. PostProcessRenderEffect.prototype._linkParameters = function () {
  32847. var _this = this;
  32848. for (var index in this._postProcesses) {
  32849. if (this.applyParameters) {
  32850. this.applyParameters(this._postProcesses[index]);
  32851. }
  32852. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32853. _this._linkTextures(effect);
  32854. });
  32855. }
  32856. };
  32857. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32858. for (var renderPassName in this._renderPasses) {
  32859. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32860. }
  32861. for (var renderEffectName in this._renderEffectAsPasses) {
  32862. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32863. }
  32864. };
  32865. return PostProcessRenderEffect;
  32866. }());
  32867. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32868. })(BABYLON || (BABYLON = {}));
  32869. var BABYLON;
  32870. (function (BABYLON) {
  32871. var PostProcessRenderPipeline = (function () {
  32872. function PostProcessRenderPipeline(engine, name) {
  32873. this._engine = engine;
  32874. this._name = name;
  32875. this._renderEffects = {};
  32876. this._renderEffectsForIsolatedPass = {};
  32877. this._cameras = [];
  32878. }
  32879. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32880. get: function () {
  32881. for (var renderEffectName in this._renderEffects) {
  32882. if (!this._renderEffects[renderEffectName].isSupported) {
  32883. return false;
  32884. }
  32885. }
  32886. return true;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32892. this._renderEffects[renderEffect._name] = renderEffect;
  32893. };
  32894. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32895. var renderEffects = this._renderEffects[renderEffectName];
  32896. if (!renderEffects) {
  32897. return;
  32898. }
  32899. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32900. };
  32901. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32902. var renderEffects = this._renderEffects[renderEffectName];
  32903. if (!renderEffects) {
  32904. return;
  32905. }
  32906. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32907. };
  32908. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32909. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32910. var indicesToDelete = [];
  32911. var i;
  32912. for (i = 0; i < _cam.length; i++) {
  32913. var camera = _cam[i];
  32914. var cameraName = camera.name;
  32915. if (this._cameras.indexOf(camera) === -1) {
  32916. this._cameras[cameraName] = camera;
  32917. }
  32918. else if (unique) {
  32919. indicesToDelete.push(i);
  32920. }
  32921. }
  32922. for (i = 0; i < indicesToDelete.length; i++) {
  32923. cameras.splice(indicesToDelete[i], 1);
  32924. }
  32925. for (var renderEffectName in this._renderEffects) {
  32926. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32927. }
  32928. };
  32929. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32930. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32931. for (var renderEffectName in this._renderEffects) {
  32932. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32933. }
  32934. for (var i = 0; i < _cam.length; i++) {
  32935. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32936. }
  32937. };
  32938. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32939. var _this = this;
  32940. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32941. var pass = null;
  32942. var renderEffectName;
  32943. for (renderEffectName in this._renderEffects) {
  32944. pass = this._renderEffects[renderEffectName].getPass(passName);
  32945. if (pass != null) {
  32946. break;
  32947. }
  32948. }
  32949. if (pass === null) {
  32950. return;
  32951. }
  32952. for (renderEffectName in this._renderEffects) {
  32953. this._renderEffects[renderEffectName]._disable(_cam);
  32954. }
  32955. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32956. for (var i = 0; i < _cam.length; i++) {
  32957. var camera = _cam[i];
  32958. var cameraName = camera.name;
  32959. 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); });
  32960. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32961. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32962. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32963. }
  32964. };
  32965. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32966. var _this = this;
  32967. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32968. for (var i = 0; i < _cam.length; i++) {
  32969. var camera = _cam[i];
  32970. var cameraName = camera.name;
  32971. 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); });
  32972. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32973. }
  32974. for (var renderEffectName in this._renderEffects) {
  32975. this._renderEffects[renderEffectName]._enable(_cam);
  32976. }
  32977. };
  32978. PostProcessRenderPipeline.prototype._update = function () {
  32979. for (var renderEffectName in this._renderEffects) {
  32980. this._renderEffects[renderEffectName]._update();
  32981. }
  32982. for (var i = 0; i < this._cameras.length; i++) {
  32983. var cameraName = this._cameras[i].name;
  32984. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32985. this._renderEffectsForIsolatedPass[cameraName]._update();
  32986. }
  32987. }
  32988. };
  32989. PostProcessRenderPipeline.prototype.dispose = function () {
  32990. // Must be implemented by children
  32991. };
  32992. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32993. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32994. return PostProcessRenderPipeline;
  32995. }());
  32996. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32997. })(BABYLON || (BABYLON = {}));
  32998. var BABYLON;
  32999. (function (BABYLON) {
  33000. var PostProcessRenderPipelineManager = (function () {
  33001. function PostProcessRenderPipelineManager() {
  33002. this._renderPipelines = {};
  33003. }
  33004. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33005. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33006. };
  33007. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33008. var renderPipeline = this._renderPipelines[renderPipelineName];
  33009. if (!renderPipeline) {
  33010. return;
  33011. }
  33012. renderPipeline._attachCameras(cameras, unique);
  33013. };
  33014. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33015. var renderPipeline = this._renderPipelines[renderPipelineName];
  33016. if (!renderPipeline) {
  33017. return;
  33018. }
  33019. renderPipeline._detachCameras(cameras);
  33020. };
  33021. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33022. var renderPipeline = this._renderPipelines[renderPipelineName];
  33023. if (!renderPipeline) {
  33024. return;
  33025. }
  33026. renderPipeline._enableEffect(renderEffectName, cameras);
  33027. };
  33028. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33029. var renderPipeline = this._renderPipelines[renderPipelineName];
  33030. if (!renderPipeline) {
  33031. return;
  33032. }
  33033. renderPipeline._disableEffect(renderEffectName, cameras);
  33034. };
  33035. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33036. var renderPipeline = this._renderPipelines[renderPipelineName];
  33037. if (!renderPipeline) {
  33038. return;
  33039. }
  33040. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33041. };
  33042. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33043. var renderPipeline = this._renderPipelines[renderPipelineName];
  33044. if (!renderPipeline) {
  33045. return;
  33046. }
  33047. renderPipeline._disableDisplayOnlyPass(cameras);
  33048. };
  33049. PostProcessRenderPipelineManager.prototype.update = function () {
  33050. for (var renderPipelineName in this._renderPipelines) {
  33051. var pipeline = this._renderPipelines[renderPipelineName];
  33052. if (!pipeline.isSupported) {
  33053. pipeline.dispose();
  33054. delete this._renderPipelines[renderPipelineName];
  33055. }
  33056. else {
  33057. pipeline._update();
  33058. }
  33059. }
  33060. };
  33061. return PostProcessRenderPipelineManager;
  33062. }());
  33063. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33064. })(BABYLON || (BABYLON = {}));
  33065. var BABYLON;
  33066. (function (BABYLON) {
  33067. var BoundingBoxRenderer = (function () {
  33068. function BoundingBoxRenderer(scene) {
  33069. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33070. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33071. this.showBackLines = true;
  33072. this.renderList = new BABYLON.SmartArray(32);
  33073. this._vertexBuffers = {};
  33074. this._scene = scene;
  33075. }
  33076. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33077. if (this._colorShader) {
  33078. return;
  33079. }
  33080. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33081. attributes: [BABYLON.VertexBuffer.PositionKind],
  33082. uniforms: ["worldViewProjection", "color"]
  33083. });
  33084. var engine = this._scene.getEngine();
  33085. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33086. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33087. 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]);
  33088. };
  33089. BoundingBoxRenderer.prototype.reset = function () {
  33090. this.renderList.reset();
  33091. };
  33092. BoundingBoxRenderer.prototype.render = function () {
  33093. if (this.renderList.length === 0) {
  33094. return;
  33095. }
  33096. this._prepareRessources();
  33097. if (!this._colorShader.isReady()) {
  33098. return;
  33099. }
  33100. var engine = this._scene.getEngine();
  33101. engine.setDepthWrite(false);
  33102. this._colorShader._preBind();
  33103. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33104. var boundingBox = this.renderList.data[boundingBoxIndex];
  33105. var min = boundingBox.minimum;
  33106. var max = boundingBox.maximum;
  33107. var diff = max.subtract(min);
  33108. var median = min.add(diff.scale(0.5));
  33109. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33110. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33111. .multiply(boundingBox.getWorldMatrix());
  33112. // VBOs
  33113. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33114. if (this.showBackLines) {
  33115. // Back
  33116. engine.setDepthFunctionToGreaterOrEqual();
  33117. this._scene.resetCachedMaterial();
  33118. this._colorShader.setColor4("color", this.backColor.toColor4());
  33119. this._colorShader.bind(worldMatrix);
  33120. // Draw order
  33121. engine.draw(false, 0, 24);
  33122. }
  33123. // Front
  33124. engine.setDepthFunctionToLess();
  33125. this._scene.resetCachedMaterial();
  33126. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33127. this._colorShader.bind(worldMatrix);
  33128. // Draw order
  33129. engine.draw(false, 0, 24);
  33130. }
  33131. this._colorShader.unbind();
  33132. engine.setDepthFunctionToLessOrEqual();
  33133. engine.setDepthWrite(true);
  33134. };
  33135. BoundingBoxRenderer.prototype.dispose = function () {
  33136. if (!this._colorShader) {
  33137. return;
  33138. }
  33139. this._colorShader.dispose();
  33140. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33141. if (buffer) {
  33142. buffer.dispose();
  33143. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33144. }
  33145. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33146. };
  33147. return BoundingBoxRenderer;
  33148. }());
  33149. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33150. })(BABYLON || (BABYLON = {}));
  33151. var BABYLON;
  33152. (function (BABYLON) {
  33153. var Condition = (function () {
  33154. function Condition(actionManager) {
  33155. this._actionManager = actionManager;
  33156. }
  33157. Condition.prototype.isValid = function () {
  33158. return true;
  33159. };
  33160. Condition.prototype._getProperty = function (propertyPath) {
  33161. return this._actionManager._getProperty(propertyPath);
  33162. };
  33163. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33164. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33165. };
  33166. Condition.prototype.serialize = function () {
  33167. };
  33168. Condition.prototype._serialize = function (serializedCondition) {
  33169. return {
  33170. type: 2,
  33171. children: [],
  33172. name: serializedCondition.name,
  33173. properties: serializedCondition.properties
  33174. };
  33175. };
  33176. return Condition;
  33177. }());
  33178. BABYLON.Condition = Condition;
  33179. var ValueCondition = (function (_super) {
  33180. __extends(ValueCondition, _super);
  33181. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33182. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33183. _super.call(this, actionManager);
  33184. this.propertyPath = propertyPath;
  33185. this.value = value;
  33186. this.operator = operator;
  33187. this._target = target;
  33188. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33189. this._property = this._getProperty(this.propertyPath);
  33190. }
  33191. Object.defineProperty(ValueCondition, "IsEqual", {
  33192. get: function () {
  33193. return ValueCondition._IsEqual;
  33194. },
  33195. enumerable: true,
  33196. configurable: true
  33197. });
  33198. Object.defineProperty(ValueCondition, "IsDifferent", {
  33199. get: function () {
  33200. return ValueCondition._IsDifferent;
  33201. },
  33202. enumerable: true,
  33203. configurable: true
  33204. });
  33205. Object.defineProperty(ValueCondition, "IsGreater", {
  33206. get: function () {
  33207. return ValueCondition._IsGreater;
  33208. },
  33209. enumerable: true,
  33210. configurable: true
  33211. });
  33212. Object.defineProperty(ValueCondition, "IsLesser", {
  33213. get: function () {
  33214. return ValueCondition._IsLesser;
  33215. },
  33216. enumerable: true,
  33217. configurable: true
  33218. });
  33219. // Methods
  33220. ValueCondition.prototype.isValid = function () {
  33221. switch (this.operator) {
  33222. case ValueCondition.IsGreater:
  33223. return this._effectiveTarget[this._property] > this.value;
  33224. case ValueCondition.IsLesser:
  33225. return this._effectiveTarget[this._property] < this.value;
  33226. case ValueCondition.IsEqual:
  33227. case ValueCondition.IsDifferent:
  33228. var check;
  33229. if (this.value.equals) {
  33230. check = this.value.equals(this._effectiveTarget[this._property]);
  33231. }
  33232. else {
  33233. check = this.value === this._effectiveTarget[this._property];
  33234. }
  33235. return this.operator === ValueCondition.IsEqual ? check : !check;
  33236. }
  33237. return false;
  33238. };
  33239. ValueCondition.prototype.serialize = function () {
  33240. return this._serialize({
  33241. name: "ValueCondition",
  33242. properties: [
  33243. BABYLON.Action._GetTargetProperty(this._target),
  33244. { name: "propertyPath", value: this.propertyPath },
  33245. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33246. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33247. ]
  33248. });
  33249. };
  33250. ValueCondition.GetOperatorName = function (operator) {
  33251. switch (operator) {
  33252. case ValueCondition._IsEqual: return "IsEqual";
  33253. case ValueCondition._IsDifferent: return "IsDifferent";
  33254. case ValueCondition._IsGreater: return "IsGreater";
  33255. case ValueCondition._IsLesser: return "IsLesser";
  33256. default: return "";
  33257. }
  33258. };
  33259. // Statics
  33260. ValueCondition._IsEqual = 0;
  33261. ValueCondition._IsDifferent = 1;
  33262. ValueCondition._IsGreater = 2;
  33263. ValueCondition._IsLesser = 3;
  33264. return ValueCondition;
  33265. }(Condition));
  33266. BABYLON.ValueCondition = ValueCondition;
  33267. var PredicateCondition = (function (_super) {
  33268. __extends(PredicateCondition, _super);
  33269. function PredicateCondition(actionManager, predicate) {
  33270. _super.call(this, actionManager);
  33271. this.predicate = predicate;
  33272. }
  33273. PredicateCondition.prototype.isValid = function () {
  33274. return this.predicate();
  33275. };
  33276. return PredicateCondition;
  33277. }(Condition));
  33278. BABYLON.PredicateCondition = PredicateCondition;
  33279. var StateCondition = (function (_super) {
  33280. __extends(StateCondition, _super);
  33281. function StateCondition(actionManager, target, value) {
  33282. _super.call(this, actionManager);
  33283. this.value = value;
  33284. this._target = target;
  33285. }
  33286. // Methods
  33287. StateCondition.prototype.isValid = function () {
  33288. return this._target.state === this.value;
  33289. };
  33290. StateCondition.prototype.serialize = function () {
  33291. return this._serialize({
  33292. name: "StateCondition",
  33293. properties: [
  33294. BABYLON.Action._GetTargetProperty(this._target),
  33295. { name: "value", value: this.value }
  33296. ]
  33297. });
  33298. };
  33299. return StateCondition;
  33300. }(Condition));
  33301. BABYLON.StateCondition = StateCondition;
  33302. })(BABYLON || (BABYLON = {}));
  33303. var BABYLON;
  33304. (function (BABYLON) {
  33305. var Action = (function () {
  33306. function Action(triggerOptions, condition) {
  33307. this.triggerOptions = triggerOptions;
  33308. if (triggerOptions.parameter) {
  33309. this.trigger = triggerOptions.trigger;
  33310. this._triggerParameter = triggerOptions.parameter;
  33311. }
  33312. else {
  33313. this.trigger = triggerOptions;
  33314. }
  33315. this._nextActiveAction = this;
  33316. this._condition = condition;
  33317. }
  33318. // Methods
  33319. Action.prototype._prepare = function () {
  33320. };
  33321. Action.prototype.getTriggerParameter = function () {
  33322. return this._triggerParameter;
  33323. };
  33324. Action.prototype._executeCurrent = function (evt) {
  33325. if (this._nextActiveAction._condition) {
  33326. var condition = this._nextActiveAction._condition;
  33327. var currentRenderId = this._actionManager.getScene().getRenderId();
  33328. // We cache the current evaluation for the current frame
  33329. if (condition._evaluationId === currentRenderId) {
  33330. if (!condition._currentResult) {
  33331. return;
  33332. }
  33333. }
  33334. else {
  33335. condition._evaluationId = currentRenderId;
  33336. if (!condition.isValid()) {
  33337. condition._currentResult = false;
  33338. return;
  33339. }
  33340. condition._currentResult = true;
  33341. }
  33342. }
  33343. this._nextActiveAction.execute(evt);
  33344. this.skipToNextActiveAction();
  33345. };
  33346. Action.prototype.execute = function (evt) {
  33347. };
  33348. Action.prototype.skipToNextActiveAction = function () {
  33349. if (this._nextActiveAction._child) {
  33350. if (!this._nextActiveAction._child._actionManager) {
  33351. this._nextActiveAction._child._actionManager = this._actionManager;
  33352. }
  33353. this._nextActiveAction = this._nextActiveAction._child;
  33354. }
  33355. else {
  33356. this._nextActiveAction = this;
  33357. }
  33358. };
  33359. Action.prototype.then = function (action) {
  33360. this._child = action;
  33361. action._actionManager = this._actionManager;
  33362. action._prepare();
  33363. return action;
  33364. };
  33365. Action.prototype._getProperty = function (propertyPath) {
  33366. return this._actionManager._getProperty(propertyPath);
  33367. };
  33368. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33369. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33370. };
  33371. Action.prototype.serialize = function (parent) {
  33372. };
  33373. // Called by BABYLON.Action objects in serialize(...). Internal use
  33374. Action.prototype._serialize = function (serializedAction, parent) {
  33375. var serializationObject = {
  33376. type: 1,
  33377. children: [],
  33378. name: serializedAction.name,
  33379. properties: serializedAction.properties || []
  33380. };
  33381. // Serialize child
  33382. if (this._child) {
  33383. this._child.serialize(serializationObject);
  33384. }
  33385. // Check if "this" has a condition
  33386. if (this._condition) {
  33387. var serializedCondition = this._condition.serialize();
  33388. serializedCondition.children.push(serializationObject);
  33389. if (parent) {
  33390. parent.children.push(serializedCondition);
  33391. }
  33392. return serializedCondition;
  33393. }
  33394. if (parent) {
  33395. parent.children.push(serializationObject);
  33396. }
  33397. return serializationObject;
  33398. };
  33399. Action._SerializeValueAsString = function (value) {
  33400. if (typeof value === "number") {
  33401. return value.toString();
  33402. }
  33403. if (typeof value === "boolean") {
  33404. return value ? "true" : "false";
  33405. }
  33406. if (value instanceof BABYLON.Vector2) {
  33407. return value.x + ", " + value.y;
  33408. }
  33409. if (value instanceof BABYLON.Vector3) {
  33410. return value.x + ", " + value.y + ", " + value.z;
  33411. }
  33412. if (value instanceof BABYLON.Color3) {
  33413. return value.r + ", " + value.g + ", " + value.b;
  33414. }
  33415. if (value instanceof BABYLON.Color4) {
  33416. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33417. }
  33418. return value; // string
  33419. };
  33420. Action._GetTargetProperty = function (target) {
  33421. return {
  33422. name: "target",
  33423. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33424. : target instanceof BABYLON.Light ? "LightProperties"
  33425. : target instanceof BABYLON.Camera ? "CameraProperties"
  33426. : "SceneProperties",
  33427. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33428. };
  33429. };
  33430. return Action;
  33431. }());
  33432. BABYLON.Action = Action;
  33433. })(BABYLON || (BABYLON = {}));
  33434. var BABYLON;
  33435. (function (BABYLON) {
  33436. /**
  33437. * ActionEvent is the event beint sent when an action is triggered.
  33438. */
  33439. var ActionEvent = (function () {
  33440. /**
  33441. * @constructor
  33442. * @param source The mesh or sprite that triggered the action.
  33443. * @param pointerX The X mouse cursor position at the time of the event
  33444. * @param pointerY The Y mouse cursor position at the time of the event
  33445. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33446. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33447. */
  33448. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33449. this.source = source;
  33450. this.pointerX = pointerX;
  33451. this.pointerY = pointerY;
  33452. this.meshUnderPointer = meshUnderPointer;
  33453. this.sourceEvent = sourceEvent;
  33454. this.additionalData = additionalData;
  33455. }
  33456. /**
  33457. * Helper function to auto-create an ActionEvent from a source mesh.
  33458. * @param source The source mesh that triggered the event
  33459. * @param evt {Event} The original (browser) event
  33460. */
  33461. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33462. var scene = source.getScene();
  33463. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33464. };
  33465. /**
  33466. * Helper function to auto-create an ActionEvent from a source mesh.
  33467. * @param source The source sprite that triggered the event
  33468. * @param scene Scene associated with the sprite
  33469. * @param evt {Event} The original (browser) event
  33470. */
  33471. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33472. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33473. };
  33474. /**
  33475. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33476. * @param scene the scene where the event occurred
  33477. * @param evt {Event} The original (browser) event
  33478. */
  33479. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33480. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33481. };
  33482. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33483. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33484. };
  33485. return ActionEvent;
  33486. }());
  33487. BABYLON.ActionEvent = ActionEvent;
  33488. /**
  33489. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33490. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33491. */
  33492. var ActionManager = (function () {
  33493. function ActionManager(scene) {
  33494. // Members
  33495. this.actions = new Array();
  33496. this._scene = scene;
  33497. scene._actionManagers.push(this);
  33498. }
  33499. Object.defineProperty(ActionManager, "NothingTrigger", {
  33500. get: function () {
  33501. return ActionManager._NothingTrigger;
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33507. get: function () {
  33508. return ActionManager._OnPickTrigger;
  33509. },
  33510. enumerable: true,
  33511. configurable: true
  33512. });
  33513. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33514. get: function () {
  33515. return ActionManager._OnLeftPickTrigger;
  33516. },
  33517. enumerable: true,
  33518. configurable: true
  33519. });
  33520. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33521. get: function () {
  33522. return ActionManager._OnRightPickTrigger;
  33523. },
  33524. enumerable: true,
  33525. configurable: true
  33526. });
  33527. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33528. get: function () {
  33529. return ActionManager._OnCenterPickTrigger;
  33530. },
  33531. enumerable: true,
  33532. configurable: true
  33533. });
  33534. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33535. get: function () {
  33536. return ActionManager._OnPickDownTrigger;
  33537. },
  33538. enumerable: true,
  33539. configurable: true
  33540. });
  33541. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33542. get: function () {
  33543. return ActionManager._OnPickUpTrigger;
  33544. },
  33545. enumerable: true,
  33546. configurable: true
  33547. });
  33548. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33549. /// This trigger will only be raised if you also declared a OnPickDown
  33550. get: function () {
  33551. return ActionManager._OnPickOutTrigger;
  33552. },
  33553. enumerable: true,
  33554. configurable: true
  33555. });
  33556. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33557. get: function () {
  33558. return ActionManager._OnLongPressTrigger;
  33559. },
  33560. enumerable: true,
  33561. configurable: true
  33562. });
  33563. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33564. get: function () {
  33565. return ActionManager._OnPointerOverTrigger;
  33566. },
  33567. enumerable: true,
  33568. configurable: true
  33569. });
  33570. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33571. get: function () {
  33572. return ActionManager._OnPointerOutTrigger;
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33578. get: function () {
  33579. return ActionManager._OnEveryFrameTrigger;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33585. get: function () {
  33586. return ActionManager._OnIntersectionEnterTrigger;
  33587. },
  33588. enumerable: true,
  33589. configurable: true
  33590. });
  33591. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33592. get: function () {
  33593. return ActionManager._OnIntersectionExitTrigger;
  33594. },
  33595. enumerable: true,
  33596. configurable: true
  33597. });
  33598. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33599. get: function () {
  33600. return ActionManager._OnKeyDownTrigger;
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33606. get: function () {
  33607. return ActionManager._OnKeyUpTrigger;
  33608. },
  33609. enumerable: true,
  33610. configurable: true
  33611. });
  33612. // Methods
  33613. ActionManager.prototype.dispose = function () {
  33614. var index = this._scene._actionManagers.indexOf(this);
  33615. if (index > -1) {
  33616. this._scene._actionManagers.splice(index, 1);
  33617. }
  33618. };
  33619. ActionManager.prototype.getScene = function () {
  33620. return this._scene;
  33621. };
  33622. /**
  33623. * Does this action manager handles actions of any of the given triggers
  33624. * @param {number[]} triggers - the triggers to be tested
  33625. * @return {boolean} whether one (or more) of the triggers is handeled
  33626. */
  33627. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33628. for (var index = 0; index < this.actions.length; index++) {
  33629. var action = this.actions[index];
  33630. if (triggers.indexOf(action.trigger) > -1) {
  33631. return true;
  33632. }
  33633. }
  33634. return false;
  33635. };
  33636. /**
  33637. * Does this action manager handles actions of a given trigger
  33638. * @param {number} trigger - the trigger to be tested
  33639. * @return {boolean} whether the trigger is handeled
  33640. */
  33641. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33642. for (var index = 0; index < this.actions.length; index++) {
  33643. var action = this.actions[index];
  33644. if (action.trigger === trigger) {
  33645. return true;
  33646. }
  33647. }
  33648. return false;
  33649. };
  33650. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33651. /**
  33652. * Does this action manager has pointer triggers
  33653. * @return {boolean} whether or not it has pointer triggers
  33654. */
  33655. get: function () {
  33656. for (var index = 0; index < this.actions.length; index++) {
  33657. var action = this.actions[index];
  33658. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33659. return true;
  33660. }
  33661. }
  33662. return false;
  33663. },
  33664. enumerable: true,
  33665. configurable: true
  33666. });
  33667. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33668. /**
  33669. * Does this action manager has pick triggers
  33670. * @return {boolean} whether or not it has pick triggers
  33671. */
  33672. get: function () {
  33673. for (var index = 0; index < this.actions.length; index++) {
  33674. var action = this.actions[index];
  33675. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33676. return true;
  33677. }
  33678. }
  33679. return false;
  33680. },
  33681. enumerable: true,
  33682. configurable: true
  33683. });
  33684. /**
  33685. * Registers an action to this action manager
  33686. * @param {BABYLON.Action} action - the action to be registered
  33687. * @return {BABYLON.Action} the action amended (prepared) after registration
  33688. */
  33689. ActionManager.prototype.registerAction = function (action) {
  33690. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33691. if (this.getScene().actionManager !== this) {
  33692. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33693. return null;
  33694. }
  33695. }
  33696. this.actions.push(action);
  33697. action._actionManager = this;
  33698. action._prepare();
  33699. return action;
  33700. };
  33701. /**
  33702. * Process a specific trigger
  33703. * @param {number} trigger - the trigger to process
  33704. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33705. */
  33706. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33707. for (var index = 0; index < this.actions.length; index++) {
  33708. var action = this.actions[index];
  33709. if (action.trigger === trigger) {
  33710. if (trigger === ActionManager.OnKeyUpTrigger
  33711. || trigger === ActionManager.OnKeyDownTrigger) {
  33712. var parameter = action.getTriggerParameter();
  33713. if (parameter) {
  33714. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33715. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33716. if (actualkey !== parameter.toLowerCase()) {
  33717. continue;
  33718. }
  33719. }
  33720. }
  33721. action._executeCurrent(evt);
  33722. }
  33723. }
  33724. };
  33725. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33726. var properties = propertyPath.split(".");
  33727. for (var index = 0; index < properties.length - 1; index++) {
  33728. target = target[properties[index]];
  33729. }
  33730. return target;
  33731. };
  33732. ActionManager.prototype._getProperty = function (propertyPath) {
  33733. var properties = propertyPath.split(".");
  33734. return properties[properties.length - 1];
  33735. };
  33736. ActionManager.prototype.serialize = function (name) {
  33737. var root = {
  33738. children: [],
  33739. name: name,
  33740. type: 3,
  33741. properties: [] // Empty for root but required
  33742. };
  33743. for (var i = 0; i < this.actions.length; i++) {
  33744. var triggerObject = {
  33745. type: 0,
  33746. children: [],
  33747. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33748. properties: []
  33749. };
  33750. var triggerOptions = this.actions[i].triggerOptions;
  33751. if (triggerOptions && typeof triggerOptions !== "number") {
  33752. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33753. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33754. }
  33755. else {
  33756. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33757. }
  33758. }
  33759. // Serialize child action, recursively
  33760. this.actions[i].serialize(triggerObject);
  33761. // Add serialized trigger
  33762. root.children.push(triggerObject);
  33763. }
  33764. return root;
  33765. };
  33766. ActionManager.Parse = function (parsedActions, object, scene) {
  33767. var actionManager = new BABYLON.ActionManager(scene);
  33768. if (object === null)
  33769. scene.actionManager = actionManager;
  33770. else
  33771. object.actionManager = actionManager;
  33772. // instanciate a new object
  33773. var instanciate = function (name, params) {
  33774. var newInstance = Object.create(BABYLON[name].prototype);
  33775. newInstance.constructor.apply(newInstance, params);
  33776. return newInstance;
  33777. };
  33778. var parseParameter = function (name, value, target, propertyPath) {
  33779. if (propertyPath === null) {
  33780. // String, boolean or float
  33781. var floatValue = parseFloat(value);
  33782. if (value === "true" || value === "false")
  33783. return value === "true";
  33784. else
  33785. return isNaN(floatValue) ? value : floatValue;
  33786. }
  33787. var effectiveTarget = propertyPath.split(".");
  33788. var values = value.split(",");
  33789. // Get effective Target
  33790. for (var i = 0; i < effectiveTarget.length; i++) {
  33791. target = target[effectiveTarget[i]];
  33792. }
  33793. // Return appropriate value with its type
  33794. if (typeof (target) === "boolean")
  33795. return values[0] === "true";
  33796. if (typeof (target) === "string")
  33797. return values[0];
  33798. // Parameters with multiple values such as Vector3 etc.
  33799. var split = new Array();
  33800. for (var i = 0; i < values.length; i++)
  33801. split.push(parseFloat(values[i]));
  33802. if (target instanceof BABYLON.Vector3)
  33803. return BABYLON.Vector3.FromArray(split);
  33804. if (target instanceof BABYLON.Vector4)
  33805. return BABYLON.Vector4.FromArray(split);
  33806. if (target instanceof BABYLON.Color3)
  33807. return BABYLON.Color3.FromArray(split);
  33808. if (target instanceof BABYLON.Color4)
  33809. return BABYLON.Color4.FromArray(split);
  33810. return parseFloat(values[0]);
  33811. };
  33812. // traverse graph per trigger
  33813. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33814. if (combineArray === void 0) { combineArray = null; }
  33815. if (parsedAction.detached)
  33816. return;
  33817. var parameters = new Array();
  33818. var target = null;
  33819. var propertyPath = null;
  33820. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33821. // Parameters
  33822. if (parsedAction.type === 2)
  33823. parameters.push(actionManager);
  33824. else
  33825. parameters.push(trigger);
  33826. if (combine) {
  33827. var actions = new Array();
  33828. for (var j = 0; j < parsedAction.combine.length; j++) {
  33829. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33830. }
  33831. parameters.push(actions);
  33832. }
  33833. else {
  33834. for (var i = 0; i < parsedAction.properties.length; i++) {
  33835. var value = parsedAction.properties[i].value;
  33836. var name = parsedAction.properties[i].name;
  33837. var targetType = parsedAction.properties[i].targetType;
  33838. if (name === "target")
  33839. if (targetType !== null && targetType === "SceneProperties")
  33840. value = target = scene;
  33841. else
  33842. value = target = scene.getNodeByName(value);
  33843. else if (name === "parent")
  33844. value = scene.getNodeByName(value);
  33845. else if (name === "sound")
  33846. value = scene.getSoundByName(value);
  33847. else if (name !== "propertyPath") {
  33848. if (parsedAction.type === 2 && name === "operator")
  33849. value = BABYLON.ValueCondition[value];
  33850. else
  33851. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33852. }
  33853. else {
  33854. propertyPath = value;
  33855. }
  33856. parameters.push(value);
  33857. }
  33858. }
  33859. if (combineArray === null) {
  33860. parameters.push(condition);
  33861. }
  33862. else {
  33863. parameters.push(null);
  33864. }
  33865. // If interpolate value action
  33866. if (parsedAction.name === "InterpolateValueAction") {
  33867. var param = parameters[parameters.length - 2];
  33868. parameters[parameters.length - 1] = param;
  33869. parameters[parameters.length - 2] = condition;
  33870. }
  33871. // Action or condition(s) and not CombineAction
  33872. var newAction = instanciate(parsedAction.name, parameters);
  33873. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33874. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33875. if (action)
  33876. action.then(nothing);
  33877. else
  33878. actionManager.registerAction(nothing);
  33879. action = nothing;
  33880. }
  33881. if (combineArray === null) {
  33882. if (newAction instanceof BABYLON.Condition) {
  33883. condition = newAction;
  33884. newAction = action;
  33885. }
  33886. else {
  33887. condition = null;
  33888. if (action)
  33889. action.then(newAction);
  33890. else
  33891. actionManager.registerAction(newAction);
  33892. }
  33893. }
  33894. else {
  33895. combineArray.push(newAction);
  33896. }
  33897. for (var i = 0; i < parsedAction.children.length; i++)
  33898. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33899. };
  33900. // triggers
  33901. for (var i = 0; i < parsedActions.children.length; i++) {
  33902. var triggerParams;
  33903. var trigger = parsedActions.children[i];
  33904. if (trigger.properties.length > 0) {
  33905. var param = trigger.properties[0].value;
  33906. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33907. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33908. }
  33909. else
  33910. triggerParams = BABYLON.ActionManager[trigger.name];
  33911. for (var j = 0; j < trigger.children.length; j++) {
  33912. if (!trigger.detached)
  33913. traverse(trigger.children[j], triggerParams, null, null);
  33914. }
  33915. }
  33916. };
  33917. ActionManager.GetTriggerName = function (trigger) {
  33918. switch (trigger) {
  33919. case 0: return "NothingTrigger";
  33920. case 1: return "OnPickTrigger";
  33921. case 2: return "OnLeftPickTrigger";
  33922. case 3: return "OnRightPickTrigger";
  33923. case 4: return "OnCenterPickTrigger";
  33924. case 5: return "OnPickDownTrigger";
  33925. case 6: return "OnPickUpTrigger";
  33926. case 7: return "OnLongPressTrigger";
  33927. case 8: return "OnPointerOverTrigger";
  33928. case 9: return "OnPointerOutTrigger";
  33929. case 10: return "OnEveryFrameTrigger";
  33930. case 11: return "OnIntersectionEnterTrigger";
  33931. case 12: return "OnIntersectionExitTrigger";
  33932. case 13: return "OnKeyDownTrigger";
  33933. case 14: return "OnKeyUpTrigger";
  33934. case 15: return "OnPickOutTrigger";
  33935. default: return "";
  33936. }
  33937. };
  33938. // Statics
  33939. ActionManager._NothingTrigger = 0;
  33940. ActionManager._OnPickTrigger = 1;
  33941. ActionManager._OnLeftPickTrigger = 2;
  33942. ActionManager._OnRightPickTrigger = 3;
  33943. ActionManager._OnCenterPickTrigger = 4;
  33944. ActionManager._OnPickDownTrigger = 5;
  33945. ActionManager._OnPickUpTrigger = 6;
  33946. ActionManager._OnLongPressTrigger = 7;
  33947. ActionManager._OnPointerOverTrigger = 8;
  33948. ActionManager._OnPointerOutTrigger = 9;
  33949. ActionManager._OnEveryFrameTrigger = 10;
  33950. ActionManager._OnIntersectionEnterTrigger = 11;
  33951. ActionManager._OnIntersectionExitTrigger = 12;
  33952. ActionManager._OnKeyDownTrigger = 13;
  33953. ActionManager._OnKeyUpTrigger = 14;
  33954. ActionManager._OnPickOutTrigger = 15;
  33955. ActionManager.DragMovementThreshold = 10; // in pixels
  33956. ActionManager.LongPressDelay = 500; // in milliseconds
  33957. return ActionManager;
  33958. }());
  33959. BABYLON.ActionManager = ActionManager;
  33960. })(BABYLON || (BABYLON = {}));
  33961. var BABYLON;
  33962. (function (BABYLON) {
  33963. var InterpolateValueAction = (function (_super) {
  33964. __extends(InterpolateValueAction, _super);
  33965. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33966. if (duration === void 0) { duration = 1000; }
  33967. _super.call(this, triggerOptions, condition);
  33968. this.propertyPath = propertyPath;
  33969. this.value = value;
  33970. this.duration = duration;
  33971. this.stopOtherAnimations = stopOtherAnimations;
  33972. this.onInterpolationDone = onInterpolationDone;
  33973. this._target = this._effectiveTarget = target;
  33974. }
  33975. InterpolateValueAction.prototype._prepare = function () {
  33976. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33977. this._property = this._getProperty(this.propertyPath);
  33978. };
  33979. InterpolateValueAction.prototype.execute = function () {
  33980. var scene = this._actionManager.getScene();
  33981. var keys = [
  33982. {
  33983. frame: 0,
  33984. value: this._effectiveTarget[this._property]
  33985. }, {
  33986. frame: 100,
  33987. value: this.value
  33988. }
  33989. ];
  33990. var dataType;
  33991. if (typeof this.value === "number") {
  33992. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33993. }
  33994. else if (this.value instanceof BABYLON.Color3) {
  33995. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33996. }
  33997. else if (this.value instanceof BABYLON.Vector3) {
  33998. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33999. }
  34000. else if (this.value instanceof BABYLON.Matrix) {
  34001. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34002. }
  34003. else if (this.value instanceof BABYLON.Quaternion) {
  34004. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34005. }
  34006. else {
  34007. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34008. return;
  34009. }
  34010. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34011. animation.setKeys(keys);
  34012. if (this.stopOtherAnimations) {
  34013. scene.stopAnimation(this._effectiveTarget);
  34014. }
  34015. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34016. };
  34017. InterpolateValueAction.prototype.serialize = function (parent) {
  34018. return _super.prototype._serialize.call(this, {
  34019. name: "InterpolateValueAction",
  34020. properties: [
  34021. BABYLON.Action._GetTargetProperty(this._target),
  34022. { name: "propertyPath", value: this.propertyPath },
  34023. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34024. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34025. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34026. ]
  34027. }, parent);
  34028. };
  34029. return InterpolateValueAction;
  34030. }(BABYLON.Action));
  34031. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34032. })(BABYLON || (BABYLON = {}));
  34033. var BABYLON;
  34034. (function (BABYLON) {
  34035. var SwitchBooleanAction = (function (_super) {
  34036. __extends(SwitchBooleanAction, _super);
  34037. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34038. _super.call(this, triggerOptions, condition);
  34039. this.propertyPath = propertyPath;
  34040. this._target = this._effectiveTarget = target;
  34041. }
  34042. SwitchBooleanAction.prototype._prepare = function () {
  34043. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34044. this._property = this._getProperty(this.propertyPath);
  34045. };
  34046. SwitchBooleanAction.prototype.execute = function () {
  34047. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34048. };
  34049. SwitchBooleanAction.prototype.serialize = function (parent) {
  34050. return _super.prototype._serialize.call(this, {
  34051. name: "SwitchBooleanAction",
  34052. properties: [
  34053. BABYLON.Action._GetTargetProperty(this._target),
  34054. { name: "propertyPath", value: this.propertyPath }
  34055. ]
  34056. }, parent);
  34057. };
  34058. return SwitchBooleanAction;
  34059. }(BABYLON.Action));
  34060. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34061. var SetStateAction = (function (_super) {
  34062. __extends(SetStateAction, _super);
  34063. function SetStateAction(triggerOptions, target, value, condition) {
  34064. _super.call(this, triggerOptions, condition);
  34065. this.value = value;
  34066. this._target = target;
  34067. }
  34068. SetStateAction.prototype.execute = function () {
  34069. this._target.state = this.value;
  34070. };
  34071. SetStateAction.prototype.serialize = function (parent) {
  34072. return _super.prototype._serialize.call(this, {
  34073. name: "SetStateAction",
  34074. properties: [
  34075. BABYLON.Action._GetTargetProperty(this._target),
  34076. { name: "value", value: this.value }
  34077. ]
  34078. }, parent);
  34079. };
  34080. return SetStateAction;
  34081. }(BABYLON.Action));
  34082. BABYLON.SetStateAction = SetStateAction;
  34083. var SetValueAction = (function (_super) {
  34084. __extends(SetValueAction, _super);
  34085. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34086. _super.call(this, triggerOptions, condition);
  34087. this.propertyPath = propertyPath;
  34088. this.value = value;
  34089. this._target = this._effectiveTarget = target;
  34090. }
  34091. SetValueAction.prototype._prepare = function () {
  34092. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34093. this._property = this._getProperty(this.propertyPath);
  34094. };
  34095. SetValueAction.prototype.execute = function () {
  34096. this._effectiveTarget[this._property] = this.value;
  34097. if (this._target.markAsDirty) {
  34098. this._target.markAsDirty(this._property);
  34099. }
  34100. };
  34101. SetValueAction.prototype.serialize = function (parent) {
  34102. return _super.prototype._serialize.call(this, {
  34103. name: "SetValueAction",
  34104. properties: [
  34105. BABYLON.Action._GetTargetProperty(this._target),
  34106. { name: "propertyPath", value: this.propertyPath },
  34107. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34108. ]
  34109. }, parent);
  34110. };
  34111. return SetValueAction;
  34112. }(BABYLON.Action));
  34113. BABYLON.SetValueAction = SetValueAction;
  34114. var IncrementValueAction = (function (_super) {
  34115. __extends(IncrementValueAction, _super);
  34116. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34117. _super.call(this, triggerOptions, condition);
  34118. this.propertyPath = propertyPath;
  34119. this.value = value;
  34120. this._target = this._effectiveTarget = target;
  34121. }
  34122. IncrementValueAction.prototype._prepare = function () {
  34123. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34124. this._property = this._getProperty(this.propertyPath);
  34125. if (typeof this._effectiveTarget[this._property] !== "number") {
  34126. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34127. }
  34128. };
  34129. IncrementValueAction.prototype.execute = function () {
  34130. this._effectiveTarget[this._property] += this.value;
  34131. if (this._target.markAsDirty) {
  34132. this._target.markAsDirty(this._property);
  34133. }
  34134. };
  34135. IncrementValueAction.prototype.serialize = function (parent) {
  34136. return _super.prototype._serialize.call(this, {
  34137. name: "IncrementValueAction",
  34138. properties: [
  34139. BABYLON.Action._GetTargetProperty(this._target),
  34140. { name: "propertyPath", value: this.propertyPath },
  34141. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34142. ]
  34143. }, parent);
  34144. };
  34145. return IncrementValueAction;
  34146. }(BABYLON.Action));
  34147. BABYLON.IncrementValueAction = IncrementValueAction;
  34148. var PlayAnimationAction = (function (_super) {
  34149. __extends(PlayAnimationAction, _super);
  34150. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34151. _super.call(this, triggerOptions, condition);
  34152. this.from = from;
  34153. this.to = to;
  34154. this.loop = loop;
  34155. this._target = target;
  34156. }
  34157. PlayAnimationAction.prototype._prepare = function () {
  34158. };
  34159. PlayAnimationAction.prototype.execute = function () {
  34160. var scene = this._actionManager.getScene();
  34161. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34162. };
  34163. PlayAnimationAction.prototype.serialize = function (parent) {
  34164. return _super.prototype._serialize.call(this, {
  34165. name: "PlayAnimationAction",
  34166. properties: [
  34167. BABYLON.Action._GetTargetProperty(this._target),
  34168. { name: "from", value: String(this.from) },
  34169. { name: "to", value: String(this.to) },
  34170. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34171. ]
  34172. }, parent);
  34173. };
  34174. return PlayAnimationAction;
  34175. }(BABYLON.Action));
  34176. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34177. var StopAnimationAction = (function (_super) {
  34178. __extends(StopAnimationAction, _super);
  34179. function StopAnimationAction(triggerOptions, target, condition) {
  34180. _super.call(this, triggerOptions, condition);
  34181. this._target = target;
  34182. }
  34183. StopAnimationAction.prototype._prepare = function () {
  34184. };
  34185. StopAnimationAction.prototype.execute = function () {
  34186. var scene = this._actionManager.getScene();
  34187. scene.stopAnimation(this._target);
  34188. };
  34189. StopAnimationAction.prototype.serialize = function (parent) {
  34190. return _super.prototype._serialize.call(this, {
  34191. name: "StopAnimationAction",
  34192. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34193. }, parent);
  34194. };
  34195. return StopAnimationAction;
  34196. }(BABYLON.Action));
  34197. BABYLON.StopAnimationAction = StopAnimationAction;
  34198. var DoNothingAction = (function (_super) {
  34199. __extends(DoNothingAction, _super);
  34200. function DoNothingAction(triggerOptions, condition) {
  34201. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34202. _super.call(this, triggerOptions, condition);
  34203. }
  34204. DoNothingAction.prototype.execute = function () {
  34205. };
  34206. DoNothingAction.prototype.serialize = function (parent) {
  34207. return _super.prototype._serialize.call(this, {
  34208. name: "DoNothingAction",
  34209. properties: []
  34210. }, parent);
  34211. };
  34212. return DoNothingAction;
  34213. }(BABYLON.Action));
  34214. BABYLON.DoNothingAction = DoNothingAction;
  34215. var CombineAction = (function (_super) {
  34216. __extends(CombineAction, _super);
  34217. function CombineAction(triggerOptions, children, condition) {
  34218. _super.call(this, triggerOptions, condition);
  34219. this.children = children;
  34220. }
  34221. CombineAction.prototype._prepare = function () {
  34222. for (var index = 0; index < this.children.length; index++) {
  34223. this.children[index]._actionManager = this._actionManager;
  34224. this.children[index]._prepare();
  34225. }
  34226. };
  34227. CombineAction.prototype.execute = function (evt) {
  34228. for (var index = 0; index < this.children.length; index++) {
  34229. this.children[index].execute(evt);
  34230. }
  34231. };
  34232. CombineAction.prototype.serialize = function (parent) {
  34233. var serializationObject = _super.prototype._serialize.call(this, {
  34234. name: "CombineAction",
  34235. properties: [],
  34236. combine: []
  34237. }, parent);
  34238. for (var i = 0; i < this.children.length; i++) {
  34239. serializationObject.combine.push(this.children[i].serialize(null));
  34240. }
  34241. return serializationObject;
  34242. };
  34243. return CombineAction;
  34244. }(BABYLON.Action));
  34245. BABYLON.CombineAction = CombineAction;
  34246. var ExecuteCodeAction = (function (_super) {
  34247. __extends(ExecuteCodeAction, _super);
  34248. function ExecuteCodeAction(triggerOptions, func, condition) {
  34249. _super.call(this, triggerOptions, condition);
  34250. this.func = func;
  34251. }
  34252. ExecuteCodeAction.prototype.execute = function (evt) {
  34253. this.func(evt);
  34254. };
  34255. return ExecuteCodeAction;
  34256. }(BABYLON.Action));
  34257. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34258. var SetParentAction = (function (_super) {
  34259. __extends(SetParentAction, _super);
  34260. function SetParentAction(triggerOptions, target, parent, condition) {
  34261. _super.call(this, triggerOptions, condition);
  34262. this._target = target;
  34263. this._parent = parent;
  34264. }
  34265. SetParentAction.prototype._prepare = function () {
  34266. };
  34267. SetParentAction.prototype.execute = function () {
  34268. if (this._target.parent === this._parent) {
  34269. return;
  34270. }
  34271. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34272. invertParentWorldMatrix.invert();
  34273. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34274. this._target.parent = this._parent;
  34275. };
  34276. SetParentAction.prototype.serialize = function (parent) {
  34277. return _super.prototype._serialize.call(this, {
  34278. name: "SetParentAction",
  34279. properties: [
  34280. BABYLON.Action._GetTargetProperty(this._target),
  34281. BABYLON.Action._GetTargetProperty(this._parent),
  34282. ]
  34283. }, parent);
  34284. };
  34285. return SetParentAction;
  34286. }(BABYLON.Action));
  34287. BABYLON.SetParentAction = SetParentAction;
  34288. var PlaySoundAction = (function (_super) {
  34289. __extends(PlaySoundAction, _super);
  34290. function PlaySoundAction(triggerOptions, sound, condition) {
  34291. _super.call(this, triggerOptions, condition);
  34292. this._sound = sound;
  34293. }
  34294. PlaySoundAction.prototype._prepare = function () {
  34295. };
  34296. PlaySoundAction.prototype.execute = function () {
  34297. if (this._sound !== undefined)
  34298. this._sound.play();
  34299. };
  34300. PlaySoundAction.prototype.serialize = function (parent) {
  34301. return _super.prototype._serialize.call(this, {
  34302. name: "PlaySoundAction",
  34303. properties: [{ name: "sound", value: this._sound.name }]
  34304. }, parent);
  34305. };
  34306. return PlaySoundAction;
  34307. }(BABYLON.Action));
  34308. BABYLON.PlaySoundAction = PlaySoundAction;
  34309. var StopSoundAction = (function (_super) {
  34310. __extends(StopSoundAction, _super);
  34311. function StopSoundAction(triggerOptions, sound, condition) {
  34312. _super.call(this, triggerOptions, condition);
  34313. this._sound = sound;
  34314. }
  34315. StopSoundAction.prototype._prepare = function () {
  34316. };
  34317. StopSoundAction.prototype.execute = function () {
  34318. if (this._sound !== undefined)
  34319. this._sound.stop();
  34320. };
  34321. StopSoundAction.prototype.serialize = function (parent) {
  34322. return _super.prototype._serialize.call(this, {
  34323. name: "StopSoundAction",
  34324. properties: [{ name: "sound", value: this._sound.name }]
  34325. }, parent);
  34326. };
  34327. return StopSoundAction;
  34328. }(BABYLON.Action));
  34329. BABYLON.StopSoundAction = StopSoundAction;
  34330. })(BABYLON || (BABYLON = {}));
  34331. var BABYLON;
  34332. (function (BABYLON) {
  34333. var Geometry = (function () {
  34334. function Geometry(id, scene, vertexData, updatable, mesh) {
  34335. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34336. this._totalVertices = 0;
  34337. this._isDisposed = false;
  34338. this.id = id;
  34339. this._engine = scene.getEngine();
  34340. this._meshes = [];
  34341. this._scene = scene;
  34342. //Init vertex buffer cache
  34343. this._vertexBuffers = {};
  34344. this._indices = [];
  34345. // vertexData
  34346. if (vertexData) {
  34347. this.setAllVerticesData(vertexData, updatable);
  34348. }
  34349. else {
  34350. this._totalVertices = 0;
  34351. this._indices = [];
  34352. }
  34353. // applyToMesh
  34354. if (mesh) {
  34355. if (mesh instanceof BABYLON.LinesMesh) {
  34356. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34357. this.updateExtend();
  34358. }
  34359. this.applyToMesh(mesh);
  34360. mesh.computeWorldMatrix(true);
  34361. }
  34362. }
  34363. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34364. /**
  34365. * 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
  34366. * @returns The Bias Vector
  34367. */
  34368. get: function () {
  34369. return this._boundingBias;
  34370. },
  34371. set: function (value) {
  34372. if (this._boundingBias && this._boundingBias.equals(value)) {
  34373. return;
  34374. }
  34375. this._boundingBias = value.clone();
  34376. this.updateBoundingInfo(true, null);
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(Geometry.prototype, "extend", {
  34382. get: function () {
  34383. return this._extend;
  34384. },
  34385. enumerable: true,
  34386. configurable: true
  34387. });
  34388. Geometry.prototype.getScene = function () {
  34389. return this._scene;
  34390. };
  34391. Geometry.prototype.getEngine = function () {
  34392. return this._engine;
  34393. };
  34394. Geometry.prototype.isReady = function () {
  34395. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34396. };
  34397. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34398. vertexData.applyToGeometry(this, updatable);
  34399. this.notifyUpdate();
  34400. };
  34401. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34402. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34403. this.setVerticesBuffer(buffer);
  34404. };
  34405. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34406. var kind = buffer.getKind();
  34407. if (this._vertexBuffers[kind]) {
  34408. this._vertexBuffers[kind].dispose();
  34409. }
  34410. this._vertexBuffers[kind] = buffer;
  34411. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34412. var data = buffer.getData();
  34413. var stride = buffer.getStrideSize();
  34414. this._totalVertices = data.length / stride;
  34415. this.updateExtend(data, stride);
  34416. var meshes = this._meshes;
  34417. var numOfMeshes = meshes.length;
  34418. for (var index = 0; index < numOfMeshes; index++) {
  34419. var mesh = meshes[index];
  34420. mesh._resetPointsArrayCache();
  34421. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34422. mesh._createGlobalSubMesh();
  34423. mesh.computeWorldMatrix(true);
  34424. }
  34425. }
  34426. this.notifyUpdate(kind);
  34427. };
  34428. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34429. var vertexBuffer = this.getVertexBuffer(kind);
  34430. if (!vertexBuffer) {
  34431. return;
  34432. }
  34433. vertexBuffer.updateDirectly(data, offset);
  34434. this.notifyUpdate(kind);
  34435. };
  34436. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34437. var vertexBuffer = this.getVertexBuffer(kind);
  34438. if (!vertexBuffer) {
  34439. return;
  34440. }
  34441. vertexBuffer.update(data);
  34442. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34443. var stride = vertexBuffer.getStrideSize();
  34444. this._totalVertices = data.length / stride;
  34445. this.updateBoundingInfo(updateExtends, data);
  34446. }
  34447. this.notifyUpdate(kind);
  34448. };
  34449. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34450. if (updateExtends) {
  34451. this.updateExtend(data);
  34452. }
  34453. var meshes = this._meshes;
  34454. var numOfMeshes = meshes.length;
  34455. for (var index = 0; index < numOfMeshes; index++) {
  34456. var mesh = meshes[index];
  34457. mesh._resetPointsArrayCache();
  34458. if (updateExtends) {
  34459. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34460. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34461. var subMesh = mesh.subMeshes[subIndex];
  34462. subMesh.refreshBoundingInfo();
  34463. }
  34464. }
  34465. }
  34466. };
  34467. Geometry.prototype.getTotalVertices = function () {
  34468. if (!this.isReady()) {
  34469. return 0;
  34470. }
  34471. return this._totalVertices;
  34472. };
  34473. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34474. var vertexBuffer = this.getVertexBuffer(kind);
  34475. if (!vertexBuffer) {
  34476. return null;
  34477. }
  34478. var orig = vertexBuffer.getData();
  34479. if (!copyWhenShared || this._meshes.length === 1) {
  34480. return orig;
  34481. }
  34482. else {
  34483. var len = orig.length;
  34484. var copy = [];
  34485. for (var i = 0; i < len; i++) {
  34486. copy.push(orig[i]);
  34487. }
  34488. return copy;
  34489. }
  34490. };
  34491. Geometry.prototype.getVertexBuffer = function (kind) {
  34492. if (!this.isReady()) {
  34493. return null;
  34494. }
  34495. return this._vertexBuffers[kind];
  34496. };
  34497. Geometry.prototype.getVertexBuffers = function () {
  34498. if (!this.isReady()) {
  34499. return null;
  34500. }
  34501. return this._vertexBuffers;
  34502. };
  34503. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34504. if (!this._vertexBuffers) {
  34505. if (this._delayInfo) {
  34506. return this._delayInfo.indexOf(kind) !== -1;
  34507. }
  34508. return false;
  34509. }
  34510. return this._vertexBuffers[kind] !== undefined;
  34511. };
  34512. Geometry.prototype.getVerticesDataKinds = function () {
  34513. var result = [];
  34514. var kind;
  34515. if (!this._vertexBuffers && this._delayInfo) {
  34516. for (kind in this._delayInfo) {
  34517. result.push(kind);
  34518. }
  34519. }
  34520. else {
  34521. for (kind in this._vertexBuffers) {
  34522. result.push(kind);
  34523. }
  34524. }
  34525. return result;
  34526. };
  34527. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34528. if (this._indexBuffer) {
  34529. this._engine._releaseBuffer(this._indexBuffer);
  34530. }
  34531. this._indices = indices;
  34532. if (this._meshes.length !== 0 && this._indices) {
  34533. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34534. }
  34535. if (totalVertices !== undefined) {
  34536. this._totalVertices = totalVertices;
  34537. }
  34538. var meshes = this._meshes;
  34539. var numOfMeshes = meshes.length;
  34540. for (var index = 0; index < numOfMeshes; index++) {
  34541. meshes[index]._createGlobalSubMesh();
  34542. }
  34543. this.notifyUpdate();
  34544. };
  34545. Geometry.prototype.getTotalIndices = function () {
  34546. if (!this.isReady()) {
  34547. return 0;
  34548. }
  34549. return this._indices.length;
  34550. };
  34551. Geometry.prototype.getIndices = function (copyWhenShared) {
  34552. if (!this.isReady()) {
  34553. return null;
  34554. }
  34555. var orig = this._indices;
  34556. if (!copyWhenShared || this._meshes.length === 1) {
  34557. return orig;
  34558. }
  34559. else {
  34560. var len = orig.length;
  34561. var copy = [];
  34562. for (var i = 0; i < len; i++) {
  34563. copy.push(orig[i]);
  34564. }
  34565. return copy;
  34566. }
  34567. };
  34568. Geometry.prototype.getIndexBuffer = function () {
  34569. if (!this.isReady()) {
  34570. return null;
  34571. }
  34572. return this._indexBuffer;
  34573. };
  34574. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34575. var meshes = this._meshes;
  34576. var index = meshes.indexOf(mesh);
  34577. if (index === -1) {
  34578. return;
  34579. }
  34580. for (var kind in this._vertexBuffers) {
  34581. this._vertexBuffers[kind].dispose();
  34582. }
  34583. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34584. this._indexBuffer = null;
  34585. }
  34586. meshes.splice(index, 1);
  34587. mesh._geometry = null;
  34588. if (meshes.length === 0 && shouldDispose) {
  34589. this.dispose();
  34590. }
  34591. };
  34592. Geometry.prototype.applyToMesh = function (mesh) {
  34593. if (mesh._geometry === this) {
  34594. return;
  34595. }
  34596. var previousGeometry = mesh._geometry;
  34597. if (previousGeometry) {
  34598. previousGeometry.releaseForMesh(mesh);
  34599. }
  34600. var meshes = this._meshes;
  34601. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34602. mesh._geometry = this;
  34603. this._scene.pushGeometry(this);
  34604. meshes.push(mesh);
  34605. if (this.isReady()) {
  34606. this._applyToMesh(mesh);
  34607. }
  34608. else {
  34609. mesh._boundingInfo = this._boundingInfo;
  34610. }
  34611. };
  34612. Geometry.prototype.updateExtend = function (data, stride) {
  34613. if (data === void 0) { data = null; }
  34614. if (!data) {
  34615. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34616. }
  34617. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34618. };
  34619. Geometry.prototype._applyToMesh = function (mesh) {
  34620. var numOfMeshes = this._meshes.length;
  34621. // vertexBuffers
  34622. for (var kind in this._vertexBuffers) {
  34623. if (numOfMeshes === 1) {
  34624. this._vertexBuffers[kind].create();
  34625. }
  34626. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34627. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34628. mesh._resetPointsArrayCache();
  34629. if (!this._extend) {
  34630. this.updateExtend(this._vertexBuffers[kind].getData());
  34631. }
  34632. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34633. mesh._createGlobalSubMesh();
  34634. //bounding info was just created again, world matrix should be applied again.
  34635. mesh._updateBoundingInfo();
  34636. }
  34637. }
  34638. // indexBuffer
  34639. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34640. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34641. }
  34642. if (this._indexBuffer) {
  34643. this._indexBuffer.references = numOfMeshes;
  34644. }
  34645. };
  34646. Geometry.prototype.notifyUpdate = function (kind) {
  34647. if (this.onGeometryUpdated) {
  34648. this.onGeometryUpdated(this, kind);
  34649. }
  34650. };
  34651. Geometry.prototype.load = function (scene, onLoaded) {
  34652. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34653. return;
  34654. }
  34655. if (this.isReady()) {
  34656. if (onLoaded) {
  34657. onLoaded();
  34658. }
  34659. return;
  34660. }
  34661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34662. this._queueLoad(scene, onLoaded);
  34663. };
  34664. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34665. var _this = this;
  34666. scene._addPendingData(this);
  34667. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34668. _this._delayLoadingFunction(JSON.parse(data), _this);
  34669. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34670. _this._delayInfo = [];
  34671. scene._removePendingData(_this);
  34672. var meshes = _this._meshes;
  34673. var numOfMeshes = meshes.length;
  34674. for (var index = 0; index < numOfMeshes; index++) {
  34675. _this._applyToMesh(meshes[index]);
  34676. }
  34677. if (onLoaded) {
  34678. onLoaded();
  34679. }
  34680. }, function () { }, scene.database);
  34681. };
  34682. /**
  34683. * Invert the geometry to move from a right handed system to a left handed one.
  34684. */
  34685. Geometry.prototype.toLeftHanded = function () {
  34686. // Flip faces
  34687. var tIndices = this.getIndices(false);
  34688. if (tIndices != null && tIndices.length > 0) {
  34689. for (var i = 0; i < tIndices.length; i += 3) {
  34690. var tTemp = tIndices[i + 0];
  34691. tIndices[i + 0] = tIndices[i + 2];
  34692. tIndices[i + 2] = tTemp;
  34693. }
  34694. this.setIndices(tIndices);
  34695. }
  34696. // Negate position.z
  34697. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34698. if (tPositions != null && tPositions.length > 0) {
  34699. for (var i = 0; i < tPositions.length; i += 3) {
  34700. tPositions[i + 2] = -tPositions[i + 2];
  34701. }
  34702. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34703. }
  34704. // Negate normal.z
  34705. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34706. if (tNormals != null && tNormals.length > 0) {
  34707. for (var i = 0; i < tNormals.length; i += 3) {
  34708. tNormals[i + 2] = -tNormals[i + 2];
  34709. }
  34710. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34711. }
  34712. };
  34713. Geometry.prototype.isDisposed = function () {
  34714. return this._isDisposed;
  34715. };
  34716. Geometry.prototype.dispose = function () {
  34717. var meshes = this._meshes;
  34718. var numOfMeshes = meshes.length;
  34719. var index;
  34720. for (index = 0; index < numOfMeshes; index++) {
  34721. this.releaseForMesh(meshes[index]);
  34722. }
  34723. this._meshes = [];
  34724. for (var kind in this._vertexBuffers) {
  34725. this._vertexBuffers[kind].dispose();
  34726. }
  34727. this._vertexBuffers = {};
  34728. this._totalVertices = 0;
  34729. if (this._indexBuffer) {
  34730. this._engine._releaseBuffer(this._indexBuffer);
  34731. }
  34732. this._indexBuffer = null;
  34733. this._indices = [];
  34734. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34735. this.delayLoadingFile = null;
  34736. this._delayLoadingFunction = null;
  34737. this._delayInfo = [];
  34738. this._boundingInfo = null;
  34739. this._scene.removeGeometry(this);
  34740. this._isDisposed = true;
  34741. };
  34742. Geometry.prototype.copy = function (id) {
  34743. var vertexData = new BABYLON.VertexData();
  34744. vertexData.indices = [];
  34745. var indices = this.getIndices();
  34746. for (var index = 0; index < indices.length; index++) {
  34747. vertexData.indices.push(indices[index]);
  34748. }
  34749. var updatable = false;
  34750. var stopChecking = false;
  34751. var kind;
  34752. for (kind in this._vertexBuffers) {
  34753. // using slice() to make a copy of the array and not just reference it
  34754. var data = this.getVerticesData(kind);
  34755. if (data instanceof Float32Array) {
  34756. vertexData.set(new Float32Array(data), kind);
  34757. }
  34758. else {
  34759. vertexData.set(data.slice(0), kind);
  34760. }
  34761. if (!stopChecking) {
  34762. updatable = this.getVertexBuffer(kind).isUpdatable();
  34763. stopChecking = !updatable;
  34764. }
  34765. }
  34766. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34767. geometry.delayLoadState = this.delayLoadState;
  34768. geometry.delayLoadingFile = this.delayLoadingFile;
  34769. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34770. for (kind in this._delayInfo) {
  34771. geometry._delayInfo = geometry._delayInfo || [];
  34772. geometry._delayInfo.push(kind);
  34773. }
  34774. // Bounding info
  34775. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34776. return geometry;
  34777. };
  34778. Geometry.prototype.serialize = function () {
  34779. var serializationObject = {};
  34780. serializationObject.id = this.id;
  34781. if (BABYLON.Tags.HasTags(this)) {
  34782. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34783. }
  34784. return serializationObject;
  34785. };
  34786. Geometry.prototype.serializeVerticeData = function () {
  34787. var serializationObject = this.serialize();
  34788. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34789. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34790. }
  34791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34792. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34793. }
  34794. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34795. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34796. }
  34797. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34798. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34799. }
  34800. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34801. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34802. }
  34803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34804. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34805. }
  34806. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34807. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34808. }
  34809. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34810. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34811. }
  34812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34813. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34814. }
  34815. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34816. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34817. serializationObject.matricesIndices._isExpanded = true;
  34818. }
  34819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34820. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34821. }
  34822. serializationObject.indices = this.getIndices();
  34823. return serializationObject;
  34824. };
  34825. // Statics
  34826. Geometry.ExtractFromMesh = function (mesh, id) {
  34827. var geometry = mesh._geometry;
  34828. if (!geometry) {
  34829. return null;
  34830. }
  34831. return geometry.copy(id);
  34832. };
  34833. /**
  34834. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34835. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34836. * Be aware Math.random() could cause collisions, but:
  34837. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  34838. */
  34839. Geometry.RandomId = function () {
  34840. return BABYLON.Tools.RandomId();
  34841. };
  34842. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34843. var scene = mesh.getScene();
  34844. // Geometry
  34845. var geometryId = parsedGeometry.geometryId;
  34846. if (geometryId) {
  34847. var geometry = scene.getGeometryByID(geometryId);
  34848. if (geometry) {
  34849. geometry.applyToMesh(mesh);
  34850. }
  34851. }
  34852. else if (parsedGeometry instanceof ArrayBuffer) {
  34853. var binaryInfo = mesh._binaryInfo;
  34854. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34855. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34856. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34857. }
  34858. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34859. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34860. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34861. }
  34862. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34863. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34864. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34865. }
  34866. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34867. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34868. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34869. }
  34870. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34871. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34872. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34873. }
  34874. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34875. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34876. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34877. }
  34878. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34879. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34880. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34881. }
  34882. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34883. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34885. }
  34886. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34887. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34888. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34889. }
  34890. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34891. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34892. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34893. }
  34894. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34895. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34896. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34897. }
  34898. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34899. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34900. mesh.setIndices(indicesData);
  34901. }
  34902. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34903. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34904. mesh.subMeshes = [];
  34905. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34906. var materialIndex = subMeshesData[(i * 5) + 0];
  34907. var verticesStart = subMeshesData[(i * 5) + 1];
  34908. var verticesCount = subMeshesData[(i * 5) + 2];
  34909. var indexStart = subMeshesData[(i * 5) + 3];
  34910. var indexCount = subMeshesData[(i * 5) + 4];
  34911. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34912. }
  34913. }
  34914. }
  34915. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34916. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34917. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34918. if (parsedGeometry.uvs) {
  34919. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34920. }
  34921. if (parsedGeometry.uvs2) {
  34922. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34923. }
  34924. if (parsedGeometry.uvs3) {
  34925. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34926. }
  34927. if (parsedGeometry.uvs4) {
  34928. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34929. }
  34930. if (parsedGeometry.uvs5) {
  34931. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34932. }
  34933. if (parsedGeometry.uvs6) {
  34934. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34935. }
  34936. if (parsedGeometry.colors) {
  34937. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34938. }
  34939. if (parsedGeometry.matricesIndices) {
  34940. if (!parsedGeometry.matricesIndices._isExpanded) {
  34941. var floatIndices = [];
  34942. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34943. var matricesIndex = parsedGeometry.matricesIndices[i];
  34944. floatIndices.push(matricesIndex & 0x000000FF);
  34945. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34946. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34947. floatIndices.push(matricesIndex >> 24);
  34948. }
  34949. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34950. }
  34951. else {
  34952. delete parsedGeometry.matricesIndices._isExpanded;
  34953. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34954. }
  34955. }
  34956. if (parsedGeometry.matricesIndicesExtra) {
  34957. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34958. var floatIndices = [];
  34959. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34960. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34961. floatIndices.push(matricesIndex & 0x000000FF);
  34962. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34963. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34964. floatIndices.push(matricesIndex >> 24);
  34965. }
  34966. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34967. }
  34968. else {
  34969. delete parsedGeometry.matricesIndices._isExpanded;
  34970. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34971. }
  34972. }
  34973. if (parsedGeometry.matricesWeights) {
  34974. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34975. }
  34976. if (parsedGeometry.matricesWeightsExtra) {
  34977. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34978. }
  34979. mesh.setIndices(parsedGeometry.indices);
  34980. }
  34981. // SubMeshes
  34982. if (parsedGeometry.subMeshes) {
  34983. mesh.subMeshes = [];
  34984. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34985. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34986. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34987. }
  34988. }
  34989. // Flat shading
  34990. if (mesh._shouldGenerateFlatShading) {
  34991. mesh.convertToFlatShadedMesh();
  34992. delete mesh._shouldGenerateFlatShading;
  34993. }
  34994. // Update
  34995. mesh.computeWorldMatrix(true);
  34996. // Octree
  34997. if (scene['_selectionOctree']) {
  34998. scene['_selectionOctree'].addMesh(mesh);
  34999. }
  35000. };
  35001. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35002. if (scene.getGeometryByID(parsedVertexData.id)) {
  35003. return null; // null since geometry could be something else than a box...
  35004. }
  35005. var geometry = new Geometry(parsedVertexData.id, scene);
  35006. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35007. if (parsedVertexData.delayLoadingFile) {
  35008. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35009. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35010. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35011. geometry._delayInfo = [];
  35012. if (parsedVertexData.hasUVs) {
  35013. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35014. }
  35015. if (parsedVertexData.hasUVs2) {
  35016. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35017. }
  35018. if (parsedVertexData.hasUVs3) {
  35019. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35020. }
  35021. if (parsedVertexData.hasUVs4) {
  35022. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35023. }
  35024. if (parsedVertexData.hasUVs5) {
  35025. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35026. }
  35027. if (parsedVertexData.hasUVs6) {
  35028. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35029. }
  35030. if (parsedVertexData.hasColors) {
  35031. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35032. }
  35033. if (parsedVertexData.hasMatricesIndices) {
  35034. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35035. }
  35036. if (parsedVertexData.hasMatricesWeights) {
  35037. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35038. }
  35039. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35040. }
  35041. else {
  35042. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35043. }
  35044. scene.pushGeometry(geometry, true);
  35045. return geometry;
  35046. };
  35047. return Geometry;
  35048. }());
  35049. BABYLON.Geometry = Geometry;
  35050. /////// Primitives //////////////////////////////////////////////
  35051. var Geometry;
  35052. (function (Geometry) {
  35053. var Primitives;
  35054. (function (Primitives) {
  35055. /// Abstract class
  35056. var _Primitive = (function (_super) {
  35057. __extends(_Primitive, _super);
  35058. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35059. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35060. this._canBeRegenerated = _canBeRegenerated;
  35061. this._beingRegenerated = true;
  35062. this.regenerate();
  35063. this._beingRegenerated = false;
  35064. }
  35065. _Primitive.prototype.canBeRegenerated = function () {
  35066. return this._canBeRegenerated;
  35067. };
  35068. _Primitive.prototype.regenerate = function () {
  35069. if (!this._canBeRegenerated) {
  35070. return;
  35071. }
  35072. this._beingRegenerated = true;
  35073. this.setAllVerticesData(this._regenerateVertexData(), false);
  35074. this._beingRegenerated = false;
  35075. };
  35076. _Primitive.prototype.asNewGeometry = function (id) {
  35077. return _super.prototype.copy.call(this, id);
  35078. };
  35079. // overrides
  35080. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35081. if (!this._beingRegenerated) {
  35082. return;
  35083. }
  35084. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35085. };
  35086. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35087. if (!this._beingRegenerated) {
  35088. return;
  35089. }
  35090. _super.prototype.setVerticesData.call(this, kind, data, false);
  35091. };
  35092. // to override
  35093. // protected
  35094. _Primitive.prototype._regenerateVertexData = function () {
  35095. throw new Error("Abstract method");
  35096. };
  35097. _Primitive.prototype.copy = function (id) {
  35098. throw new Error("Must be overriden in sub-classes.");
  35099. };
  35100. _Primitive.prototype.serialize = function () {
  35101. var serializationObject = _super.prototype.serialize.call(this);
  35102. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35103. return serializationObject;
  35104. };
  35105. return _Primitive;
  35106. }(Geometry));
  35107. Primitives._Primitive = _Primitive;
  35108. var Ribbon = (function (_super) {
  35109. __extends(Ribbon, _super);
  35110. // Members
  35111. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35112. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35113. _super.call(this, id, scene, canBeRegenerated, mesh);
  35114. this.pathArray = pathArray;
  35115. this.closeArray = closeArray;
  35116. this.closePath = closePath;
  35117. this.offset = offset;
  35118. this.side = side;
  35119. }
  35120. Ribbon.prototype._regenerateVertexData = function () {
  35121. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35122. };
  35123. Ribbon.prototype.copy = function (id) {
  35124. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35125. };
  35126. return Ribbon;
  35127. }(_Primitive));
  35128. Primitives.Ribbon = Ribbon;
  35129. var Box = (function (_super) {
  35130. __extends(Box, _super);
  35131. // Members
  35132. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35133. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35134. _super.call(this, id, scene, canBeRegenerated, mesh);
  35135. this.size = size;
  35136. this.side = side;
  35137. }
  35138. Box.prototype._regenerateVertexData = function () {
  35139. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35140. };
  35141. Box.prototype.copy = function (id) {
  35142. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35143. };
  35144. Box.prototype.serialize = function () {
  35145. var serializationObject = _super.prototype.serialize.call(this);
  35146. serializationObject.size = this.size;
  35147. return serializationObject;
  35148. };
  35149. Box.Parse = function (parsedBox, scene) {
  35150. if (scene.getGeometryByID(parsedBox.id)) {
  35151. return null; // null since geometry could be something else than a box...
  35152. }
  35153. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35154. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35155. scene.pushGeometry(box, true);
  35156. return box;
  35157. };
  35158. return Box;
  35159. }(_Primitive));
  35160. Primitives.Box = Box;
  35161. var Sphere = (function (_super) {
  35162. __extends(Sphere, _super);
  35163. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35164. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35165. _super.call(this, id, scene, canBeRegenerated, mesh);
  35166. this.segments = segments;
  35167. this.diameter = diameter;
  35168. this.side = side;
  35169. }
  35170. Sphere.prototype._regenerateVertexData = function () {
  35171. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35172. };
  35173. Sphere.prototype.copy = function (id) {
  35174. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35175. };
  35176. Sphere.prototype.serialize = function () {
  35177. var serializationObject = _super.prototype.serialize.call(this);
  35178. serializationObject.segments = this.segments;
  35179. serializationObject.diameter = this.diameter;
  35180. return serializationObject;
  35181. };
  35182. Sphere.Parse = function (parsedSphere, scene) {
  35183. if (scene.getGeometryByID(parsedSphere.id)) {
  35184. return null; // null since geometry could be something else than a sphere...
  35185. }
  35186. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35187. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35188. scene.pushGeometry(sphere, true);
  35189. return sphere;
  35190. };
  35191. return Sphere;
  35192. }(_Primitive));
  35193. Primitives.Sphere = Sphere;
  35194. var Disc = (function (_super) {
  35195. __extends(Disc, _super);
  35196. // Members
  35197. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35198. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35199. _super.call(this, id, scene, canBeRegenerated, mesh);
  35200. this.radius = radius;
  35201. this.tessellation = tessellation;
  35202. this.side = side;
  35203. }
  35204. Disc.prototype._regenerateVertexData = function () {
  35205. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35206. };
  35207. Disc.prototype.copy = function (id) {
  35208. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35209. };
  35210. return Disc;
  35211. }(_Primitive));
  35212. Primitives.Disc = Disc;
  35213. var Cylinder = (function (_super) {
  35214. __extends(Cylinder, _super);
  35215. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35216. if (subdivisions === void 0) { subdivisions = 1; }
  35217. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35218. _super.call(this, id, scene, canBeRegenerated, mesh);
  35219. this.height = height;
  35220. this.diameterTop = diameterTop;
  35221. this.diameterBottom = diameterBottom;
  35222. this.tessellation = tessellation;
  35223. this.subdivisions = subdivisions;
  35224. this.side = side;
  35225. }
  35226. Cylinder.prototype._regenerateVertexData = function () {
  35227. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35228. };
  35229. Cylinder.prototype.copy = function (id) {
  35230. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35231. };
  35232. Cylinder.prototype.serialize = function () {
  35233. var serializationObject = _super.prototype.serialize.call(this);
  35234. serializationObject.height = this.height;
  35235. serializationObject.diameterTop = this.diameterTop;
  35236. serializationObject.diameterBottom = this.diameterBottom;
  35237. serializationObject.tessellation = this.tessellation;
  35238. return serializationObject;
  35239. };
  35240. Cylinder.Parse = function (parsedCylinder, scene) {
  35241. if (scene.getGeometryByID(parsedCylinder.id)) {
  35242. return null; // null since geometry could be something else than a cylinder...
  35243. }
  35244. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35245. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35246. scene.pushGeometry(cylinder, true);
  35247. return cylinder;
  35248. };
  35249. return Cylinder;
  35250. }(_Primitive));
  35251. Primitives.Cylinder = Cylinder;
  35252. var Torus = (function (_super) {
  35253. __extends(Torus, _super);
  35254. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35256. _super.call(this, id, scene, canBeRegenerated, mesh);
  35257. this.diameter = diameter;
  35258. this.thickness = thickness;
  35259. this.tessellation = tessellation;
  35260. this.side = side;
  35261. }
  35262. Torus.prototype._regenerateVertexData = function () {
  35263. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35264. };
  35265. Torus.prototype.copy = function (id) {
  35266. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35267. };
  35268. Torus.prototype.serialize = function () {
  35269. var serializationObject = _super.prototype.serialize.call(this);
  35270. serializationObject.diameter = this.diameter;
  35271. serializationObject.thickness = this.thickness;
  35272. serializationObject.tessellation = this.tessellation;
  35273. return serializationObject;
  35274. };
  35275. Torus.Parse = function (parsedTorus, scene) {
  35276. if (scene.getGeometryByID(parsedTorus.id)) {
  35277. return null; // null since geometry could be something else than a torus...
  35278. }
  35279. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35280. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35281. scene.pushGeometry(torus, true);
  35282. return torus;
  35283. };
  35284. return Torus;
  35285. }(_Primitive));
  35286. Primitives.Torus = Torus;
  35287. var Ground = (function (_super) {
  35288. __extends(Ground, _super);
  35289. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35290. _super.call(this, id, scene, canBeRegenerated, mesh);
  35291. this.width = width;
  35292. this.height = height;
  35293. this.subdivisions = subdivisions;
  35294. }
  35295. Ground.prototype._regenerateVertexData = function () {
  35296. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35297. };
  35298. Ground.prototype.copy = function (id) {
  35299. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35300. };
  35301. Ground.prototype.serialize = function () {
  35302. var serializationObject = _super.prototype.serialize.call(this);
  35303. serializationObject.width = this.width;
  35304. serializationObject.height = this.height;
  35305. serializationObject.subdivisions = this.subdivisions;
  35306. return serializationObject;
  35307. };
  35308. Ground.Parse = function (parsedGround, scene) {
  35309. if (scene.getGeometryByID(parsedGround.id)) {
  35310. return null; // null since geometry could be something else than a ground...
  35311. }
  35312. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35313. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35314. scene.pushGeometry(ground, true);
  35315. return ground;
  35316. };
  35317. return Ground;
  35318. }(_Primitive));
  35319. Primitives.Ground = Ground;
  35320. var TiledGround = (function (_super) {
  35321. __extends(TiledGround, _super);
  35322. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35323. _super.call(this, id, scene, canBeRegenerated, mesh);
  35324. this.xmin = xmin;
  35325. this.zmin = zmin;
  35326. this.xmax = xmax;
  35327. this.zmax = zmax;
  35328. this.subdivisions = subdivisions;
  35329. this.precision = precision;
  35330. }
  35331. TiledGround.prototype._regenerateVertexData = function () {
  35332. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35333. };
  35334. TiledGround.prototype.copy = function (id) {
  35335. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35336. };
  35337. return TiledGround;
  35338. }(_Primitive));
  35339. Primitives.TiledGround = TiledGround;
  35340. var Plane = (function (_super) {
  35341. __extends(Plane, _super);
  35342. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35343. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35344. _super.call(this, id, scene, canBeRegenerated, mesh);
  35345. this.size = size;
  35346. this.side = side;
  35347. }
  35348. Plane.prototype._regenerateVertexData = function () {
  35349. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35350. };
  35351. Plane.prototype.copy = function (id) {
  35352. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35353. };
  35354. Plane.prototype.serialize = function () {
  35355. var serializationObject = _super.prototype.serialize.call(this);
  35356. serializationObject.size = this.size;
  35357. return serializationObject;
  35358. };
  35359. Plane.Parse = function (parsedPlane, scene) {
  35360. if (scene.getGeometryByID(parsedPlane.id)) {
  35361. return null; // null since geometry could be something else than a ground...
  35362. }
  35363. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35364. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35365. scene.pushGeometry(plane, true);
  35366. return plane;
  35367. };
  35368. return Plane;
  35369. }(_Primitive));
  35370. Primitives.Plane = Plane;
  35371. var TorusKnot = (function (_super) {
  35372. __extends(TorusKnot, _super);
  35373. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35375. _super.call(this, id, scene, canBeRegenerated, mesh);
  35376. this.radius = radius;
  35377. this.tube = tube;
  35378. this.radialSegments = radialSegments;
  35379. this.tubularSegments = tubularSegments;
  35380. this.p = p;
  35381. this.q = q;
  35382. this.side = side;
  35383. }
  35384. TorusKnot.prototype._regenerateVertexData = function () {
  35385. 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 });
  35386. };
  35387. TorusKnot.prototype.copy = function (id) {
  35388. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35389. };
  35390. TorusKnot.prototype.serialize = function () {
  35391. var serializationObject = _super.prototype.serialize.call(this);
  35392. serializationObject.radius = this.radius;
  35393. serializationObject.tube = this.tube;
  35394. serializationObject.radialSegments = this.radialSegments;
  35395. serializationObject.tubularSegments = this.tubularSegments;
  35396. serializationObject.p = this.p;
  35397. serializationObject.q = this.q;
  35398. return serializationObject;
  35399. };
  35400. ;
  35401. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35402. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35403. return null; // null since geometry could be something else than a ground...
  35404. }
  35405. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35406. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35407. scene.pushGeometry(torusKnot, true);
  35408. return torusKnot;
  35409. };
  35410. return TorusKnot;
  35411. }(_Primitive));
  35412. Primitives.TorusKnot = TorusKnot;
  35413. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35414. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35415. })(BABYLON || (BABYLON = {}));
  35416. var BABYLON;
  35417. (function (BABYLON) {
  35418. var GroundMesh = (function (_super) {
  35419. __extends(GroundMesh, _super);
  35420. function GroundMesh(name, scene) {
  35421. _super.call(this, name, scene);
  35422. this.generateOctree = false;
  35423. this._worldInverse = new BABYLON.Matrix();
  35424. }
  35425. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35426. get: function () {
  35427. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35428. },
  35429. enumerable: true,
  35430. configurable: true
  35431. });
  35432. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35433. get: function () {
  35434. return this._subdivisionsX;
  35435. },
  35436. enumerable: true,
  35437. configurable: true
  35438. });
  35439. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35440. get: function () {
  35441. return this._subdivisionsY;
  35442. },
  35443. enumerable: true,
  35444. configurable: true
  35445. });
  35446. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35447. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35448. this._subdivisionsX = chunksCount;
  35449. this._subdivisionsY = chunksCount;
  35450. this.subdivide(chunksCount);
  35451. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35452. };
  35453. /**
  35454. * Returns a height (y) value in the Worl system :
  35455. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35456. * Returns the ground y position if (x, z) are outside the ground surface.
  35457. * Not pertinent if the ground is rotated.
  35458. */
  35459. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35460. // express x and y in the ground local system
  35461. x -= this.position.x;
  35462. z -= this.position.z;
  35463. x /= this.scaling.x;
  35464. z /= this.scaling.z;
  35465. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35466. return this.position.y;
  35467. }
  35468. if (!this._heightQuads || this._heightQuads.length == 0) {
  35469. this._initHeightQuads();
  35470. this._computeHeightQuads();
  35471. }
  35472. var facet = this._getFacetAt(x, z);
  35473. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35474. // return y in the World system
  35475. return y * this.scaling.y + this.position.y;
  35476. };
  35477. /**
  35478. * Returns a normalized vector (Vector3) orthogonal to the ground
  35479. * at the ground coordinates (x, z) expressed in the World system.
  35480. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35481. * Not pertinent if the ground is rotated.
  35482. */
  35483. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35484. var normal = new BABYLON.Vector3(0, 1, 0);
  35485. this.getNormalAtCoordinatesToRef(x, z, normal);
  35486. return normal;
  35487. };
  35488. /**
  35489. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35490. * at the ground coordinates (x, z) expressed in the World system.
  35491. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35492. * Not pertinent if the ground is rotated.
  35493. */
  35494. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35495. // express x and y in the ground local system
  35496. x -= this.position.x;
  35497. z -= this.position.z;
  35498. x /= this.scaling.x;
  35499. z /= this.scaling.z;
  35500. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35501. return;
  35502. }
  35503. if (!this._heightQuads || this._heightQuads.length == 0) {
  35504. this._initHeightQuads();
  35505. this._computeHeightQuads();
  35506. }
  35507. var facet = this._getFacetAt(x, z);
  35508. ref.x = facet.x;
  35509. ref.y = facet.y;
  35510. ref.z = facet.z;
  35511. };
  35512. /**
  35513. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35514. * if the ground has been updated.
  35515. * This can be used in the render loop
  35516. */
  35517. GroundMesh.prototype.updateCoordinateHeights = function () {
  35518. if (!this._heightQuads || this._heightQuads.length == 0) {
  35519. this._initHeightQuads();
  35520. }
  35521. this._computeHeightQuads();
  35522. };
  35523. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35524. GroundMesh.prototype._getFacetAt = function (x, z) {
  35525. // retrieve col and row from x, z coordinates in the ground local system
  35526. var subdivisionsX = this._subdivisionsX;
  35527. var subdivisionsY = this._subdivisionsY;
  35528. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35529. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35530. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35531. var facet;
  35532. if (z < quad.slope.x * x + quad.slope.y) {
  35533. facet = quad.facet1;
  35534. }
  35535. else {
  35536. facet = quad.facet2;
  35537. }
  35538. return facet;
  35539. };
  35540. // Creates and populates the heightMap array with "facet" elements :
  35541. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35542. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35543. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35544. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35545. GroundMesh.prototype._initHeightQuads = function () {
  35546. var subdivisionsX = this._subdivisionsX;
  35547. var subdivisionsY = this._subdivisionsY;
  35548. this._heightQuads = new Array();
  35549. for (var row = 0; row < subdivisionsY; row++) {
  35550. for (var col = 0; col < subdivisionsX; col++) {
  35551. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35552. this._heightQuads[row * subdivisionsX + col] = quad;
  35553. }
  35554. }
  35555. };
  35556. // Compute each quad element values and update the the heightMap array :
  35557. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35558. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35559. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35560. GroundMesh.prototype._computeHeightQuads = function () {
  35561. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35562. var v1 = BABYLON.Tmp.Vector3[3];
  35563. var v2 = BABYLON.Tmp.Vector3[2];
  35564. var v3 = BABYLON.Tmp.Vector3[1];
  35565. var v4 = BABYLON.Tmp.Vector3[0];
  35566. var v1v2 = BABYLON.Tmp.Vector3[4];
  35567. var v1v3 = BABYLON.Tmp.Vector3[5];
  35568. var v1v4 = BABYLON.Tmp.Vector3[6];
  35569. var norm1 = BABYLON.Tmp.Vector3[7];
  35570. var norm2 = BABYLON.Tmp.Vector3[8];
  35571. var i = 0;
  35572. var j = 0;
  35573. var k = 0;
  35574. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35575. var h = 0;
  35576. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35577. var d2 = 0;
  35578. var subdivisionsX = this._subdivisionsX;
  35579. var subdivisionsY = this._subdivisionsY;
  35580. for (var row = 0; row < subdivisionsY; row++) {
  35581. for (var col = 0; col < subdivisionsX; col++) {
  35582. i = col * 3;
  35583. j = row * (subdivisionsX + 1) * 3;
  35584. k = (row + 1) * (subdivisionsX + 1) * 3;
  35585. v1.x = positions[j + i];
  35586. v1.y = positions[j + i + 1];
  35587. v1.z = positions[j + i + 2];
  35588. v2.x = positions[j + i + 3];
  35589. v2.y = positions[j + i + 4];
  35590. v2.z = positions[j + i + 5];
  35591. v3.x = positions[k + i];
  35592. v3.y = positions[k + i + 1];
  35593. v3.z = positions[k + i + 2];
  35594. v4.x = positions[k + i + 3];
  35595. v4.y = positions[k + i + 4];
  35596. v4.z = positions[k + i + 5];
  35597. // 2D slope V1V4
  35598. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35599. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35600. // facet equations :
  35601. // we compute each facet normal vector
  35602. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35603. // we compute the value d by applying the equation to v1 which belongs to the plane
  35604. // then we store the facet equation in a Vector4
  35605. v2.subtractToRef(v1, v1v2);
  35606. v3.subtractToRef(v1, v1v3);
  35607. v4.subtractToRef(v1, v1v4);
  35608. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35609. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35610. norm1.normalize();
  35611. norm2.normalize();
  35612. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35613. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35614. var quad = this._heightQuads[row * subdivisionsX + col];
  35615. quad.slope.copyFromFloats(cd, h);
  35616. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35617. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35618. }
  35619. }
  35620. };
  35621. return GroundMesh;
  35622. }(BABYLON.Mesh));
  35623. BABYLON.GroundMesh = GroundMesh;
  35624. })(BABYLON || (BABYLON = {}));
  35625. var BABYLON;
  35626. (function (BABYLON) {
  35627. var LinesMesh = (function (_super) {
  35628. __extends(LinesMesh, _super);
  35629. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35630. if (parent === void 0) { parent = null; }
  35631. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35632. this.color = new BABYLON.Color3(1, 1, 1);
  35633. this.alpha = 1;
  35634. this._positionBuffer = {};
  35635. if (source) {
  35636. this.color = source.color.clone();
  35637. this.alpha = source.alpha;
  35638. }
  35639. this._intersectionThreshold = 0.1;
  35640. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35641. attributes: [BABYLON.VertexBuffer.PositionKind],
  35642. uniforms: ["worldViewProjection", "color"],
  35643. needAlphaBlending: true
  35644. });
  35645. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35646. }
  35647. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35648. /**
  35649. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35650. * This margin is expressed in world space coordinates, so its value may vary.
  35651. * Default value is 0.1
  35652. * @returns the intersection Threshold value.
  35653. */
  35654. get: function () {
  35655. return this._intersectionThreshold;
  35656. },
  35657. /**
  35658. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35659. * This margin is expressed in world space coordinates, so its value may vary.
  35660. * @param value the new threshold to apply
  35661. */
  35662. set: function (value) {
  35663. if (this._intersectionThreshold === value) {
  35664. return;
  35665. }
  35666. this._intersectionThreshold = value;
  35667. if (this.geometry) {
  35668. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35669. }
  35670. },
  35671. enumerable: true,
  35672. configurable: true
  35673. });
  35674. Object.defineProperty(LinesMesh.prototype, "material", {
  35675. get: function () {
  35676. return this._colorShader;
  35677. },
  35678. enumerable: true,
  35679. configurable: true
  35680. });
  35681. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35682. get: function () {
  35683. return false;
  35684. },
  35685. enumerable: true,
  35686. configurable: true
  35687. });
  35688. LinesMesh.prototype.createInstance = function (name) {
  35689. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35690. return null;
  35691. };
  35692. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35693. var engine = this.getScene().getEngine();
  35694. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35695. // VBOs
  35696. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35697. // Color
  35698. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35699. };
  35700. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35701. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35702. return;
  35703. }
  35704. var engine = this.getScene().getEngine();
  35705. // Draw order
  35706. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35707. };
  35708. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35709. this._colorShader.dispose();
  35710. _super.prototype.dispose.call(this, doNotRecurse);
  35711. };
  35712. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35713. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35714. };
  35715. return LinesMesh;
  35716. }(BABYLON.Mesh));
  35717. BABYLON.LinesMesh = LinesMesh;
  35718. })(BABYLON || (BABYLON = {}));
  35719. var BABYLON;
  35720. (function (BABYLON) {
  35721. var DefaultLoadingScreen = (function () {
  35722. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35723. var _this = this;
  35724. if (_loadingText === void 0) { _loadingText = ""; }
  35725. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35726. this._renderingCanvas = _renderingCanvas;
  35727. this._loadingText = _loadingText;
  35728. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35729. // Resize
  35730. this._resizeLoadingUI = function () {
  35731. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35732. _this._loadingDiv.style.position = "absolute";
  35733. _this._loadingDiv.style.left = canvasRect.left + "px";
  35734. _this._loadingDiv.style.top = canvasRect.top + "px";
  35735. _this._loadingDiv.style.width = canvasRect.width + "px";
  35736. _this._loadingDiv.style.height = canvasRect.height + "px";
  35737. };
  35738. }
  35739. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35740. var _this = this;
  35741. if (this._loadingDiv) {
  35742. // Do not add a loading screen if there is already one
  35743. return;
  35744. }
  35745. this._loadingDiv = document.createElement("div");
  35746. this._loadingDiv.id = "babylonjsLoadingDiv";
  35747. this._loadingDiv.style.opacity = "0";
  35748. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35749. // Loading text
  35750. this._loadingTextDiv = document.createElement("div");
  35751. this._loadingTextDiv.style.position = "absolute";
  35752. this._loadingTextDiv.style.left = "0";
  35753. this._loadingTextDiv.style.top = "50%";
  35754. this._loadingTextDiv.style.marginTop = "80px";
  35755. this._loadingTextDiv.style.width = "100%";
  35756. this._loadingTextDiv.style.height = "20px";
  35757. this._loadingTextDiv.style.fontFamily = "Arial";
  35758. this._loadingTextDiv.style.fontSize = "14px";
  35759. this._loadingTextDiv.style.color = "white";
  35760. this._loadingTextDiv.style.textAlign = "center";
  35761. this._loadingTextDiv.innerHTML = "Loading";
  35762. this._loadingDiv.appendChild(this._loadingTextDiv);
  35763. //set the predefined text
  35764. this._loadingTextDiv.innerHTML = this._loadingText;
  35765. // Loading img
  35766. var imgBack = new Image();
  35767. 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==";
  35768. imgBack.style.position = "absolute";
  35769. imgBack.style.left = "50%";
  35770. imgBack.style.top = "50%";
  35771. imgBack.style.marginLeft = "-50px";
  35772. imgBack.style.marginTop = "-50px";
  35773. imgBack.style.transition = "transform 1.0s ease";
  35774. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35775. var deg = 360;
  35776. var onTransitionEnd = function () {
  35777. deg += 360;
  35778. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35779. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35780. };
  35781. imgBack.addEventListener("transitionend", onTransitionEnd);
  35782. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35783. this._loadingDiv.appendChild(imgBack);
  35784. // front image
  35785. var imgFront = new Image();
  35786. 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=";
  35787. imgFront.style.position = "absolute";
  35788. imgFront.style.left = "50%";
  35789. imgFront.style.top = "50%";
  35790. imgFront.style.marginLeft = "-50px";
  35791. imgFront.style.marginTop = "-50px";
  35792. this._loadingDiv.appendChild(imgFront);
  35793. this._resizeLoadingUI();
  35794. window.addEventListener("resize", this._resizeLoadingUI);
  35795. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35796. document.body.appendChild(this._loadingDiv);
  35797. setTimeout(function () {
  35798. _this._loadingDiv.style.opacity = "1";
  35799. imgBack.style.transform = "rotateZ(360deg)";
  35800. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35801. }, 0);
  35802. };
  35803. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35804. var _this = this;
  35805. if (!this._loadingDiv) {
  35806. return;
  35807. }
  35808. var onTransitionEnd = function () {
  35809. if (!_this._loadingDiv) {
  35810. return;
  35811. }
  35812. document.body.removeChild(_this._loadingDiv);
  35813. window.removeEventListener("resize", _this._resizeLoadingUI);
  35814. _this._loadingDiv = null;
  35815. };
  35816. this._loadingDiv.style.opacity = "0";
  35817. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35818. };
  35819. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35820. set: function (text) {
  35821. this._loadingText = text;
  35822. if (this._loadingTextDiv) {
  35823. this._loadingTextDiv.innerHTML = this._loadingText;
  35824. }
  35825. },
  35826. enumerable: true,
  35827. configurable: true
  35828. });
  35829. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35830. get: function () {
  35831. return this._loadingDivBackgroundColor;
  35832. },
  35833. set: function (color) {
  35834. this._loadingDivBackgroundColor = color;
  35835. if (!this._loadingDiv) {
  35836. return;
  35837. }
  35838. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35839. },
  35840. enumerable: true,
  35841. configurable: true
  35842. });
  35843. return DefaultLoadingScreen;
  35844. }());
  35845. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35846. })(BABYLON || (BABYLON = {}));
  35847. var BABYLON;
  35848. (function (BABYLON) {
  35849. var AudioEngine = (function () {
  35850. function AudioEngine() {
  35851. this._audioContext = null;
  35852. this._audioContextInitialized = false;
  35853. this.canUseWebAudio = false;
  35854. this.WarnedWebAudioUnsupported = false;
  35855. this.unlocked = false;
  35856. this.isMP3supported = false;
  35857. this.isOGGsupported = false;
  35858. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35859. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35860. this.canUseWebAudio = true;
  35861. }
  35862. var audioElem = document.createElement('audio');
  35863. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35864. this.isMP3supported = true;
  35865. }
  35866. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35867. this.isOGGsupported = true;
  35868. }
  35869. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35870. this._unlockiOSaudio();
  35871. }
  35872. else {
  35873. this.unlocked = true;
  35874. }
  35875. }
  35876. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35877. get: function () {
  35878. if (!this._audioContextInitialized) {
  35879. this._initializeAudioContext();
  35880. }
  35881. return this._audioContext;
  35882. },
  35883. enumerable: true,
  35884. configurable: true
  35885. });
  35886. AudioEngine.prototype._unlockiOSaudio = function () {
  35887. var _this = this;
  35888. var unlockaudio = function () {
  35889. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35890. var source = _this.audioContext.createBufferSource();
  35891. source.buffer = buffer;
  35892. source.connect(_this.audioContext.destination);
  35893. source.start(0);
  35894. setTimeout(function () {
  35895. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35896. _this.unlocked = true;
  35897. window.removeEventListener('touchend', unlockaudio, false);
  35898. if (_this.onAudioUnlocked) {
  35899. _this.onAudioUnlocked();
  35900. }
  35901. }
  35902. }, 0);
  35903. };
  35904. window.addEventListener('touchend', unlockaudio, false);
  35905. };
  35906. AudioEngine.prototype._initializeAudioContext = function () {
  35907. try {
  35908. if (this.canUseWebAudio) {
  35909. this._audioContext = new AudioContext();
  35910. // create a global volume gain node
  35911. this.masterGain = this._audioContext.createGain();
  35912. this.masterGain.gain.value = 1;
  35913. this.masterGain.connect(this._audioContext.destination);
  35914. this._audioContextInitialized = true;
  35915. }
  35916. }
  35917. catch (e) {
  35918. this.canUseWebAudio = false;
  35919. BABYLON.Tools.Error("Web Audio: " + e.message);
  35920. }
  35921. };
  35922. AudioEngine.prototype.dispose = function () {
  35923. if (this.canUseWebAudio && this._audioContextInitialized) {
  35924. if (this._connectedAnalyser) {
  35925. this._connectedAnalyser.stopDebugCanvas();
  35926. this._connectedAnalyser.dispose();
  35927. this.masterGain.disconnect();
  35928. this.masterGain.connect(this._audioContext.destination);
  35929. this._connectedAnalyser = null;
  35930. }
  35931. this.masterGain.gain.value = 1;
  35932. }
  35933. this.WarnedWebAudioUnsupported = false;
  35934. };
  35935. AudioEngine.prototype.getGlobalVolume = function () {
  35936. if (this.canUseWebAudio && this._audioContextInitialized) {
  35937. return this.masterGain.gain.value;
  35938. }
  35939. else {
  35940. return -1;
  35941. }
  35942. };
  35943. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35944. if (this.canUseWebAudio && this._audioContextInitialized) {
  35945. this.masterGain.gain.value = newVolume;
  35946. }
  35947. };
  35948. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35949. if (this._connectedAnalyser) {
  35950. this._connectedAnalyser.stopDebugCanvas();
  35951. }
  35952. if (this.canUseWebAudio && this._audioContextInitialized) {
  35953. this._connectedAnalyser = analyser;
  35954. this.masterGain.disconnect();
  35955. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35956. }
  35957. };
  35958. return AudioEngine;
  35959. }());
  35960. BABYLON.AudioEngine = AudioEngine;
  35961. })(BABYLON || (BABYLON = {}));
  35962. var BABYLON;
  35963. (function (BABYLON) {
  35964. var Sound = (function () {
  35965. /**
  35966. * Create a sound and attach it to a scene
  35967. * @param name Name of your sound
  35968. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35969. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35970. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35971. */
  35972. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35973. var _this = this;
  35974. this.autoplay = false;
  35975. this.loop = false;
  35976. this.useCustomAttenuation = false;
  35977. this.spatialSound = false;
  35978. this.refDistance = 1;
  35979. this.rolloffFactor = 1;
  35980. this.maxDistance = 100;
  35981. this.distanceModel = "linear";
  35982. this._panningModel = "equalpower";
  35983. this._playbackRate = 1;
  35984. this._streaming = false;
  35985. this._startTime = 0;
  35986. this._startOffset = 0;
  35987. this._position = BABYLON.Vector3.Zero();
  35988. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35989. this._volume = 1;
  35990. this._isLoaded = false;
  35991. this._isReadyToPlay = false;
  35992. this.isPlaying = false;
  35993. this.isPaused = false;
  35994. this._isDirectional = false;
  35995. // Used if you'd like to create a directional sound.
  35996. // If not set, the sound will be omnidirectional
  35997. this._coneInnerAngle = 360;
  35998. this._coneOuterAngle = 360;
  35999. this._coneOuterGain = 0;
  36000. this._isOutputConnected = false;
  36001. this._urlType = "Unknown";
  36002. this.name = name;
  36003. this._scene = scene;
  36004. this._readyToPlayCallback = readyToPlayCallback;
  36005. // Default custom attenuation function is a linear attenuation
  36006. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36007. if (currentDistance < maxDistance) {
  36008. return currentVolume * (1 - currentDistance / maxDistance);
  36009. }
  36010. else {
  36011. return 0;
  36012. }
  36013. };
  36014. if (options) {
  36015. this.autoplay = options.autoplay || false;
  36016. this.loop = options.loop || false;
  36017. // if volume === 0, we need another way to check this option
  36018. if (options.volume !== undefined) {
  36019. this._volume = options.volume;
  36020. }
  36021. this.spatialSound = options.spatialSound || false;
  36022. this.maxDistance = options.maxDistance || 100;
  36023. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36024. this.rolloffFactor = options.rolloffFactor || 1;
  36025. this.refDistance = options.refDistance || 1;
  36026. this.distanceModel = options.distanceModel || "linear";
  36027. this._playbackRate = options.playbackRate || 1;
  36028. this._streaming = options.streaming || false;
  36029. }
  36030. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36031. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36032. this._soundGain.gain.value = this._volume;
  36033. this._inputAudioNode = this._soundGain;
  36034. this._ouputAudioNode = this._soundGain;
  36035. if (this.spatialSound) {
  36036. this._createSpatialParameters();
  36037. }
  36038. this._scene.mainSoundTrack.AddSound(this);
  36039. var validParameter = true;
  36040. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36041. if (urlOrArrayBuffer) {
  36042. if (typeof (urlOrArrayBuffer) === "string")
  36043. this._urlType = "String";
  36044. if (Array.isArray(urlOrArrayBuffer))
  36045. this._urlType = "Array";
  36046. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36047. this._urlType = "ArrayBuffer";
  36048. var urls = [];
  36049. var codecSupportedFound = false;
  36050. switch (this._urlType) {
  36051. case "ArrayBuffer":
  36052. if (urlOrArrayBuffer.byteLength > 0) {
  36053. codecSupportedFound = true;
  36054. this._soundLoaded(urlOrArrayBuffer);
  36055. }
  36056. break;
  36057. case "String":
  36058. urls.push(urlOrArrayBuffer);
  36059. case "Array":
  36060. if (urls.length === 0)
  36061. urls = urlOrArrayBuffer;
  36062. // If we found a supported format, we load it immediately and stop the loop
  36063. for (var i = 0; i < urls.length; i++) {
  36064. var url = urls[i];
  36065. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36066. codecSupportedFound = true;
  36067. }
  36068. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36069. codecSupportedFound = true;
  36070. }
  36071. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36072. codecSupportedFound = true;
  36073. }
  36074. if (codecSupportedFound) {
  36075. // Loading sound using XHR2
  36076. if (!this._streaming) {
  36077. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36078. }
  36079. else {
  36080. this._htmlAudioElement = new Audio(url);
  36081. this._htmlAudioElement.controls = false;
  36082. this._htmlAudioElement.loop = this.loop;
  36083. this._htmlAudioElement.crossOrigin = "anonymous";
  36084. this._htmlAudioElement.preload = "auto";
  36085. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36086. _this._isReadyToPlay = true;
  36087. if (_this.autoplay) {
  36088. _this.play();
  36089. }
  36090. if (_this._readyToPlayCallback) {
  36091. _this._readyToPlayCallback();
  36092. }
  36093. });
  36094. document.body.appendChild(this._htmlAudioElement);
  36095. }
  36096. break;
  36097. }
  36098. }
  36099. break;
  36100. default:
  36101. validParameter = false;
  36102. break;
  36103. }
  36104. if (!validParameter) {
  36105. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36106. }
  36107. else {
  36108. if (!codecSupportedFound) {
  36109. this._isReadyToPlay = true;
  36110. // Simulating a ready to play event to avoid breaking code path
  36111. if (this._readyToPlayCallback) {
  36112. window.setTimeout(function () {
  36113. _this._readyToPlayCallback();
  36114. }, 1000);
  36115. }
  36116. }
  36117. }
  36118. }
  36119. }
  36120. else {
  36121. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36122. this._scene.mainSoundTrack.AddSound(this);
  36123. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36124. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36125. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36126. }
  36127. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36128. if (this._readyToPlayCallback) {
  36129. window.setTimeout(function () {
  36130. _this._readyToPlayCallback();
  36131. }, 1000);
  36132. }
  36133. }
  36134. }
  36135. Sound.prototype.dispose = function () {
  36136. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36137. if (this.isPlaying) {
  36138. this.stop();
  36139. }
  36140. this._isReadyToPlay = false;
  36141. if (this.soundTrackId === -1) {
  36142. this._scene.mainSoundTrack.RemoveSound(this);
  36143. }
  36144. else {
  36145. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36146. }
  36147. if (this._soundGain) {
  36148. this._soundGain.disconnect();
  36149. this._soundGain = null;
  36150. }
  36151. if (this._soundPanner) {
  36152. this._soundPanner.disconnect();
  36153. this._soundPanner = null;
  36154. }
  36155. if (this._soundSource) {
  36156. this._soundSource.disconnect();
  36157. this._soundSource = null;
  36158. }
  36159. this._audioBuffer = null;
  36160. if (this._htmlAudioElement) {
  36161. this._htmlAudioElement.pause();
  36162. this._htmlAudioElement.src = "";
  36163. document.body.removeChild(this._htmlAudioElement);
  36164. }
  36165. if (this._connectedMesh) {
  36166. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36167. this._connectedMesh = null;
  36168. }
  36169. }
  36170. };
  36171. Sound.prototype._soundLoaded = function (audioData) {
  36172. var _this = this;
  36173. this._isLoaded = true;
  36174. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36175. _this._audioBuffer = buffer;
  36176. _this._isReadyToPlay = true;
  36177. if (_this.autoplay) {
  36178. _this.play();
  36179. }
  36180. if (_this._readyToPlayCallback) {
  36181. _this._readyToPlayCallback();
  36182. }
  36183. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36184. };
  36185. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36187. this._audioBuffer = audioBuffer;
  36188. this._isReadyToPlay = true;
  36189. }
  36190. };
  36191. Sound.prototype.updateOptions = function (options) {
  36192. if (options) {
  36193. this.loop = options.loop || this.loop;
  36194. this.maxDistance = options.maxDistance || this.maxDistance;
  36195. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36196. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36197. this.refDistance = options.refDistance || this.refDistance;
  36198. this.distanceModel = options.distanceModel || this.distanceModel;
  36199. this._playbackRate = options.playbackRate || this._playbackRate;
  36200. this._updateSpatialParameters();
  36201. if (this.isPlaying) {
  36202. if (this._streaming) {
  36203. this._htmlAudioElement.playbackRate = this._playbackRate;
  36204. }
  36205. else {
  36206. this._soundSource.playbackRate.value = this._playbackRate;
  36207. }
  36208. }
  36209. }
  36210. };
  36211. Sound.prototype._createSpatialParameters = function () {
  36212. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36213. if (this._scene.headphone) {
  36214. this._panningModel = "HRTF";
  36215. }
  36216. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36217. this._updateSpatialParameters();
  36218. this._soundPanner.connect(this._ouputAudioNode);
  36219. this._inputAudioNode = this._soundPanner;
  36220. }
  36221. };
  36222. Sound.prototype._updateSpatialParameters = function () {
  36223. if (this.spatialSound) {
  36224. if (this.useCustomAttenuation) {
  36225. // Tricks to disable in a way embedded Web Audio attenuation
  36226. this._soundPanner.distanceModel = "linear";
  36227. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36228. this._soundPanner.refDistance = 1;
  36229. this._soundPanner.rolloffFactor = 1;
  36230. this._soundPanner.panningModel = this._panningModel;
  36231. }
  36232. else {
  36233. this._soundPanner.distanceModel = this.distanceModel;
  36234. this._soundPanner.maxDistance = this.maxDistance;
  36235. this._soundPanner.refDistance = this.refDistance;
  36236. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36237. this._soundPanner.panningModel = this._panningModel;
  36238. }
  36239. }
  36240. };
  36241. Sound.prototype.switchPanningModelToHRTF = function () {
  36242. this._panningModel = "HRTF";
  36243. this._switchPanningModel();
  36244. };
  36245. Sound.prototype.switchPanningModelToEqualPower = function () {
  36246. this._panningModel = "equalpower";
  36247. this._switchPanningModel();
  36248. };
  36249. Sound.prototype._switchPanningModel = function () {
  36250. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36251. this._soundPanner.panningModel = this._panningModel;
  36252. }
  36253. };
  36254. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36256. if (this._isOutputConnected) {
  36257. this._ouputAudioNode.disconnect();
  36258. }
  36259. this._ouputAudioNode.connect(soundTrackAudioNode);
  36260. this._isOutputConnected = true;
  36261. }
  36262. };
  36263. /**
  36264. * Transform this sound into a directional source
  36265. * @param coneInnerAngle Size of the inner cone in degree
  36266. * @param coneOuterAngle Size of the outer cone in degree
  36267. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36268. */
  36269. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36270. if (coneOuterAngle < coneInnerAngle) {
  36271. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36272. return;
  36273. }
  36274. this._coneInnerAngle = coneInnerAngle;
  36275. this._coneOuterAngle = coneOuterAngle;
  36276. this._coneOuterGain = coneOuterGain;
  36277. this._isDirectional = true;
  36278. if (this.isPlaying && this.loop) {
  36279. this.stop();
  36280. this.play();
  36281. }
  36282. };
  36283. Sound.prototype.setPosition = function (newPosition) {
  36284. this._position = newPosition;
  36285. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36286. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36287. }
  36288. };
  36289. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36290. this._localDirection = newLocalDirection;
  36291. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36292. this._updateDirection();
  36293. }
  36294. };
  36295. Sound.prototype._updateDirection = function () {
  36296. var mat = this._connectedMesh.getWorldMatrix();
  36297. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36298. direction.normalize();
  36299. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36300. };
  36301. Sound.prototype.updateDistanceFromListener = function () {
  36302. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36303. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36304. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36305. }
  36306. };
  36307. Sound.prototype.setAttenuationFunction = function (callback) {
  36308. this._customAttenuationFunction = callback;
  36309. };
  36310. /**
  36311. * Play the sound
  36312. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36313. * @param offset (optional) Start the sound setting it at a specific time
  36314. */
  36315. Sound.prototype.play = function (time, offset) {
  36316. var _this = this;
  36317. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36318. try {
  36319. if (this._startOffset < 0) {
  36320. time = -this._startOffset;
  36321. this._startOffset = 0;
  36322. }
  36323. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36324. if (!this._soundSource || !this._streamingSource) {
  36325. if (this.spatialSound) {
  36326. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36327. if (this._isDirectional) {
  36328. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36329. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36330. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36331. if (this._connectedMesh) {
  36332. this._updateDirection();
  36333. }
  36334. else {
  36335. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36336. }
  36337. }
  36338. }
  36339. }
  36340. if (this._streaming) {
  36341. if (!this._streamingSource) {
  36342. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36343. this._htmlAudioElement.onended = function () { _this._onended(); };
  36344. this._htmlAudioElement.playbackRate = this._playbackRate;
  36345. }
  36346. this._streamingSource.disconnect();
  36347. this._streamingSource.connect(this._inputAudioNode);
  36348. this._htmlAudioElement.play();
  36349. }
  36350. else {
  36351. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36352. this._soundSource.buffer = this._audioBuffer;
  36353. this._soundSource.connect(this._inputAudioNode);
  36354. this._soundSource.loop = this.loop;
  36355. this._soundSource.playbackRate.value = this._playbackRate;
  36356. this._soundSource.onended = function () { _this._onended(); };
  36357. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36358. }
  36359. this._startTime = startTime;
  36360. this.isPlaying = true;
  36361. this.isPaused = false;
  36362. }
  36363. catch (ex) {
  36364. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36365. }
  36366. }
  36367. };
  36368. Sound.prototype._onended = function () {
  36369. this.isPlaying = false;
  36370. if (this.onended) {
  36371. this.onended();
  36372. }
  36373. };
  36374. /**
  36375. * Stop the sound
  36376. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36377. */
  36378. Sound.prototype.stop = function (time) {
  36379. if (this.isPlaying) {
  36380. if (this._streaming) {
  36381. this._htmlAudioElement.pause();
  36382. // Test needed for Firefox or it will generate an Invalid State Error
  36383. if (this._htmlAudioElement.currentTime > 0) {
  36384. this._htmlAudioElement.currentTime = 0;
  36385. }
  36386. }
  36387. else {
  36388. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36389. this._soundSource.stop(stopTime);
  36390. this._soundSource.onended = null;
  36391. if (!this.isPaused) {
  36392. this._startOffset = 0;
  36393. }
  36394. }
  36395. this.isPlaying = false;
  36396. }
  36397. };
  36398. Sound.prototype.pause = function () {
  36399. if (this.isPlaying) {
  36400. this.isPaused = true;
  36401. if (this._streaming) {
  36402. this._htmlAudioElement.pause();
  36403. }
  36404. else {
  36405. this.stop(0);
  36406. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36407. }
  36408. }
  36409. };
  36410. Sound.prototype.setVolume = function (newVolume, time) {
  36411. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36412. if (time) {
  36413. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36414. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36415. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36416. }
  36417. else {
  36418. this._soundGain.gain.value = newVolume;
  36419. }
  36420. }
  36421. this._volume = newVolume;
  36422. };
  36423. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36424. this._playbackRate = newPlaybackRate;
  36425. if (this.isPlaying) {
  36426. if (this._streaming) {
  36427. this._htmlAudioElement.playbackRate = this._playbackRate;
  36428. }
  36429. else {
  36430. this._soundSource.playbackRate.value = this._playbackRate;
  36431. }
  36432. }
  36433. };
  36434. Sound.prototype.getVolume = function () {
  36435. return this._volume;
  36436. };
  36437. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36438. var _this = this;
  36439. if (this._connectedMesh) {
  36440. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36441. this._registerFunc = null;
  36442. }
  36443. this._connectedMesh = meshToConnectTo;
  36444. if (!this.spatialSound) {
  36445. this.spatialSound = true;
  36446. this._createSpatialParameters();
  36447. if (this.isPlaying && this.loop) {
  36448. this.stop();
  36449. this.play();
  36450. }
  36451. }
  36452. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36453. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36454. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36455. };
  36456. Sound.prototype.detachFromMesh = function () {
  36457. if (this._connectedMesh) {
  36458. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36459. this._registerFunc = null;
  36460. this._connectedMesh = null;
  36461. }
  36462. };
  36463. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36464. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36465. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36466. this._updateDirection();
  36467. }
  36468. };
  36469. Sound.prototype.clone = function () {
  36470. var _this = this;
  36471. if (!this._streaming) {
  36472. var setBufferAndRun = function () {
  36473. if (_this._isReadyToPlay) {
  36474. clonedSound._audioBuffer = _this.getAudioBuffer();
  36475. clonedSound._isReadyToPlay = true;
  36476. if (clonedSound.autoplay) {
  36477. clonedSound.play();
  36478. }
  36479. }
  36480. else {
  36481. window.setTimeout(setBufferAndRun, 300);
  36482. }
  36483. };
  36484. var currentOptions = {
  36485. autoplay: this.autoplay, loop: this.loop,
  36486. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36487. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36488. refDistance: this.refDistance, distanceModel: this.distanceModel
  36489. };
  36490. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36491. if (this.useCustomAttenuation) {
  36492. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36493. }
  36494. clonedSound.setPosition(this._position);
  36495. clonedSound.setPlaybackRate(this._playbackRate);
  36496. setBufferAndRun();
  36497. return clonedSound;
  36498. }
  36499. else {
  36500. return null;
  36501. }
  36502. };
  36503. Sound.prototype.getAudioBuffer = function () {
  36504. return this._audioBuffer;
  36505. };
  36506. Sound.prototype.serialize = function () {
  36507. var serializationObject = {
  36508. name: this.name,
  36509. url: this.name,
  36510. autoplay: this.autoplay,
  36511. loop: this.loop,
  36512. volume: this._volume,
  36513. spatialSound: this.spatialSound,
  36514. maxDistance: this.maxDistance,
  36515. rolloffFactor: this.rolloffFactor,
  36516. refDistance: this.refDistance,
  36517. distanceModel: this.distanceModel,
  36518. playbackRate: this._playbackRate,
  36519. panningModel: this._panningModel,
  36520. soundTrackId: this.soundTrackId
  36521. };
  36522. if (this.spatialSound) {
  36523. if (this._connectedMesh)
  36524. serializationObject.connectedMeshId = this._connectedMesh.id;
  36525. serializationObject.position = this._position.asArray();
  36526. serializationObject.refDistance = this.refDistance;
  36527. serializationObject.distanceModel = this.distanceModel;
  36528. serializationObject.isDirectional = this._isDirectional;
  36529. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36530. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36531. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36532. serializationObject.coneOuterGain = this._coneOuterGain;
  36533. }
  36534. return serializationObject;
  36535. };
  36536. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36537. var soundName = parsedSound.name;
  36538. var soundUrl;
  36539. if (parsedSound.url) {
  36540. soundUrl = rootUrl + parsedSound.url;
  36541. }
  36542. else {
  36543. soundUrl = rootUrl + soundName;
  36544. }
  36545. var options = {
  36546. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36547. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36548. rolloffFactor: parsedSound.rolloffFactor,
  36549. refDistance: parsedSound.refDistance,
  36550. distanceModel: parsedSound.distanceModel,
  36551. playbackRate: parsedSound.playbackRate
  36552. };
  36553. var newSound;
  36554. if (!sourceSound) {
  36555. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36556. scene._addPendingData(newSound);
  36557. }
  36558. else {
  36559. var setBufferAndRun = function () {
  36560. if (sourceSound._isReadyToPlay) {
  36561. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36562. newSound._isReadyToPlay = true;
  36563. if (newSound.autoplay) {
  36564. newSound.play();
  36565. }
  36566. }
  36567. else {
  36568. window.setTimeout(setBufferAndRun, 300);
  36569. }
  36570. };
  36571. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36572. setBufferAndRun();
  36573. }
  36574. if (parsedSound.position) {
  36575. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36576. newSound.setPosition(soundPosition);
  36577. }
  36578. if (parsedSound.isDirectional) {
  36579. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36580. if (parsedSound.localDirectionToMesh) {
  36581. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36582. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36583. }
  36584. }
  36585. if (parsedSound.connectedMeshId) {
  36586. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36587. if (connectedMesh) {
  36588. newSound.attachToMesh(connectedMesh);
  36589. }
  36590. }
  36591. return newSound;
  36592. };
  36593. return Sound;
  36594. }());
  36595. BABYLON.Sound = Sound;
  36596. })(BABYLON || (BABYLON = {}));
  36597. var BABYLON;
  36598. (function (BABYLON) {
  36599. var SoundTrack = (function () {
  36600. function SoundTrack(scene, options) {
  36601. this.id = -1;
  36602. this._isMainTrack = false;
  36603. this._isInitialized = false;
  36604. this._scene = scene;
  36605. this.soundCollection = new Array();
  36606. this._options = options;
  36607. if (!this._isMainTrack) {
  36608. this._scene.soundTracks.push(this);
  36609. this.id = this._scene.soundTracks.length - 1;
  36610. }
  36611. }
  36612. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36613. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36614. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36615. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36616. if (this._options) {
  36617. if (this._options.volume) {
  36618. this._outputAudioNode.gain.value = this._options.volume;
  36619. }
  36620. if (this._options.mainTrack) {
  36621. this._isMainTrack = this._options.mainTrack;
  36622. }
  36623. }
  36624. this._isInitialized = true;
  36625. }
  36626. };
  36627. SoundTrack.prototype.dispose = function () {
  36628. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36629. if (this._connectedAnalyser) {
  36630. this._connectedAnalyser.stopDebugCanvas();
  36631. }
  36632. while (this.soundCollection.length) {
  36633. this.soundCollection[0].dispose();
  36634. }
  36635. if (this._outputAudioNode) {
  36636. this._outputAudioNode.disconnect();
  36637. }
  36638. this._outputAudioNode = null;
  36639. }
  36640. };
  36641. SoundTrack.prototype.AddSound = function (sound) {
  36642. if (!this._isInitialized) {
  36643. this._initializeSoundTrackAudioGraph();
  36644. }
  36645. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36646. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36647. }
  36648. if (sound.soundTrackId) {
  36649. if (sound.soundTrackId === -1) {
  36650. this._scene.mainSoundTrack.RemoveSound(sound);
  36651. }
  36652. else {
  36653. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36654. }
  36655. }
  36656. this.soundCollection.push(sound);
  36657. sound.soundTrackId = this.id;
  36658. };
  36659. SoundTrack.prototype.RemoveSound = function (sound) {
  36660. var index = this.soundCollection.indexOf(sound);
  36661. if (index !== -1) {
  36662. this.soundCollection.splice(index, 1);
  36663. }
  36664. };
  36665. SoundTrack.prototype.setVolume = function (newVolume) {
  36666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36667. this._outputAudioNode.gain.value = newVolume;
  36668. }
  36669. };
  36670. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36671. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36672. for (var i = 0; i < this.soundCollection.length; i++) {
  36673. this.soundCollection[i].switchPanningModelToHRTF();
  36674. }
  36675. }
  36676. };
  36677. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36678. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36679. for (var i = 0; i < this.soundCollection.length; i++) {
  36680. this.soundCollection[i].switchPanningModelToEqualPower();
  36681. }
  36682. }
  36683. };
  36684. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36685. if (this._connectedAnalyser) {
  36686. this._connectedAnalyser.stopDebugCanvas();
  36687. }
  36688. this._connectedAnalyser = analyser;
  36689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36690. this._outputAudioNode.disconnect();
  36691. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36692. }
  36693. };
  36694. return SoundTrack;
  36695. }());
  36696. BABYLON.SoundTrack = SoundTrack;
  36697. })(BABYLON || (BABYLON = {}));
  36698. var BABYLON;
  36699. (function (BABYLON) {
  36700. /**
  36701. * Special Glow Blur post process only blurring the alpha channel
  36702. * It enforces keeping the most luminous color in the color channel.
  36703. */
  36704. var GlowBlurPostProcess = (function (_super) {
  36705. __extends(GlowBlurPostProcess, _super);
  36706. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  36707. var _this = this;
  36708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36709. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  36710. this.direction = direction;
  36711. this.blurWidth = blurWidth;
  36712. this.onApplyObservable.add(function (effect) {
  36713. effect.setFloat2("screenSize", _this.width, _this.height);
  36714. effect.setVector2("direction", _this.direction);
  36715. effect.setFloat("blurWidth", _this.blurWidth);
  36716. });
  36717. }
  36718. return GlowBlurPostProcess;
  36719. }(BABYLON.PostProcess));
  36720. /**
  36721. * The highlight layer Helps adding a glow effect around a mesh.
  36722. *
  36723. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  36724. * glowy meshes to your scene.
  36725. *
  36726. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  36727. */
  36728. var HighlightLayer = (function () {
  36729. /**
  36730. * Instantiates a new highlight Layer and references it to the scene..
  36731. * @param name The name of the layer
  36732. * @param scene The scene to use the layer in
  36733. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  36734. */
  36735. function HighlightLayer(name, scene, options) {
  36736. this._vertexBuffers = {};
  36737. this._mainTextureDesiredSize = { width: 0, height: 0 };
  36738. this._meshes = {};
  36739. this._maxSize = 0;
  36740. this._shouldRender = false;
  36741. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  36742. /**
  36743. * Specifies whether or not the inner glow is ACTIVE in the layer.
  36744. */
  36745. this.innerGlow = true;
  36746. /**
  36747. * Specifies whether or not the outer glow is ACTIVE in the layer.
  36748. */
  36749. this.outerGlow = true;
  36750. /**
  36751. * An event triggered when the highlight layer has been disposed.
  36752. * @type {BABYLON.Observable}
  36753. */
  36754. this.onDisposeObservable = new BABYLON.Observable();
  36755. /**
  36756. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  36757. * @type {BABYLON.Observable}
  36758. */
  36759. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  36760. /**
  36761. * An event triggered when the highlight layer is being blurred.
  36762. * @type {BABYLON.Observable}
  36763. */
  36764. this.onBeforeBlurObservable = new BABYLON.Observable();
  36765. /**
  36766. * An event triggered when the highlight layer has been blurred.
  36767. * @type {BABYLON.Observable}
  36768. */
  36769. this.onAfterBlurObservable = new BABYLON.Observable();
  36770. /**
  36771. * An event triggered when the glowing blurred texture is being merged in the scene.
  36772. * @type {BABYLON.Observable}
  36773. */
  36774. this.onBeforeComposeObservable = new BABYLON.Observable();
  36775. /**
  36776. * An event triggered when the glowing blurred texture has been merged in the scene.
  36777. * @type {BABYLON.Observable}
  36778. */
  36779. this.onAfterComposeObservable = new BABYLON.Observable();
  36780. /**
  36781. * An event triggered when the highlight layer changes its size.
  36782. * @type {BABYLON.Observable}
  36783. */
  36784. this.onSizeChangedObservable = new BABYLON.Observable();
  36785. this._scene = scene;
  36786. var engine = scene.getEngine();
  36787. this._engine = engine;
  36788. this._maxSize = this._engine.getCaps().maxTextureSize;
  36789. this._scene.highlightLayers.push(this);
  36790. // Warn on stencil.
  36791. if (!this._engine.isStencilEnable) {
  36792. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  36793. }
  36794. // Adapt options
  36795. this._options = options || {
  36796. mainTextureRatio: 0.25,
  36797. blurTextureSizeRatio: 0.5,
  36798. blurHorizontalSize: 1,
  36799. blurVerticalSize: 1,
  36800. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  36801. };
  36802. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  36803. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  36804. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  36805. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  36806. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  36807. // VBO
  36808. var vertices = [];
  36809. vertices.push(1, 1);
  36810. vertices.push(-1, 1);
  36811. vertices.push(-1, -1);
  36812. vertices.push(1, -1);
  36813. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36814. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  36815. // Indices
  36816. var indices = [];
  36817. indices.push(0);
  36818. indices.push(1);
  36819. indices.push(2);
  36820. indices.push(0);
  36821. indices.push(2);
  36822. indices.push(3);
  36823. this._indexBuffer = engine.createIndexBuffer(indices);
  36824. // Effect
  36825. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  36826. // Render target
  36827. this.setMainTextureSize();
  36828. // Create Textures and post processes
  36829. this.createTextureAndPostProcesses();
  36830. }
  36831. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  36832. /**
  36833. * Gets the horizontal size of the blur.
  36834. */
  36835. get: function () {
  36836. return this._horizontalBlurPostprocess.blurWidth;
  36837. },
  36838. /**
  36839. * Specifies the horizontal size of the blur.
  36840. */
  36841. set: function (value) {
  36842. this._horizontalBlurPostprocess.blurWidth = value;
  36843. },
  36844. enumerable: true,
  36845. configurable: true
  36846. });
  36847. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  36848. /**
  36849. * Gets the vertical size of the blur.
  36850. */
  36851. get: function () {
  36852. return this._verticalBlurPostprocess.blurWidth;
  36853. },
  36854. /**
  36855. * Specifies the vertical size of the blur.
  36856. */
  36857. set: function (value) {
  36858. this._verticalBlurPostprocess.blurWidth = value;
  36859. },
  36860. enumerable: true,
  36861. configurable: true
  36862. });
  36863. /**
  36864. * Creates the render target textures and post processes used in the highlight layer.
  36865. */
  36866. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  36867. var _this = this;
  36868. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  36869. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  36870. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  36871. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  36872. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  36873. width: this._mainTextureDesiredSize.width,
  36874. height: this._mainTextureDesiredSize.height
  36875. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36876. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36877. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36878. this._mainTexture.anisotropicFilteringLevel = 1;
  36879. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36880. this._mainTexture.renderParticles = false;
  36881. this._mainTexture.renderList = null;
  36882. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  36883. width: blurTextureWidth,
  36884. height: blurTextureHeight
  36885. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36886. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36887. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36888. this._blurTexture.anisotropicFilteringLevel = 16;
  36889. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36890. this._blurTexture.renderParticles = false;
  36891. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36892. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  36893. effect.setTexture("textureSampler", _this._mainTexture);
  36894. });
  36895. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36896. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  36897. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36898. });
  36899. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36900. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  36901. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36902. });
  36903. this._mainTexture.onAfterUnbindObservable.add(function () {
  36904. _this.onBeforeBlurObservable.notifyObservers(_this);
  36905. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  36906. _this.onAfterBlurObservable.notifyObservers(_this);
  36907. });
  36908. // Custom render function
  36909. var renderSubMesh = function (subMesh) {
  36910. var mesh = subMesh.getRenderingMesh();
  36911. var scene = _this._scene;
  36912. var engine = scene.getEngine();
  36913. // Culling
  36914. engine.setState(subMesh.getMaterial().backFaceCulling);
  36915. // Managing instances
  36916. var batch = mesh._getInstancesRenderList(subMesh._id);
  36917. if (batch.mustReturn) {
  36918. return;
  36919. }
  36920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  36921. var highlightLayerMesh = _this._meshes[mesh.id];
  36922. var material = subMesh.getMaterial();
  36923. var emissiveTexture = null;
  36924. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  36925. emissiveTexture = material.emissiveTexture;
  36926. }
  36927. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  36928. engine.enableEffect(_this._glowMapGenerationEffect);
  36929. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  36930. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  36931. if (highlightLayerMesh) {
  36932. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  36933. }
  36934. else {
  36935. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  36936. }
  36937. // Alpha test
  36938. if (material && material.needAlphaTesting()) {
  36939. var alphaTexture = material.getAlphaTestTexture();
  36940. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  36941. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36942. }
  36943. // Glow emissive only
  36944. if (emissiveTexture) {
  36945. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  36946. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  36947. }
  36948. // Bones
  36949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36950. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36951. }
  36952. // Draw
  36953. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  36954. }
  36955. else {
  36956. // Need to reset refresh rate of the shadowMap
  36957. _this._mainTexture.resetRefreshCounter();
  36958. }
  36959. };
  36960. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36961. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  36962. var index;
  36963. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36964. renderSubMesh(opaqueSubMeshes.data[index]);
  36965. }
  36966. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36967. renderSubMesh(alphaTestSubMeshes.data[index]);
  36968. }
  36969. for (index = 0; index < transparentSubMeshes.length; index++) {
  36970. renderSubMesh(transparentSubMeshes.data[index]);
  36971. }
  36972. };
  36973. this._mainTexture.onClearObservable.add(function (engine) {
  36974. engine.clear(HighlightLayer.neutralColor, true, true, true);
  36975. });
  36976. };
  36977. /**
  36978. * Checks for the readiness of the element composing the layer.
  36979. * @param subMesh the mesh to check for
  36980. * @param useInstances specify wether or not to use instances to render the mesh
  36981. * @param emissiveTexture the associated emissive texture used to generate the glow
  36982. * @return true if ready otherwise, false
  36983. */
  36984. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  36985. if (!subMesh.getMaterial().isReady()) {
  36986. return false;
  36987. }
  36988. var defines = [];
  36989. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36990. var mesh = subMesh.getMesh();
  36991. var material = subMesh.getMaterial();
  36992. var uv1 = false;
  36993. var uv2 = false;
  36994. // Alpha test
  36995. if (material && material.needAlphaTesting()) {
  36996. var alphaTexture = material.getAlphaTestTexture();
  36997. if (alphaTexture) {
  36998. defines.push("#define ALPHATEST");
  36999. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37000. alphaTexture.coordinatesIndex === 1) {
  37001. defines.push("#define DIFFUSEUV2");
  37002. uv2 = true;
  37003. }
  37004. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37005. defines.push("#define DIFFUSEUV1");
  37006. uv1 = true;
  37007. }
  37008. }
  37009. }
  37010. // Emissive
  37011. if (emissiveTexture) {
  37012. defines.push("#define EMISSIVE");
  37013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37014. emissiveTexture.coordinatesIndex === 1) {
  37015. defines.push("#define EMISSIVEUV2");
  37016. uv2 = true;
  37017. }
  37018. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37019. defines.push("#define EMISSIVEUV1");
  37020. uv1 = true;
  37021. }
  37022. }
  37023. if (uv1) {
  37024. attribs.push(BABYLON.VertexBuffer.UVKind);
  37025. defines.push("#define UV1");
  37026. }
  37027. if (uv2) {
  37028. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37029. defines.push("#define UV2");
  37030. }
  37031. // Bones
  37032. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37033. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37034. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37035. if (mesh.numBoneInfluencers > 4) {
  37036. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37037. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37038. }
  37039. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37040. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37041. }
  37042. else {
  37043. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37044. }
  37045. // Instances
  37046. if (useInstances) {
  37047. defines.push("#define INSTANCES");
  37048. attribs.push("world0");
  37049. attribs.push("world1");
  37050. attribs.push("world2");
  37051. attribs.push("world3");
  37052. }
  37053. // Get correct effect
  37054. var join = defines.join("\n");
  37055. if (this._cachedDefines !== join) {
  37056. this._cachedDefines = join;
  37057. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37058. }
  37059. return this._glowMapGenerationEffect.isReady();
  37060. };
  37061. /**
  37062. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37063. */
  37064. HighlightLayer.prototype.render = function () {
  37065. var currentEffect = this._glowMapMergeEffect;
  37066. // Check
  37067. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37068. return;
  37069. var engine = this._scene.getEngine();
  37070. this.onBeforeComposeObservable.notifyObservers(this);
  37071. // Render
  37072. engine.enableEffect(currentEffect);
  37073. engine.setState(false);
  37074. // Cache
  37075. var previousStencilBuffer = engine.getStencilBuffer();
  37076. var previousStencilFunction = engine.getStencilFunction();
  37077. var previousStencilMask = engine.getStencilMask();
  37078. var previousAlphaMode = engine.getAlphaMode();
  37079. // Texture
  37080. currentEffect.setTexture("textureSampler", this._blurTexture);
  37081. // VBOs
  37082. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37083. // Draw order
  37084. engine.setAlphaMode(this._options.alphaBlendingMode);
  37085. engine.setStencilMask(0x00);
  37086. engine.setStencilBuffer(true);
  37087. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37088. if (this.outerGlow) {
  37089. currentEffect.setFloat("offset", 0);
  37090. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37091. engine.draw(true, 0, 6);
  37092. }
  37093. if (this.innerGlow) {
  37094. currentEffect.setFloat("offset", 1);
  37095. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37096. engine.draw(true, 0, 6);
  37097. }
  37098. // Restore Cache
  37099. engine.setStencilFunction(previousStencilFunction);
  37100. engine.setStencilMask(previousStencilMask);
  37101. engine.setAlphaMode(previousAlphaMode);
  37102. engine.setStencilBuffer(previousStencilBuffer);
  37103. this.onAfterComposeObservable.notifyObservers(this);
  37104. // Handle size changes.
  37105. var size = this._mainTexture.getSize();
  37106. this.setMainTextureSize();
  37107. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37108. // Recreate RTT and post processes on size change.
  37109. this.onSizeChangedObservable.notifyObservers(this);
  37110. this.disposeTextureAndPostProcesses();
  37111. this.createTextureAndPostProcesses();
  37112. }
  37113. };
  37114. /**
  37115. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37116. * @param mesh The mesh to highlight
  37117. * @param color The color of the highlight
  37118. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37119. */
  37120. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37121. var _this = this;
  37122. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37123. var meshHighlight = this._meshes[mesh.id];
  37124. if (meshHighlight) {
  37125. meshHighlight.color = color;
  37126. }
  37127. else {
  37128. this._meshes[mesh.id] = {
  37129. mesh: mesh,
  37130. color: color,
  37131. // Lambda required for capture due to Observable this context
  37132. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37133. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37134. }),
  37135. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37136. glowEmissiveOnly: glowEmissiveOnly
  37137. };
  37138. }
  37139. this._shouldRender = true;
  37140. };
  37141. /**
  37142. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37143. * @param mesh The mesh to highlight
  37144. */
  37145. HighlightLayer.prototype.removeMesh = function (mesh) {
  37146. var meshHighlight = this._meshes[mesh.id];
  37147. if (meshHighlight) {
  37148. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37149. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37150. }
  37151. this._meshes[mesh.id] = undefined;
  37152. this._shouldRender = false;
  37153. for (var meshHighlightToCheck in this._meshes) {
  37154. if (meshHighlightToCheck) {
  37155. this._shouldRender = true;
  37156. break;
  37157. }
  37158. }
  37159. };
  37160. /**
  37161. * Returns true if the layer contains information to display, otherwise false.
  37162. */
  37163. HighlightLayer.prototype.shouldRender = function () {
  37164. return this._shouldRender;
  37165. };
  37166. /**
  37167. * Sets the main texture desired size which is the closest power of two
  37168. * of the engine canvas size.
  37169. */
  37170. HighlightLayer.prototype.setMainTextureSize = function () {
  37171. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37172. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37173. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37174. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37175. };
  37176. /**
  37177. * Force the stencil to the normal expected value for none glowing parts
  37178. */
  37179. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37180. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37181. };
  37182. /**
  37183. * Dispose only the render target textures and post process.
  37184. */
  37185. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37186. this._blurTexture.dispose();
  37187. this._mainTexture.dispose();
  37188. this._downSamplePostprocess.dispose();
  37189. this._horizontalBlurPostprocess.dispose();
  37190. this._verticalBlurPostprocess.dispose();
  37191. };
  37192. /**
  37193. * Dispose the highlight layer and free resources.
  37194. */
  37195. HighlightLayer.prototype.dispose = function () {
  37196. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37197. if (vertexBuffer) {
  37198. vertexBuffer.dispose();
  37199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37200. }
  37201. if (this._indexBuffer) {
  37202. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37203. this._indexBuffer = null;
  37204. }
  37205. // Clean textures and post processes
  37206. this.disposeTextureAndPostProcesses();
  37207. // Clean mesh references
  37208. for (var id in this._meshes) {
  37209. var meshHighlight = this._meshes[id];
  37210. if (meshHighlight && meshHighlight.mesh) {
  37211. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37212. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37213. }
  37214. }
  37215. this._meshes = null;
  37216. // Remove from scene
  37217. var index = this._scene.highlightLayers.indexOf(this, 0);
  37218. if (index > -1) {
  37219. this._scene.highlightLayers.splice(index, 1);
  37220. }
  37221. // Callback
  37222. this.onDisposeObservable.notifyObservers(this);
  37223. this.onDisposeObservable.clear();
  37224. this.onBeforeRenderMainTextureObservable.clear();
  37225. this.onBeforeBlurObservable.clear();
  37226. this.onBeforeComposeObservable.clear();
  37227. this.onAfterComposeObservable.clear();
  37228. this.onSizeChangedObservable.clear();
  37229. };
  37230. /**
  37231. * The neutral color used during the preparation of the glow effect.
  37232. * This is black by default as the blend operation is a blend operation.
  37233. */
  37234. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37235. /**
  37236. * Stencil value used for glowing meshes.
  37237. */
  37238. HighlightLayer.glowingMeshStencilReference = 0x02;
  37239. /**
  37240. * Stencil value used for the other meshes in the scene.
  37241. */
  37242. HighlightLayer.normalMeshStencilReference = 0x01;
  37243. return HighlightLayer;
  37244. }());
  37245. BABYLON.HighlightLayer = HighlightLayer;
  37246. })(BABYLON || (BABYLON = {}));
  37247. var BABYLON;
  37248. (function (BABYLON) {
  37249. var SIMDVector3 = (function () {
  37250. function SIMDVector3() {
  37251. }
  37252. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37253. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37254. };
  37255. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37256. var m = transformation.m;
  37257. var m0 = SIMD.Float32x4.load(m, 0);
  37258. var m1 = SIMD.Float32x4.load(m, 4);
  37259. var m2 = SIMD.Float32x4.load(m, 8);
  37260. var m3 = SIMD.Float32x4.load(m, 12);
  37261. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  37262. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37263. result.x = SIMD.Float32x4.extractLane(r, 0);
  37264. result.y = SIMD.Float32x4.extractLane(r, 1);
  37265. result.z = SIMD.Float32x4.extractLane(r, 2);
  37266. };
  37267. return SIMDVector3;
  37268. }());
  37269. var SIMDMatrix = (function () {
  37270. function SIMDMatrix() {
  37271. }
  37272. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37273. var tm = this.m;
  37274. var om = other.m;
  37275. var m0 = SIMD.Float32x4.load(om, 0);
  37276. var m1 = SIMD.Float32x4.load(om, 4);
  37277. var m2 = SIMD.Float32x4.load(om, 8);
  37278. var m3 = SIMD.Float32x4.load(om, 12);
  37279. for (var i = 0; i < 16; i += 4) {
  37280. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  37281. }
  37282. return this;
  37283. };
  37284. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37285. var src = this.m;
  37286. var dest = other.m;
  37287. // Load the 4 rows
  37288. var src0 = SIMD.Float32x4.load(src, 0);
  37289. var src1 = SIMD.Float32x4.load(src, 4);
  37290. var src2 = SIMD.Float32x4.load(src, 8);
  37291. var src3 = SIMD.Float32x4.load(src, 12);
  37292. // Transpose the source matrix. Sort of. Not a true transpose operation
  37293. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37294. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37295. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37296. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37297. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37298. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37299. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37300. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37301. // This is a true transposition, but it will lead to an incorrect result
  37302. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37303. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37304. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37305. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37306. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37307. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37308. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37309. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37310. // ----
  37311. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37312. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37313. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37314. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37315. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37316. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37317. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37318. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37319. // ----
  37320. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37321. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37322. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37323. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37324. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37325. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37326. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37327. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37328. // ----
  37329. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37330. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37331. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37332. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37333. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37334. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37335. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37336. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37337. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37338. // ----
  37339. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37340. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37341. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37342. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37343. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37344. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37345. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37346. // ----
  37347. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37348. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37349. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37350. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37351. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37352. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37353. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37354. // ----
  37355. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37356. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37357. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37358. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37359. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37360. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37361. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37362. // Compute determinant
  37363. var det = SIMD.Float32x4.mul(row0, minor0);
  37364. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37365. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37366. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37367. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37368. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37369. // These shuffles aren't necessary if the faulty transposition is done
  37370. // up at the top of this function.
  37371. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37372. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37373. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37374. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37375. // Compute final values by multiplying with 1/det
  37376. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37377. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37378. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37379. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37380. return this;
  37381. };
  37382. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37383. var out = result.m;
  37384. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37385. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37386. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37387. // cc.kmVec3Subtract(f, pCenter, pEye);
  37388. var f = SIMD.Float32x4.sub(center, eye);
  37389. // cc.kmVec3Normalize(f, f);
  37390. var tmp = SIMD.Float32x4.mul(f, f);
  37391. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37392. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37393. // cc.kmVec3Assign(up, pUp);
  37394. // cc.kmVec3Normalize(up, up);
  37395. tmp = SIMD.Float32x4.mul(up, up);
  37396. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37397. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37398. // cc.kmVec3Cross(s, f, up);
  37399. 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)));
  37400. // cc.kmVec3Normalize(s, s);
  37401. tmp = SIMD.Float32x4.mul(s, s);
  37402. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37403. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37404. // cc.kmVec3Cross(u, s, f);
  37405. 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)));
  37406. // cc.kmVec3Normalize(s, s);
  37407. tmp = SIMD.Float32x4.mul(s, s);
  37408. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37409. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37410. var zero = SIMD.Float32x4.splat(0.0);
  37411. s = SIMD.Float32x4.neg(s);
  37412. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37413. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37414. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37415. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37416. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  37417. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37418. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37419. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37420. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37421. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37422. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37423. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37424. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37425. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37426. };
  37427. return SIMDMatrix;
  37428. }());
  37429. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37430. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37431. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37432. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37433. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37434. var SIMDHelper = (function () {
  37435. function SIMDHelper() {
  37436. }
  37437. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37438. get: function () {
  37439. return SIMDHelper._isEnabled;
  37440. },
  37441. enumerable: true,
  37442. configurable: true
  37443. });
  37444. SIMDHelper.DisableSIMD = function () {
  37445. // Replace functions
  37446. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37447. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37448. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37449. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37450. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37451. SIMDHelper._isEnabled = false;
  37452. };
  37453. SIMDHelper.EnableSIMD = function () {
  37454. if (self.SIMD === undefined) {
  37455. return;
  37456. }
  37457. // check if polyfills needed
  37458. if (!self.Math.fround) {
  37459. self.Math.fround = (function (array) { return function (x) {
  37460. return array[0] = x, array[0];
  37461. }; })(new Float32Array(1));
  37462. }
  37463. if (!self.Math.imul) {
  37464. self.Math.imul = function (a, b) {
  37465. var ah = (a >>> 16) & 0xffff;
  37466. var al = a & 0xffff;
  37467. var bh = (b >>> 16) & 0xffff;
  37468. var bl = b & 0xffff;
  37469. // the shift by 0 fixes the sign on the high part
  37470. // the final |0 converts the unsigned value into a signed value
  37471. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37472. };
  37473. }
  37474. // Replace functions
  37475. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37476. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37477. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37478. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37480. SIMDHelper._isEnabled = true;
  37481. };
  37482. SIMDHelper._isEnabled = false;
  37483. return SIMDHelper;
  37484. }());
  37485. BABYLON.SIMDHelper = SIMDHelper;
  37486. })(BABYLON || (BABYLON = {}));
  37487. var BABYLON;
  37488. (function (BABYLON) {
  37489. /**
  37490. * This class describe a rectangle that were added to the map.
  37491. * You have access to its coordinates either in pixel or normalized (UV)
  37492. */
  37493. var PackedRect = (function () {
  37494. function PackedRect(root, parent, pos, size) {
  37495. this._pos = pos;
  37496. this._size = size;
  37497. this._root = root;
  37498. this._parent = parent;
  37499. }
  37500. Object.defineProperty(PackedRect.prototype, "pos", {
  37501. /**
  37502. * @returns the position of this node into the map
  37503. */
  37504. get: function () {
  37505. return this._pos;
  37506. },
  37507. enumerable: true,
  37508. configurable: true
  37509. });
  37510. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37511. /**
  37512. * @returns the size of the rectangle this node handles
  37513. */
  37514. get: function () {
  37515. return this._contentSize;
  37516. },
  37517. enumerable: true,
  37518. configurable: true
  37519. });
  37520. Object.defineProperty(PackedRect.prototype, "UVs", {
  37521. /**
  37522. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37523. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37524. */
  37525. get: function () {
  37526. return this.getUVsForCustomSize(this._root._size);
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. /**
  37532. * 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.
  37533. * This method will return the UVs for this part by given the custom size of what you really use
  37534. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37535. */
  37536. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37537. var mainWidth = this._root._size.width;
  37538. var mainHeight = this._root._size.height;
  37539. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37540. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37541. var uvs = new Array();
  37542. uvs.push(topLeft);
  37543. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37544. uvs.push(rightBottom);
  37545. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37546. return uvs;
  37547. };
  37548. /**
  37549. * Free this rectangle from the map.
  37550. * Call this method when you no longer need the rectangle to be in the map.
  37551. */
  37552. PackedRect.prototype.freeContent = function () {
  37553. if (!this.contentSize) {
  37554. return;
  37555. }
  37556. this._contentSize = null;
  37557. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37558. this.attemptDefrag();
  37559. };
  37560. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37561. get: function () {
  37562. return this._contentSize != null || this._leftNode != null;
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37568. var node = this.findNode(contentSize);
  37569. // Not enough space...
  37570. if (!node) {
  37571. return null;
  37572. }
  37573. node.splitNode(contentSize);
  37574. return node;
  37575. };
  37576. PackedRect.prototype.findNode = function (size) {
  37577. var resNode = null;
  37578. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37579. if (this.isUsed) {
  37580. if (this._leftNode) {
  37581. resNode = this._leftNode.findNode(size);
  37582. }
  37583. if (!resNode && this._rightNode) {
  37584. resNode = this._rightNode.findNode(size);
  37585. }
  37586. if (!resNode && this._bottomNode) {
  37587. resNode = this._bottomNode.findNode(size);
  37588. }
  37589. }
  37590. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37591. resNode = this;
  37592. }
  37593. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37594. resNode = this;
  37595. }
  37596. return resNode;
  37597. };
  37598. PackedRect.prototype.splitNode = function (contentSize) {
  37599. // 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)
  37600. if (!this._contentSize && this._initialSize) {
  37601. 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));
  37602. return this._leftNode.splitNode(contentSize);
  37603. }
  37604. else {
  37605. this._contentSize = contentSize.clone();
  37606. this._initialSize = contentSize.clone();
  37607. if (contentSize.width !== this._size.width) {
  37608. 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));
  37609. }
  37610. if (contentSize.height !== this._size.height) {
  37611. 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));
  37612. }
  37613. return this;
  37614. }
  37615. };
  37616. PackedRect.prototype.attemptDefrag = function () {
  37617. if (!this.isUsed && this.isRecursiveFree) {
  37618. this.clearNode();
  37619. if (this._parent) {
  37620. this._parent.attemptDefrag();
  37621. }
  37622. }
  37623. };
  37624. PackedRect.prototype.clearNode = function () {
  37625. this._initialSize = null;
  37626. this._rightNode = null;
  37627. this._bottomNode = null;
  37628. };
  37629. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37630. get: function () {
  37631. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37632. },
  37633. enumerable: true,
  37634. configurable: true
  37635. });
  37636. PackedRect.prototype.evalFreeSize = function (size) {
  37637. var levelSize = 0;
  37638. if (!this.isUsed) {
  37639. if (this._initialSize) {
  37640. levelSize = this._initialSize.surface;
  37641. }
  37642. else {
  37643. levelSize = this._size.surface;
  37644. }
  37645. }
  37646. if (this._rightNode) {
  37647. levelSize += this._rightNode.evalFreeSize(0);
  37648. }
  37649. if (this._bottomNode) {
  37650. levelSize += this._bottomNode.evalFreeSize(0);
  37651. }
  37652. return levelSize + size;
  37653. };
  37654. return PackedRect;
  37655. }());
  37656. BABYLON.PackedRect = PackedRect;
  37657. /**
  37658. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37659. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37660. * 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.
  37661. */
  37662. var RectPackingMap = (function (_super) {
  37663. __extends(RectPackingMap, _super);
  37664. /**
  37665. * Create an instance of the object with a dimension using the given size
  37666. * @param size The dimension of the rectangle that will contain all the sub ones.
  37667. */
  37668. function RectPackingMap(size) {
  37669. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37670. this._root = this;
  37671. }
  37672. /**
  37673. * Add a rectangle, finding the best location to store it into the map
  37674. * @param size the dimension of the rectangle to store
  37675. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37676. */
  37677. RectPackingMap.prototype.addRect = function (size) {
  37678. var node = this.findAndSplitNode(size);
  37679. return node;
  37680. };
  37681. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37682. /**
  37683. * Return the current space free normalized between [0;1]
  37684. * @returns {}
  37685. */
  37686. get: function () {
  37687. var freeSize = 0;
  37688. freeSize = this.evalFreeSize(freeSize);
  37689. return freeSize / (this._size.width * this._size.height);
  37690. },
  37691. enumerable: true,
  37692. configurable: true
  37693. });
  37694. return RectPackingMap;
  37695. }(PackedRect));
  37696. BABYLON.RectPackingMap = RectPackingMap;
  37697. })(BABYLON || (BABYLON = {}));
  37698. var BABYLON;
  37699. (function (BABYLON) {
  37700. var DynamicFloatArrayElementInfo = (function () {
  37701. function DynamicFloatArrayElementInfo() {
  37702. }
  37703. return DynamicFloatArrayElementInfo;
  37704. }());
  37705. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37706. /**
  37707. * 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.
  37708. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37709. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37710. * 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.
  37711. * 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.
  37712. * 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".
  37713. */
  37714. var DynamicFloatArray = (function () {
  37715. /**
  37716. * Construct an instance of the dynamic float array
  37717. * @param stride size of one element in float (i.e. not bytes!)
  37718. * @param initialElementCount the number of available entries at construction
  37719. */
  37720. function DynamicFloatArray(stride, initialElementCount) {
  37721. this.compareValueOffset = null;
  37722. this.sortingAscending = true;
  37723. this._stride = stride;
  37724. this.buffer = new Float32Array(stride * initialElementCount);
  37725. this._lastUsed = 0;
  37726. this._firstFree = 0;
  37727. this._allEntries = new Array(initialElementCount);
  37728. this._freeEntries = new Array(initialElementCount);
  37729. for (var i = 0; i < initialElementCount; i++) {
  37730. var element = new DynamicFloatArrayElementInfo();
  37731. element.offset = i * stride;
  37732. this._allEntries[i] = element;
  37733. this._freeEntries[initialElementCount - i - 1] = element;
  37734. }
  37735. }
  37736. /**
  37737. * Allocate an element in the array.
  37738. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37739. * Beware, this offset may change when you call pack()
  37740. */
  37741. DynamicFloatArray.prototype.allocElement = function () {
  37742. if (this._freeEntries.length === 0) {
  37743. this._growBuffer();
  37744. }
  37745. var el = this._freeEntries.pop();
  37746. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37747. if (el.offset === this._firstFree) {
  37748. if (this._freeEntries.length > 0) {
  37749. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37750. }
  37751. else {
  37752. this._firstFree += this._stride;
  37753. }
  37754. }
  37755. return el;
  37756. };
  37757. /**
  37758. * Free the element corresponding to the given element info
  37759. * @param elInfo the element that describe the allocated element
  37760. */
  37761. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37762. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37763. this._freeEntries.push(elInfo);
  37764. };
  37765. /**
  37766. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37767. * 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().
  37768. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37769. */
  37770. DynamicFloatArray.prototype.pack = function () {
  37771. // no free slot? no need to pack
  37772. if (this._freeEntries.length === 0) {
  37773. return this.buffer;
  37774. }
  37775. // If the buffer is already packed the last used will always be lower than the first free
  37776. // 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.
  37777. if (this._lastUsed < this._firstFree) {
  37778. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37779. return elementsBuffer_1;
  37780. }
  37781. var s = this._stride;
  37782. // 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
  37783. var lastFree = new DynamicFloatArrayElementInfo();
  37784. lastFree.offset = this.totalElementCount * s;
  37785. this._freeEntries.push(lastFree);
  37786. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37787. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37788. var firstFreeSlotOffset = sortedFree[0].offset;
  37789. var freeZoneSize = 1;
  37790. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37791. var prevOffset = sortedFree[0].offset;
  37792. for (var i = 1; i < sortedFree.length; i++) {
  37793. // 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
  37794. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37795. break;
  37796. }
  37797. var curFree = sortedFree[i];
  37798. var curOffset = curFree.offset;
  37799. // Compute the distance between this offset and the previous
  37800. var distance = curOffset - prevOffset;
  37801. // If the distance is the stride size, they are adjacent, it good, move to the next
  37802. if (distance === s) {
  37803. // Free zone is one element bigger
  37804. ++freeZoneSize;
  37805. // as we're about to iterate to the next, the cur becomes the previous...
  37806. prevOffset = curOffset;
  37807. continue;
  37808. }
  37809. // Distance is bigger, which means there's x element between the previous free and this one
  37810. var usedRange = (distance / s) - 1;
  37811. // Two cases the free zone is smaller than the data to move or bigger
  37812. // Copy what can fit in the free zone
  37813. var curMoveOffset = curOffset - s;
  37814. var copyCount = Math.min(freeZoneSize, usedRange);
  37815. for (var j = 0; j < copyCount; j++) {
  37816. var freeI = firstFreeSlotOffset / s;
  37817. var curI = curMoveOffset / s;
  37818. var moveEl = sortedAll[curI];
  37819. this._moveElement(moveEl, firstFreeSlotOffset);
  37820. var replacedEl = sortedAll[freeI];
  37821. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37822. replacedEl.offset = curMoveOffset;
  37823. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37824. sortedAll[freeI] = moveEl;
  37825. sortedAll[curI] = replacedEl;
  37826. curMoveOffset -= s;
  37827. firstFreeSlotOffset += s;
  37828. }
  37829. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37830. if (freeZoneSize <= usedRange) {
  37831. firstFreeSlotOffset = curMoveOffset + s;
  37832. freeZoneSize = 1 + copyCount;
  37833. }
  37834. else {
  37835. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37836. }
  37837. // as we're about to iterate to the next, the cur becomes the previous...
  37838. prevOffset = curOffset;
  37839. }
  37840. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37841. this._lastUsed = firstFreeSlotOffset - s;
  37842. this._firstFree = firstFreeSlotOffset;
  37843. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37844. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37845. this._allEntries = sortedAll;
  37846. return elementsBuffer;
  37847. };
  37848. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37849. for (var i = 0; i < this._stride; i++) {
  37850. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37851. }
  37852. element.offset = destOffset;
  37853. };
  37854. DynamicFloatArray.prototype._growBuffer = function () {
  37855. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37856. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37857. var newBuffer = new Float32Array(newElCount * this._stride);
  37858. newBuffer.set(this.buffer);
  37859. var curCount = this.totalElementCount;
  37860. var addedCount = newElCount - this.totalElementCount;
  37861. for (var i = 0; i < addedCount; i++) {
  37862. var element = new DynamicFloatArrayElementInfo();
  37863. element.offset = (curCount + i) * this.stride;
  37864. this._allEntries.push(element);
  37865. this._freeEntries[addedCount - i - 1] = element;
  37866. }
  37867. this._firstFree = curCount * this.stride;
  37868. this.buffer = newBuffer;
  37869. };
  37870. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37871. /**
  37872. * Get the total count of entries that can fit in the current buffer
  37873. * @returns the elements count
  37874. */
  37875. get: function () {
  37876. return this._allEntries.length;
  37877. },
  37878. enumerable: true,
  37879. configurable: true
  37880. });
  37881. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37882. /**
  37883. * Get the count of free entries that can still be allocated without resizing the buffer
  37884. * @returns the free elements count
  37885. */
  37886. get: function () {
  37887. return this._freeEntries.length;
  37888. },
  37889. enumerable: true,
  37890. configurable: true
  37891. });
  37892. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37893. /**
  37894. * Get the count of allocated elements
  37895. * @returns the allocated elements count
  37896. */
  37897. get: function () {
  37898. return this._allEntries.length - this._freeEntries.length;
  37899. },
  37900. enumerable: true,
  37901. configurable: true
  37902. });
  37903. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37904. /**
  37905. * Return the size of one element in float
  37906. * @returns the size in float
  37907. */
  37908. get: function () {
  37909. return this._stride;
  37910. },
  37911. enumerable: true,
  37912. configurable: true
  37913. });
  37914. DynamicFloatArray.prototype.sort = function () {
  37915. var _this = this;
  37916. if (!this.compareValueOffset) {
  37917. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37918. }
  37919. var count = this.usedElementCount;
  37920. // Do we have to (re)create the sort table?
  37921. if (!this._sortTable || this._sortTable.length < count) {
  37922. // 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...
  37923. var newCount = Math.min(this.totalElementCount, count * 2);
  37924. this._sortTable = new Array(newCount);
  37925. }
  37926. if (!this._sortedTable || this._sortedTable.length !== count) {
  37927. this._sortedTable = new Array(count);
  37928. }
  37929. // Because, you know...
  37930. this.pack();
  37931. //let stride = this.stride;
  37932. //for (let i = 0; i < count; i++) {
  37933. // let si = this._sortTable[i];
  37934. // if (!si) {
  37935. // si = new SortInfo();
  37936. // this._sortTable[i] = si;
  37937. // }
  37938. // si.entry = this._allEntries[i];
  37939. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37940. // si.swapedOffset = null;
  37941. // this._sortedTable[i] = si;
  37942. //}
  37943. var curOffset = 0;
  37944. var stride = this.stride;
  37945. for (var i = 0; i < count; i++, curOffset += stride) {
  37946. var si = this._sortTable[i];
  37947. if (!si) {
  37948. si = new SortInfo();
  37949. this._sortTable[i] = si;
  37950. }
  37951. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37952. si.offset = curOffset;
  37953. si.swapedOffset = null;
  37954. this._sortedTable[i] = si;
  37955. }
  37956. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37957. if (this.sortingAscending) {
  37958. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37959. }
  37960. else {
  37961. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37962. }
  37963. var swapElements = function (src, dst) {
  37964. for (var i = 0; i < stride; i++) {
  37965. var tps = _this.buffer[dst + i];
  37966. _this.buffer[dst + i] = _this.buffer[src + i];
  37967. _this.buffer[src + i] = tps;
  37968. }
  37969. };
  37970. // 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:
  37971. // 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),
  37972. // and I still want something with a good algorithm complexity.
  37973. // 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,
  37974. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37975. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37976. // 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
  37977. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37978. // 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
  37979. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37980. for (var i = 0; i < count; i++) {
  37981. // Get the element to move
  37982. var sourceSI = this._sortedTable[i];
  37983. var destSI = this._sortTable[i];
  37984. var sourceOff = sourceSI.offset;
  37985. // If the source changed location, find the new one
  37986. if (sourceSI.swapedOffset) {
  37987. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37988. var curSI = sourceSI;
  37989. while (curSI.swapedOffset) {
  37990. curSI = this._sortTable[curSI.swapedOffset / stride];
  37991. }
  37992. // Finally get the right location
  37993. sourceOff = curSI.offset;
  37994. }
  37995. // Tag the element being replaced with its new location
  37996. destSI.swapedOffset = sourceOff;
  37997. // Swap elements (only if needed)
  37998. if (sourceOff !== destSI.offset) {
  37999. swapElements(sourceOff, destSI.offset);
  38000. }
  38001. // Update the offset in the corresponding DFAE
  38002. //sourceSI.entry.offset = destSI.entry.offset;
  38003. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38004. }
  38005. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38006. return true;
  38007. };
  38008. return DynamicFloatArray;
  38009. }());
  38010. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38011. var SortInfo = (function () {
  38012. function SortInfo() {
  38013. this.compareData = this.offset = this.swapedOffset = null;
  38014. }
  38015. return SortInfo;
  38016. }());
  38017. })(BABYLON || (BABYLON = {}));
  38018. var BABYLON;
  38019. (function (BABYLON) {
  38020. /**
  38021. * This class given information about a given character.
  38022. */
  38023. var CharInfo = (function () {
  38024. function CharInfo() {
  38025. }
  38026. return CharInfo;
  38027. }());
  38028. BABYLON.CharInfo = CharInfo;
  38029. var FontTexture = (function (_super) {
  38030. __extends(FontTexture, _super);
  38031. /**
  38032. * Create a new instance of the FontTexture class
  38033. * @param name the name of the texture
  38034. * @param font the font to use, use the W3C CSS notation
  38035. * @param scene the scene that owns the texture
  38036. * @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
  38037. * @param samplingMode the texture sampling mode
  38038. * @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.
  38039. */
  38040. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  38041. if (maxCharCount === void 0) { maxCharCount = 200; }
  38042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38043. if (superSample === void 0) { superSample = false; }
  38044. _super.call(this, null, scene, true, false, samplingMode);
  38045. this._charInfos = {};
  38046. this._curCharCount = 0;
  38047. this._lastUpdateCharCount = -1;
  38048. this._usedCounter = 1;
  38049. this.name = name;
  38050. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38051. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38052. this._superSample = false;
  38053. if (superSample) {
  38054. var sfont = this.getSuperSampleFont(font);
  38055. if (sfont) {
  38056. this._superSample = true;
  38057. font = sfont;
  38058. }
  38059. }
  38060. // First canvas creation to determine the size of the texture to create
  38061. this._canvas = document.createElement("canvas");
  38062. this._context = this._canvas.getContext("2d");
  38063. this._context.font = font;
  38064. this._context.fillStyle = "white";
  38065. this._cachedFontId = null;
  38066. var res = this.getFontHeight(font);
  38067. this._lineHeightSuper = res.height;
  38068. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  38069. this._offset = res.offset - 1;
  38070. var maxCharWidth = this._context.measureText("W").width;
  38071. this._spaceWidthSuper = this._context.measureText(" ").width;
  38072. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38073. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38074. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  38075. var edge = Math.sqrt(totalEstSurface);
  38076. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38077. // Create the texture that will store the font characters
  38078. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38079. var textureSize = this.getSize();
  38080. this.hasAlpha = true;
  38081. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38082. this._canvas = document.createElement("canvas");
  38083. this._canvas.width = textureSize.width;
  38084. this._canvas.height = textureSize.height;
  38085. this._context = this._canvas.getContext("2d");
  38086. this._context.textBaseline = "top";
  38087. this._context.font = font;
  38088. this._context.fillStyle = "white";
  38089. this._context.imageSmoothingEnabled = false;
  38090. this._currentFreePosition = BABYLON.Vector2.Zero();
  38091. // Add the basic ASCII based characters
  38092. for (var i = 0x20; i < 0x7F; i++) {
  38093. var c = String.fromCharCode(i);
  38094. this.getChar(c);
  38095. }
  38096. this.update();
  38097. }
  38098. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38099. get: function () {
  38100. return this._superSample;
  38101. },
  38102. enumerable: true,
  38103. configurable: true
  38104. });
  38105. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38106. get: function () {
  38107. return this._spaceWidth;
  38108. },
  38109. enumerable: true,
  38110. configurable: true
  38111. });
  38112. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38113. get: function () {
  38114. return this._lineHeight;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  38120. if (supersample === void 0) { supersample = false; }
  38121. var s = scene;
  38122. if (!s.__fontTextureCache__) {
  38123. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38124. }
  38125. var dic = s.__fontTextureCache__;
  38126. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38127. var ft = dic.get(lfn);
  38128. if (ft) {
  38129. ++ft._usedCounter;
  38130. return ft;
  38131. }
  38132. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  38133. ft._cachedFontId = lfn;
  38134. dic.add(lfn, ft);
  38135. return ft;
  38136. };
  38137. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38138. if (supersample === void 0) { supersample = false; }
  38139. var s = scene;
  38140. var dic = s.__fontTextureCache__;
  38141. if (!dic) {
  38142. return;
  38143. }
  38144. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38145. var font = dic.get(lfn);
  38146. if (--font._usedCounter === 0) {
  38147. dic.remove(lfn);
  38148. font.dispose();
  38149. }
  38150. };
  38151. /**
  38152. * Make sure the given char is present in the font map.
  38153. * @param char the character to get or add
  38154. * @return the CharInfo instance corresponding to the given character
  38155. */
  38156. FontTexture.prototype.getChar = function (char) {
  38157. if (char.length !== 1) {
  38158. return null;
  38159. }
  38160. var info = this._charInfos[char];
  38161. if (info) {
  38162. return info;
  38163. }
  38164. info = new CharInfo();
  38165. var measure = this._context.measureText(char);
  38166. var textureSize = this.getSize();
  38167. // we reached the end of the current line?
  38168. var width = Math.round(measure.width);
  38169. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38170. var yMargin = xMargin;
  38171. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38172. this._currentFreePosition.x = 0;
  38173. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38174. // No more room?
  38175. if (this._currentFreePosition.y > textureSize.height) {
  38176. return this.getChar("!");
  38177. }
  38178. }
  38179. // Draw the character in the texture
  38180. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38181. // Fill the CharInfo object
  38182. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38183. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38184. info.charWidth = this._superSample ? (width / 2) : width;
  38185. // Add the info structure
  38186. this._charInfos[char] = info;
  38187. this._curCharCount++;
  38188. // Set the next position
  38189. this._currentFreePosition.x += width + xMargin;
  38190. return info;
  38191. };
  38192. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38193. if (tabulationSize === void 0) { tabulationSize = 4; }
  38194. var maxWidth = 0;
  38195. var curWidth = 0;
  38196. var lineCount = 1;
  38197. var charxpos = 0;
  38198. // Parse each char of the string
  38199. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  38200. var char = text_1[_i];
  38201. // Next line feed?
  38202. if (char === "\n") {
  38203. maxWidth = Math.max(maxWidth, curWidth);
  38204. charxpos = 0;
  38205. curWidth = 0;
  38206. ++lineCount;
  38207. continue;
  38208. }
  38209. // Tabulation ?
  38210. if (char === "\t") {
  38211. var nextPos = charxpos + tabulationSize;
  38212. nextPos = nextPos - (nextPos % tabulationSize);
  38213. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38214. charxpos = nextPos;
  38215. continue;
  38216. }
  38217. if (char < " ") {
  38218. continue;
  38219. }
  38220. curWidth += this.getChar(char).charWidth;
  38221. ++charxpos;
  38222. }
  38223. maxWidth = Math.max(maxWidth, curWidth);
  38224. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38225. };
  38226. FontTexture.prototype.getSuperSampleFont = function (font) {
  38227. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38228. 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*$/;
  38229. var res = font.toLocaleLowerCase().match(regex);
  38230. if (res == null) {
  38231. return null;
  38232. }
  38233. var size = parseInt(res[4]);
  38234. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38235. var newFont = "";
  38236. for (var j = 1; j < res.length; j++) {
  38237. if (res[j] != null) {
  38238. newFont += res[j] + " ";
  38239. }
  38240. }
  38241. return newFont;
  38242. };
  38243. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38244. FontTexture.prototype.getFontHeight = function (font) {
  38245. var fontDraw = document.createElement("canvas");
  38246. var ctx = fontDraw.getContext('2d');
  38247. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38248. ctx.textBaseline = 'top';
  38249. ctx.fillStyle = 'white';
  38250. ctx.font = font;
  38251. ctx.fillText('jH|', 0, 0);
  38252. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38253. var start = -1;
  38254. var end = -1;
  38255. for (var row = 0; row < fontDraw.height; row++) {
  38256. for (var column = 0; column < fontDraw.width; column++) {
  38257. var index = (row * fontDraw.width + column) * 4;
  38258. if (pixels[index] === 0) {
  38259. if (column === fontDraw.width - 1 && start !== -1) {
  38260. end = row;
  38261. row = fontDraw.height;
  38262. break;
  38263. }
  38264. continue;
  38265. }
  38266. else {
  38267. if (start === -1) {
  38268. start = row;
  38269. }
  38270. break;
  38271. }
  38272. }
  38273. }
  38274. return { height: (end - start) + 1, offset: start - 1 };
  38275. };
  38276. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38277. get: function () {
  38278. return false;
  38279. },
  38280. enumerable: true,
  38281. configurable: true
  38282. });
  38283. FontTexture.prototype.getContext = function () {
  38284. return this._context;
  38285. };
  38286. /**
  38287. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38288. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38289. */
  38290. FontTexture.prototype.update = function () {
  38291. // Update only if there's new char added since the previous update
  38292. if (this._lastUpdateCharCount < this._curCharCount) {
  38293. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38294. this._lastUpdateCharCount = this._curCharCount;
  38295. }
  38296. };
  38297. // cloning should be prohibited, there's no point to duplicate this texture at all
  38298. FontTexture.prototype.clone = function () {
  38299. return null;
  38300. };
  38301. /**
  38302. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38303. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38304. */
  38305. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38306. ++this._usedCounter;
  38307. };
  38308. /**
  38309. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38310. */
  38311. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38312. var s = this.getScene();
  38313. var dic = s.__fontTextureCache__;
  38314. if (!dic) {
  38315. return;
  38316. }
  38317. if (--this._usedCounter === 0) {
  38318. dic.remove(this._cachedFontId);
  38319. this.dispose();
  38320. }
  38321. };
  38322. return FontTexture;
  38323. }(BABYLON.Texture));
  38324. BABYLON.FontTexture = FontTexture;
  38325. })(BABYLON || (BABYLON = {}));
  38326. var BABYLON;
  38327. (function (BABYLON) {
  38328. var MapTexture = (function (_super) {
  38329. __extends(MapTexture, _super);
  38330. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38332. if (useMipMap === void 0) { useMipMap = false; }
  38333. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38334. this.name = name;
  38335. this._size = size;
  38336. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38337. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38338. // Create the rectPackMap that will allocate portion of the texture
  38339. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38340. // Create the texture that will store the content
  38341. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38342. }
  38343. /**
  38344. * Allocate a rectangle of a given size in the texture map
  38345. * @param size the size of the rectangle to allocation
  38346. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38347. */
  38348. MapTexture.prototype.allocateRect = function (size) {
  38349. return this._rectPackingMap.addRect(size);
  38350. };
  38351. /**
  38352. * Free a given rectangle from the texture map
  38353. * @param rectInfo the instance corresponding to the rect to free.
  38354. */
  38355. MapTexture.prototype.freeRect = function (rectInfo) {
  38356. if (rectInfo) {
  38357. rectInfo.freeContent();
  38358. }
  38359. };
  38360. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38361. /**
  38362. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38363. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38364. * @returns {}
  38365. */
  38366. get: function () {
  38367. return this._rectPackingMap.freeSpace;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. /**
  38373. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38374. * 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.
  38375. * Don't forget to call unbindTexture when you're done rendering
  38376. * @param rect the zone to render to
  38377. * @param clear true to clear the portion's color/depth data
  38378. */
  38379. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38380. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38381. };
  38382. /**
  38383. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38384. * 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.
  38385. * Don't forget to call unbindTexture when you're done rendering
  38386. * @param pos the position into the texture
  38387. * @param size the portion to fit the clip space to
  38388. * @param clear true to clear the portion's color/depth data
  38389. */
  38390. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38391. var engine = this.getScene().getEngine();
  38392. engine.bindFramebuffer(this._texture);
  38393. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38394. if (clear) {
  38395. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38396. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38397. }
  38398. };
  38399. /**
  38400. * Unbind the texture map from the rendering engine.
  38401. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38402. * @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.
  38403. */
  38404. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38405. // Dump ?
  38406. if (dumpForDebug) {
  38407. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38408. }
  38409. var engine = this.getScene().getEngine();
  38410. if (this._replacedViewport) {
  38411. engine.setViewport(this._replacedViewport);
  38412. this._replacedViewport = null;
  38413. }
  38414. engine.unBindFramebuffer(this._texture);
  38415. };
  38416. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38417. get: function () {
  38418. return false;
  38419. },
  38420. enumerable: true,
  38421. configurable: true
  38422. });
  38423. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38424. // Anyway, there's not much point to use this method for this kind of texture I guess
  38425. MapTexture.prototype.clone = function () {
  38426. return null;
  38427. };
  38428. return MapTexture;
  38429. }(BABYLON.Texture));
  38430. BABYLON.MapTexture = MapTexture;
  38431. })(BABYLON || (BABYLON = {}));
  38432. var BABYLON;
  38433. (function (BABYLON) {
  38434. /**
  38435. * Stores 2D Bounding Information.
  38436. * This class handles a circle area and a bounding rectangle one.
  38437. */
  38438. var BoundingInfo2D = (function () {
  38439. function BoundingInfo2D() {
  38440. this.radius = 0;
  38441. this.center = BABYLON.Vector2.Zero();
  38442. this.extent = BABYLON.Vector2.Zero();
  38443. }
  38444. /**
  38445. * Create a BoundingInfo2D object from a given size
  38446. * @param size the size that will be used to set the extend, radius will be computed from it.
  38447. */
  38448. BoundingInfo2D.CreateFromSize = function (size) {
  38449. var r = new BoundingInfo2D();
  38450. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38451. return r;
  38452. };
  38453. /**
  38454. * Create a BoundingInfo2D object from a given radius
  38455. * @param radius the radius to use, the extent will be computed from it.
  38456. */
  38457. BoundingInfo2D.CreateFromRadius = function (radius) {
  38458. var r = new BoundingInfo2D();
  38459. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38460. return r;
  38461. };
  38462. /**
  38463. * Create a BoundingInfo2D object from a list of points.
  38464. * The resulted object will be the smallest bounding area that includes all the given points.
  38465. * @param points an array of points to compute the bounding object from.
  38466. */
  38467. BoundingInfo2D.CreateFromPoints = function (points) {
  38468. var r = new BoundingInfo2D();
  38469. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38470. return r;
  38471. };
  38472. /**
  38473. * Update a BoundingInfo2D object using the given Size as input
  38474. * @param size the bounding data will be computed from this size.
  38475. * @param b must be a valid/allocated object, it will contain the result of the operation
  38476. */
  38477. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38478. if (!size) {
  38479. size = BABYLON.Size.Zero();
  38480. }
  38481. b.center.x = +size.width / 2;
  38482. b.center.y = +size.height / 2;
  38483. b.extent.x = b.center.x;
  38484. b.extent.y = b.center.y;
  38485. b.radius = b.extent.length();
  38486. };
  38487. /**
  38488. * Update a BoundingInfo2D object using the given radius as input
  38489. * @param radius the bounding data will be computed from this radius
  38490. * @param b must be a valid/allocated object, it will contain the result of the operation
  38491. */
  38492. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38493. b.center.x = b.center.y = 0;
  38494. var r = +radius;
  38495. b.extent.x = r;
  38496. b.extent.y = r;
  38497. b.radius = r;
  38498. };
  38499. /**
  38500. * Update a BoundingInfo2D object using the given points array as input
  38501. * @param points the point array to use to update the bounding data
  38502. * @param b must be a valid/allocated object, it will contain the result of the operation
  38503. */
  38504. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38505. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38506. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  38507. var p = points_1[_i];
  38508. xmin = Math.min(p.x, xmin);
  38509. xmax = Math.max(p.x, xmax);
  38510. ymin = Math.min(p.y, ymin);
  38511. ymax = Math.max(p.y, ymax);
  38512. }
  38513. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38514. };
  38515. /**
  38516. * Update a BoundingInfo2D object using the given min/max values as input
  38517. * @param xmin the smallest x coordinate
  38518. * @param xmax the biggest x coordinate
  38519. * @param ymin the smallest y coordinate
  38520. * @param ymax the buggest y coordinate
  38521. * @param b must be a valid/allocated object, it will contain the result of the operation
  38522. */
  38523. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38524. var w = xmax - xmin;
  38525. var h = ymax - ymin;
  38526. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38527. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38528. b.radius = b.extent.length();
  38529. };
  38530. /**
  38531. * Duplicate this instance and return a new one
  38532. * @return the duplicated instance
  38533. */
  38534. BoundingInfo2D.prototype.clone = function () {
  38535. var r = new BoundingInfo2D();
  38536. r.center = this.center.clone();
  38537. r.radius = this.radius;
  38538. r.extent = this.extent.clone();
  38539. return r;
  38540. };
  38541. BoundingInfo2D.prototype.clear = function () {
  38542. this.center.copyFromFloats(0, 0);
  38543. this.radius = 0;
  38544. this.extent.copyFromFloats(0, 0);
  38545. };
  38546. BoundingInfo2D.prototype.copyFrom = function (src) {
  38547. this.center.copyFrom(src.center);
  38548. this.radius = src.radius;
  38549. this.extent.copyFrom(src.extent);
  38550. };
  38551. /**
  38552. * return the max extend of the bounding info
  38553. */
  38554. BoundingInfo2D.prototype.max = function () {
  38555. var r = BABYLON.Vector2.Zero();
  38556. this.maxToRef(r);
  38557. return r;
  38558. };
  38559. /**
  38560. * Update a vector2 with the max extend of the bounding info
  38561. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38562. */
  38563. BoundingInfo2D.prototype.maxToRef = function (result) {
  38564. result.x = this.center.x + this.extent.x;
  38565. result.y = this.center.y + this.extent.y;
  38566. };
  38567. /**
  38568. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38569. * @param matrix the transformation matrix to apply
  38570. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38571. */
  38572. BoundingInfo2D.prototype.transform = function (matrix) {
  38573. var r = new BoundingInfo2D();
  38574. this.transformToRef(matrix, r);
  38575. return r;
  38576. };
  38577. /**
  38578. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38579. * @param other the second BoundingInfo2D to compute the union with this one
  38580. * @return a new instance containing the result of the union
  38581. */
  38582. BoundingInfo2D.prototype.union = function (other) {
  38583. var r = new BoundingInfo2D();
  38584. this.unionToRef(other, r);
  38585. return r;
  38586. };
  38587. /**
  38588. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38589. * 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.
  38590. * @param matrix The matrix to use to compute the transformation
  38591. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38592. */
  38593. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38594. // Construct a bounding box based on the extent values
  38595. var p = BoundingInfo2D._transform;
  38596. p[0].x = this.center.x + this.extent.x;
  38597. p[0].y = this.center.y + this.extent.y;
  38598. p[1].x = this.center.x + this.extent.x;
  38599. p[1].y = this.center.y - this.extent.y;
  38600. p[2].x = this.center.x - this.extent.x;
  38601. p[2].y = this.center.y - this.extent.y;
  38602. p[3].x = this.center.x - this.extent.x;
  38603. p[3].y = this.center.y + this.extent.y;
  38604. // Transform the four points of the bounding box with the matrix
  38605. for (var i = 0; i < 4; i++) {
  38606. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38607. }
  38608. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38609. };
  38610. /**
  38611. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38612. * 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.
  38613. * @param other the second object used to compute the union
  38614. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38615. */
  38616. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38617. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38618. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38619. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38620. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38621. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38622. };
  38623. /**
  38624. * Check if the given point is inside the BoundingInfo.
  38625. * The test is first made on the radius, then inside the rectangle described by the extent
  38626. * @param pickPosition the position to test
  38627. * @return true if the point is inside, false otherwise
  38628. */
  38629. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38630. // is it inside the radius?
  38631. var pickLocal = pickPosition.subtract(this.center);
  38632. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38633. // is it inside the rectangle?
  38634. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38635. }
  38636. return false;
  38637. };
  38638. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38639. return BoundingInfo2D;
  38640. }());
  38641. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38642. })(BABYLON || (BABYLON = {}));
  38643. var BABYLON;
  38644. (function (BABYLON) {
  38645. var LayoutEngineBase = (function () {
  38646. function LayoutEngineBase() {
  38647. this.layoutDirtyOnPropertyChangedMask = 0;
  38648. }
  38649. LayoutEngineBase.prototype.updateLayout = function (prim) {
  38650. };
  38651. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  38652. get: function () {
  38653. return false;
  38654. },
  38655. enumerable: true,
  38656. configurable: true
  38657. });
  38658. LayoutEngineBase.prototype.isLocked = function () {
  38659. return this._isLocked;
  38660. };
  38661. LayoutEngineBase.prototype.lock = function () {
  38662. if (this._isLocked) {
  38663. return false;
  38664. }
  38665. this._isLocked = true;
  38666. return true;
  38667. };
  38668. LayoutEngineBase = __decorate([
  38669. BABYLON.className("LayoutEngineBase")
  38670. ], LayoutEngineBase);
  38671. return LayoutEngineBase;
  38672. }());
  38673. BABYLON.LayoutEngineBase = LayoutEngineBase;
  38674. var CanvasLayoutEngine = (function (_super) {
  38675. __extends(CanvasLayoutEngine, _super);
  38676. function CanvasLayoutEngine() {
  38677. _super.apply(this, arguments);
  38678. }
  38679. // A very simple (no) layout computing...
  38680. // The Canvas and its direct children gets the Canvas' size as Layout Area
  38681. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  38682. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  38683. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  38684. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  38685. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  38686. var child = _a[_i];
  38687. this._doUpdate(child);
  38688. }
  38689. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38690. }
  38691. };
  38692. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  38693. // Canvas ?
  38694. if (prim instanceof BABYLON.Canvas2D) {
  38695. prim.layoutArea = prim.actualSize;
  38696. }
  38697. else if (prim.parent instanceof BABYLON.Canvas2D) {
  38698. prim.layoutArea = prim.owner.actualSize;
  38699. }
  38700. else {
  38701. prim.layoutArea = prim.parent.contentArea;
  38702. }
  38703. };
  38704. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  38705. get: function () {
  38706. return true;
  38707. },
  38708. enumerable: true,
  38709. configurable: true
  38710. });
  38711. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  38712. CanvasLayoutEngine = __decorate([
  38713. BABYLON.className("CanvasLayoutEngine")
  38714. ], CanvasLayoutEngine);
  38715. return CanvasLayoutEngine;
  38716. }(LayoutEngineBase));
  38717. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  38718. var StackPanelLayoutEngine = (function (_super) {
  38719. __extends(StackPanelLayoutEngine, _super);
  38720. function StackPanelLayoutEngine() {
  38721. _super.call(this);
  38722. this._isHorizontal = true;
  38723. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  38724. }
  38725. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  38726. get: function () {
  38727. if (!StackPanelLayoutEngine._horizontal) {
  38728. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  38729. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  38730. StackPanelLayoutEngine._horizontal.lock();
  38731. }
  38732. return StackPanelLayoutEngine._horizontal;
  38733. },
  38734. enumerable: true,
  38735. configurable: true
  38736. });
  38737. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  38738. get: function () {
  38739. if (!StackPanelLayoutEngine._vertical) {
  38740. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  38741. StackPanelLayoutEngine._vertical.isHorizontal = false;
  38742. StackPanelLayoutEngine._vertical.lock();
  38743. }
  38744. return StackPanelLayoutEngine._vertical;
  38745. },
  38746. enumerable: true,
  38747. configurable: true
  38748. });
  38749. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  38750. get: function () {
  38751. return this._isHorizontal;
  38752. },
  38753. set: function (val) {
  38754. if (this.isLocked()) {
  38755. return;
  38756. }
  38757. this._isHorizontal = val;
  38758. },
  38759. enumerable: true,
  38760. configurable: true
  38761. });
  38762. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  38763. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  38764. var x = 0;
  38765. var y = 0;
  38766. var h = this.isHorizontal;
  38767. var max = 0;
  38768. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  38769. var child = _a[_i];
  38770. var layoutArea = void 0;
  38771. if (child._hasMargin) {
  38772. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine.dstOffset, StackPanelLayoutEngine.dstArea, true);
  38773. layoutArea = StackPanelLayoutEngine.dstArea.clone();
  38774. child.layoutArea = layoutArea;
  38775. }
  38776. else {
  38777. layoutArea = child.layoutArea;
  38778. child.margin.computeArea(child.actualSize, layoutArea);
  38779. }
  38780. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  38781. }
  38782. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  38783. var child = _c[_b];
  38784. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  38785. var layoutArea = child.layoutArea;
  38786. if (h) {
  38787. x += layoutArea.width;
  38788. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  38789. }
  38790. else {
  38791. y += layoutArea.height;
  38792. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  38793. }
  38794. }
  38795. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  38796. }
  38797. };
  38798. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  38799. get: function () {
  38800. return false;
  38801. },
  38802. enumerable: true,
  38803. configurable: true
  38804. });
  38805. StackPanelLayoutEngine._horizontal = null;
  38806. StackPanelLayoutEngine._vertical = null;
  38807. StackPanelLayoutEngine.dstOffset = BABYLON.Vector2.Zero();
  38808. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  38809. StackPanelLayoutEngine = __decorate([
  38810. BABYLON.className("StackPanelLayoutEngine")
  38811. ], StackPanelLayoutEngine);
  38812. return StackPanelLayoutEngine;
  38813. }(LayoutEngineBase));
  38814. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  38815. })(BABYLON || (BABYLON = {}));
  38816. var BABYLON;
  38817. (function (BABYLON) {
  38818. /**
  38819. * Base class implementing the ILocable interface.
  38820. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38821. */
  38822. var LockableBase = (function () {
  38823. function LockableBase() {
  38824. }
  38825. LockableBase.prototype.isLocked = function () {
  38826. return this._isLocked;
  38827. };
  38828. LockableBase.prototype.lock = function () {
  38829. if (this._isLocked) {
  38830. return true;
  38831. }
  38832. this.onLock();
  38833. this._isLocked = true;
  38834. return false;
  38835. };
  38836. /**
  38837. * Protected handler that will be called when the instance is about to be locked.
  38838. */
  38839. LockableBase.prototype.onLock = function () {
  38840. };
  38841. return LockableBase;
  38842. }());
  38843. BABYLON.LockableBase = LockableBase;
  38844. var SolidColorBrush2D = (function (_super) {
  38845. __extends(SolidColorBrush2D, _super);
  38846. function SolidColorBrush2D(color, lock) {
  38847. if (lock === void 0) { lock = false; }
  38848. _super.call(this);
  38849. this._color = color;
  38850. if (lock) {
  38851. {
  38852. this.lock();
  38853. }
  38854. }
  38855. }
  38856. /**
  38857. * Return true if the brush is transparent, false if it's totally opaque
  38858. */
  38859. SolidColorBrush2D.prototype.isTransparent = function () {
  38860. return this._color && this._color.a < 1.0;
  38861. };
  38862. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38863. /**
  38864. * The color used by this instance to render
  38865. * @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.
  38866. */
  38867. get: function () {
  38868. return this._color;
  38869. },
  38870. set: function (value) {
  38871. if (this.isLocked()) {
  38872. return;
  38873. }
  38874. this._color = value;
  38875. },
  38876. enumerable: true,
  38877. configurable: true
  38878. });
  38879. /**
  38880. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38881. */
  38882. SolidColorBrush2D.prototype.toString = function () {
  38883. return this._color.toHexString();
  38884. };
  38885. SolidColorBrush2D = __decorate([
  38886. BABYLON.className("SolidColorBrush2D")
  38887. ], SolidColorBrush2D);
  38888. return SolidColorBrush2D;
  38889. }(LockableBase));
  38890. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38891. var GradientColorBrush2D = (function (_super) {
  38892. __extends(GradientColorBrush2D, _super);
  38893. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38894. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38895. if (rotation === void 0) { rotation = 0; }
  38896. if (scale === void 0) { scale = 1; }
  38897. if (lock === void 0) { lock = false; }
  38898. _super.call(this);
  38899. this._color1 = color1;
  38900. this._color2 = color2;
  38901. this._translation = translation;
  38902. this._rotation = rotation;
  38903. this._scale = scale;
  38904. if (lock) {
  38905. this.lock();
  38906. }
  38907. }
  38908. /**
  38909. * Return true if the brush is transparent, false if it's totally opaque
  38910. */
  38911. GradientColorBrush2D.prototype.isTransparent = function () {
  38912. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38913. };
  38914. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38915. /**
  38916. * First color, the blend will start from this color
  38917. */
  38918. get: function () {
  38919. return this._color1;
  38920. },
  38921. set: function (value) {
  38922. if (this.isLocked()) {
  38923. return;
  38924. }
  38925. this._color1 = value;
  38926. },
  38927. enumerable: true,
  38928. configurable: true
  38929. });
  38930. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38931. /**
  38932. * Second color, the blend will end to this color
  38933. */
  38934. get: function () {
  38935. return this._color2;
  38936. },
  38937. set: function (value) {
  38938. if (this.isLocked()) {
  38939. return;
  38940. }
  38941. this._color2 = value;
  38942. },
  38943. enumerable: true,
  38944. configurable: true
  38945. });
  38946. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38947. /**
  38948. * Translation vector to apply on the blend
  38949. * Default is [0;0]
  38950. */
  38951. get: function () {
  38952. return this._translation;
  38953. },
  38954. set: function (value) {
  38955. if (this.isLocked()) {
  38956. return;
  38957. }
  38958. this._translation = value;
  38959. },
  38960. enumerable: true,
  38961. configurable: true
  38962. });
  38963. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38964. /**
  38965. * Rotation in radian to apply to the brush
  38966. * Default direction of the brush is vertical, you can change this using this property.
  38967. * Default is 0.
  38968. */
  38969. get: function () {
  38970. return this._rotation;
  38971. },
  38972. set: function (value) {
  38973. if (this.isLocked()) {
  38974. return;
  38975. }
  38976. this._rotation = value;
  38977. },
  38978. enumerable: true,
  38979. configurable: true
  38980. });
  38981. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38982. /**
  38983. * Scale factor to apply to the gradient.
  38984. * Default is 1: no scale.
  38985. */
  38986. get: function () {
  38987. return this._scale;
  38988. },
  38989. set: function (value) {
  38990. if (this.isLocked()) {
  38991. return;
  38992. }
  38993. this._scale = value;
  38994. },
  38995. enumerable: true,
  38996. configurable: true
  38997. });
  38998. /**
  38999. * Return a string describing the brush
  39000. */
  39001. GradientColorBrush2D.prototype.toString = function () {
  39002. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  39003. };
  39004. /**
  39005. * Build a unique key string for the given parameters
  39006. */
  39007. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  39008. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  39009. };
  39010. GradientColorBrush2D = __decorate([
  39011. BABYLON.className("GradientColorBrush2D")
  39012. ], GradientColorBrush2D);
  39013. return GradientColorBrush2D;
  39014. }(LockableBase));
  39015. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  39016. })(BABYLON || (BABYLON = {}));
  39017. var BABYLON;
  39018. (function (BABYLON) {
  39019. var Prim2DClassInfo = (function () {
  39020. function Prim2DClassInfo() {
  39021. }
  39022. return Prim2DClassInfo;
  39023. }());
  39024. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  39025. var Prim2DPropInfo = (function () {
  39026. function Prim2DPropInfo() {
  39027. }
  39028. Prim2DPropInfo.PROPKIND_MODEL = 1;
  39029. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  39030. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  39031. return Prim2DPropInfo;
  39032. }());
  39033. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  39034. /**
  39035. * Custom type of the propertyChanged observable
  39036. */
  39037. var PropertyChangedInfo = (function () {
  39038. function PropertyChangedInfo() {
  39039. }
  39040. return PropertyChangedInfo;
  39041. }());
  39042. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  39043. var ClassTreeInfo = (function () {
  39044. function ClassTreeInfo(baseClass, type, classContentFactory) {
  39045. this._baseClass = baseClass;
  39046. this._type = type;
  39047. this._subClasses = new Array();
  39048. this._levelContent = new BABYLON.StringDictionary();
  39049. this._classContentFactory = classContentFactory;
  39050. }
  39051. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  39052. get: function () {
  39053. if (!this._classContent) {
  39054. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  39055. }
  39056. return this._classContent;
  39057. },
  39058. enumerable: true,
  39059. configurable: true
  39060. });
  39061. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  39062. get: function () {
  39063. return this._type;
  39064. },
  39065. enumerable: true,
  39066. configurable: true
  39067. });
  39068. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  39069. get: function () {
  39070. return this._levelContent;
  39071. },
  39072. enumerable: true,
  39073. configurable: true
  39074. });
  39075. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  39076. get: function () {
  39077. if (!this._fullContent) {
  39078. var dic_1 = new BABYLON.StringDictionary();
  39079. var curLevel = this;
  39080. while (curLevel) {
  39081. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  39082. curLevel = curLevel._baseClass;
  39083. }
  39084. this._fullContent = dic_1;
  39085. }
  39086. return this._fullContent;
  39087. },
  39088. enumerable: true,
  39089. configurable: true
  39090. });
  39091. ClassTreeInfo.prototype.getLevelOf = function (type) {
  39092. // Are we already there?
  39093. if (type === this._type) {
  39094. return this;
  39095. }
  39096. var baseProto = Object.getPrototypeOf(type);
  39097. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  39098. if (!curProtoContent) {
  39099. this.getLevelOf(baseProto);
  39100. }
  39101. return this.getOrAddType(baseProto, type);
  39102. };
  39103. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  39104. // Are we at the level corresponding to the baseType?
  39105. // If so, get or add the level we're looking for
  39106. if (baseType === this._type) {
  39107. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  39108. var subType = _a[_i];
  39109. if (subType.type === type) {
  39110. return subType.node;
  39111. }
  39112. }
  39113. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  39114. var info = { type: type, node: node };
  39115. this._subClasses.push(info);
  39116. return info.node;
  39117. }
  39118. // Recurse down to keep looking for the node corresponding to the baseTypeName
  39119. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  39120. var subType = _c[_b];
  39121. var info = subType.node.getOrAddType(baseType, type);
  39122. if (info) {
  39123. return info;
  39124. }
  39125. }
  39126. return null;
  39127. };
  39128. ClassTreeInfo.get = function (type) {
  39129. var dic = type["__classTreeInfo"];
  39130. if (!dic) {
  39131. return null;
  39132. }
  39133. return dic.getLevelOf(type);
  39134. };
  39135. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  39136. var dic = type["__classTreeInfo"];
  39137. if (!dic) {
  39138. dic = new ClassTreeInfo(null, type, classContentFactory);
  39139. type["__classTreeInfo"] = dic;
  39140. }
  39141. return dic;
  39142. };
  39143. return ClassTreeInfo;
  39144. }());
  39145. BABYLON.ClassTreeInfo = ClassTreeInfo;
  39146. var SmartPropertyPrim = (function () {
  39147. function SmartPropertyPrim() {
  39148. this._flags = 0;
  39149. this._modelKey = null;
  39150. this._instanceDirtyFlags = 0;
  39151. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  39152. this.animations = new Array();
  39153. }
  39154. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  39155. /**
  39156. * Check if the object is disposed or not.
  39157. * @returns true if the object is dispose, false otherwise.
  39158. */
  39159. get: function () {
  39160. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  39161. },
  39162. enumerable: true,
  39163. configurable: true
  39164. });
  39165. /**
  39166. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  39167. * @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.
  39168. */
  39169. SmartPropertyPrim.prototype.dispose = function () {
  39170. if (this.isDisposed) {
  39171. return false;
  39172. }
  39173. // Don't set to null, it may upset somebody...
  39174. this.animations.splice(0);
  39175. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  39176. return true;
  39177. };
  39178. /**
  39179. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  39180. * Look at Sprite2D for more information
  39181. */
  39182. SmartPropertyPrim.prototype.getAnimatables = function () {
  39183. return new Array();
  39184. };
  39185. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  39186. /**
  39187. * Property giving the Model Key associated to the property.
  39188. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  39189. * @returns the model key string.
  39190. */
  39191. get: function () {
  39192. var _this = this;
  39193. // No need to compute it?
  39194. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  39195. return this._modelKey;
  39196. }
  39197. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  39198. var propDic = this.propDic;
  39199. propDic.forEach(function (k, v) {
  39200. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  39201. var propVal = _this[v.name];
  39202. // 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
  39203. if (propVal && propVal.constructor === Array) {
  39204. var firstVal = propVal[0];
  39205. if (!firstVal) {
  39206. propVal = 0;
  39207. }
  39208. else {
  39209. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  39210. }
  39211. }
  39212. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  39213. }
  39214. });
  39215. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  39216. this._modelKey = modelKey;
  39217. return modelKey;
  39218. },
  39219. enumerable: true,
  39220. configurable: true
  39221. });
  39222. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  39223. /**
  39224. * States if the Primitive is dirty and should be rendered again next time.
  39225. * @returns true is dirty, false otherwise
  39226. */
  39227. get: function () {
  39228. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  39229. },
  39230. enumerable: true,
  39231. configurable: true
  39232. });
  39233. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  39234. /**
  39235. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  39236. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  39237. */
  39238. get: function () {
  39239. if (!this._propInfo) {
  39240. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  39241. if (!cti) {
  39242. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  39243. }
  39244. this._propInfo = cti.fullContent;
  39245. }
  39246. return this._propInfo;
  39247. },
  39248. enumerable: true,
  39249. configurable: true
  39250. });
  39251. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  39252. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  39253. var node = dic.getLevelOf(target);
  39254. var propInfo = node.levelContent.get(propId.toString());
  39255. if (propInfo) {
  39256. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  39257. }
  39258. // Create, setup and add the PropInfo object to our prop dictionary
  39259. propInfo = new Prim2DPropInfo();
  39260. propInfo.id = propId;
  39261. propInfo.flagId = Math.pow(2, propId);
  39262. propInfo.kind = kind;
  39263. propInfo.name = propName;
  39264. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  39265. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  39266. propInfo.typeLevelCompare = typeLevelCompare;
  39267. node.levelContent.add(propName, propInfo);
  39268. return propInfo;
  39269. };
  39270. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  39271. // Nothing to nothing: nothing to do!
  39272. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  39273. return true;
  39274. }
  39275. // Check value unchanged
  39276. if ((curValue != null) && (newValue != null)) {
  39277. if (typeof (curValue.equals) == "function") {
  39278. if (curValue.equals(newValue)) {
  39279. return true;
  39280. }
  39281. }
  39282. else {
  39283. if (curValue === newValue) {
  39284. return true;
  39285. }
  39286. }
  39287. }
  39288. return false;
  39289. };
  39290. SmartPropertyPrim.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  39291. if (this.isDisposed) {
  39292. return;
  39293. }
  39294. if (!propInfo) {
  39295. return;
  39296. }
  39297. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  39298. };
  39299. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  39300. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39301. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  39302. if (this instanceof BABYLON.Prim2DBase) {
  39303. var curprim = this;
  39304. while (curprim) {
  39305. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  39306. if (curprim.isSizeAuto) {
  39307. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  39308. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  39309. }
  39310. if (curprim instanceof BABYLON.Group2D) {
  39311. if (curprim.isRenderableGroup) {
  39312. break;
  39313. }
  39314. }
  39315. curprim = curprim.parent;
  39316. }
  39317. }
  39318. };
  39319. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  39320. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  39321. if (propInfo.dirtyBoundingInfo) {
  39322. this._boundingBoxDirty();
  39323. }
  39324. else if (propInfo.dirtyParentBoundingInfo) {
  39325. var p = this._parent;
  39326. if (p != null) {
  39327. p._boundingBoxDirty();
  39328. }
  39329. }
  39330. // Trigger property changed
  39331. var info = SmartPropertyPrim.propChangedInfo;
  39332. info.oldValue = curValue;
  39333. info.newValue = newValue;
  39334. info.propertyName = propName;
  39335. var propMask = propInfo.flagId;
  39336. this.propertyChanged.notifyObservers(info, propMask);
  39337. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  39338. if (this instanceof BABYLON.Group2D) {
  39339. this.handleGroupChanged(propInfo);
  39340. }
  39341. // Check for parent layout dirty
  39342. if (this instanceof BABYLON.Prim2DBase) {
  39343. var p = this._parent;
  39344. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  39345. p._setLayoutDirty();
  39346. }
  39347. }
  39348. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  39349. var instanceDirty = false;
  39350. if (typeLevelCompare && curValue != null && newValue != null) {
  39351. var cvProto = curValue.__proto__;
  39352. var nvProto = newValue.__proto__;
  39353. instanceDirty = (cvProto === nvProto);
  39354. }
  39355. // Set the dirty flags
  39356. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  39357. if (!this.isDirty) {
  39358. this._setFlags(SmartPropertyPrim.flagModelDirty);
  39359. }
  39360. }
  39361. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  39362. this.onPrimitivePropertyDirty(propMask);
  39363. }
  39364. };
  39365. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  39366. this.onPrimBecomesDirty();
  39367. this._instanceDirtyFlags |= propFlagId;
  39368. };
  39369. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  39370. };
  39371. /**
  39372. * Check if a given set of properties are dirty or not.
  39373. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39374. * @return true if at least one property is dirty, false if none of them are.
  39375. */
  39376. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  39377. return (this._instanceDirtyFlags & flags) !== 0;
  39378. };
  39379. /**
  39380. * Clear a given set of properties.
  39381. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39382. * @return the new set of property still marked as dirty
  39383. */
  39384. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  39385. this._instanceDirtyFlags &= ~flags;
  39386. return this._instanceDirtyFlags;
  39387. };
  39388. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  39389. this._instanceDirtyFlags = 0;
  39390. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  39391. };
  39392. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  39393. /**
  39394. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  39395. */
  39396. get: function () {
  39397. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  39398. this.updateLevelBoundingInfo();
  39399. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39400. }
  39401. return this._levelBoundingInfo;
  39402. },
  39403. enumerable: true,
  39404. configurable: true
  39405. });
  39406. /**
  39407. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  39408. */
  39409. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  39410. };
  39411. /**
  39412. * Property method called when the Primitive becomes dirty
  39413. */
  39414. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  39415. };
  39416. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  39417. return function (target, propName, descriptor) {
  39418. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  39419. if (piStore) {
  39420. piStore(propInfo);
  39421. }
  39422. var getter = descriptor.get, setter = descriptor.set;
  39423. // Overload the property setter implementation to add our own logic
  39424. descriptor.set = function (val) {
  39425. // check for disposed first, do nothing
  39426. if (this.isDisposed) {
  39427. return;
  39428. }
  39429. var curVal = getter.call(this);
  39430. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  39431. return;
  39432. }
  39433. // Cast the object we're working one
  39434. var prim = this;
  39435. // Change the value
  39436. setter.call(this, val);
  39437. // Notify change, dirty flags update
  39438. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  39439. };
  39440. };
  39441. };
  39442. /**
  39443. * Add an externally attached data from its key.
  39444. * This method call will fail and return false, if such key already exists.
  39445. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  39446. * @param key the unique key that identifies the data
  39447. * @param data the data object to associate to the key for this Engine instance
  39448. * @return true if no such key were already present and the data was added successfully, false otherwise
  39449. */
  39450. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  39451. if (!this._externalData) {
  39452. this._externalData = new BABYLON.StringDictionary();
  39453. }
  39454. return this._externalData.add(key, data);
  39455. };
  39456. /**
  39457. * Get an externally attached data from its key
  39458. * @param key the unique key that identifies the data
  39459. * @return the associated data, if present (can be null), or undefined if not present
  39460. */
  39461. SmartPropertyPrim.prototype.getExternalData = function (key) {
  39462. if (!this._externalData) {
  39463. return null;
  39464. }
  39465. return this._externalData.get(key);
  39466. };
  39467. /**
  39468. * Get an externally attached data from its key, create it using a factory if it's not already present
  39469. * @param key the unique key that identifies the data
  39470. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  39471. * @return the associated data, can be null if the factory returned null.
  39472. */
  39473. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  39474. if (!this._externalData) {
  39475. this._externalData = new BABYLON.StringDictionary();
  39476. }
  39477. return this._externalData.getOrAddWithFactory(key, factory);
  39478. };
  39479. /**
  39480. * Remove an externally attached data from the Engine instance
  39481. * @param key the unique key that identifies the data
  39482. * @return true if the data was successfully removed, false if it doesn't exist
  39483. */
  39484. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  39485. if (!this._externalData) {
  39486. return false;
  39487. }
  39488. return this._externalData.remove(key);
  39489. };
  39490. /**
  39491. * Check if a given flag is set
  39492. * @param flag the flag value
  39493. * @return true if set, false otherwise
  39494. */
  39495. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  39496. return (this._flags & flag) !== 0;
  39497. };
  39498. /**
  39499. * Check if all given flags are set
  39500. * @param flags the flags ORed
  39501. * @return true if all the flags are set, false otherwise
  39502. */
  39503. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  39504. return (this._flags & flags) === flags;
  39505. };
  39506. /**
  39507. * Check if at least one flag of the given flags is set
  39508. * @param flags the flags ORed
  39509. * @return true if at least one flag is set, false otherwise
  39510. */
  39511. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  39512. return (this._flags & flags) !== 0;
  39513. };
  39514. /**
  39515. * Clear the given flags
  39516. * @param flags the flags to clear
  39517. */
  39518. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  39519. this._flags &= ~flags;
  39520. };
  39521. /**
  39522. * Set the given flags to true state
  39523. * @param flags the flags ORed to set
  39524. * @return the flags state before this call
  39525. */
  39526. SmartPropertyPrim.prototype._setFlags = function (flags) {
  39527. var cur = this._flags;
  39528. this._flags |= flags;
  39529. return cur;
  39530. };
  39531. /**
  39532. * Change the state of the given flags
  39533. * @param flags the flags ORed to change
  39534. * @param state true to set them, false to clear them
  39535. */
  39536. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  39537. if (state) {
  39538. this._flags |= flags;
  39539. }
  39540. else {
  39541. this._flags &= ~flags;
  39542. }
  39543. };
  39544. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  39545. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  39546. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  39547. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  39548. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  39549. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  39550. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  39551. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  39552. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  39553. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  39554. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  39555. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  39556. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  39557. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  39558. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  39559. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  39560. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  39561. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  39562. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  39563. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  39564. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  39565. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  39566. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0100000; // set if the layout bounding info is dirty
  39567. SmartPropertyPrim = __decorate([
  39568. BABYLON.className("SmartPropertyPrim")
  39569. ], SmartPropertyPrim);
  39570. return SmartPropertyPrim;
  39571. }());
  39572. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  39573. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39574. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39575. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39576. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39577. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  39578. }
  39579. BABYLON.modelLevelProperty = modelLevelProperty;
  39580. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39581. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39582. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39583. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39584. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  39585. }
  39586. BABYLON.instanceLevelProperty = instanceLevelProperty;
  39587. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39588. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39589. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39590. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39591. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  39592. }
  39593. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  39594. })(BABYLON || (BABYLON = {}));
  39595. var BABYLON;
  39596. (function (BABYLON) {
  39597. var PrepareRender2DContext = (function () {
  39598. function PrepareRender2DContext() {
  39599. this.forceRefreshPrimitive = false;
  39600. }
  39601. return PrepareRender2DContext;
  39602. }());
  39603. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  39604. var Render2DContext = (function () {
  39605. function Render2DContext(renderMode) {
  39606. this._renderMode = renderMode;
  39607. this.useInstancing = false;
  39608. this.groupInfoPartData = null;
  39609. this.partDataStartIndex = this.partDataEndIndex = null;
  39610. this.instancedBuffers = null;
  39611. }
  39612. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  39613. /**
  39614. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  39615. */
  39616. get: function () {
  39617. return this._renderMode;
  39618. },
  39619. enumerable: true,
  39620. configurable: true
  39621. });
  39622. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39623. /**
  39624. * The set of primitives to render is opaque.
  39625. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39626. */
  39627. get: function () {
  39628. return Render2DContext._renderModeOpaque;
  39629. },
  39630. enumerable: true,
  39631. configurable: true
  39632. });
  39633. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39634. /**
  39635. * The set of primitives to render is using Alpha Test (aka masking).
  39636. * 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.
  39637. */
  39638. get: function () {
  39639. return Render2DContext._renderModeAlphaTest;
  39640. },
  39641. enumerable: true,
  39642. configurable: true
  39643. });
  39644. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39645. /**
  39646. * The set of primitives to render is transparent.
  39647. * 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.
  39648. */
  39649. get: function () {
  39650. return Render2DContext._renderModeTransparent;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Render2DContext._renderModeOpaque = 1;
  39656. Render2DContext._renderModeAlphaTest = 2;
  39657. Render2DContext._renderModeTransparent = 3;
  39658. return Render2DContext;
  39659. }());
  39660. BABYLON.Render2DContext = Render2DContext;
  39661. /**
  39662. * This class store information for the pointerEventObservable Observable.
  39663. * 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.
  39664. */
  39665. var PrimitivePointerInfo = (function () {
  39666. function PrimitivePointerInfo() {
  39667. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39668. this.tilt = BABYLON.Vector2.Zero();
  39669. this.cancelBubble = false;
  39670. }
  39671. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39672. // 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.
  39673. /**
  39674. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39675. * Bubbles: yes
  39676. */
  39677. get: function () {
  39678. return PrimitivePointerInfo._pointerOver;
  39679. },
  39680. enumerable: true,
  39681. configurable: true
  39682. });
  39683. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39684. /**
  39685. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39686. * Bubbles: no
  39687. */
  39688. get: function () {
  39689. return PrimitivePointerInfo._pointerEnter;
  39690. },
  39691. enumerable: true,
  39692. configurable: true
  39693. });
  39694. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39695. /**
  39696. * 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.
  39697. * Bubbles: yes
  39698. */
  39699. get: function () {
  39700. return PrimitivePointerInfo._pointerDown;
  39701. },
  39702. enumerable: true,
  39703. configurable: true
  39704. });
  39705. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39706. /**
  39707. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39708. * Bubbles: yes
  39709. */
  39710. get: function () {
  39711. return PrimitivePointerInfo._pointerMouseWheel;
  39712. },
  39713. enumerable: true,
  39714. configurable: true
  39715. });
  39716. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39717. /**
  39718. * 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.
  39719. * Bubbles: yes
  39720. */
  39721. get: function () {
  39722. return PrimitivePointerInfo._pointerMove;
  39723. },
  39724. enumerable: true,
  39725. configurable: true
  39726. });
  39727. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39728. /**
  39729. * 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.
  39730. * Bubbles: yes
  39731. */
  39732. get: function () {
  39733. return PrimitivePointerInfo._pointerUp;
  39734. },
  39735. enumerable: true,
  39736. configurable: true
  39737. });
  39738. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39739. /**
  39740. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39741. * Bubbles: yes
  39742. */
  39743. get: function () {
  39744. return PrimitivePointerInfo._pointerOut;
  39745. },
  39746. enumerable: true,
  39747. configurable: true
  39748. });
  39749. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39750. /**
  39751. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39752. * Bubbles: no
  39753. */
  39754. get: function () {
  39755. return PrimitivePointerInfo._pointerLeave;
  39756. },
  39757. enumerable: true,
  39758. configurable: true
  39759. });
  39760. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39761. /**
  39762. * 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.
  39763. * Bubbles: yes
  39764. */
  39765. get: function () {
  39766. return PrimitivePointerInfo._pointerGotCapture;
  39767. },
  39768. enumerable: true,
  39769. configurable: true
  39770. });
  39771. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39772. /**
  39773. * This event type is raised after pointer capture is released for a pointer.
  39774. * Bubbles: yes
  39775. */
  39776. get: function () {
  39777. return PrimitivePointerInfo._pointerLostCapture;
  39778. },
  39779. enumerable: true,
  39780. configurable: true
  39781. });
  39782. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39783. get: function () {
  39784. return PrimitivePointerInfo._mouseWheelPrecision;
  39785. },
  39786. enumerable: true,
  39787. configurable: true
  39788. });
  39789. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39790. this.relatedTarget = prim;
  39791. this.relatedTargetPointerPos = primPointerPos;
  39792. };
  39793. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39794. switch (mask) {
  39795. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39796. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39797. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39798. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39799. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39800. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39801. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39802. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39803. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39804. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39805. }
  39806. };
  39807. PrimitivePointerInfo._pointerOver = 0x0001;
  39808. PrimitivePointerInfo._pointerEnter = 0x0002;
  39809. PrimitivePointerInfo._pointerDown = 0x0004;
  39810. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39811. PrimitivePointerInfo._pointerMove = 0x0010;
  39812. PrimitivePointerInfo._pointerUp = 0x0020;
  39813. PrimitivePointerInfo._pointerOut = 0x0040;
  39814. PrimitivePointerInfo._pointerLeave = 0x0080;
  39815. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39816. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39817. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39818. return PrimitivePointerInfo;
  39819. }());
  39820. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39821. /**
  39822. * Defines the horizontal and vertical alignment information for a Primitive.
  39823. */
  39824. var PrimitiveAlignment = (function () {
  39825. function PrimitiveAlignment(changeCallback) {
  39826. this._changedCallback = changeCallback;
  39827. this._horizontal = PrimitiveAlignment.AlignLeft;
  39828. this._vertical = PrimitiveAlignment.AlignBottom;
  39829. }
  39830. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39831. /**
  39832. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39833. */
  39834. get: function () { return PrimitiveAlignment._AlignLeft; },
  39835. enumerable: true,
  39836. configurable: true
  39837. });
  39838. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39839. /**
  39840. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39841. */
  39842. get: function () { return PrimitiveAlignment._AlignTop; },
  39843. enumerable: true,
  39844. configurable: true
  39845. });
  39846. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39847. /**
  39848. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39849. */
  39850. get: function () { return PrimitiveAlignment._AlignRight; },
  39851. enumerable: true,
  39852. configurable: true
  39853. });
  39854. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39855. /**
  39856. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39857. */
  39858. get: function () { return PrimitiveAlignment._AlignBottom; },
  39859. enumerable: true,
  39860. configurable: true
  39861. });
  39862. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39863. /**
  39864. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39865. */
  39866. get: function () { return PrimitiveAlignment._AlignCenter; },
  39867. enumerable: true,
  39868. configurable: true
  39869. });
  39870. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39871. /**
  39872. * The content is stretched toward the opposite edges of the Primitive
  39873. */
  39874. get: function () { return PrimitiveAlignment._AlignStretch; },
  39875. enumerable: true,
  39876. configurable: true
  39877. });
  39878. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39879. /**
  39880. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39881. */
  39882. get: function () {
  39883. return this._horizontal;
  39884. },
  39885. set: function (value) {
  39886. if (this._horizontal === value) {
  39887. return;
  39888. }
  39889. this._horizontal = value;
  39890. this._changedCallback();
  39891. },
  39892. enumerable: true,
  39893. configurable: true
  39894. });
  39895. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39896. /**
  39897. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39898. */
  39899. get: function () {
  39900. return this._vertical;
  39901. },
  39902. set: function (value) {
  39903. if (this._vertical === value) {
  39904. return;
  39905. }
  39906. this._vertical = value;
  39907. this._changedCallback();
  39908. },
  39909. enumerable: true,
  39910. configurable: true
  39911. });
  39912. /**
  39913. * Set the horizontal alignment from a string value.
  39914. * @param text can be either: 'left','right','center','stretch'
  39915. */
  39916. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39917. var v = text.trim().toLocaleLowerCase();
  39918. switch (v) {
  39919. case "left":
  39920. this.horizontal = PrimitiveAlignment.AlignLeft;
  39921. return;
  39922. case "right":
  39923. this.horizontal = PrimitiveAlignment.AlignRight;
  39924. return;
  39925. case "center":
  39926. this.horizontal = PrimitiveAlignment.AlignCenter;
  39927. return;
  39928. case "stretch":
  39929. this.horizontal = PrimitiveAlignment.AlignStretch;
  39930. return;
  39931. }
  39932. };
  39933. /**
  39934. * Set the vertical alignment from a string value.
  39935. * @param text can be either: 'top','bottom','center','stretch'
  39936. */
  39937. PrimitiveAlignment.prototype.setVertical = function (text) {
  39938. var v = text.trim().toLocaleLowerCase();
  39939. switch (v) {
  39940. case "top":
  39941. this.vertical = PrimitiveAlignment.AlignTop;
  39942. return;
  39943. case "bottom":
  39944. this.vertical = PrimitiveAlignment.AlignBottom;
  39945. return;
  39946. case "center":
  39947. this.vertical = PrimitiveAlignment.AlignCenter;
  39948. return;
  39949. case "stretch":
  39950. this.vertical = PrimitiveAlignment.AlignStretch;
  39951. return;
  39952. }
  39953. };
  39954. /**
  39955. * Set the horizontal and or vertical alignments from a string value.
  39956. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39957. */
  39958. PrimitiveAlignment.prototype.fromString = function (value) {
  39959. var m = value.trim().split(",");
  39960. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  39961. var v = m_1[_i];
  39962. v = v.toLocaleLowerCase().trim();
  39963. // Horizontal
  39964. var i = v.indexOf("h:");
  39965. if (i === -1) {
  39966. i = v.indexOf("horizontal:");
  39967. }
  39968. if (i !== -1) {
  39969. v = v.substr(v.indexOf(":") + 1);
  39970. this.setHorizontal(v);
  39971. continue;
  39972. }
  39973. // Vertical
  39974. i = v.indexOf("v:");
  39975. if (i === -1) {
  39976. i = v.indexOf("vertical:");
  39977. }
  39978. if (i !== -1) {
  39979. v = v.substr(v.indexOf(":") + 1);
  39980. this.setVertical(v);
  39981. continue;
  39982. }
  39983. }
  39984. };
  39985. PrimitiveAlignment._AlignLeft = 1;
  39986. PrimitiveAlignment._AlignTop = 1; // Same as left
  39987. PrimitiveAlignment._AlignRight = 2;
  39988. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39989. PrimitiveAlignment._AlignCenter = 3;
  39990. PrimitiveAlignment._AlignStretch = 4;
  39991. return PrimitiveAlignment;
  39992. }());
  39993. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39994. /**
  39995. * Stores information about a Primitive that was intersected
  39996. */
  39997. var PrimitiveIntersectedInfo = (function () {
  39998. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39999. this.prim = prim;
  40000. this.intersectionLocation = intersectionLocation;
  40001. }
  40002. return PrimitiveIntersectedInfo;
  40003. }());
  40004. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  40005. /**
  40006. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  40007. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  40008. */
  40009. var PrimitiveThickness = (function () {
  40010. function PrimitiveThickness(parentAccess, changedCallback) {
  40011. this._parentAccess = parentAccess;
  40012. this._changedCallback = changedCallback;
  40013. this._pixels = new Array(4);
  40014. this._percentages = new Array(4);
  40015. this._setType(0, PrimitiveThickness.Auto);
  40016. this._setType(1, PrimitiveThickness.Auto);
  40017. this._setType(2, PrimitiveThickness.Auto);
  40018. this._setType(3, PrimitiveThickness.Auto);
  40019. this._pixels[0] = 0;
  40020. this._pixels[1] = 0;
  40021. this._pixels[2] = 0;
  40022. this._pixels[3] = 0;
  40023. }
  40024. /**
  40025. * Set the thickness from a string value
  40026. * @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.
  40027. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40028. */
  40029. PrimitiveThickness.prototype.fromString = function (thickness) {
  40030. this._clear();
  40031. var m = thickness.trim().split(",");
  40032. // Special case, one value to apply to all edges
  40033. if (m.length === 1 && thickness.indexOf(":") === -1) {
  40034. this._setStringValue(m[0], 0, false);
  40035. this._setStringValue(m[0], 1, false);
  40036. this._setStringValue(m[0], 2, false);
  40037. this._setStringValue(m[0], 3, false);
  40038. this._changedCallback();
  40039. return;
  40040. }
  40041. var res = false;
  40042. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  40043. var cm = m_2[_i];
  40044. res = this._extractString(cm, false) || res;
  40045. }
  40046. if (!res) {
  40047. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  40048. }
  40049. // Check the margin that weren't set and set them in auto
  40050. if ((this._flags & 0x000F) === 0)
  40051. this._flags |= PrimitiveThickness.Pixel << 0;
  40052. if ((this._flags & 0x00F0) === 0)
  40053. this._flags |= PrimitiveThickness.Pixel << 4;
  40054. if ((this._flags & 0x0F00) === 0)
  40055. this._flags |= PrimitiveThickness.Pixel << 8;
  40056. if ((this._flags & 0xF000) === 0)
  40057. this._flags |= PrimitiveThickness.Pixel << 12;
  40058. this._changedCallback();
  40059. };
  40060. /**
  40061. * Set the thickness from multiple string
  40062. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40063. * @param top the top thickness to set
  40064. * @param left the left thickness to set
  40065. * @param right the right thickness to set
  40066. * @param bottom the bottom thickness to set
  40067. */
  40068. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  40069. this._clear();
  40070. this._setStringValue(top, 0, false);
  40071. this._setStringValue(left, 1, false);
  40072. this._setStringValue(right, 2, false);
  40073. this._setStringValue(bottom, 3, false);
  40074. this._changedCallback();
  40075. return this;
  40076. };
  40077. /**
  40078. * Set the thickness from pixel values
  40079. * @param top the top thickness in pixels to set
  40080. * @param left the left thickness in pixels to set
  40081. * @param right the right thickness in pixels to set
  40082. * @param bottom the bottom thickness in pixels to set
  40083. */
  40084. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  40085. this._clear();
  40086. this._pixels[0] = top;
  40087. this._pixels[1] = left;
  40088. this._pixels[2] = right;
  40089. this._pixels[3] = bottom;
  40090. this._changedCallback();
  40091. return this;
  40092. };
  40093. /**
  40094. * Apply the same pixel value to all edges
  40095. * @param margin the value to set, in pixels.
  40096. */
  40097. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  40098. this._clear();
  40099. this._pixels[0] = margin;
  40100. this._pixels[1] = margin;
  40101. this._pixels[2] = margin;
  40102. this._pixels[3] = margin;
  40103. this._changedCallback();
  40104. return this;
  40105. };
  40106. /**
  40107. * Set all edges in auto
  40108. */
  40109. PrimitiveThickness.prototype.auto = function () {
  40110. this._clear();
  40111. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  40112. this._pixels[0] = 0;
  40113. this._pixels[1] = 0;
  40114. this._pixels[2] = 0;
  40115. this._pixels[3] = 0;
  40116. this._changedCallback();
  40117. return this;
  40118. };
  40119. PrimitiveThickness.prototype._clear = function () {
  40120. this._flags = 0;
  40121. this._pixels[0] = 0;
  40122. this._pixels[1] = 0;
  40123. this._pixels[2] = 0;
  40124. this._pixels[3] = 0;
  40125. this._percentages[0] = null;
  40126. this._percentages[1] = null;
  40127. this._percentages[2] = null;
  40128. this._percentages[3] = null;
  40129. };
  40130. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  40131. var v = value.trim().toLocaleLowerCase();
  40132. if (v.indexOf("top:") === 0) {
  40133. v = v.substr(4).trim();
  40134. return this._setStringValue(v, 0, emitChanged);
  40135. }
  40136. if (v.indexOf("left:") === 0) {
  40137. v = v.substr(5).trim();
  40138. return this._setStringValue(v, 1, emitChanged);
  40139. }
  40140. if (v.indexOf("right:") === 0) {
  40141. v = v.substr(6).trim();
  40142. return this._setStringValue(v, 2, emitChanged);
  40143. }
  40144. if (v.indexOf("bottom:") === 0) {
  40145. v = v.substr(7).trim();
  40146. return this._setStringValue(v, 3, emitChanged);
  40147. }
  40148. return false;
  40149. };
  40150. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  40151. // Check for auto
  40152. var v = value.trim().toLocaleLowerCase();
  40153. if (v === "auto") {
  40154. if (this._isType(index, PrimitiveThickness.Auto)) {
  40155. return true;
  40156. }
  40157. this._setType(index, PrimitiveThickness.Auto);
  40158. this._pixels[index] = 0;
  40159. if (emitChanged) {
  40160. this._changedCallback();
  40161. }
  40162. }
  40163. else if (v === "inherit") {
  40164. if (this._isType(index, PrimitiveThickness.Inherit)) {
  40165. return true;
  40166. }
  40167. this._setType(index, PrimitiveThickness.Inherit);
  40168. this._pixels[index] = null;
  40169. if (emitChanged) {
  40170. this._changedCallback();
  40171. }
  40172. }
  40173. else {
  40174. var pI = v.indexOf("%");
  40175. // Check for percentage
  40176. if (pI !== -1) {
  40177. var n_1 = v.substr(0, pI);
  40178. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  40179. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  40180. return true;
  40181. }
  40182. this._setType(index, PrimitiveThickness.Percentage);
  40183. if (isNaN(number_1)) {
  40184. return false;
  40185. }
  40186. this._percentages[index] = number_1;
  40187. if (emitChanged) {
  40188. this._changedCallback();
  40189. }
  40190. return true;
  40191. }
  40192. // Check for pixel
  40193. var n = void 0;
  40194. pI = v.indexOf("px");
  40195. if (pI !== -1) {
  40196. n = v.substr(0, pI).trim();
  40197. }
  40198. else {
  40199. n = v;
  40200. }
  40201. var number = Number(n);
  40202. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  40203. return true;
  40204. }
  40205. if (isNaN(number)) {
  40206. return false;
  40207. }
  40208. this._pixels[index] = number;
  40209. this._setType(index, PrimitiveThickness.Pixel);
  40210. if (emitChanged) {
  40211. this._changedCallback();
  40212. }
  40213. return true;
  40214. }
  40215. };
  40216. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  40217. // 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
  40218. value = Math.round(value);
  40219. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  40220. return;
  40221. }
  40222. this._setType(index, PrimitiveThickness.Pixel);
  40223. this._pixels[index] = value;
  40224. if (emitChanged) {
  40225. this._changedCallback();
  40226. }
  40227. };
  40228. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  40229. // Clip Value to bounds
  40230. value = Math.min(1, value);
  40231. value = Math.max(0, value);
  40232. value = Math.round(value * 100) / 100; // 0.01 precision
  40233. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  40234. return;
  40235. }
  40236. this._setType(index, PrimitiveThickness.Percentage);
  40237. this._percentages[index] = value;
  40238. if (emitChanged) {
  40239. this._changedCallback();
  40240. }
  40241. };
  40242. PrimitiveThickness.prototype._getStringValue = function (index) {
  40243. var f = (this._flags >> (index * 4)) & 0xF;
  40244. switch (f) {
  40245. case PrimitiveThickness.Auto:
  40246. return "auto";
  40247. case PrimitiveThickness.Pixel:
  40248. return this._pixels[index] + "px";
  40249. case PrimitiveThickness.Percentage:
  40250. return this._percentages[index] * 100 + "%";
  40251. case PrimitiveThickness.Inherit:
  40252. return "inherit";
  40253. }
  40254. return "";
  40255. };
  40256. PrimitiveThickness.prototype._isType = function (index, type) {
  40257. var f = (this._flags >> (index * 4)) & 0xF;
  40258. return f === type;
  40259. };
  40260. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  40261. var t = (this._flags >> (index * 4)) & 0xF;
  40262. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  40263. var p = this._parentAccess();
  40264. if (p) {
  40265. return p._getType(index, true);
  40266. }
  40267. return PrimitiveThickness.Auto;
  40268. }
  40269. return t;
  40270. };
  40271. PrimitiveThickness.prototype._setType = function (index, type) {
  40272. this._flags &= ~(0xF << (index * 4));
  40273. this._flags |= type << (index * 4);
  40274. };
  40275. PrimitiveThickness.prototype.setTop = function (value) {
  40276. if (typeof value === "string") {
  40277. this._setStringValue(value, 0, true);
  40278. }
  40279. else {
  40280. this.topPixels = value;
  40281. }
  40282. };
  40283. PrimitiveThickness.prototype.setLeft = function (value) {
  40284. if (typeof value === "string") {
  40285. this._setStringValue(value, 1, true);
  40286. }
  40287. else {
  40288. this.leftPixels = value;
  40289. }
  40290. };
  40291. PrimitiveThickness.prototype.setRight = function (value) {
  40292. if (typeof value === "string") {
  40293. this._setStringValue(value, 2, true);
  40294. }
  40295. else {
  40296. this.rightPixels = value;
  40297. }
  40298. };
  40299. PrimitiveThickness.prototype.setBottom = function (value) {
  40300. if (typeof value === "string") {
  40301. this._setStringValue(value, 3, true);
  40302. }
  40303. else {
  40304. this.bottomPixels = value;
  40305. }
  40306. };
  40307. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  40308. /**
  40309. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40310. */
  40311. get: function () {
  40312. return this._getStringValue(0);
  40313. },
  40314. set: function (value) {
  40315. this._setStringValue(value, 0, true);
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  40321. /**
  40322. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40323. */
  40324. get: function () {
  40325. return this._getStringValue(1);
  40326. },
  40327. set: function (value) {
  40328. this._setStringValue(value, 1, true);
  40329. },
  40330. enumerable: true,
  40331. configurable: true
  40332. });
  40333. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  40334. /**
  40335. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40336. */
  40337. get: function () {
  40338. return this._getStringValue(2);
  40339. },
  40340. set: function (value) {
  40341. this._setStringValue(value, 2, true);
  40342. },
  40343. enumerable: true,
  40344. configurable: true
  40345. });
  40346. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  40347. /**
  40348. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40349. */
  40350. get: function () {
  40351. return this._getStringValue(3);
  40352. },
  40353. set: function (value) {
  40354. this._setStringValue(value, 3, true);
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  40360. /**
  40361. * Get/set the top thickness in pixel.
  40362. */
  40363. get: function () {
  40364. return this._pixels[0];
  40365. },
  40366. set: function (value) {
  40367. this._setPixels(value, 0, true);
  40368. },
  40369. enumerable: true,
  40370. configurable: true
  40371. });
  40372. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  40373. /**
  40374. * Get/set the left thickness in pixel.
  40375. */
  40376. get: function () {
  40377. return this._pixels[1];
  40378. },
  40379. set: function (value) {
  40380. this._setPixels(value, 1, true);
  40381. },
  40382. enumerable: true,
  40383. configurable: true
  40384. });
  40385. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  40386. /**
  40387. * Get/set the right thickness in pixel.
  40388. */
  40389. get: function () {
  40390. return this._pixels[2];
  40391. },
  40392. set: function (value) {
  40393. this._setPixels(value, 2, true);
  40394. },
  40395. enumerable: true,
  40396. configurable: true
  40397. });
  40398. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  40399. /**
  40400. * Get/set the bottom thickness in pixel.
  40401. */
  40402. get: function () {
  40403. return this._pixels[3];
  40404. },
  40405. set: function (value) {
  40406. this._setPixels(value, 3, true);
  40407. },
  40408. enumerable: true,
  40409. configurable: true
  40410. });
  40411. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  40412. /**
  40413. * Get/set the top thickness in percentage.
  40414. * The get will return a valid value only if the edge type is percentage.
  40415. * The Set will change the edge mode if needed
  40416. */
  40417. get: function () {
  40418. return this._percentages[0];
  40419. },
  40420. set: function (value) {
  40421. this._setPercentage(value, 0, true);
  40422. },
  40423. enumerable: true,
  40424. configurable: true
  40425. });
  40426. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  40427. /**
  40428. * Get/set the left thickness in percentage.
  40429. * The get will return a valid value only if the edge mode is percentage.
  40430. * The Set will change the edge mode if needed
  40431. */
  40432. get: function () {
  40433. return this._percentages[1];
  40434. },
  40435. set: function (value) {
  40436. this._setPercentage(value, 1, true);
  40437. },
  40438. enumerable: true,
  40439. configurable: true
  40440. });
  40441. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  40442. /**
  40443. * Get/set the right thickness in percentage.
  40444. * The get will return a valid value only if the edge mode is percentage.
  40445. * The Set will change the edge mode if needed
  40446. */
  40447. get: function () {
  40448. return this._percentages[2];
  40449. },
  40450. set: function (value) {
  40451. this._setPercentage(value, 2, true);
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  40457. /**
  40458. * Get/set the bottom thickness in percentage.
  40459. * The get will return a valid value only if the edge mode is percentage.
  40460. * The Set will change the edge mode if needed
  40461. */
  40462. get: function () {
  40463. return this._percentages[3];
  40464. },
  40465. set: function (value) {
  40466. this._setPercentage(value, 3, true);
  40467. },
  40468. enumerable: true,
  40469. configurable: true
  40470. });
  40471. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  40472. /**
  40473. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  40474. */
  40475. get: function () {
  40476. return this._getType(0, false);
  40477. },
  40478. set: function (mode) {
  40479. this._setType(0, mode);
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  40485. /**
  40486. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  40487. */
  40488. get: function () {
  40489. return this._getType(1, false);
  40490. },
  40491. set: function (mode) {
  40492. this._setType(1, mode);
  40493. },
  40494. enumerable: true,
  40495. configurable: true
  40496. });
  40497. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  40498. /**
  40499. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  40500. */
  40501. get: function () {
  40502. return this._getType(2, false);
  40503. },
  40504. set: function (mode) {
  40505. this._setType(2, mode);
  40506. },
  40507. enumerable: true,
  40508. configurable: true
  40509. });
  40510. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  40511. /**
  40512. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  40513. */
  40514. get: function () {
  40515. return this._getType(3, false);
  40516. },
  40517. set: function (mode) {
  40518. this._setType(3, mode);
  40519. },
  40520. enumerable: true,
  40521. configurable: true
  40522. });
  40523. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  40524. var type = this._getType(index, false);
  40525. if (type === PrimitiveThickness.Inherit) {
  40526. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  40527. return;
  40528. }
  40529. if (type !== PrimitiveThickness.Percentage) {
  40530. return;
  40531. }
  40532. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  40533. this._pixels[index] = pixels;
  40534. if (emitChanged) {
  40535. this._changedCallback();
  40536. }
  40537. };
  40538. /**
  40539. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  40540. * @param sourceArea the source area where the content must be sized/positioned
  40541. * @param contentSize the content size to position/resize
  40542. * @param alignment the alignment setting
  40543. * @param dstOffset the position of the content
  40544. * @param dstArea the new size of the content
  40545. */
  40546. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  40547. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  40548. // Fetch some data
  40549. var topType = this._getType(0, true);
  40550. var leftType = this._getType(1, true);
  40551. var rightType = this._getType(2, true);
  40552. var bottomType = this._getType(3, true);
  40553. var hasWidth = contentSize && (contentSize.width != null);
  40554. var hasHeight = contentSize && (contentSize.height != null);
  40555. var width = hasWidth ? contentSize.width : 0;
  40556. var height = hasHeight ? contentSize.height : 0;
  40557. var isTopAuto = topType === PrimitiveThickness.Auto;
  40558. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  40559. var isRightAuto = rightType === PrimitiveThickness.Auto;
  40560. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  40561. switch (alignment.horizontal) {
  40562. case PrimitiveAlignment.AlignLeft:
  40563. {
  40564. if (isLeftAuto) {
  40565. dstOffset.x = 0;
  40566. }
  40567. else {
  40568. this._computePixels(1, sourceArea, true);
  40569. dstOffset.x = this.leftPixels;
  40570. }
  40571. dstArea.width = width;
  40572. if (computeLayoutArea) {
  40573. dstArea.width += this.leftPixels;
  40574. }
  40575. break;
  40576. }
  40577. case PrimitiveAlignment.AlignRight:
  40578. {
  40579. if (isRightAuto) {
  40580. dstOffset.x = Math.round(sourceArea.width - width);
  40581. }
  40582. else {
  40583. this._computePixels(2, sourceArea, true);
  40584. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  40585. }
  40586. dstArea.width = width;
  40587. if (computeLayoutArea) {
  40588. dstArea.width += this.rightPixels;
  40589. }
  40590. break;
  40591. }
  40592. case PrimitiveAlignment.AlignStretch:
  40593. {
  40594. if (isLeftAuto) {
  40595. dstOffset.x = 0;
  40596. }
  40597. else {
  40598. this._computePixels(1, sourceArea, true);
  40599. dstOffset.x = this.leftPixels;
  40600. }
  40601. var right = 0;
  40602. if (!isRightAuto) {
  40603. this._computePixels(2, sourceArea, true);
  40604. right = this.rightPixels;
  40605. }
  40606. dstArea.width = sourceArea.width - (dstOffset.x + right);
  40607. break;
  40608. }
  40609. case PrimitiveAlignment.AlignCenter:
  40610. {
  40611. if (!isLeftAuto) {
  40612. this._computePixels(1, sourceArea, true);
  40613. }
  40614. if (!isRightAuto) {
  40615. this._computePixels(2, sourceArea, true);
  40616. }
  40617. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  40618. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  40619. dstArea.width = width;
  40620. break;
  40621. }
  40622. }
  40623. switch (alignment.vertical) {
  40624. case PrimitiveAlignment.AlignTop:
  40625. {
  40626. if (isTopAuto) {
  40627. dstOffset.y = sourceArea.height - height;
  40628. }
  40629. else {
  40630. this._computePixels(0, sourceArea, true);
  40631. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40632. }
  40633. dstArea.height = height;
  40634. if (computeLayoutArea) {
  40635. dstArea.height += this.topPixels;
  40636. }
  40637. break;
  40638. }
  40639. case PrimitiveAlignment.AlignBottom:
  40640. {
  40641. if (isBottomAuto) {
  40642. dstOffset.y = 0;
  40643. }
  40644. else {
  40645. this._computePixels(3, sourceArea, true);
  40646. dstOffset.y = this.bottomPixels;
  40647. }
  40648. dstArea.height = height;
  40649. if (computeLayoutArea) {
  40650. dstArea.height += this.bottomPixels;
  40651. }
  40652. break;
  40653. }
  40654. case PrimitiveAlignment.AlignStretch:
  40655. {
  40656. if (isBottomAuto) {
  40657. dstOffset.y = 0;
  40658. }
  40659. else {
  40660. this._computePixels(3, sourceArea, true);
  40661. dstOffset.y = this.bottomPixels;
  40662. }
  40663. var top_1 = 0;
  40664. if (!isTopAuto) {
  40665. this._computePixels(0, sourceArea, true);
  40666. top_1 = this.topPixels;
  40667. }
  40668. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40669. break;
  40670. }
  40671. case PrimitiveAlignment.AlignCenter:
  40672. {
  40673. if (!isTopAuto) {
  40674. this._computePixels(0, sourceArea, true);
  40675. }
  40676. if (!isBottomAuto) {
  40677. this._computePixels(3, sourceArea, true);
  40678. }
  40679. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40680. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40681. dstArea.height = height;
  40682. break;
  40683. }
  40684. }
  40685. };
  40686. /**
  40687. * Compute an area and its position considering this thickness properties based on a given source area
  40688. * @param sourceArea the source area
  40689. * @param dstOffset the position of the resulting area
  40690. * @param dstArea the size of the resulting area
  40691. */
  40692. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40693. this._computePixels(0, sourceArea, true);
  40694. this._computePixels(1, sourceArea, true);
  40695. this._computePixels(2, sourceArea, true);
  40696. this._computePixels(3, sourceArea, true);
  40697. dstOffset.x = this.leftPixels;
  40698. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40699. dstOffset.y = this.bottomPixels;
  40700. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40701. };
  40702. /**
  40703. * Compute an area considering this thickness properties based on a given source area
  40704. * @param sourceArea the source area
  40705. * @param result the resulting area
  40706. */
  40707. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40708. this._computePixels(0, sourceArea, true);
  40709. this._computePixels(1, sourceArea, true);
  40710. this._computePixels(2, sourceArea, true);
  40711. this._computePixels(3, sourceArea, true);
  40712. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40713. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40714. };
  40715. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40716. this._computePixels(0, sourceArea, true);
  40717. this._computePixels(1, sourceArea, true);
  40718. this._computePixels(2, sourceArea, true);
  40719. this._computePixels(3, sourceArea, true);
  40720. dstOffset.x = this.leftPixels;
  40721. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40722. dstOffset.y = this.bottomPixels;
  40723. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40724. };
  40725. PrimitiveThickness.Auto = 0x1;
  40726. PrimitiveThickness.Inherit = 0x2;
  40727. PrimitiveThickness.Percentage = 0x4;
  40728. PrimitiveThickness.Pixel = 0x8;
  40729. return PrimitiveThickness;
  40730. }());
  40731. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40732. /**
  40733. * Main class used for the Primitive Intersection API
  40734. */
  40735. var IntersectInfo2D = (function () {
  40736. function IntersectInfo2D() {
  40737. this.findFirstOnly = false;
  40738. this.intersectHidden = false;
  40739. this.pickPosition = BABYLON.Vector2.Zero();
  40740. }
  40741. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40742. /**
  40743. * true if at least one primitive intersected during the test
  40744. */
  40745. get: function () {
  40746. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40747. },
  40748. enumerable: true,
  40749. configurable: true
  40750. });
  40751. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40752. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40753. var cur = _a[_i];
  40754. if (cur.prim === prim) {
  40755. return cur.intersectionLocation;
  40756. }
  40757. }
  40758. return null;
  40759. };
  40760. // Internals, don't use
  40761. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40762. if (firstLevel) {
  40763. this._globalPickPosition = null;
  40764. }
  40765. };
  40766. return IntersectInfo2D;
  40767. }());
  40768. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40769. var Prim2DBase = (function (_super) {
  40770. __extends(Prim2DBase, _super);
  40771. function Prim2DBase(settings) {
  40772. // Avoid checking every time if the object exists
  40773. if (settings == null) {
  40774. settings = {};
  40775. }
  40776. // BASE CLASS CALL
  40777. _super.call(this);
  40778. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40779. var owner;
  40780. var parent;
  40781. if (Prim2DBase._isCanvasInit) {
  40782. owner = this;
  40783. parent = null;
  40784. this._canvasPreInit(settings);
  40785. }
  40786. else {
  40787. if (settings.parent != null) {
  40788. parent = settings.parent;
  40789. owner = settings.parent.owner;
  40790. if (!owner) {
  40791. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40792. }
  40793. 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)) {
  40794. 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");
  40795. }
  40796. }
  40797. }
  40798. // Fields initialization
  40799. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40800. this._size = null; //Size.Zero();
  40801. this._scale = new BABYLON.Vector2(1, 1);
  40802. this._actualSize = null;
  40803. this._boundingSize = BABYLON.Size.Zero();
  40804. this._layoutArea = BABYLON.Size.Zero();
  40805. this._layoutAreaPos = null;
  40806. this._layoutBoundingInfo = null;
  40807. this._marginOffset = BABYLON.Vector2.Zero();
  40808. this._paddingOffset = BABYLON.Vector2.Zero();
  40809. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40810. this._parentContentArea = BABYLON.Size.Zero();
  40811. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40812. this._contentArea = new BABYLON.Size(null, null);
  40813. this._pointerEventObservable = new BABYLON.Observable();
  40814. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40815. this._owner = owner;
  40816. this._parent = null;
  40817. this._margin = null;
  40818. this._padding = null;
  40819. this._marginAlignment = null;
  40820. this._id = settings.id;
  40821. this.propertyChanged = new BABYLON.Observable();
  40822. this._children = new Array();
  40823. this._localTransform = new BABYLON.Matrix();
  40824. this._globalTransform = null;
  40825. this._invGlobalTransform = null;
  40826. this._globalTransformProcessStep = 0;
  40827. this._globalTransformStep = 0;
  40828. this._renderGroup = null;
  40829. this._primLinearPosition = 0;
  40830. this._manualZOrder = null;
  40831. this._zOrder = 0;
  40832. this._zMax = 0;
  40833. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40834. this._actualOpacity = 0;
  40835. this._actualScale = BABYLON.Vector2.Zero();
  40836. var isPickable = true;
  40837. var isContainer = true;
  40838. if (settings.isPickable !== undefined) {
  40839. isPickable = settings.isPickable;
  40840. }
  40841. if (settings.isContainer !== undefined) {
  40842. isContainer = settings.isContainer;
  40843. }
  40844. if (settings.dontInheritParentScale) {
  40845. this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  40846. }
  40847. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  40848. if (settings.opacity != null) {
  40849. this._opacity = settings.opacity;
  40850. }
  40851. else {
  40852. this._opacity = 1;
  40853. }
  40854. this._updateRenderMode();
  40855. if (settings.childrenFlatZOrder) {
  40856. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40857. }
  40858. // If the parent is given, initialize the hierarchy/owner related data
  40859. if (parent != null) {
  40860. parent.addChild(this);
  40861. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40862. this._patchHierarchy(parent.owner);
  40863. }
  40864. // If it's a group, detect its own states
  40865. if (this.owner && this instanceof BABYLON.Group2D) {
  40866. var group = this;
  40867. group.detectGroupStates();
  40868. }
  40869. // Time to insert children if some are specified
  40870. if (settings.children != null) {
  40871. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40872. var child = _a[_i];
  40873. this.addChild(child);
  40874. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40875. if (this.owner != null) {
  40876. child._patchHierarchy(this.owner);
  40877. }
  40878. }
  40879. }
  40880. if (settings.zOrder != null) {
  40881. this.zOrder = settings.zOrder;
  40882. }
  40883. // Set the model related properties
  40884. if (settings.position != null) {
  40885. this.position = settings.position;
  40886. }
  40887. else if (settings.x != null || settings.y != null) {
  40888. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40889. }
  40890. else {
  40891. this._position = null;
  40892. }
  40893. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40894. if (settings.scale != null) {
  40895. this.scale = settings.scale;
  40896. }
  40897. else {
  40898. if (settings.scaleX != null) {
  40899. this.scaleX = settings.scaleX;
  40900. }
  40901. if (settings.scaleY != null) {
  40902. this.scaleY = settings.scaleY;
  40903. }
  40904. }
  40905. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40906. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40907. // Layout Engine
  40908. if (settings.layoutEngine != null) {
  40909. if (typeof settings.layoutEngine === "string") {
  40910. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40911. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40912. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40913. }
  40914. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40915. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40916. }
  40917. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40918. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40919. }
  40920. }
  40921. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40922. this.layoutEngine = settings.layoutEngine;
  40923. }
  40924. }
  40925. // Set the layout/margin stuffs
  40926. if (settings.marginTop) {
  40927. this.margin.setTop(settings.marginTop);
  40928. }
  40929. if (settings.marginLeft) {
  40930. this.margin.setLeft(settings.marginLeft);
  40931. }
  40932. if (settings.marginRight) {
  40933. this.margin.setRight(settings.marginRight);
  40934. }
  40935. if (settings.marginBottom) {
  40936. this.margin.setBottom(settings.marginBottom);
  40937. }
  40938. if (settings.margin) {
  40939. if (typeof settings.margin === "string") {
  40940. this.margin.fromString(settings.margin);
  40941. }
  40942. else {
  40943. this.margin.fromUniformPixels(settings.margin);
  40944. }
  40945. }
  40946. if (settings.marginHAlignment) {
  40947. this.marginAlignment.horizontal = settings.marginHAlignment;
  40948. }
  40949. if (settings.marginVAlignment) {
  40950. this.marginAlignment.vertical = settings.marginVAlignment;
  40951. }
  40952. if (settings.marginAlignment) {
  40953. this.marginAlignment.fromString(settings.marginAlignment);
  40954. }
  40955. if (settings.paddingTop) {
  40956. this.padding.setTop(settings.paddingTop);
  40957. }
  40958. if (settings.paddingLeft) {
  40959. this.padding.setLeft(settings.paddingLeft);
  40960. }
  40961. if (settings.paddingRight) {
  40962. this.padding.setRight(settings.paddingRight);
  40963. }
  40964. if (settings.paddingBottom) {
  40965. this.padding.setBottom(settings.paddingBottom);
  40966. }
  40967. if (settings.padding) {
  40968. this.padding.fromString(settings.padding);
  40969. }
  40970. // Dirty layout and positioning
  40971. this._parentLayoutDirty();
  40972. this._positioningDirty();
  40973. }
  40974. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40975. get: function () {
  40976. if (!this._actionManager) {
  40977. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40978. }
  40979. return this._actionManager;
  40980. },
  40981. enumerable: true,
  40982. configurable: true
  40983. });
  40984. /**
  40985. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40986. * @param predicate the predicate to test on each parent
  40987. * @return the first primitive where the predicate was successful
  40988. */
  40989. Prim2DBase.prototype.traverseUp = function (predicate) {
  40990. var p = this;
  40991. while (p != null) {
  40992. if (predicate(p)) {
  40993. return p;
  40994. }
  40995. p = p._parent;
  40996. }
  40997. return null;
  40998. };
  40999. Object.defineProperty(Prim2DBase.prototype, "owner", {
  41000. /**
  41001. * Retrieve the owner Canvas2D
  41002. */
  41003. get: function () {
  41004. return this._owner;
  41005. },
  41006. enumerable: true,
  41007. configurable: true
  41008. });
  41009. Object.defineProperty(Prim2DBase.prototype, "parent", {
  41010. /**
  41011. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  41012. */
  41013. get: function () {
  41014. return this._parent;
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. Object.defineProperty(Prim2DBase.prototype, "children", {
  41020. /**
  41021. * The array of direct children primitives
  41022. */
  41023. get: function () {
  41024. return this._children;
  41025. },
  41026. enumerable: true,
  41027. configurable: true
  41028. });
  41029. Object.defineProperty(Prim2DBase.prototype, "id", {
  41030. /**
  41031. * The identifier of this primitive, may not be unique, it's for information purpose only
  41032. */
  41033. get: function () {
  41034. return this._id;
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  41040. get: function () {
  41041. if (this._actualPosition != null) {
  41042. return this._actualPosition;
  41043. }
  41044. if (this._position != null) {
  41045. return this._position;
  41046. }
  41047. // At least return 0,0, we can't return null on actualPosition
  41048. return Prim2DBase._nullPosition;
  41049. },
  41050. /**
  41051. * DO NOT INVOKE for internal purpose only
  41052. */
  41053. set: function (val) {
  41054. this._actualPosition = val;
  41055. },
  41056. enumerable: true,
  41057. configurable: true
  41058. });
  41059. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  41060. /**
  41061. * Shortcut to actualPosition.x
  41062. */
  41063. get: function () {
  41064. return this.actualPosition.x;
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  41070. /**
  41071. * Shortcut to actualPosition.y
  41072. */
  41073. get: function () {
  41074. return this.actualPosition.y;
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. Object.defineProperty(Prim2DBase.prototype, "position", {
  41080. /**
  41081. * Position of the primitive, relative to its parent.
  41082. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  41083. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  41084. * Setting this property may have no effect is specific alignment are in effect.
  41085. */
  41086. get: function () {
  41087. return this._position || Prim2DBase._nullPosition;
  41088. },
  41089. set: function (value) {
  41090. if (!this._checkPositionChange()) {
  41091. return;
  41092. }
  41093. this._position = value;
  41094. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. Object.defineProperty(Prim2DBase.prototype, "x", {
  41100. /**
  41101. * Direct access to the position.x value of the primitive
  41102. * Use this property when you only want to change one component of the position property
  41103. */
  41104. get: function () {
  41105. if (!this._position) {
  41106. return null;
  41107. }
  41108. return this._position.x;
  41109. },
  41110. set: function (value) {
  41111. if (!this._checkPositionChange()) {
  41112. return;
  41113. }
  41114. if (!this._position) {
  41115. this._position = BABYLON.Vector2.Zero();
  41116. }
  41117. if (this._position.x === value) {
  41118. return;
  41119. }
  41120. this._position.x = value;
  41121. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  41122. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(Prim2DBase.prototype, "y", {
  41128. /**
  41129. * Direct access to the position.y value of the primitive
  41130. * Use this property when you only want to change one component of the position property
  41131. */
  41132. get: function () {
  41133. if (!this._position) {
  41134. return null;
  41135. }
  41136. return this._position.y;
  41137. },
  41138. set: function (value) {
  41139. if (!this._checkPositionChange()) {
  41140. return;
  41141. }
  41142. if (!this._position) {
  41143. this._position = BABYLON.Vector2.Zero();
  41144. }
  41145. if (this._position.y === value) {
  41146. return;
  41147. }
  41148. this._position.y = value;
  41149. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  41150. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  41151. },
  41152. enumerable: true,
  41153. configurable: true
  41154. });
  41155. Object.defineProperty(Prim2DBase.prototype, "size", {
  41156. /**
  41157. * Size of the primitive or its bounding area
  41158. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  41159. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  41160. */
  41161. get: function () {
  41162. if (!this._size || this._size.width == null || this._size.height == null) {
  41163. if (Prim2DBase.boundinbBoxReentrency) {
  41164. return Prim2DBase.nullSize;
  41165. }
  41166. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41167. return this._boundingSize;
  41168. }
  41169. Prim2DBase.boundinbBoxReentrency = true;
  41170. var b = this.boundingInfo;
  41171. Prim2DBase.boundinbBoxReentrency = false;
  41172. return this._boundingSize;
  41173. }
  41174. return this._size;
  41175. },
  41176. set: function (value) {
  41177. this._size = value;
  41178. },
  41179. enumerable: true,
  41180. configurable: true
  41181. });
  41182. Object.defineProperty(Prim2DBase.prototype, "width", {
  41183. /**
  41184. * Direct access to the size.width value of the primitive
  41185. * Use this property when you only want to change one component of the size property
  41186. */
  41187. get: function () {
  41188. if (!this.size) {
  41189. return null;
  41190. }
  41191. return this.size.width;
  41192. },
  41193. set: function (value) {
  41194. if (!this.size) {
  41195. this.size = new BABYLON.Size(value, 0);
  41196. return;
  41197. }
  41198. if (this.size.width === value) {
  41199. return;
  41200. }
  41201. this.size.width = value;
  41202. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  41203. this._positioningDirty();
  41204. },
  41205. enumerable: true,
  41206. configurable: true
  41207. });
  41208. Object.defineProperty(Prim2DBase.prototype, "height", {
  41209. /**
  41210. * Direct access to the size.height value of the primitive
  41211. * Use this property when you only want to change one component of the size property
  41212. */
  41213. get: function () {
  41214. if (!this.size) {
  41215. return null;
  41216. }
  41217. return this.size.height;
  41218. },
  41219. set: function (value) {
  41220. if (!this.size) {
  41221. this.size = new BABYLON.Size(0, value);
  41222. return;
  41223. }
  41224. if (this.size.height === value) {
  41225. return;
  41226. }
  41227. this.size.height = value;
  41228. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  41229. this._positioningDirty();
  41230. },
  41231. enumerable: true,
  41232. configurable: true
  41233. });
  41234. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  41235. get: function () {
  41236. return this._rotation;
  41237. },
  41238. set: function (value) {
  41239. this._rotation = value;
  41240. },
  41241. enumerable: true,
  41242. configurable: true
  41243. });
  41244. Object.defineProperty(Prim2DBase.prototype, "scale", {
  41245. get: function () {
  41246. return this._scale.x;
  41247. },
  41248. set: function (value) {
  41249. this._scale.x = this._scale.y = value;
  41250. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41251. this._spreadActualScaleDirty();
  41252. },
  41253. enumerable: true,
  41254. configurable: true
  41255. });
  41256. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  41257. /**
  41258. * Return the size of the primitive as it's being rendered into the target.
  41259. * 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.
  41260. * BEWARE: don't use the setter, it's for internal purpose only
  41261. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  41262. */
  41263. get: function () {
  41264. if (this._actualSize) {
  41265. return this._actualSize;
  41266. }
  41267. return this._size;
  41268. },
  41269. set: function (value) {
  41270. if (this._actualSize.equals(value)) {
  41271. return;
  41272. }
  41273. this._actualSize = value;
  41274. },
  41275. enumerable: true,
  41276. configurable: true
  41277. });
  41278. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  41279. get: function () {
  41280. if (this._manualZOrder != null) {
  41281. return this._manualZOrder;
  41282. }
  41283. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41284. this._updateZOrder();
  41285. }
  41286. return (1 - this._zOrder);
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  41292. /**
  41293. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  41294. * The Primitive's size won't be less than specified.
  41295. * The default value depends of the Primitive type
  41296. */
  41297. get: function () {
  41298. return this._minSize;
  41299. },
  41300. set: function (value) {
  41301. if (this._minSize && value && this._minSize.equals(value)) {
  41302. return;
  41303. }
  41304. this._minSize = value;
  41305. this._parentLayoutDirty();
  41306. },
  41307. enumerable: true,
  41308. configurable: true
  41309. });
  41310. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  41311. /**
  41312. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  41313. * The Primitive's size won't be more than specified.
  41314. * The default value depends of the Primitive type
  41315. */
  41316. get: function () {
  41317. return this._maxSize;
  41318. },
  41319. set: function (value) {
  41320. if (this._maxSize && value && this._maxSize.equals(value)) {
  41321. return;
  41322. }
  41323. this._maxSize = value;
  41324. this._parentLayoutDirty();
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(Prim2DBase.prototype, "origin", {
  41330. /**
  41331. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  41332. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  41333. * For instance:
  41334. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  41335. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  41336. * 0,1 means the center is top/left
  41337. * @returns The normalized center.
  41338. */
  41339. get: function () {
  41340. return this._origin;
  41341. },
  41342. set: function (value) {
  41343. this._origin = value;
  41344. },
  41345. enumerable: true,
  41346. configurable: true
  41347. });
  41348. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  41349. get: function () {
  41350. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  41351. },
  41352. set: function (value) {
  41353. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  41354. },
  41355. enumerable: true,
  41356. configurable: true
  41357. });
  41358. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  41359. get: function () {
  41360. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  41361. },
  41362. set: function (value) {
  41363. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  41364. },
  41365. enumerable: true,
  41366. configurable: true
  41367. });
  41368. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  41369. get: function () {
  41370. return this._manualZOrder;
  41371. },
  41372. set: function (value) {
  41373. if (this._manualZOrder === value) {
  41374. return;
  41375. }
  41376. this._manualZOrder = value;
  41377. this.onZOrderChanged();
  41378. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41379. this._actualZOrderChangedObservable.notifyObservers(value);
  41380. }
  41381. },
  41382. enumerable: true,
  41383. configurable: true
  41384. });
  41385. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  41386. get: function () {
  41387. return this._manualZOrder != null;
  41388. },
  41389. enumerable: true,
  41390. configurable: true
  41391. });
  41392. Object.defineProperty(Prim2DBase.prototype, "margin", {
  41393. get: function () {
  41394. var _this = this;
  41395. if (!this._margin) {
  41396. this._margin = new PrimitiveThickness(function () {
  41397. if (!_this.parent) {
  41398. return null;
  41399. }
  41400. return _this.parent.margin;
  41401. }, function () { return _this._positioningDirty(); });
  41402. }
  41403. return this._margin;
  41404. },
  41405. enumerable: true,
  41406. configurable: true
  41407. });
  41408. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  41409. get: function () {
  41410. return (this._margin !== null) || (this._marginAlignment !== null);
  41411. },
  41412. enumerable: true,
  41413. configurable: true
  41414. });
  41415. Object.defineProperty(Prim2DBase.prototype, "padding", {
  41416. get: function () {
  41417. var _this = this;
  41418. if (!this._padding) {
  41419. this._padding = new PrimitiveThickness(function () {
  41420. if (!_this.parent) {
  41421. return null;
  41422. }
  41423. return _this.parent.padding;
  41424. }, function () { return _this._positioningDirty(); });
  41425. }
  41426. return this._padding;
  41427. },
  41428. enumerable: true,
  41429. configurable: true
  41430. });
  41431. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  41432. get: function () {
  41433. return this._padding !== null;
  41434. },
  41435. enumerable: true,
  41436. configurable: true
  41437. });
  41438. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  41439. get: function () {
  41440. var _this = this;
  41441. if (!this._marginAlignment) {
  41442. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  41443. }
  41444. return this._marginAlignment;
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  41450. get: function () {
  41451. return this._opacity;
  41452. },
  41453. set: function (value) {
  41454. if (value < 0) {
  41455. value = 0;
  41456. }
  41457. else if (value > 1) {
  41458. value = 1;
  41459. }
  41460. if (this._opacity === value) {
  41461. return;
  41462. }
  41463. this._opacity = value;
  41464. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41465. this._spreadActualOpacityChanged();
  41466. this._updateRenderMode();
  41467. },
  41468. enumerable: true,
  41469. configurable: true
  41470. });
  41471. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  41472. get: function () {
  41473. return this._scale.x;
  41474. },
  41475. set: function (value) {
  41476. this._scale.x = value;
  41477. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41478. this._spreadActualScaleDirty();
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  41484. get: function () {
  41485. return this._scale.y;
  41486. },
  41487. set: function (value) {
  41488. this._scale.y = value;
  41489. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41490. this._spreadActualScaleDirty();
  41491. },
  41492. enumerable: true,
  41493. configurable: true
  41494. });
  41495. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  41496. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41497. var child = _a[_i];
  41498. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41499. child._spreadActualScaleDirty();
  41500. }
  41501. };
  41502. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  41503. /**
  41504. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  41505. */
  41506. get: function () {
  41507. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  41508. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  41509. var sx = this.scaleX;
  41510. var sy = this.scaleY;
  41511. while (cur) {
  41512. sx *= cur.scaleX;
  41513. sy *= cur.scaleY;
  41514. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  41515. }
  41516. this._actualScale.copyFromFloats(sx, sy);
  41517. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41518. }
  41519. return this._actualScale;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  41525. /**
  41526. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  41527. */
  41528. get: function () {
  41529. return this.actualScale.x;
  41530. },
  41531. enumerable: true,
  41532. configurable: true
  41533. });
  41534. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  41535. /**
  41536. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  41537. */
  41538. get: function () {
  41539. return this.actualScale.y;
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  41545. /**
  41546. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  41547. */
  41548. get: function () {
  41549. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  41550. var cur = this.parent;
  41551. var op = this.opacity;
  41552. while (cur) {
  41553. op *= cur.opacity;
  41554. cur = cur.parent;
  41555. }
  41556. this._actualOpacity = op;
  41557. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41558. }
  41559. return this._actualOpacity;
  41560. },
  41561. enumerable: true,
  41562. configurable: true
  41563. });
  41564. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  41565. /**
  41566. * Get/set the layout engine to use for this primitive.
  41567. * The default layout engine is the CanvasLayoutEngine.
  41568. */
  41569. get: function () {
  41570. if (!this._layoutEngine) {
  41571. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  41572. }
  41573. return this._layoutEngine;
  41574. },
  41575. set: function (value) {
  41576. if (this._layoutEngine === value) {
  41577. return;
  41578. }
  41579. this._changeLayoutEngine(value);
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  41585. /**
  41586. * Get/set the layout are of this primitive.
  41587. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  41588. * The setter should only be called by a Layout Engine class.
  41589. */
  41590. get: function () {
  41591. return this._layoutArea;
  41592. },
  41593. set: function (val) {
  41594. if (this._layoutArea.equals(val)) {
  41595. return;
  41596. }
  41597. this._positioningDirty();
  41598. if (this.parent) {
  41599. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41600. }
  41601. this._layoutArea = val;
  41602. },
  41603. enumerable: true,
  41604. configurable: true
  41605. });
  41606. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  41607. /**
  41608. * Get/set the layout area position (relative to the parent primitive).
  41609. * The setter should only be called by a Layout Engine class.
  41610. */
  41611. get: function () {
  41612. return this._layoutAreaPos || Prim2DBase._nullPosition;
  41613. },
  41614. set: function (val) {
  41615. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  41616. return;
  41617. }
  41618. if (this.parent) {
  41619. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41620. }
  41621. this._positioningDirty();
  41622. this._layoutAreaPos = val;
  41623. },
  41624. enumerable: true,
  41625. configurable: true
  41626. });
  41627. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  41628. /**
  41629. * Define if the Primitive can be subject to intersection test or not (default is true)
  41630. */
  41631. get: function () {
  41632. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  41633. },
  41634. set: function (value) {
  41635. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  41636. },
  41637. enumerable: true,
  41638. configurable: true
  41639. });
  41640. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  41641. /**
  41642. * Define if the Primitive acts as a container or not
  41643. * A container will encapsulate its children for interaction event.
  41644. * If it's not a container events will be process down to children if the primitive is not pickable.
  41645. * Default value is true
  41646. */
  41647. get: function () {
  41648. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  41649. },
  41650. set: function (value) {
  41651. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  41652. },
  41653. enumerable: true,
  41654. configurable: true
  41655. });
  41656. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  41657. /**
  41658. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  41659. */
  41660. get: function () {
  41661. return this._hierarchyDepth;
  41662. },
  41663. enumerable: true,
  41664. configurable: true
  41665. });
  41666. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  41667. /**
  41668. * Retrieve the Group that is responsible to render this primitive
  41669. */
  41670. get: function () {
  41671. return this._renderGroup;
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  41677. /**
  41678. * Get the global transformation matrix of the primitive
  41679. */
  41680. get: function () {
  41681. this._updateLocalTransform();
  41682. return this._globalTransform;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. /**
  41688. * return the global position of the primitive, relative to its canvas
  41689. */
  41690. Prim2DBase.prototype.getGlobalPosition = function () {
  41691. var v = new BABYLON.Vector2(0, 0);
  41692. this.getGlobalPositionByRef(v);
  41693. return v;
  41694. };
  41695. /**
  41696. * return the global position of the primitive, relative to its canvas
  41697. * @param v the valid Vector2 object where the global position will be stored
  41698. */
  41699. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  41700. v.x = this.globalTransform.m[12];
  41701. v.y = this.globalTransform.m[13];
  41702. };
  41703. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  41704. /**
  41705. * Get invert of the global transformation matrix of the primitive
  41706. */
  41707. get: function () {
  41708. this._updateLocalTransform();
  41709. return this._invGlobalTransform;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41715. /**
  41716. * Get the local transformation of the primitive
  41717. */
  41718. get: function () {
  41719. this._updateLocalTransform();
  41720. return this._localTransform;
  41721. },
  41722. enumerable: true,
  41723. configurable: true
  41724. });
  41725. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41726. /**
  41727. * Get the boundingInfo associated to the primitive and its children.
  41728. * The value is supposed to be always up to date
  41729. */
  41730. get: function () {
  41731. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41732. if (this.owner) {
  41733. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41734. }
  41735. if (this.isSizedByContent) {
  41736. this._boundingInfo.clear();
  41737. }
  41738. else {
  41739. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41740. }
  41741. var bi = this._boundingInfo;
  41742. var tps = new BABYLON.BoundingInfo2D();
  41743. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41744. var curChild = _a[_i];
  41745. var bb = curChild.boundingInfo;
  41746. bb.transformToRef(curChild.localTransform, tps);
  41747. bi.unionToRef(tps, bi);
  41748. }
  41749. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41750. 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);
  41751. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41752. }
  41753. return this._boundingInfo;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  41759. /**
  41760. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  41761. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  41762. */
  41763. get: function () {
  41764. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  41765. if (!this._layoutBoundingInfo) {
  41766. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  41767. }
  41768. if (this.isSizedByContent) {
  41769. this._layoutBoundingInfo.clear();
  41770. }
  41771. else {
  41772. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  41773. }
  41774. var bi = this._layoutBoundingInfo;
  41775. var tps = new BABYLON.BoundingInfo2D();
  41776. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41777. var curChild = _a[_i];
  41778. var bb = void 0;
  41779. if (curChild._layoutAreaPos) {
  41780. var s = curChild._layoutArea;
  41781. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase._tpsBB);
  41782. bb = Prim2DBase._tpsBB;
  41783. }
  41784. else {
  41785. bb = curChild.boundingInfo;
  41786. }
  41787. bb.transformToRef(curChild.localTransform, tps);
  41788. bi.unionToRef(tps, bi);
  41789. }
  41790. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  41791. }
  41792. return this._layoutBoundingInfo;
  41793. },
  41794. enumerable: true,
  41795. configurable: true
  41796. });
  41797. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41798. /**
  41799. * Determine if the size is automatically computed or fixed because manually specified.
  41800. * Use the actualSize property to get the final/real size of the primitive
  41801. * @returns true if the size is automatically computed, false if it were manually specified.
  41802. */
  41803. get: function () {
  41804. return this._size == null;
  41805. },
  41806. enumerable: true,
  41807. configurable: true
  41808. });
  41809. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41810. /**
  41811. * Return true if this prim has an auto size which is set by the children's global bounding box
  41812. */
  41813. get: function () {
  41814. return (this._size == null) && (this._children.length > 0);
  41815. },
  41816. enumerable: true,
  41817. configurable: true
  41818. });
  41819. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41820. /**
  41821. * Determine if the position is automatically computed or fixed because manually specified.
  41822. * Use the actualPosition property to get the final/real position of the primitive
  41823. * @returns true if the position is automatically computed, false if it were manually specified.
  41824. */
  41825. get: function () {
  41826. return this._position == null;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41832. /**
  41833. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41834. */
  41835. get: function () {
  41836. return this._pointerEventObservable;
  41837. },
  41838. enumerable: true,
  41839. configurable: true
  41840. });
  41841. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41842. get: function () {
  41843. if (!this._actualZOrderChangedObservable) {
  41844. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41845. }
  41846. return this._actualZOrderChangedObservable;
  41847. },
  41848. enumerable: true,
  41849. configurable: true
  41850. });
  41851. Prim2DBase.prototype.findById = function (id) {
  41852. if (this._id === id) {
  41853. return this;
  41854. }
  41855. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41856. var child = _a[_i];
  41857. var r = child.findById(id);
  41858. if (r != null) {
  41859. return r;
  41860. }
  41861. }
  41862. };
  41863. Prim2DBase.prototype.onZOrderChanged = function () {
  41864. };
  41865. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41866. return false;
  41867. };
  41868. /**
  41869. * Capture all the Events of the given PointerId for this primitive.
  41870. * Don't forget to call releasePointerEventsCapture when done.
  41871. * @param pointerId the Id of the pointer to capture the events from.
  41872. */
  41873. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41874. return this.owner._setPointerCapture(pointerId, this);
  41875. };
  41876. /**
  41877. * Release a captured pointer made with setPointerEventCapture.
  41878. * @param pointerId the Id of the pointer to release the capture from.
  41879. */
  41880. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41881. return this.owner._releasePointerCapture(pointerId, this);
  41882. };
  41883. /**
  41884. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41885. * @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.
  41886. */
  41887. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41888. if (!intersectInfo) {
  41889. return false;
  41890. }
  41891. // If this is null it means this method is call for the first level, initialize stuffs
  41892. var firstLevel = !intersectInfo._globalPickPosition;
  41893. if (firstLevel) {
  41894. // 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).
  41895. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41896. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41897. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41898. intersectInfo.intersectedPrimitives = new Array();
  41899. intersectInfo.topMostIntersectedPrimitive = null;
  41900. }
  41901. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41902. return false;
  41903. }
  41904. var id = this.id;
  41905. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41906. var ownerGroup = this.getExternalData("__cachedGroup__");
  41907. return ownerGroup.intersect(intersectInfo);
  41908. }
  41909. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  41910. var isIntersectionTest = false;
  41911. if (this instanceof BABYLON.Group2D) {
  41912. var g = this;
  41913. isIntersectionTest = g.isCachedGroup;
  41914. }
  41915. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41916. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41917. intersectInfo._exit(firstLevel);
  41918. return false;
  41919. }
  41920. // Fast rejection test with boundingInfo
  41921. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41922. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41923. intersectInfo._exit(firstLevel);
  41924. return false;
  41925. }
  41926. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41927. var levelIntersectRes = false;
  41928. if (this.isPickable) {
  41929. levelIntersectRes = this.levelIntersect(intersectInfo);
  41930. if (levelIntersectRes) {
  41931. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41932. intersectInfo.intersectedPrimitives.push(pii);
  41933. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41934. intersectInfo.topMostIntersectedPrimitive = pii;
  41935. }
  41936. // If we must stop at the first intersection, we're done, quit!
  41937. if (intersectInfo.findFirstOnly) {
  41938. intersectInfo._exit(firstLevel);
  41939. return true;
  41940. }
  41941. }
  41942. }
  41943. // Recurse to children if needed
  41944. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41945. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41946. var curChild = _a[_i];
  41947. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41948. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41949. continue;
  41950. }
  41951. // Must compute the localPickLocation for the children level
  41952. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41953. // If we got an intersection with the child and we only need to find the first one, quit!
  41954. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41955. intersectInfo._exit(firstLevel);
  41956. return true;
  41957. }
  41958. }
  41959. }
  41960. intersectInfo._exit(firstLevel);
  41961. return intersectInfo.isIntersected;
  41962. };
  41963. /**
  41964. * Move a child object into a new position regarding its siblings to change its rendering order.
  41965. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41966. * @param child the object to move
  41967. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41968. */
  41969. Prim2DBase.prototype.moveChild = function (child, previous) {
  41970. if (child.parent !== this) {
  41971. return false;
  41972. }
  41973. var childIndex = this._children.indexOf(child);
  41974. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41975. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41976. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41977. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41978. }
  41979. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41980. return true;
  41981. };
  41982. /**
  41983. * Move the given child so it's displayed on the top of all its siblings
  41984. * @param child the primitive to move to the top
  41985. */
  41986. Prim2DBase.prototype.moveChildToTop = function (child) {
  41987. return this.moveChild(child, this._children[this._children.length - 1]);
  41988. };
  41989. /**
  41990. * Move the given child so it's displayed on the bottom of all its siblings
  41991. * @param child the primitive to move to the top
  41992. */
  41993. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41994. return this.moveChild(child, null);
  41995. };
  41996. /**
  41997. * Move this primitive to be at the top among all its sibling
  41998. */
  41999. Prim2DBase.prototype.moveToTop = function () {
  42000. if (this.parent == null) {
  42001. return false;
  42002. }
  42003. return this.parent.moveChildToTop(this);
  42004. };
  42005. /**
  42006. * Move this primitive to be at the bottom among all its sibling
  42007. */
  42008. Prim2DBase.prototype.moveToBottom = function () {
  42009. if (this.parent == null) {
  42010. return false;
  42011. }
  42012. return this.parent.moveChildToBottom(this);
  42013. };
  42014. Prim2DBase.prototype.addChild = function (child) {
  42015. child._parent = this;
  42016. this._boundingBoxDirty();
  42017. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42018. if (flat) {
  42019. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42020. child._setZOrder(this._zOrder, true);
  42021. child._zMax = this._zOrder;
  42022. }
  42023. else {
  42024. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42025. }
  42026. var length = this._children.push(child);
  42027. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  42028. };
  42029. /**
  42030. * Dispose the primitive, remove it from its parent.
  42031. */
  42032. Prim2DBase.prototype.dispose = function () {
  42033. if (!_super.prototype.dispose.call(this)) {
  42034. return false;
  42035. }
  42036. if (this._actionManager) {
  42037. this._actionManager.dispose();
  42038. this._actionManager = null;
  42039. }
  42040. // If there's a parent, remove this object from its parent list
  42041. if (this._parent) {
  42042. if (this instanceof BABYLON.Group2D) {
  42043. var g = this;
  42044. if (g.isRenderableGroup) {
  42045. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  42046. if (parentRenderable != null) {
  42047. var l = parentRenderable._renderableData._childrenRenderableGroups;
  42048. var i_1 = l.indexOf(g);
  42049. if (i_1 !== -1) {
  42050. l.splice(i_1, 1);
  42051. }
  42052. }
  42053. }
  42054. }
  42055. var i = this._parent._children.indexOf(this);
  42056. if (i !== undefined) {
  42057. this._parent._children.splice(i, 1);
  42058. }
  42059. this._parent = null;
  42060. }
  42061. // Recurse dispose to children
  42062. if (this._children) {
  42063. while (this._children.length > 0) {
  42064. this._children[this._children.length - 1].dispose();
  42065. }
  42066. }
  42067. return true;
  42068. };
  42069. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  42070. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  42071. this._renderGroup._addPrimToDirtyList(this);
  42072. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  42073. }
  42074. };
  42075. Prim2DBase.prototype._needPrepare = function () {
  42076. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  42077. };
  42078. Prim2DBase.prototype._prepareRender = function (context) {
  42079. this._prepareRenderPre(context);
  42080. this._prepareRenderPost(context);
  42081. };
  42082. Prim2DBase.prototype._prepareRenderPre = function (context) {
  42083. };
  42084. Prim2DBase.prototype._prepareRenderPost = function (context) {
  42085. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  42086. if (this instanceof BABYLON.Group2D) {
  42087. var self = this;
  42088. if (self.isRenderableGroup) {
  42089. return;
  42090. }
  42091. }
  42092. // Check if we need to recurse the prepare to children primitives
  42093. // - must have children
  42094. // - the global transform of this level have changed, or
  42095. // - the visible state of primitive has changed
  42096. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  42097. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  42098. this._children.forEach(function (c) {
  42099. // As usual stop the recursion if we meet a renderable group
  42100. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  42101. c._prepareRender(context);
  42102. }
  42103. });
  42104. }
  42105. // Finally reset the dirty flags as we've processed everything
  42106. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42107. this._instanceDirtyFlags = 0;
  42108. };
  42109. Prim2DBase.prototype._canvasPreInit = function (settings) {
  42110. };
  42111. Prim2DBase.CheckParent = function (parent) {
  42112. //if (!Prim2DBase._isCanvasInit && !parent) {
  42113. // 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)");
  42114. //}
  42115. };
  42116. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  42117. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  42118. var cur = list_1[_i];
  42119. cur.updateCachedStates(recurse);
  42120. }
  42121. };
  42122. Prim2DBase.prototype._parentLayoutDirty = function () {
  42123. if (!this._parent || this._parent.isDisposed) {
  42124. return;
  42125. }
  42126. this._parent._setLayoutDirty();
  42127. };
  42128. Prim2DBase.prototype._setLayoutDirty = function () {
  42129. this.onPrimBecomesDirty();
  42130. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  42131. };
  42132. Prim2DBase.prototype._checkPositionChange = function () {
  42133. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  42134. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  42135. return false;
  42136. }
  42137. return true;
  42138. };
  42139. Prim2DBase.prototype._positioningDirty = function () {
  42140. this.onPrimBecomesDirty();
  42141. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42142. };
  42143. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  42144. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42145. var child = _a[_i];
  42146. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  42147. child._updateRenderMode();
  42148. child.onPrimBecomesDirty();
  42149. child._spreadActualOpacityChanged();
  42150. }
  42151. };
  42152. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  42153. this._layoutEngine = engine;
  42154. };
  42155. Prim2DBase.prototype._updateLocalTransform = function () {
  42156. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  42157. if (this.checkPropertiesDirty(tflags)) {
  42158. if (this.owner) {
  42159. this.owner.addupdateLocalTransformCounter(1);
  42160. }
  42161. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  42162. var local;
  42163. var pos = this._position ? this.position : this.layoutAreaPos;
  42164. if (this._origin.x === 0 && this._origin.y === 0) {
  42165. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  42166. this._localTransform = local;
  42167. }
  42168. else {
  42169. // -Origin offset
  42170. var as = this.actualSize;
  42171. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  42172. // -Origin * rotation
  42173. rot.toRotationMatrix(Prim2DBase._t1);
  42174. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  42175. // -Origin * rotation * scale
  42176. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  42177. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  42178. // -Origin * rotation * scale * (Origin + Position)
  42179. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x + this._marginOffset.x, (as.height * this._origin.y) + pos.y + this._marginOffset.y, 0, Prim2DBase._t2);
  42180. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  42181. }
  42182. this.clearPropertiesDirty(tflags);
  42183. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  42184. return true;
  42185. }
  42186. return false;
  42187. };
  42188. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  42189. if (this.isDisposed) {
  42190. return;
  42191. }
  42192. this.owner.addCachedGroupRenderCounter(1);
  42193. // Check if the parent is synced
  42194. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  42195. this._parent.updateCachedStates(false);
  42196. }
  42197. // Update Z-Order if needed
  42198. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42199. this._updateZOrder();
  42200. }
  42201. // Update actualSize only if there' not positioning to recompute and the size changed
  42202. // Otherwise positioning will take care of it.
  42203. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42204. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  42205. var size = this.size;
  42206. if (size) {
  42207. if (this.size.width != null) {
  42208. this.actualSize.width = this.size.width;
  42209. }
  42210. if (this.size.height != null) {
  42211. this.actualSize.height = this.size.height;
  42212. }
  42213. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42214. }
  42215. }
  42216. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42217. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42218. // Check for layout update
  42219. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  42220. this.owner.addUpdateLayoutCounter(1);
  42221. this._layoutEngine.updateLayout(this);
  42222. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  42223. }
  42224. var autoContentChanged = false;
  42225. if (this.isSizeAuto) {
  42226. if (!this._lastAutoSizeArea) {
  42227. autoContentChanged = this.actualSize !== null;
  42228. }
  42229. else {
  42230. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  42231. }
  42232. }
  42233. // Check for positioning update
  42234. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  42235. this._updatePositioning();
  42236. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42237. if (sizeDirty) {
  42238. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  42239. }
  42240. positioningComputed = true;
  42241. }
  42242. if (positioningComputed && this._parent) {
  42243. this._parentContentArea.copyFrom(this._parent.contentArea);
  42244. }
  42245. // Check if we must update this prim
  42246. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  42247. this.owner.addUpdateGlobalTransformCounter(1);
  42248. var curVisibleState = this.isVisible;
  42249. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  42250. // Detect a change of visibility
  42251. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  42252. // Get/compute the localTransform
  42253. var localDirty = this._updateLocalTransform();
  42254. var parentPaddingChanged = false;
  42255. var parentPaddingOffset = Prim2DBase._v0;
  42256. if (this._parent) {
  42257. parentPaddingOffset = this._parent._paddingOffset;
  42258. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  42259. }
  42260. // Check if there are changes in the parent that will force us to update the global matrix
  42261. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  42262. // Check if we have to update the globalTransform
  42263. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  42264. var globalTransform = this._parent ? this._parent._globalTransform : null;
  42265. var localTransform = void 0;
  42266. Prim2DBase._transMtx.copyFrom(this._localTransform);
  42267. Prim2DBase._transMtx.m[12] += parentPaddingOffset.x;
  42268. Prim2DBase._transMtx.m[13] += parentPaddingOffset.y;
  42269. localTransform = Prim2DBase._transMtx;
  42270. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  42271. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  42272. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  42273. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  42274. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  42275. }
  42276. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  42277. }
  42278. if (recurse) {
  42279. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42280. var child = _a[_i];
  42281. // Stop the recursion if we meet a renderable group
  42282. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  42283. }
  42284. }
  42285. };
  42286. Prim2DBase.prototype._updatePositioning = function () {
  42287. if (this.owner) {
  42288. this.owner.addUpdatePositioningCounter(1);
  42289. }
  42290. // From this point we assume that the primitive layoutArea is computed and up to date.
  42291. // We know have to :
  42292. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  42293. // 2. Determine the contentArea based on the padding property.
  42294. // 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
  42295. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  42296. if (this.actualSize.width == null) {
  42297. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  42298. }
  42299. if (this.actualSize.height == null) {
  42300. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  42301. }
  42302. }
  42303. // Apply margin
  42304. if (this._hasMargin) {
  42305. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42306. this.actualSize = Prim2DBase._size.clone();
  42307. }
  42308. var isSizeAuto = this.isSizeAuto;
  42309. if (this._hasPadding) {
  42310. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  42311. if (isSizeAuto) {
  42312. var content = this.size.clone();
  42313. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  42314. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42315. this._contentArea.copyFrom(content);
  42316. this.actualSize = Prim2DBase._size.clone();
  42317. // Changing the padding has resize the prim, which forces us to recompute margin again
  42318. if (this._hasMargin) {
  42319. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  42320. }
  42321. }
  42322. else {
  42323. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42324. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42325. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42326. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  42327. this._paddingOffset.x += Prim2DBase._icPos.x;
  42328. this._paddingOffset.y += Prim2DBase._icPos.y;
  42329. this._contentArea.copyFrom(Prim2DBase._size);
  42330. }
  42331. }
  42332. else {
  42333. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  42334. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  42335. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  42336. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  42337. this._contentArea.copyFrom(Prim2DBase._icArea);
  42338. }
  42339. if (!this._position) {
  42340. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  42341. this.actualPosition = aPos;
  42342. }
  42343. if (isSizeAuto) {
  42344. this._lastAutoSizeArea = this.actualSize;
  42345. }
  42346. };
  42347. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  42348. /**
  42349. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  42350. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  42351. */
  42352. get: function () {
  42353. // Check for positioning update
  42354. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  42355. this._updatePositioning();
  42356. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  42357. }
  42358. return this._contentArea;
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Prim2DBase.prototype._patchHierarchy = function (owner) {
  42364. this._owner = owner;
  42365. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  42366. if (this._renderGroup != null) {
  42367. return;
  42368. }
  42369. if (this instanceof BABYLON.Group2D) {
  42370. var group = this;
  42371. group.detectGroupStates();
  42372. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42373. group.owner._registerTrackedNode(this);
  42374. }
  42375. }
  42376. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  42377. if (this._parent) {
  42378. this._parentLayoutDirty();
  42379. }
  42380. // Make sure the prim is in the dirtyList if it should be
  42381. if (this._renderGroup && this.isDirty) {
  42382. var list = this._renderGroup._renderableData._primDirtyList;
  42383. var i = list.indexOf(this);
  42384. if (i === -1) {
  42385. list.push(this);
  42386. }
  42387. }
  42388. // Recurse
  42389. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42390. var child = _a[_i];
  42391. child._hierarchyDepth = this._hierarchyDepth + 1;
  42392. child._patchHierarchy(owner);
  42393. }
  42394. };
  42395. Prim2DBase.prototype._updateZOrder = function () {
  42396. var prevLinPos = this._primLinearPosition;
  42397. var startI = 0;
  42398. var startZ = this._zOrder;
  42399. // 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
  42400. var childrenCount = this._children.length;
  42401. if (this._firstZDirtyIndex > 0) {
  42402. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  42403. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  42404. prevLinPos = prevPrim._primLinearPosition;
  42405. startI = this._firstZDirtyIndex - 1;
  42406. startZ = prevPrim._zOrder;
  42407. }
  42408. }
  42409. var startPos = prevLinPos;
  42410. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  42411. Prim2DBase._totalCount = 0;
  42412. for (var i = startI; i < childrenCount; i++) {
  42413. var child = this._children[i];
  42414. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42415. }
  42416. // Compute the new Z-Order for all the primitives
  42417. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  42418. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  42419. // 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.
  42420. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  42421. // 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...
  42422. if (Prim2DBase._zRebuildReentrency) {
  42423. var p = this._parent;
  42424. if (p == null) {
  42425. // 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...)
  42426. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  42427. Prim2DBase._zRebuildReentrency = false;
  42428. return;
  42429. }
  42430. p._firstZDirtyIndex = 0;
  42431. return p._updateZOrder();
  42432. }
  42433. Prim2DBase._zRebuildReentrency = true;
  42434. this._firstZDirtyIndex = 0;
  42435. this._updateZOrder();
  42436. Prim2DBase._zRebuildReentrency = false;
  42437. }
  42438. for (var i = startI; i < childrenCount; i++) {
  42439. var child = this._children[i];
  42440. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  42441. }
  42442. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  42443. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  42444. var p = _a[_i];
  42445. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  42446. }
  42447. Prim2DBase._zOrderChangedNotifList.splice(0);
  42448. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42449. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42450. };
  42451. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  42452. if (this.isManualZOrder) {
  42453. return prevLinPos;
  42454. }
  42455. this._primLinearPosition = ++prevLinPos;
  42456. Prim2DBase._totalCount++;
  42457. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42458. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  42459. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42460. var child = _a[_i];
  42461. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42462. }
  42463. }
  42464. return prevLinPos;
  42465. };
  42466. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  42467. if (this.isManualZOrder) {
  42468. return null;
  42469. }
  42470. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  42471. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42472. this._setZOrder(newZ, false);
  42473. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42474. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42475. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42476. }
  42477. var curZ = newZ;
  42478. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42479. if (isFlat) {
  42480. if (this._children.length > 0) {
  42481. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  42482. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42483. var child = _a[_i];
  42484. child._updatePrimitiveFlatZOrder(this._zOrder);
  42485. }
  42486. }
  42487. }
  42488. else {
  42489. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  42490. var child = _c[_b];
  42491. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  42492. if (r != null) {
  42493. curZ = r;
  42494. }
  42495. }
  42496. }
  42497. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  42498. return curZ;
  42499. };
  42500. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  42501. if (this.isManualZOrder) {
  42502. return;
  42503. }
  42504. this._setZOrder(newZ, false);
  42505. this._zMax = newZ;
  42506. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42507. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42508. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42509. }
  42510. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42511. var child = _a[_i];
  42512. child._updatePrimitiveFlatZOrder(newZ);
  42513. }
  42514. };
  42515. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  42516. if (newZ !== this._zOrder) {
  42517. this._zOrder = newZ;
  42518. this.onPrimBecomesDirty();
  42519. this.onZOrderChanged();
  42520. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  42521. if (directEmit) {
  42522. this._actualZOrderChangedObservable.notifyObservers(newZ);
  42523. }
  42524. else {
  42525. Prim2DBase._zOrderChangedNotifList.push(this);
  42526. }
  42527. }
  42528. }
  42529. };
  42530. Prim2DBase.prototype._updateRenderMode = function () {
  42531. };
  42532. /**
  42533. * This method is used to alter the contentArea of the Primitive before margin is applied.
  42534. * 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.
  42535. * @param primSize the current size of the primitive
  42536. * @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!
  42537. * @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!
  42538. */
  42539. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42540. initialContentArea.copyFrom(primSize);
  42541. initialContentPosition.x = initialContentPosition.y = 0;
  42542. };
  42543. /**
  42544. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  42545. * Check the Rectangle2D implementation for a concrete application.
  42546. * @param primSize the current size of the primitive
  42547. * @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!
  42548. */
  42549. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42550. newPrimSize.copyFrom(primSize);
  42551. };
  42552. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  42553. Prim2DBase._bigInt = Math.pow(2, 30);
  42554. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  42555. Prim2DBase.boundinbBoxReentrency = false;
  42556. Prim2DBase.nullSize = BABYLON.Size.Zero();
  42557. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  42558. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  42559. Prim2DBase._isCanvasInit = false;
  42560. Prim2DBase._t0 = new BABYLON.Matrix();
  42561. Prim2DBase._t1 = new BABYLON.Matrix();
  42562. Prim2DBase._t2 = new BABYLON.Matrix();
  42563. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  42564. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  42565. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  42566. Prim2DBase._icArea = BABYLON.Size.Zero();
  42567. Prim2DBase._size = BABYLON.Size.Zero();
  42568. Prim2DBase._zOrderChangedNotifList = new Array();
  42569. Prim2DBase._zRebuildReentrency = false;
  42570. Prim2DBase._totalCount = 0;
  42571. __decorate([
  42572. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  42573. ], Prim2DBase.prototype, "actualPosition", null);
  42574. __decorate([
  42575. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  42576. ], Prim2DBase.prototype, "position", null);
  42577. __decorate([
  42578. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  42579. ], Prim2DBase.prototype, "size", null);
  42580. __decorate([
  42581. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  42582. ], Prim2DBase.prototype, "rotation", null);
  42583. __decorate([
  42584. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  42585. ], Prim2DBase.prototype, "scale", null);
  42586. __decorate([
  42587. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  42588. ], Prim2DBase.prototype, "origin", null);
  42589. __decorate([
  42590. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  42591. ], Prim2DBase.prototype, "levelVisible", null);
  42592. __decorate([
  42593. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  42594. ], Prim2DBase.prototype, "isVisible", null);
  42595. __decorate([
  42596. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  42597. ], Prim2DBase.prototype, "zOrder", null);
  42598. __decorate([
  42599. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  42600. ], Prim2DBase.prototype, "margin", null);
  42601. __decorate([
  42602. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  42603. ], Prim2DBase.prototype, "padding", null);
  42604. __decorate([
  42605. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  42606. ], Prim2DBase.prototype, "marginAlignment", null);
  42607. __decorate([
  42608. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  42609. ], Prim2DBase.prototype, "opacity", null);
  42610. __decorate([
  42611. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  42612. ], Prim2DBase.prototype, "scaleX", null);
  42613. __decorate([
  42614. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  42615. ], Prim2DBase.prototype, "scaleY", null);
  42616. Prim2DBase = __decorate([
  42617. BABYLON.className("Prim2DBase")
  42618. ], Prim2DBase);
  42619. return Prim2DBase;
  42620. }(BABYLON.SmartPropertyPrim));
  42621. BABYLON.Prim2DBase = Prim2DBase;
  42622. })(BABYLON || (BABYLON = {}));
  42623. var BABYLON;
  42624. (function (BABYLON) {
  42625. var GroupInstanceInfo = (function () {
  42626. function GroupInstanceInfo(owner, mrc, partCount) {
  42627. this._partCount = partCount;
  42628. this.owner = owner;
  42629. this.modelRenderCache = mrc;
  42630. this.modelRenderCache.addRef();
  42631. this.partIndexFromId = new BABYLON.StringDictionary();
  42632. this._usedShaderCategories = new Array(partCount);
  42633. this._strides = new Array(partCount);
  42634. this._opaqueData = null;
  42635. this._alphaTestData = null;
  42636. this._transparentData = null;
  42637. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  42638. }
  42639. GroupInstanceInfo.prototype.dispose = function () {
  42640. if (this._isDisposed) {
  42641. return false;
  42642. }
  42643. if (this.modelRenderCache) {
  42644. this.modelRenderCache.dispose();
  42645. this.modelRenderCache = null;
  42646. }
  42647. var engine = this.owner.owner.engine;
  42648. if (this._opaqueData) {
  42649. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  42650. this._opaqueData = null;
  42651. }
  42652. if (this._alphaTestData) {
  42653. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  42654. this._alphaTestData = null;
  42655. }
  42656. if (this._transparentData) {
  42657. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  42658. this._transparentData = null;
  42659. }
  42660. this.partIndexFromId = null;
  42661. this._isDisposed = true;
  42662. return true;
  42663. };
  42664. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  42665. get: function () {
  42666. return this._opaqueData != null;
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  42672. get: function () {
  42673. return this._alphaTestData != null;
  42674. },
  42675. enumerable: true,
  42676. configurable: true
  42677. });
  42678. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  42679. get: function () {
  42680. return this._transparentData != null;
  42681. },
  42682. enumerable: true,
  42683. configurable: true
  42684. });
  42685. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  42686. get: function () {
  42687. if (!this._opaqueData) {
  42688. this._opaqueData = new Array(this._partCount);
  42689. for (var i = 0; i < this._partCount; i++) {
  42690. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  42691. }
  42692. }
  42693. return this._opaqueData;
  42694. },
  42695. enumerable: true,
  42696. configurable: true
  42697. });
  42698. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  42699. get: function () {
  42700. if (!this._alphaTestData) {
  42701. this._alphaTestData = new Array(this._partCount);
  42702. for (var i = 0; i < this._partCount; i++) {
  42703. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  42704. }
  42705. }
  42706. return this._alphaTestData;
  42707. },
  42708. enumerable: true,
  42709. configurable: true
  42710. });
  42711. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  42712. get: function () {
  42713. if (!this._transparentData) {
  42714. this._transparentData = new Array(this._partCount);
  42715. for (var i = 0; i < this._partCount; i++) {
  42716. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  42717. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  42718. }
  42719. }
  42720. return this._transparentData;
  42721. },
  42722. enumerable: true,
  42723. configurable: true
  42724. });
  42725. GroupInstanceInfo.prototype.sortTransparentData = function () {
  42726. if (!this.transparentOrderDirty) {
  42727. return;
  42728. }
  42729. for (var i = 0; i < this._transparentData.length; i++) {
  42730. var td = this._transparentData[i];
  42731. td._partData.sort();
  42732. }
  42733. this.transparentOrderDirty = false;
  42734. };
  42735. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  42736. get: function () {
  42737. return this._usedShaderCategories;
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  42743. get: function () {
  42744. return this._strides;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. return GroupInstanceInfo;
  42750. }());
  42751. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  42752. var TransparentSegment = (function () {
  42753. function TransparentSegment() {
  42754. this.groupInsanceInfo = null;
  42755. this.startZ = 0;
  42756. this.endZ = 0;
  42757. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  42758. this.endDataIndex = 0;
  42759. this.partBuffers = null;
  42760. }
  42761. TransparentSegment.prototype.dispose = function (engine) {
  42762. if (this.partBuffers) {
  42763. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42764. this.partBuffers.splice(0);
  42765. this.partBuffers = null;
  42766. }
  42767. };
  42768. return TransparentSegment;
  42769. }());
  42770. BABYLON.TransparentSegment = TransparentSegment;
  42771. var GroupInfoPartData = (function () {
  42772. function GroupInfoPartData(stride) {
  42773. this._partData = null;
  42774. this._partBuffer = null;
  42775. this._partBufferSize = 0;
  42776. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42777. this._isDisposed = false;
  42778. }
  42779. GroupInfoPartData.prototype.dispose = function (engine) {
  42780. if (this._isDisposed) {
  42781. return false;
  42782. }
  42783. if (this._partBuffer) {
  42784. engine._releaseBuffer(this._partBuffer);
  42785. this._partBuffer = null;
  42786. }
  42787. this._partData = null;
  42788. this._isDisposed = true;
  42789. };
  42790. return GroupInfoPartData;
  42791. }());
  42792. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42793. var TransparentGroupInfoPartData = (function (_super) {
  42794. __extends(TransparentGroupInfoPartData, _super);
  42795. function TransparentGroupInfoPartData(stride, zoff) {
  42796. _super.call(this, stride);
  42797. this._partData.compareValueOffset = zoff;
  42798. this._partData.sortingAscending = false;
  42799. }
  42800. return TransparentGroupInfoPartData;
  42801. }(GroupInfoPartData));
  42802. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42803. var ModelRenderCache = (function () {
  42804. function ModelRenderCache(engine, modelKey) {
  42805. this._engine = engine;
  42806. this._modelKey = modelKey;
  42807. this._nextKey = 1;
  42808. this._refCounter = 1;
  42809. this._partData = null;
  42810. }
  42811. ModelRenderCache.prototype.dispose = function () {
  42812. if (--this._refCounter !== 0) {
  42813. return false;
  42814. }
  42815. // Remove the Model Render Cache from the global dictionary
  42816. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42817. if (edata) {
  42818. edata.DisposeModelRenderCache(this);
  42819. }
  42820. return true;
  42821. };
  42822. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42823. get: function () {
  42824. return this._refCounter <= 0;
  42825. },
  42826. enumerable: true,
  42827. configurable: true
  42828. });
  42829. ModelRenderCache.prototype.addRef = function () {
  42830. return ++this._refCounter;
  42831. };
  42832. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42833. get: function () {
  42834. return this._modelKey;
  42835. },
  42836. enumerable: true,
  42837. configurable: true
  42838. });
  42839. /**
  42840. * Render the model instances
  42841. * @param instanceInfo
  42842. * @param context
  42843. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42844. */
  42845. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42846. return true;
  42847. };
  42848. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42849. for (var i = 0; i < this._partData.length; i++) {
  42850. if (this._partData[i]._partId === partId) {
  42851. return i;
  42852. }
  42853. }
  42854. return null;
  42855. };
  42856. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42857. var i = this.getPartIndexFromId(partId);
  42858. if (i === null) {
  42859. return null;
  42860. }
  42861. var ci = this._partsClassInfo[i];
  42862. var categories = this._partData[i]._partUsedCategories;
  42863. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42864. return res;
  42865. };
  42866. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42867. var pd = this._partData[partIndex];
  42868. var offset = (pd._partDataStride / 4) * elementCount;
  42869. var pci = this._partsClassInfo[partIndex];
  42870. var self = this;
  42871. pci.fullContent.forEach(function (k, v) {
  42872. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42873. switch (v.dataType) {
  42874. case 4 /* float */:
  42875. {
  42876. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42877. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42878. break;
  42879. }
  42880. case 0 /* Vector2 */:
  42881. {
  42882. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42883. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42884. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42885. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42886. break;
  42887. }
  42888. case 5 /* Color3 */:
  42889. case 1 /* Vector3 */:
  42890. {
  42891. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42892. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42893. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42894. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42895. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42896. break;
  42897. }
  42898. case 6 /* Color4 */:
  42899. case 2 /* Vector4 */:
  42900. {
  42901. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42902. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42903. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42904. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42905. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42906. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42907. break;
  42908. }
  42909. default:
  42910. }
  42911. }
  42912. });
  42913. };
  42914. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42915. // let i = this.getPartIndexFromId(partId);
  42916. // if (i === null) {
  42917. // return null;
  42918. // }
  42919. // let pci = this._partsClassInfo[i];
  42920. // pci.fullContent.forEach((k, v) => {
  42921. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42922. // v.uniformLocation = effect.getUniform(v.attributeName);
  42923. // }
  42924. // });
  42925. //}
  42926. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42927. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42928. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42929. return ModelRenderCache;
  42930. }());
  42931. BABYLON.ModelRenderCache = ModelRenderCache;
  42932. var ModelRenderCachePartData = (function () {
  42933. function ModelRenderCachePartData() {
  42934. }
  42935. return ModelRenderCachePartData;
  42936. }());
  42937. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42938. })(BABYLON || (BABYLON = {}));
  42939. var BABYLON;
  42940. (function (BABYLON) {
  42941. var InstanceClassInfo = (function () {
  42942. function InstanceClassInfo(base) {
  42943. this._baseInfo = base;
  42944. this._nextOffset = new BABYLON.StringDictionary();
  42945. this._attributes = new Array();
  42946. }
  42947. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42948. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42949. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42950. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42951. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42952. if (push) {
  42953. this._attributes.push(propInfo);
  42954. }
  42955. };
  42956. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42957. var catInline = ";" + categories.join(";") + ";";
  42958. var res = new Array();
  42959. var curInfo = this;
  42960. while (curInfo) {
  42961. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42962. var attrib = _a[_i];
  42963. // 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
  42964. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42965. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42966. var iai = new BABYLON.InstancingAttributeInfo();
  42967. iai.index = index;
  42968. 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)
  42969. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42970. iai.attributeName = attrib.attributeName;
  42971. res.push(iai);
  42972. }
  42973. }
  42974. curInfo = curInfo._baseInfo;
  42975. }
  42976. return res;
  42977. };
  42978. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42979. var res = new Array();
  42980. var curInfo = this;
  42981. while (curInfo) {
  42982. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42983. var attrib = _a[_i];
  42984. // 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
  42985. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42986. res.push(attrib.attributeName);
  42987. }
  42988. }
  42989. curInfo = curInfo._baseInfo;
  42990. }
  42991. return res;
  42992. };
  42993. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42994. var curOffset = 0;
  42995. var curBase = this._baseInfo;
  42996. while (curBase) {
  42997. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42998. curBase = curBase._baseInfo;
  42999. }
  43000. return curOffset;
  43001. };
  43002. return InstanceClassInfo;
  43003. }());
  43004. BABYLON.InstanceClassInfo = InstanceClassInfo;
  43005. var InstancePropInfo = (function () {
  43006. function InstancePropInfo() {
  43007. this.instanceOffset = new BABYLON.StringDictionary();
  43008. }
  43009. InstancePropInfo.prototype.setSize = function (val) {
  43010. if (val instanceof BABYLON.Vector2) {
  43011. this.size = 8;
  43012. this.dataType = 0 /* Vector2 */;
  43013. return;
  43014. }
  43015. if (val instanceof BABYLON.Vector3) {
  43016. this.size = 12;
  43017. this.dataType = 1 /* Vector3 */;
  43018. return;
  43019. }
  43020. if (val instanceof BABYLON.Vector4) {
  43021. this.size = 16;
  43022. this.dataType = 2 /* Vector4 */;
  43023. return;
  43024. }
  43025. if (val instanceof BABYLON.Matrix) {
  43026. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  43027. }
  43028. if (typeof (val) === "number") {
  43029. this.size = 4;
  43030. this.dataType = 4 /* float */;
  43031. return;
  43032. }
  43033. if (val instanceof BABYLON.Color3) {
  43034. this.size = 12;
  43035. this.dataType = 5 /* Color3 */;
  43036. return;
  43037. }
  43038. if (val instanceof BABYLON.Color4) {
  43039. this.size = 16;
  43040. this.dataType = 6 /* Color4 */;
  43041. return;
  43042. }
  43043. if (val instanceof BABYLON.Size) {
  43044. this.size = 8;
  43045. this.dataType = 7 /* Size */;
  43046. return;
  43047. }
  43048. return;
  43049. };
  43050. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  43051. switch (this.dataType) {
  43052. case 0 /* Vector2 */:
  43053. {
  43054. var v = val;
  43055. array[offset + 0] = v.x;
  43056. array[offset + 1] = v.y;
  43057. break;
  43058. }
  43059. case 1 /* Vector3 */:
  43060. {
  43061. var v = val;
  43062. array[offset + 0] = v.x;
  43063. array[offset + 1] = v.y;
  43064. array[offset + 2] = v.z;
  43065. break;
  43066. }
  43067. case 2 /* Vector4 */:
  43068. {
  43069. var v = val;
  43070. array[offset + 0] = v.x;
  43071. array[offset + 1] = v.y;
  43072. array[offset + 2] = v.z;
  43073. array[offset + 3] = v.w;
  43074. break;
  43075. }
  43076. case 5 /* Color3 */:
  43077. {
  43078. var v = val;
  43079. array[offset + 0] = v.r;
  43080. array[offset + 1] = v.g;
  43081. array[offset + 2] = v.b;
  43082. break;
  43083. }
  43084. case 6 /* Color4 */:
  43085. {
  43086. var v = val;
  43087. array[offset + 0] = v.r;
  43088. array[offset + 1] = v.g;
  43089. array[offset + 2] = v.b;
  43090. array[offset + 3] = v.a;
  43091. break;
  43092. }
  43093. case 4 /* float */:
  43094. {
  43095. var v = val;
  43096. array[offset] = v;
  43097. break;
  43098. }
  43099. case 3 /* Matrix */:
  43100. {
  43101. var v = val;
  43102. for (var i = 0; i < 16; i++) {
  43103. array[offset + i] = v.m[i];
  43104. }
  43105. break;
  43106. }
  43107. case 7 /* Size */:
  43108. {
  43109. var s = val;
  43110. array[offset + 0] = s.width;
  43111. array[offset + 1] = s.height;
  43112. break;
  43113. }
  43114. }
  43115. };
  43116. return InstancePropInfo;
  43117. }());
  43118. BABYLON.InstancePropInfo = InstancePropInfo;
  43119. function instanceData(category, shaderAttributeName) {
  43120. return function (target, propName, descriptor) {
  43121. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  43122. var node = dic.getLevelOf(target);
  43123. var instanceDataName = propName;
  43124. shaderAttributeName = shaderAttributeName || instanceDataName;
  43125. var info = node.levelContent.get(instanceDataName);
  43126. if (info) {
  43127. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  43128. }
  43129. info = new InstancePropInfo();
  43130. info.attributeName = shaderAttributeName;
  43131. info.category = category || null;
  43132. if (info.category) {
  43133. info.delimitedCategory = ";" + info.category + ";";
  43134. }
  43135. node.levelContent.add(instanceDataName, info);
  43136. descriptor.get = function () {
  43137. return null;
  43138. };
  43139. descriptor.set = function (val) {
  43140. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  43141. // Quit if it's the case, otherwise we could overwrite data somewhere...
  43142. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  43143. return;
  43144. }
  43145. if (!info.size) {
  43146. info.setSize(val);
  43147. node.classContent.mapProperty(info, true);
  43148. }
  43149. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  43150. node.classContent.mapProperty(info, false);
  43151. }
  43152. var obj = this;
  43153. if (obj.dataBuffer && obj.dataElements) {
  43154. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  43155. info.writeData(obj.dataBuffer.buffer, offset, val);
  43156. }
  43157. };
  43158. };
  43159. }
  43160. BABYLON.instanceData = instanceData;
  43161. var InstanceDataBase = (function () {
  43162. function InstanceDataBase(partId, dataElementCount) {
  43163. this.id = partId;
  43164. this.curElement = 0;
  43165. this._dataElementCount = dataElementCount;
  43166. this.renderMode = 0;
  43167. this.arrayLengthChanged = false;
  43168. }
  43169. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  43170. get: function () {
  43171. return null;
  43172. },
  43173. set: function (value) {
  43174. },
  43175. enumerable: true,
  43176. configurable: true
  43177. });
  43178. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  43179. get: function () {
  43180. return null;
  43181. },
  43182. set: function (value) {
  43183. },
  43184. enumerable: true,
  43185. configurable: true
  43186. });
  43187. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  43188. get: function () {
  43189. return null;
  43190. },
  43191. set: function (value) {
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  43197. get: function () {
  43198. return null;
  43199. },
  43200. set: function (value) {
  43201. },
  43202. enumerable: true,
  43203. configurable: true
  43204. });
  43205. InstanceDataBase.prototype.getClassTreeInfo = function () {
  43206. if (!this.typeInfo) {
  43207. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  43208. }
  43209. return this.typeInfo;
  43210. };
  43211. InstanceDataBase.prototype.allocElements = function () {
  43212. if (!this.dataBuffer || this.dataElements) {
  43213. return;
  43214. }
  43215. var res = new Array(this.dataElementCount);
  43216. for (var i = 0; i < this.dataElementCount; i++) {
  43217. res[i] = this.dataBuffer.allocElement();
  43218. }
  43219. this.dataElements = res;
  43220. };
  43221. InstanceDataBase.prototype.freeElements = function () {
  43222. if (!this.dataElements) {
  43223. return;
  43224. }
  43225. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  43226. var ei = _a[_i];
  43227. this.dataBuffer.freeElement(ei);
  43228. }
  43229. this.dataElements = null;
  43230. };
  43231. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  43232. get: function () {
  43233. return this._dataElementCount;
  43234. },
  43235. set: function (value) {
  43236. if (value === this._dataElementCount) {
  43237. return;
  43238. }
  43239. this.arrayLengthChanged = true;
  43240. this.freeElements();
  43241. this._dataElementCount = value;
  43242. this.allocElements();
  43243. },
  43244. enumerable: true,
  43245. configurable: true
  43246. });
  43247. __decorate([
  43248. instanceData()
  43249. ], InstanceDataBase.prototype, "zBias", null);
  43250. __decorate([
  43251. instanceData()
  43252. ], InstanceDataBase.prototype, "transformX", null);
  43253. __decorate([
  43254. instanceData()
  43255. ], InstanceDataBase.prototype, "transformY", null);
  43256. __decorate([
  43257. instanceData()
  43258. ], InstanceDataBase.prototype, "opacity", null);
  43259. return InstanceDataBase;
  43260. }());
  43261. BABYLON.InstanceDataBase = InstanceDataBase;
  43262. var RenderablePrim2D = (function (_super) {
  43263. __extends(RenderablePrim2D, _super);
  43264. function RenderablePrim2D(settings) {
  43265. _super.call(this, settings);
  43266. this._transparentPrimitiveInfo = null;
  43267. }
  43268. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  43269. get: function () {
  43270. return this._useTextureAlpha() || this._isPrimAlphaTest();
  43271. },
  43272. enumerable: true,
  43273. configurable: true
  43274. });
  43275. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  43276. get: function () {
  43277. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  43278. },
  43279. enumerable: true,
  43280. configurable: true
  43281. });
  43282. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  43283. get: function () {
  43284. return this._renderMode;
  43285. },
  43286. enumerable: true,
  43287. configurable: true
  43288. });
  43289. /**
  43290. * Dispose the primitive and its resources, remove it from its parent
  43291. */
  43292. RenderablePrim2D.prototype.dispose = function () {
  43293. if (!_super.prototype.dispose.call(this)) {
  43294. return false;
  43295. }
  43296. if (this.renderGroup) {
  43297. this.renderGroup._setCacheGroupDirty();
  43298. }
  43299. if (this._transparentPrimitiveInfo) {
  43300. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43301. this._transparentPrimitiveInfo = null;
  43302. }
  43303. if (this._instanceDataParts) {
  43304. this._cleanupInstanceDataParts();
  43305. }
  43306. if (this._modelRenderCache) {
  43307. this._modelRenderCache.dispose();
  43308. this._modelRenderCache = null;
  43309. }
  43310. if (this._instanceDataParts) {
  43311. this._instanceDataParts.forEach(function (p) {
  43312. p.freeElements();
  43313. });
  43314. this._instanceDataParts = null;
  43315. }
  43316. return true;
  43317. };
  43318. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  43319. var gii = null;
  43320. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43321. var part = _a[_i];
  43322. part.freeElements();
  43323. gii = part.groupInstanceInfo;
  43324. }
  43325. if (gii) {
  43326. var usedCount = 0;
  43327. if (gii.hasOpaqueData) {
  43328. var od = gii.opaqueData[0];
  43329. usedCount += od._partData.usedElementCount;
  43330. gii.opaqueDirty = true;
  43331. }
  43332. if (gii.hasAlphaTestData) {
  43333. var atd = gii.alphaTestData[0];
  43334. usedCount += atd._partData.usedElementCount;
  43335. gii.alphaTestDirty = true;
  43336. }
  43337. if (gii.hasTransparentData) {
  43338. var td = gii.transparentData[0];
  43339. usedCount += td._partData.usedElementCount;
  43340. gii.transparentDirty = true;
  43341. }
  43342. if (usedCount === 0 && gii.modelRenderCache != null) {
  43343. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  43344. gii.dispose();
  43345. }
  43346. if (this._modelRenderCache) {
  43347. this._modelRenderCache.dispose();
  43348. this._modelRenderCache = null;
  43349. }
  43350. }
  43351. this._instanceDataParts = null;
  43352. };
  43353. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  43354. _super.prototype._prepareRenderPre.call(this, context);
  43355. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  43356. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  43357. this._cleanupInstanceDataParts();
  43358. }
  43359. // Need to create the model?
  43360. var setupModelRenderCache = false;
  43361. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  43362. setupModelRenderCache = this._createModelRenderCache();
  43363. }
  43364. var gii = null;
  43365. var newInstance = false;
  43366. // Need to create the instance data parts?
  43367. if (!this._instanceDataParts) {
  43368. // Yes, flag it for later, more processing will have to be done
  43369. newInstance = true;
  43370. gii = this._createModelDataParts();
  43371. }
  43372. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  43373. if (setupModelRenderCache) {
  43374. this.setupModelRenderCache(this._modelRenderCache);
  43375. }
  43376. // 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.
  43377. // 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.
  43378. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  43379. this._updateInstanceDataParts(gii);
  43380. }
  43381. };
  43382. RenderablePrim2D.prototype._createModelRenderCache = function () {
  43383. var _this = this;
  43384. var setupModelRenderCache = false;
  43385. if (this._modelRenderCache) {
  43386. this._modelRenderCache.dispose();
  43387. }
  43388. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  43389. var mrc = _this.createModelRenderCache(key);
  43390. setupModelRenderCache = true;
  43391. return mrc;
  43392. });
  43393. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  43394. // if this is still false it means the MRC already exists, so we add a reference to it
  43395. if (!setupModelRenderCache) {
  43396. this._modelRenderCache.addRef();
  43397. }
  43398. return setupModelRenderCache;
  43399. };
  43400. RenderablePrim2D.prototype._createModelDataParts = function () {
  43401. var _this = this;
  43402. // Create the instance data parts of the primitive and store them
  43403. var parts = this.createInstanceDataParts();
  43404. this._instanceDataParts = parts;
  43405. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  43406. if (!this._modelRenderCache._partData) {
  43407. this._setupModelRenderCache(parts);
  43408. }
  43409. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  43410. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  43411. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  43412. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  43413. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  43414. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  43415. var part = _this._instanceDataParts[j];
  43416. res.partIndexFromId.add(part.id.toString(), j);
  43417. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  43418. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  43419. }
  43420. return res;
  43421. });
  43422. // Get the GroupInfoDataPart corresponding to the render category of the part
  43423. var rm = 0;
  43424. var gipd = null;
  43425. if (this.isTransparent) {
  43426. gipd = gii.transparentData;
  43427. rm = BABYLON.Render2DContext.RenderModeTransparent;
  43428. }
  43429. else if (this.isAlphaTest) {
  43430. gipd = gii.alphaTestData;
  43431. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  43432. }
  43433. else {
  43434. gipd = gii.opaqueData;
  43435. rm = BABYLON.Render2DContext.RenderModeOpaque;
  43436. }
  43437. // For each instance data part of the primitive, allocate the instanced element it needs for render
  43438. for (var i = 0; i < parts.length; i++) {
  43439. var part = parts[i];
  43440. part.dataBuffer = gipd[i]._partData;
  43441. part.allocElements();
  43442. part.renderMode = rm;
  43443. part.groupInstanceInfo = gii;
  43444. }
  43445. return gii;
  43446. };
  43447. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  43448. var ctiArray = new Array();
  43449. this._modelRenderCache._partData = new Array();
  43450. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  43451. var dataPart = parts_1[_i];
  43452. var pd = new BABYLON.ModelRenderCachePartData();
  43453. this._modelRenderCache._partData.push(pd);
  43454. var cat = this.getUsedShaderCategories(dataPart);
  43455. var cti = dataPart.getClassTreeInfo();
  43456. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  43457. var curVisible = this.isVisible;
  43458. this.isVisible = true;
  43459. // 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.
  43460. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  43461. var joinCat = ";" + cat.join(";") + ";";
  43462. pd._partJoinedUsedCategories = joinCat;
  43463. InstanceClassInfo._CurCategories = joinCat;
  43464. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  43465. if (!this.refreshInstanceDataPart(dataPart)) {
  43466. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  43467. }
  43468. this.afterRefreshForLayoutConstruction(dataPart, obj);
  43469. this.isVisible = curVisible;
  43470. var size = 0;
  43471. cti.fullContent.forEach(function (k, v) {
  43472. if (!v.category || cat.indexOf(v.category) !== -1) {
  43473. if (v.attributeName === "zBias") {
  43474. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  43475. }
  43476. if (!v.size) {
  43477. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  43478. }
  43479. else {
  43480. size += v.size;
  43481. }
  43482. }
  43483. });
  43484. pd._partDataStride = size;
  43485. pd._partUsedCategories = cat;
  43486. pd._partId = dataPart.id;
  43487. ctiArray.push(cti);
  43488. }
  43489. this._modelRenderCache._partsClassInfo = ctiArray;
  43490. };
  43491. RenderablePrim2D.prototype.onZOrderChanged = function () {
  43492. if (this.isTransparent && this._transparentPrimitiveInfo) {
  43493. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  43494. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  43495. // Flag the transparentData dirty has will have to sort it again
  43496. gii.transparentOrderDirty = true;
  43497. }
  43498. };
  43499. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  43500. return false;
  43501. };
  43502. RenderablePrim2D.prototype._useTextureAlpha = function () {
  43503. return false;
  43504. };
  43505. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  43506. return false;
  43507. };
  43508. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  43509. return false;
  43510. };
  43511. RenderablePrim2D.prototype._isPrimTransparent = function () {
  43512. return false;
  43513. };
  43514. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  43515. // Fetch the GroupInstanceInfo if we don't already have it
  43516. var rd = this.renderGroup._renderableData;
  43517. if (!gii) {
  43518. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  43519. }
  43520. var isTransparent = this.isTransparent;
  43521. var isAlphaTest = this.isAlphaTest;
  43522. var wereTransparent = false;
  43523. // Check a render mode change
  43524. var rmChanged = false;
  43525. if (this._instanceDataParts.length > 0) {
  43526. var firstPart = this._instanceDataParts[0];
  43527. var partRM = firstPart.renderMode;
  43528. var curRM = this.renderMode;
  43529. if (partRM !== curRM) {
  43530. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  43531. rmChanged = true;
  43532. var gipd = void 0;
  43533. switch (curRM) {
  43534. case BABYLON.Render2DContext.RenderModeTransparent:
  43535. gipd = gii.transparentData;
  43536. break;
  43537. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43538. gipd = gii.alphaTestData;
  43539. break;
  43540. default:
  43541. gipd = gii.opaqueData;
  43542. }
  43543. for (var i = 0; i < this._instanceDataParts.length; i++) {
  43544. var part = this._instanceDataParts[i];
  43545. part.freeElements();
  43546. part.dataBuffer = gipd[i]._partData;
  43547. part.renderMode = curRM;
  43548. }
  43549. }
  43550. }
  43551. // Handle changes related to ZOffset
  43552. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  43553. if (isTransparent || wereTransparent) {
  43554. // Handle visibility change, which is also triggered when the primitive just got created
  43555. if (visChanged || rmChanged) {
  43556. if (this.isVisible && !wereTransparent) {
  43557. if (!this._transparentPrimitiveInfo) {
  43558. // Add the primitive to the list of transparent ones in the group that render is
  43559. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  43560. }
  43561. }
  43562. else {
  43563. if (this._transparentPrimitiveInfo) {
  43564. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43565. this._transparentPrimitiveInfo = null;
  43566. }
  43567. }
  43568. gii.transparentOrderDirty = true;
  43569. }
  43570. }
  43571. var rebuildTrans = false;
  43572. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  43573. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43574. var part = _a[_i];
  43575. var justAllocated = false;
  43576. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  43577. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  43578. part.allocElements();
  43579. justAllocated = true;
  43580. }
  43581. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  43582. // Will return false if the instance should not be rendered (not visible or other any reasons)
  43583. part.arrayLengthChanged = false;
  43584. if (!this.refreshInstanceDataPart(part)) {
  43585. // Free the data element
  43586. if (part.dataElements) {
  43587. part.freeElements();
  43588. }
  43589. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  43590. if (this.isVisible) {
  43591. rd._primNewDirtyList.push(this);
  43592. }
  43593. }
  43594. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  43595. }
  43596. this._instanceDirtyFlags = 0;
  43597. // Make the appropriate data dirty
  43598. if (isTransparent) {
  43599. gii.transparentDirty = true;
  43600. if (rebuildTrans) {
  43601. rd._transparentListChanged = true;
  43602. }
  43603. }
  43604. else if (isAlphaTest) {
  43605. gii.alphaTestDirty = true;
  43606. }
  43607. else {
  43608. gii.opaqueDirty = true;
  43609. }
  43610. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  43611. };
  43612. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  43613. var minOff = BABYLON.Prim2DBase._bigInt;
  43614. var maxOff = 0;
  43615. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43616. var part = _a[_i];
  43617. if (part && part.dataElements) {
  43618. part.dataBuffer.pack();
  43619. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  43620. var el = _c[_b];
  43621. minOff = Math.min(minOff, el.offset);
  43622. maxOff = Math.max(maxOff, el.offset);
  43623. }
  43624. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  43625. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  43626. }
  43627. }
  43628. };
  43629. // This internal method is mainly used for transparency processing
  43630. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  43631. var length = this._instanceDataParts.length;
  43632. for (var i = 0; i < length; i++) {
  43633. var part = this._instanceDataParts[i];
  43634. if (part) {
  43635. var stride = part.dataBuffer.stride;
  43636. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  43637. // check if it's the last in the DFA
  43638. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  43639. return null;
  43640. }
  43641. // Return the Z of the next primitive that lies in the DFA
  43642. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43643. }
  43644. }
  43645. return null;
  43646. };
  43647. // This internal method is mainly used for transparency processing
  43648. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  43649. var length = this._instanceDataParts.length;
  43650. for (var i = 0; i < length; i++) {
  43651. var part = this._instanceDataParts[i];
  43652. if (part) {
  43653. var stride = part.dataBuffer.stride;
  43654. var firstElementOffset = part.dataElements[0].offset;
  43655. // check if it's the first in the DFA
  43656. if (firstElementOffset === 0) {
  43657. return null;
  43658. }
  43659. // Return the Z of the previous primitive that lies in the DFA
  43660. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43661. }
  43662. }
  43663. return null;
  43664. };
  43665. /**
  43666. * Transform a given point using the Primitive's origin setting.
  43667. * This method requires the Primitive's actualSize to be accurate
  43668. * @param p the point to transform
  43669. * @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.
  43670. * @param res an allocated Vector2 that will receive the transformed content
  43671. */
  43672. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  43673. var actualSize = this.actualSize;
  43674. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  43675. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  43676. };
  43677. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  43678. this.transformPointWithOriginByRef(p, originOffset, res);
  43679. return res;
  43680. };
  43681. /**
  43682. * Get the info for a given effect based on the dataPart metadata
  43683. * @param dataPartId partId in part list to get the info
  43684. * @param vertexBufferAttributes vertex buffer attributes to manually add
  43685. * @param uniforms uniforms to manually add
  43686. * @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
  43687. */
  43688. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  43689. if (uniforms === void 0) { uniforms = null; }
  43690. if (useInstanced === void 0) { useInstanced = null; }
  43691. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  43692. if (!dataPart) {
  43693. return null;
  43694. }
  43695. var instancedArray = this.owner.supportInstancedArray;
  43696. if (useInstanced != null) {
  43697. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  43698. if (useInstanced && instancedArray === false) {
  43699. return null;
  43700. }
  43701. // Use the caller's setting
  43702. instancedArray = useInstanced;
  43703. }
  43704. var cti = dataPart.getClassTreeInfo();
  43705. var categories = this.getUsedShaderCategories(dataPart);
  43706. var att = cti.classContent.getShaderAttributes(categories);
  43707. var defines = "";
  43708. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  43709. if (instancedArray) {
  43710. defines += "#define Instanced\n";
  43711. }
  43712. return {
  43713. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  43714. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  43715. defines: defines
  43716. };
  43717. };
  43718. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  43719. get: function () {
  43720. return this._modelRenderCache;
  43721. },
  43722. enumerable: true,
  43723. configurable: true
  43724. });
  43725. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  43726. return null;
  43727. };
  43728. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43729. };
  43730. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  43731. return null;
  43732. };
  43733. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  43734. return [];
  43735. };
  43736. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43737. };
  43738. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43739. };
  43740. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  43741. return true;
  43742. };
  43743. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  43744. if (!this.isVisible) {
  43745. return false;
  43746. }
  43747. part.isVisible = this.isVisible;
  43748. // 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)
  43749. if (part.dataElementCount === 1) {
  43750. part.curElement = 0;
  43751. this.updateInstanceDataPart(part);
  43752. }
  43753. return true;
  43754. };
  43755. /**
  43756. * Update the instanceDataBase level properties of a part
  43757. * @param part the part to update
  43758. * @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).
  43759. */
  43760. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  43761. if (positionOffset === void 0) { positionOffset = null; }
  43762. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  43763. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  43764. var size = this.renderGroup.viewportSize;
  43765. var zBias = this.actualZOffset;
  43766. var offX = 0;
  43767. var offY = 0;
  43768. // If there's an offset, apply the global transformation matrix on it to get a global offset
  43769. if (positionOffset) {
  43770. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  43771. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  43772. }
  43773. // 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
  43774. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  43775. // So for X:
  43776. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  43777. // - 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].
  43778. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  43779. var w = size.width;
  43780. var h = size.height;
  43781. var invZBias = 1 / zBias;
  43782. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  43783. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  43784. if (!this.applyActualScaleOnTransform()) {
  43785. var las = this.actualScale;
  43786. tx.x /= las.x;
  43787. ty.y /= las.y;
  43788. }
  43789. part.transformX = tx;
  43790. part.transformY = ty;
  43791. part.opacity = this.actualOpacity;
  43792. // 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)
  43793. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43794. };
  43795. RenderablePrim2D.prototype._updateRenderMode = function () {
  43796. if (this.isTransparent) {
  43797. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43798. }
  43799. else if (this.isAlphaTest) {
  43800. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43801. }
  43802. else {
  43803. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43804. }
  43805. };
  43806. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43807. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  43808. __decorate([
  43809. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43810. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43811. __decorate([
  43812. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43813. ], RenderablePrim2D.prototype, "isTransparent", null);
  43814. RenderablePrim2D = __decorate([
  43815. BABYLON.className("RenderablePrim2D")
  43816. ], RenderablePrim2D);
  43817. return RenderablePrim2D;
  43818. }(BABYLON.Prim2DBase));
  43819. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43820. })(BABYLON || (BABYLON = {}));
  43821. var BABYLON;
  43822. (function (BABYLON) {
  43823. var Shape2D = (function (_super) {
  43824. __extends(Shape2D, _super);
  43825. function Shape2D(settings) {
  43826. _super.call(this, settings);
  43827. if (!settings) {
  43828. settings = {};
  43829. }
  43830. var borderBrush = null;
  43831. if (settings.border) {
  43832. if (typeof (settings.border) === "string") {
  43833. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43834. }
  43835. else {
  43836. borderBrush = settings.border;
  43837. }
  43838. }
  43839. var fillBrush = null;
  43840. if (settings.fill) {
  43841. if (typeof (settings.fill) === "string") {
  43842. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43843. }
  43844. else {
  43845. fillBrush = settings.fill;
  43846. }
  43847. }
  43848. this._isTransparent = false;
  43849. this._oldTransparent = false;
  43850. this.border = borderBrush;
  43851. this.fill = fillBrush;
  43852. this._updateTransparencyStatus();
  43853. this.borderThickness = settings.borderThickness;
  43854. }
  43855. Object.defineProperty(Shape2D.prototype, "border", {
  43856. get: function () {
  43857. return this._border;
  43858. },
  43859. set: function (value) {
  43860. this._border = value;
  43861. this._updateTransparencyStatus();
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. Object.defineProperty(Shape2D.prototype, "fill", {
  43867. /**
  43868. * Get/set the brush to render the Fill part of the Primitive
  43869. */
  43870. get: function () {
  43871. return this._fill;
  43872. },
  43873. set: function (value) {
  43874. this._fill = value;
  43875. this._updateTransparencyStatus();
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43881. get: function () {
  43882. return this._borderThickness;
  43883. },
  43884. set: function (value) {
  43885. this._borderThickness = value;
  43886. },
  43887. enumerable: true,
  43888. configurable: true
  43889. });
  43890. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43891. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43892. // Fill Part
  43893. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43894. var fill = this.fill;
  43895. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43896. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43897. }
  43898. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43899. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43900. }
  43901. }
  43902. // Border Part
  43903. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43904. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43905. var border = this.border;
  43906. if (border instanceof BABYLON.SolidColorBrush2D) {
  43907. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43908. }
  43909. if (border instanceof BABYLON.GradientColorBrush2D) {
  43910. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43911. }
  43912. }
  43913. return cat;
  43914. };
  43915. Shape2D.prototype.applyActualScaleOnTransform = function () {
  43916. return false;
  43917. };
  43918. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43919. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43920. return false;
  43921. }
  43922. // Fill Part
  43923. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43924. var d = part;
  43925. if (this.fill) {
  43926. var fill = this.fill;
  43927. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43928. d.fillSolidColor = fill.color;
  43929. }
  43930. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43931. d.fillGradientColor1 = fill.color1;
  43932. d.fillGradientColor2 = fill.color2;
  43933. 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));
  43934. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43935. d.fillGradientTY = ty;
  43936. }
  43937. }
  43938. }
  43939. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43940. var d = part;
  43941. if (this.border) {
  43942. d.borderThickness = this.borderThickness;
  43943. var border = this.border;
  43944. if (border instanceof BABYLON.SolidColorBrush2D) {
  43945. d.borderSolidColor = border.color;
  43946. }
  43947. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43948. d.borderGradientColor1 = border.color1;
  43949. d.borderGradientColor2 = border.color2;
  43950. 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));
  43951. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43952. d.borderGradientTY = ty;
  43953. }
  43954. }
  43955. }
  43956. return true;
  43957. };
  43958. Shape2D.prototype._updateTransparencyStatus = function () {
  43959. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43960. if (this._isTransparent !== this._oldTransparent) {
  43961. this._oldTransparent = this._isTransparent;
  43962. this._updateRenderMode();
  43963. }
  43964. };
  43965. Shape2D.prototype._mustUpdateInstance = function () {
  43966. var res = this._oldTransparent !== this._isTransparent;
  43967. if (res) {
  43968. this._updateRenderMode();
  43969. this._oldTransparent = this._isTransparent;
  43970. }
  43971. return res;
  43972. };
  43973. Shape2D.prototype._isPrimTransparent = function () {
  43974. return this._isTransparent;
  43975. };
  43976. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43977. Shape2D.SHAPE2D_FILLPARTID = 2;
  43978. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43979. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43980. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43981. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43982. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43983. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43984. __decorate([
  43985. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43986. ], Shape2D.prototype, "border", null);
  43987. __decorate([
  43988. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43989. ], Shape2D.prototype, "fill", null);
  43990. __decorate([
  43991. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43992. ], Shape2D.prototype, "borderThickness", null);
  43993. Shape2D = __decorate([
  43994. BABYLON.className("Shape2D")
  43995. ], Shape2D);
  43996. return Shape2D;
  43997. }(BABYLON.RenderablePrim2D));
  43998. BABYLON.Shape2D = Shape2D;
  43999. var Shape2DInstanceData = (function (_super) {
  44000. __extends(Shape2DInstanceData, _super);
  44001. function Shape2DInstanceData() {
  44002. _super.apply(this, arguments);
  44003. }
  44004. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  44005. // FILL ATTRIBUTES
  44006. get: function () {
  44007. return null;
  44008. },
  44009. set: function (value) {
  44010. },
  44011. enumerable: true,
  44012. configurable: true
  44013. });
  44014. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  44015. get: function () {
  44016. return null;
  44017. },
  44018. set: function (value) {
  44019. },
  44020. enumerable: true,
  44021. configurable: true
  44022. });
  44023. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  44024. get: function () {
  44025. return null;
  44026. },
  44027. set: function (value) {
  44028. },
  44029. enumerable: true,
  44030. configurable: true
  44031. });
  44032. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  44033. get: function () {
  44034. return null;
  44035. },
  44036. set: function (value) {
  44037. },
  44038. enumerable: true,
  44039. configurable: true
  44040. });
  44041. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  44042. // BORDER ATTRIBUTES
  44043. get: function () {
  44044. return null;
  44045. },
  44046. set: function (value) {
  44047. },
  44048. enumerable: true,
  44049. configurable: true
  44050. });
  44051. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  44052. get: function () {
  44053. return null;
  44054. },
  44055. set: function (value) {
  44056. },
  44057. enumerable: true,
  44058. configurable: true
  44059. });
  44060. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  44061. get: function () {
  44062. return null;
  44063. },
  44064. set: function (value) {
  44065. },
  44066. enumerable: true,
  44067. configurable: true
  44068. });
  44069. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  44070. get: function () {
  44071. return null;
  44072. },
  44073. set: function (value) {
  44074. },
  44075. enumerable: true,
  44076. configurable: true
  44077. });
  44078. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  44079. get: function () {
  44080. return null;
  44081. },
  44082. set: function (value) {
  44083. },
  44084. enumerable: true,
  44085. configurable: true
  44086. });
  44087. __decorate([
  44088. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  44089. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  44090. __decorate([
  44091. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44092. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  44093. __decorate([
  44094. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44095. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  44096. __decorate([
  44097. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44098. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  44099. __decorate([
  44100. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  44101. ], Shape2DInstanceData.prototype, "borderThickness", null);
  44102. __decorate([
  44103. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  44104. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  44105. __decorate([
  44106. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44107. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  44108. __decorate([
  44109. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44110. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  44111. __decorate([
  44112. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  44113. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  44114. return Shape2DInstanceData;
  44115. }(BABYLON.InstanceDataBase));
  44116. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  44117. })(BABYLON || (BABYLON = {}));
  44118. var BABYLON;
  44119. (function (BABYLON) {
  44120. var Group2D = (function (_super) {
  44121. __extends(Group2D, _super);
  44122. /**
  44123. * Create an Logical or Renderable Group.
  44124. * @param settings a combination of settings, possible ones are
  44125. * - 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)
  44126. * - children: an array of direct children
  44127. * - id a text identifier, for information purpose
  44128. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44129. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44130. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44131. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  44132. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44133. * - zOrder: override the zOrder with the specified value
  44134. * - origin: define the normalized origin point location, default [0.5;0.5]
  44135. * - 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.
  44136. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  44137. * - 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).
  44138. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44139. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44140. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44141. * - 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!
  44142. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44143. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44144. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44145. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44146. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44147. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44148. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44149. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44150. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44151. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44152. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44153. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44154. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44155. */
  44156. function Group2D(settings) {
  44157. if (settings == null) {
  44158. settings = {};
  44159. }
  44160. if (settings.origin == null) {
  44161. settings.origin = new BABYLON.Vector2(0, 0);
  44162. }
  44163. _super.call(this, settings);
  44164. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  44165. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  44166. if (this._trackedNode && this.owner) {
  44167. this.owner._registerTrackedNode(this);
  44168. }
  44169. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  44170. var rd = this._renderableData;
  44171. if (rd) {
  44172. rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44173. }
  44174. this.size = size;
  44175. this._viewportPosition = BABYLON.Vector2.Zero();
  44176. this._viewportSize = BABYLON.Size.Zero();
  44177. }
  44178. Group2D._createCachedCanvasGroup = function (owner) {
  44179. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  44180. return g;
  44181. };
  44182. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  44183. this._bindCacheTarget();
  44184. if (vertexData) {
  44185. var uv = vertexData.uvs;
  44186. var nodeuv = this._renderableData._cacheNodeUVs;
  44187. for (var i = 0; i < 4; i++) {
  44188. uv[i * 2 + 0] = nodeuv[i].x;
  44189. uv[i * 2 + 1] = nodeuv[i].y;
  44190. }
  44191. }
  44192. if (material) {
  44193. material.diffuseTexture = this._renderableData._cacheTexture;
  44194. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  44195. }
  44196. this._renderableData._cacheTexture.hasAlpha = true;
  44197. this._unbindCacheTarget();
  44198. };
  44199. Object.defineProperty(Group2D.prototype, "cachedRect", {
  44200. /**
  44201. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  44202. * 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.
  44203. */
  44204. get: function () {
  44205. if (!this._renderableData) {
  44206. return null;
  44207. }
  44208. return this._renderableData._cacheNode;
  44209. },
  44210. enumerable: true,
  44211. configurable: true
  44212. });
  44213. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  44214. /**
  44215. * The UVs into the MapTexture that map the cached group
  44216. */
  44217. get: function () {
  44218. if (!this._renderableData) {
  44219. return null;
  44220. }
  44221. return this._renderableData._cacheNodeUVs;
  44222. },
  44223. enumerable: true,
  44224. configurable: true
  44225. });
  44226. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  44227. get: function () {
  44228. if (!this._renderableData) {
  44229. return null;
  44230. }
  44231. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  44232. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  44233. }
  44234. return this._renderableData._cacheNodeUVsChangedObservable;
  44235. },
  44236. enumerable: true,
  44237. configurable: true
  44238. });
  44239. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  44240. /**
  44241. * Access the texture that maintains a cached version of the Group2D.
  44242. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  44243. */
  44244. get: function () {
  44245. if (!this._renderableData) {
  44246. return null;
  44247. }
  44248. return this._renderableData._cacheTexture;
  44249. },
  44250. enumerable: true,
  44251. configurable: true
  44252. });
  44253. /**
  44254. * Call this method to remove this Group and its children from the Canvas
  44255. */
  44256. Group2D.prototype.dispose = function () {
  44257. if (!_super.prototype.dispose.call(this)) {
  44258. return false;
  44259. }
  44260. if (this._trackedNode != null) {
  44261. this.owner._unregisterTrackedNode(this);
  44262. this._trackedNode = null;
  44263. }
  44264. if (this._renderableData) {
  44265. this._renderableData.dispose(this.owner);
  44266. this._renderableData = null;
  44267. }
  44268. return true;
  44269. };
  44270. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  44271. /**
  44272. * @returns Returns true if the Group render content, false if it's a logical group only
  44273. */
  44274. get: function () {
  44275. return this._isRenderableGroup;
  44276. },
  44277. enumerable: true,
  44278. configurable: true
  44279. });
  44280. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  44281. /**
  44282. * @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
  44283. */
  44284. get: function () {
  44285. return this._isCachedGroup;
  44286. },
  44287. enumerable: true,
  44288. configurable: true
  44289. });
  44290. Object.defineProperty(Group2D.prototype, "size", {
  44291. get: function () {
  44292. return this._size;
  44293. },
  44294. /**
  44295. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  44296. * 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.
  44297. */
  44298. set: function (val) {
  44299. this._size = val;
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. Object.defineProperty(Group2D.prototype, "viewportSize", {
  44305. get: function () {
  44306. return this._viewportSize;
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. Object.defineProperty(Group2D.prototype, "actualSize", {
  44312. get: function () {
  44313. // The computed size will be floor on both width and height
  44314. var actualSize;
  44315. // Return the actualSize if set
  44316. if (this._actualSize) {
  44317. return this._actualSize;
  44318. }
  44319. // Return the size if set by the user
  44320. if (this._size) {
  44321. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  44322. }
  44323. else {
  44324. var m = this.layoutBoundingInfo.max();
  44325. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  44326. }
  44327. // 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)
  44328. if (!actualSize.equals(this._actualSize)) {
  44329. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  44330. this._actualSize = actualSize;
  44331. this.handleGroupChanged(Group2D.actualSizeProperty);
  44332. }
  44333. return actualSize;
  44334. },
  44335. set: function (value) {
  44336. this._actualSize = value;
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  44342. /**
  44343. * 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.
  44344. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  44345. * 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.
  44346. */
  44347. get: function () {
  44348. return this._cacheBehavior;
  44349. },
  44350. enumerable: true,
  44351. configurable: true
  44352. });
  44353. Group2D.prototype._addPrimToDirtyList = function (prim) {
  44354. this._renderableData._primDirtyList.push(prim);
  44355. };
  44356. Group2D.prototype._renderCachedCanvas = function () {
  44357. this.owner._addGroupRenderCount(1);
  44358. this.updateCachedStates(true);
  44359. var context = new BABYLON.PrepareRender2DContext();
  44360. this._prepareGroupRender(context);
  44361. this._groupRender();
  44362. };
  44363. Object.defineProperty(Group2D.prototype, "trackedNode", {
  44364. /**
  44365. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  44366. */
  44367. get: function () {
  44368. return this._trackedNode;
  44369. },
  44370. set: function (val) {
  44371. if (val != null) {
  44372. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44373. this.owner._registerTrackedNode(this);
  44374. }
  44375. this._trackedNode = val;
  44376. }
  44377. else {
  44378. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  44379. this.owner._unregisterTrackedNode(this);
  44380. }
  44381. this._trackedNode = null;
  44382. }
  44383. },
  44384. enumerable: true,
  44385. configurable: true
  44386. });
  44387. Group2D.prototype.levelIntersect = function (intersectInfo) {
  44388. // 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
  44389. return true;
  44390. };
  44391. Group2D.prototype.updateLevelBoundingInfo = function () {
  44392. var size;
  44393. // If the size is set by the user, the boundingInfo is computed from this value
  44394. if (this.size) {
  44395. size = this.size;
  44396. }
  44397. else {
  44398. size = new BABYLON.Size(0, 0);
  44399. }
  44400. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  44401. };
  44402. // Method called only on renderable groups to prepare the rendering
  44403. Group2D.prototype._prepareGroupRender = function (context) {
  44404. var sortedDirtyList = null;
  44405. // Update the Global Transformation and visibility status of the changed primitives
  44406. var rd = this._renderableData;
  44407. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44408. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44409. this.updateCachedStatesOf(sortedDirtyList, true);
  44410. }
  44411. var s = this.actualSize;
  44412. var a = this.actualScale;
  44413. var sw = Math.ceil(s.width * a.x);
  44414. var sh = Math.ceil(s.height * a.y);
  44415. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  44416. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  44417. if (this instanceof BABYLON.Canvas2D) {
  44418. var c = this;
  44419. if (c.designSize != null) {
  44420. sw = this.owner.engine.getRenderWidth();
  44421. sh = this.owner.engine.getRenderHeight();
  44422. }
  44423. }
  44424. // Setup the size of the rendering viewport
  44425. // 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
  44426. if (!this._isCachedGroup) {
  44427. // Compute the WebGL viewport's location/size
  44428. var t = this._globalTransform.getTranslation();
  44429. var rs = this.owner._renderingSize;
  44430. sh = Math.min(sh, rs.height - t.y);
  44431. sw = Math.min(sw, rs.width - t.x);
  44432. var x = t.x;
  44433. var y = t.y;
  44434. // 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
  44435. this._viewportPosition.x = x;
  44436. this._viewportPosition.y = y;
  44437. }
  44438. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  44439. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  44440. context.forceRefreshPrimitive = true;
  44441. this._viewportSize.width = sw;
  44442. this._viewportSize.height = sh;
  44443. }
  44444. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44445. // If the group is cached, set the dirty flag to true because of the incoming changes
  44446. this._cacheGroupDirty = this._isCachedGroup;
  44447. rd._primNewDirtyList.splice(0);
  44448. // If it's a force refresh, prepare all the children
  44449. if (context.forceRefreshPrimitive) {
  44450. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  44451. var p = _a[_i];
  44452. p._prepareRender(context);
  44453. }
  44454. }
  44455. else {
  44456. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  44457. // the hierarchyDepth in order to prepare primitives from top to bottom
  44458. if (!sortedDirtyList) {
  44459. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44460. }
  44461. sortedDirtyList.forEach(function (p) {
  44462. // 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.
  44463. // 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.
  44464. if (!p.isDisposed && p._needPrepare()) {
  44465. p._prepareRender(context);
  44466. }
  44467. });
  44468. }
  44469. // Everything is updated, clear the dirty list
  44470. rd._primDirtyList.forEach(function (p) {
  44471. if (rd._primNewDirtyList.indexOf(p) === -1) {
  44472. p._resetPropertiesDirty();
  44473. }
  44474. else {
  44475. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  44476. }
  44477. });
  44478. rd._primDirtyList.splice(0);
  44479. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  44480. }
  44481. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  44482. rd._childrenRenderableGroups.forEach(function (g) {
  44483. g._prepareGroupRender(context);
  44484. });
  44485. };
  44486. Group2D.prototype._groupRender = function () {
  44487. var _this = this;
  44488. var engine = this.owner.engine;
  44489. var failedCount = 0;
  44490. // First recurse to children render group to render them (in their cache or on screen)
  44491. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  44492. var childGroup = _a[_i];
  44493. childGroup._groupRender();
  44494. }
  44495. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  44496. if (!this.isCachedGroup || this._cacheGroupDirty) {
  44497. this.owner._addGroupRenderCount(1);
  44498. if (this.isCachedGroup) {
  44499. this._bindCacheTarget();
  44500. }
  44501. else {
  44502. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  44503. }
  44504. var curAlphaTest = engine.getAlphaTesting() === true;
  44505. var curDepthWrite = engine.getDepthWrite() === true;
  44506. // ===================================================================
  44507. // First pass, update the InstancedArray and render Opaque primitives
  44508. // Disable Alpha Testing, Enable Depth Write
  44509. engine.setAlphaTesting(false);
  44510. engine.setDepthWrite(true);
  44511. // For each different model of primitive to render
  44512. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  44513. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44514. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44515. var renderCount = _this._prepareContext(engine, context_1, v);
  44516. // If null is returned, there's no opaque data to render
  44517. if (renderCount === null) {
  44518. return;
  44519. }
  44520. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44521. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44522. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44523. var renderFailed = !v.modelRenderCache.render(v, context_1);
  44524. // Update dirty flag/related
  44525. v.opaqueDirty = renderFailed;
  44526. failedCount += renderFailed ? 1 : 0;
  44527. }
  44528. });
  44529. // =======================================================================
  44530. // Second pass, update the InstancedArray and render AlphaTest primitives
  44531. // Enable Alpha Testing, Enable Depth Write
  44532. engine.setAlphaTesting(true);
  44533. engine.setDepthWrite(true);
  44534. // For each different model of primitive to render
  44535. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  44536. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44537. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44538. var renderCount = _this._prepareContext(engine, context_1, v);
  44539. // If null is returned, there's no opaque data to render
  44540. if (renderCount === null) {
  44541. return;
  44542. }
  44543. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44544. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44545. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44546. var renderFailed = !v.modelRenderCache.render(v, context_1);
  44547. // Update dirty flag/related
  44548. v.opaqueDirty = renderFailed;
  44549. failedCount += renderFailed ? 1 : 0;
  44550. }
  44551. });
  44552. // =======================================================================
  44553. // Third pass, transparent primitive rendering
  44554. // Enable Alpha Testing, Disable Depth Write
  44555. engine.setAlphaTesting(true);
  44556. engine.setDepthWrite(false);
  44557. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  44558. if (this._renderableData._transparentListChanged) {
  44559. this._updateTransparentData();
  44560. }
  44561. // From this point on we have up to date data to render, so let's go
  44562. failedCount += this._renderTransparentData();
  44563. // =======================================================================
  44564. // Unbind target/restore viewport setting, clear dirty flag, and quit
  44565. // The group's content is no longer dirty
  44566. this._cacheGroupDirty = failedCount !== 0;
  44567. if (this.isCachedGroup) {
  44568. this._unbindCacheTarget();
  44569. }
  44570. else {
  44571. if (curVP) {
  44572. engine.setViewport(curVP);
  44573. }
  44574. }
  44575. // Restore saved states
  44576. engine.setAlphaTesting(curAlphaTest);
  44577. engine.setDepthWrite(curDepthWrite);
  44578. }
  44579. };
  44580. Group2D.prototype._setCacheGroupDirty = function () {
  44581. this._cacheGroupDirty = true;
  44582. };
  44583. Group2D.prototype._updateTransparentData = function () {
  44584. this.owner._addUpdateTransparentDataCount(1);
  44585. var rd = this._renderableData;
  44586. // Sort all the primitive from their depth, max (bottom) to min (top)
  44587. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  44588. var checkAndAddPrimInSegment = function (seg, tpiI) {
  44589. var tpi = rd._transparentPrimitives[tpiI];
  44590. // Fast rejection: if gii are different
  44591. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  44592. return false;
  44593. }
  44594. //let tpiZ = tpi._primitive.actualZOffset;
  44595. // We've made it so far, the tpi can be part of the segment, add it
  44596. tpi._transparentSegment = seg;
  44597. tpi._primitive._updateTransparentSegmentIndices(seg);
  44598. return true;
  44599. };
  44600. // Free the existing TransparentSegments
  44601. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  44602. var ts = _a[_i];
  44603. ts.dispose(this.owner.engine);
  44604. }
  44605. rd._transparentSegments.splice(0);
  44606. var prevSeg = null;
  44607. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  44608. var tpi = rd._transparentPrimitives[tpiI];
  44609. // Check if the Data in which the primitive is stored is not sorted properly
  44610. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  44611. tpi._groupInstanceInfo.sortTransparentData();
  44612. }
  44613. // Reset the segment, we have to create/rebuild it
  44614. tpi._transparentSegment = null;
  44615. // If there's a previous valid segment, check if this prim can be part of it
  44616. if (prevSeg) {
  44617. checkAndAddPrimInSegment(prevSeg, tpiI);
  44618. }
  44619. // If we couldn't insert in the adjacent segments, he have to create one
  44620. if (!tpi._transparentSegment) {
  44621. var ts = new BABYLON.TransparentSegment();
  44622. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  44623. var prim = tpi._primitive;
  44624. ts.startZ = prim.actualZOffset;
  44625. prim._updateTransparentSegmentIndices(ts);
  44626. ts.endZ = ts.startZ;
  44627. tpi._transparentSegment = ts;
  44628. rd._transparentSegments.push(ts);
  44629. }
  44630. // Update prevSeg
  44631. prevSeg = tpi._transparentSegment;
  44632. }
  44633. //rd._firstChangedPrim = null;
  44634. rd._transparentListChanged = false;
  44635. };
  44636. Group2D.prototype._renderTransparentData = function () {
  44637. var failedCount = 0;
  44638. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  44639. var rd = this._renderableData;
  44640. var useInstanced = this.owner.supportInstancedArray;
  44641. var length = rd._transparentSegments.length;
  44642. for (var i = 0; i < length; i++) {
  44643. context.instancedBuffers = null;
  44644. var ts = rd._transparentSegments[i];
  44645. var gii = ts.groupInsanceInfo;
  44646. var mrc = gii.modelRenderCache;
  44647. var engine = this.owner.engine;
  44648. var count = ts.endDataIndex - ts.startDataIndex;
  44649. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  44650. // We don't want to create an Instanced Buffer for less that 5 prims
  44651. if (useInstanced && count >= 5) {
  44652. if (!ts.partBuffers) {
  44653. var buffers = new Array();
  44654. for (var j = 0; j < gii.transparentData.length; j++) {
  44655. var gitd = gii.transparentData[j];
  44656. var dfa = gitd._partData;
  44657. var data = dfa.pack();
  44658. var stride = dfa.stride;
  44659. var neededSize = count * stride * 4;
  44660. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44661. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44662. engine.updateArrayBuffer(segData);
  44663. buffers.push(buffer);
  44664. }
  44665. ts.partBuffers = buffers;
  44666. }
  44667. else if (gii.transparentDirty) {
  44668. for (var j = 0; j < gii.transparentData.length; j++) {
  44669. var gitd = gii.transparentData[j];
  44670. var dfa = gitd._partData;
  44671. var data = dfa.pack();
  44672. var stride = dfa.stride;
  44673. var buffer = ts.partBuffers[j];
  44674. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44675. engine.bindArrayBuffer(buffer);
  44676. engine.updateArrayBuffer(segData);
  44677. }
  44678. }
  44679. context.useInstancing = true;
  44680. context.instancesCount = count;
  44681. context.instancedBuffers = ts.partBuffers;
  44682. context.groupInfoPartData = gii.transparentData;
  44683. var renderFailed = !mrc.render(gii, context);
  44684. failedCount += renderFailed ? 1 : 0;
  44685. }
  44686. else {
  44687. context.useInstancing = false;
  44688. context.partDataStartIndex = ts.startDataIndex;
  44689. context.partDataEndIndex = ts.endDataIndex;
  44690. context.groupInfoPartData = gii.transparentData;
  44691. var renderFailed = !mrc.render(gii, context);
  44692. failedCount += renderFailed ? 1 : 0;
  44693. }
  44694. }
  44695. return failedCount;
  44696. };
  44697. Group2D.prototype._prepareContext = function (engine, context, gii) {
  44698. var gipd = null;
  44699. var setDirty;
  44700. var getDirty;
  44701. // Render Mode specifics
  44702. switch (context.renderMode) {
  44703. case BABYLON.Render2DContext.RenderModeOpaque:
  44704. {
  44705. if (!gii.hasOpaqueData) {
  44706. return null;
  44707. }
  44708. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  44709. getDirty = function () { return gii.opaqueDirty; };
  44710. context.groupInfoPartData = gii.opaqueData;
  44711. gipd = gii.opaqueData;
  44712. break;
  44713. }
  44714. case BABYLON.Render2DContext.RenderModeAlphaTest:
  44715. {
  44716. if (!gii.hasAlphaTestData) {
  44717. return null;
  44718. }
  44719. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  44720. getDirty = function () { return gii.alphaTestDirty; };
  44721. context.groupInfoPartData = gii.alphaTestData;
  44722. gipd = gii.alphaTestData;
  44723. break;
  44724. }
  44725. default:
  44726. throw new Error("_prepareContext is only for opaque or alphaTest");
  44727. }
  44728. var renderCount = 0;
  44729. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  44730. // Skip it if instanced arrays are not supported
  44731. if (this.owner.supportInstancedArray) {
  44732. // Flag for instancing
  44733. context.useInstancing = true;
  44734. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  44735. for (var i = 0; i < gipd.length; i++) {
  44736. var pid = gipd[i];
  44737. // If the instances of the model was changed, pack the data
  44738. var array = pid._partData;
  44739. var instanceData_1 = array.pack();
  44740. renderCount += array.usedElementCount;
  44741. // Compute the size the instance buffer should have
  44742. var neededSize = array.usedElementCount * array.stride * 4;
  44743. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  44744. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  44745. if (pid._partBuffer) {
  44746. engine.deleteInstancesBuffer(pid._partBuffer);
  44747. }
  44748. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44749. pid._partBufferSize = neededSize;
  44750. setDirty(false);
  44751. // Update the WebGL buffer to match the new content of the instances data
  44752. engine.updateArrayBuffer(instanceData_1);
  44753. }
  44754. else if (getDirty()) {
  44755. // Update the WebGL buffer to match the new content of the instances data
  44756. engine.bindArrayBuffer(pid._partBuffer);
  44757. engine.updateArrayBuffer(instanceData_1);
  44758. }
  44759. }
  44760. setDirty(false);
  44761. }
  44762. else {
  44763. context.partDataStartIndex = 0;
  44764. // Find the first valid object to get the count
  44765. if (context.groupInfoPartData.length > 0) {
  44766. var i = 0;
  44767. while (!context.groupInfoPartData[i]) {
  44768. i++;
  44769. }
  44770. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  44771. }
  44772. }
  44773. return renderCount;
  44774. };
  44775. Group2D.prototype._setRenderingScale = function (scale) {
  44776. if (this._renderableData._renderingScale === scale) {
  44777. return;
  44778. }
  44779. this._renderableData._renderingScale = scale;
  44780. };
  44781. Group2D.prototype._bindCacheTarget = function () {
  44782. var curWidth;
  44783. var curHeight;
  44784. var rd = this._renderableData;
  44785. var rs = rd._renderingScale;
  44786. var noResizeScale = rd._noResizeOnScale;
  44787. var isCanvas = this.parent == null;
  44788. var scale;
  44789. if (noResizeScale) {
  44790. scale = isCanvas ? Group2D._uV : this.parent.actualScale;
  44791. }
  44792. else {
  44793. scale = this.actualScale;
  44794. }
  44795. Group2D._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  44796. Group2D._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  44797. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  44798. if (rd._cacheNode) {
  44799. var size = rd._cacheNode.contentSize;
  44800. // Check if we have to deallocate because the size is too small
  44801. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  44802. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  44803. // For World space: no over-provisioning
  44804. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  44805. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  44806. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  44807. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  44808. rd._cacheTexture.freeRect(rd._cacheNode);
  44809. rd._cacheNode = null;
  44810. }
  44811. }
  44812. if (!rd._cacheNode) {
  44813. // Check if we have to allocate a rendering zone in the global cache texture
  44814. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  44815. rd._cacheNode = res.node;
  44816. rd._cacheTexture = res.texture;
  44817. rd._cacheRenderSprite = res.sprite;
  44818. sizeChanged = true;
  44819. }
  44820. if (sizeChanged) {
  44821. rd._cacheSize.copyFrom(Group2D._s);
  44822. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  44823. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  44824. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  44825. }
  44826. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  44827. }
  44828. var n = rd._cacheNode;
  44829. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  44830. };
  44831. Group2D.prototype._unbindCacheTarget = function () {
  44832. if (this._renderableData._cacheTexture) {
  44833. this._renderableData._cacheTexture.unbindTexture();
  44834. }
  44835. };
  44836. Group2D.prototype.handleGroupChanged = function (prop) {
  44837. // This method is only for cachedGroup
  44838. var rd = this._renderableData;
  44839. if (!rd) {
  44840. return;
  44841. }
  44842. var cachedSprite = rd._cacheRenderSprite;
  44843. if (!this.isCachedGroup || !cachedSprite) {
  44844. return;
  44845. }
  44846. // For now we only support these property changes
  44847. // TODO: add more! :)
  44848. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44849. cachedSprite.actualPosition = this.actualPosition.clone();
  44850. if (cachedSprite.position != null) {
  44851. cachedSprite.position = cachedSprite.actualPosition.clone();
  44852. }
  44853. }
  44854. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44855. cachedSprite.rotation = this.rotation;
  44856. }
  44857. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44858. cachedSprite.scale = this.scale;
  44859. }
  44860. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44861. cachedSprite.origin = this.origin.clone();
  44862. }
  44863. else if (prop.id === Group2D.actualSizeProperty.id) {
  44864. cachedSprite.size = this.actualSize.clone();
  44865. }
  44866. };
  44867. Group2D.prototype.detectGroupStates = function () {
  44868. var isCanvas = this instanceof BABYLON.Canvas2D;
  44869. var canvasStrat = this.owner.cachingStrategy;
  44870. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44871. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44872. this._isRenderableGroup = isCanvas;
  44873. this._isCachedGroup = false;
  44874. }
  44875. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44876. if (isCanvas) {
  44877. this._isRenderableGroup = true;
  44878. this._isCachedGroup = true;
  44879. }
  44880. else {
  44881. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44882. this._isCachedGroup = false;
  44883. }
  44884. }
  44885. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44886. if (isCanvas) {
  44887. this._isRenderableGroup = true;
  44888. this._isCachedGroup = false;
  44889. }
  44890. else {
  44891. if (this.hierarchyDepth === 1) {
  44892. this._isRenderableGroup = true;
  44893. this._isCachedGroup = true;
  44894. }
  44895. else {
  44896. this._isRenderableGroup = false;
  44897. this._isCachedGroup = false;
  44898. }
  44899. }
  44900. }
  44901. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44902. var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK;
  44903. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44904. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44905. this._isCachedGroup = false;
  44906. }
  44907. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44908. this._isRenderableGroup = true;
  44909. this._isCachedGroup = true;
  44910. }
  44911. }
  44912. if (this._isRenderableGroup) {
  44913. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44914. if (!this._renderableData) {
  44915. this._renderableData = new RenderableGroupData();
  44916. }
  44917. }
  44918. // If the group is tagged as renderable we add it to the renderable tree
  44919. if (this._isCachedGroup) {
  44920. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44921. var cur = this.parent;
  44922. while (cur) {
  44923. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44924. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44925. cur._renderableData._childrenRenderableGroups.push(this);
  44926. }
  44927. break;
  44928. }
  44929. cur = cur.parent;
  44930. }
  44931. }
  44932. };
  44933. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44934. /**
  44935. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44936. */
  44937. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44938. /**
  44939. * When used, this group's content won't be cached, no matter which strategy used.
  44940. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44941. */
  44942. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44943. /**
  44944. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44945. */
  44946. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44947. /**
  44948. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  44949. */
  44950. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  44951. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  44952. Group2D._uV = new BABYLON.Vector2(1, 1);
  44953. Group2D._s = BABYLON.Size.Zero();
  44954. __decorate([
  44955. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44956. ], Group2D.prototype, "size", null);
  44957. __decorate([
  44958. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44959. ], Group2D.prototype, "actualSize", null);
  44960. Group2D = __decorate([
  44961. BABYLON.className("Group2D")
  44962. ], Group2D);
  44963. return Group2D;
  44964. }(BABYLON.Prim2DBase));
  44965. BABYLON.Group2D = Group2D;
  44966. var RenderableGroupData = (function () {
  44967. function RenderableGroupData() {
  44968. this._primDirtyList = new Array();
  44969. this._primNewDirtyList = new Array();
  44970. this._childrenRenderableGroups = new Array();
  44971. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44972. this._transparentPrimitives = new Array();
  44973. this._transparentSegments = new Array();
  44974. this._transparentListChanged = false;
  44975. this._cacheNode = null;
  44976. this._cacheTexture = null;
  44977. this._cacheRenderSprite = null;
  44978. this._renderingScale = 1;
  44979. this._cacheNodeUVs = null;
  44980. this._cacheNodeUVsChangedObservable = null;
  44981. this._cacheSize = BABYLON.Size.Zero();
  44982. this._useMipMap = false;
  44983. this._anisotropicLevel = 1;
  44984. this._noResizeOnScale = false;
  44985. }
  44986. RenderableGroupData.prototype.dispose = function (owner) {
  44987. var engine = owner.engine;
  44988. if (this._cacheRenderSprite) {
  44989. this._cacheRenderSprite.dispose();
  44990. this._cacheRenderSprite = null;
  44991. }
  44992. if (this._cacheTexture && this._cacheNode) {
  44993. this._cacheTexture.freeRect(this._cacheNode);
  44994. this._cacheTexture = null;
  44995. this._cacheNode = null;
  44996. }
  44997. if (this._primDirtyList) {
  44998. this._primDirtyList.splice(0);
  44999. this._primDirtyList = null;
  45000. }
  45001. if (this._renderGroupInstancesInfo) {
  45002. this._renderGroupInstancesInfo.forEach(function (k, v) {
  45003. v.dispose();
  45004. });
  45005. this._renderGroupInstancesInfo = null;
  45006. }
  45007. if (this._cacheNodeUVsChangedObservable) {
  45008. this._cacheNodeUVsChangedObservable.clear();
  45009. this._cacheNodeUVsChangedObservable = null;
  45010. }
  45011. if (this._transparentSegments) {
  45012. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  45013. var ts = _a[_i];
  45014. ts.dispose(engine);
  45015. }
  45016. this._transparentSegments.splice(0);
  45017. this._transparentSegments = null;
  45018. }
  45019. };
  45020. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  45021. var tpi = new TransparentPrimitiveInfo();
  45022. tpi._primitive = prim;
  45023. tpi._groupInstanceInfo = gii;
  45024. tpi._transparentSegment = null;
  45025. this._transparentPrimitives.push(tpi);
  45026. this._transparentListChanged = true;
  45027. return tpi;
  45028. };
  45029. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  45030. var index = this._transparentPrimitives.indexOf(tpi);
  45031. if (index !== -1) {
  45032. this._transparentPrimitives.splice(index, 1);
  45033. this._transparentListChanged = true;
  45034. }
  45035. };
  45036. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  45037. this._transparentListChanged = true;
  45038. //this.updateSmallestZChangedPrim(tpi);
  45039. };
  45040. return RenderableGroupData;
  45041. }());
  45042. BABYLON.RenderableGroupData = RenderableGroupData;
  45043. var TransparentPrimitiveInfo = (function () {
  45044. function TransparentPrimitiveInfo() {
  45045. }
  45046. return TransparentPrimitiveInfo;
  45047. }());
  45048. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  45049. })(BABYLON || (BABYLON = {}));
  45050. var BABYLON;
  45051. (function (BABYLON) {
  45052. var Rectangle2DRenderCache = (function (_super) {
  45053. __extends(Rectangle2DRenderCache, _super);
  45054. function Rectangle2DRenderCache(engine, modelKey) {
  45055. _super.call(this, engine, modelKey);
  45056. this.effectsReady = false;
  45057. this.fillVB = null;
  45058. this.fillIB = null;
  45059. this.fillIndicesCount = 0;
  45060. this.instancingFillAttributes = null;
  45061. this.effectFill = null;
  45062. this.effectFillInstanced = null;
  45063. this.borderVB = null;
  45064. this.borderIB = null;
  45065. this.borderIndicesCount = 0;
  45066. this.instancingBorderAttributes = null;
  45067. this.effectBorder = null;
  45068. this.effectBorderInstanced = null;
  45069. }
  45070. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  45071. // Do nothing if the shader is still loading/preparing
  45072. if (!this.effectsReady) {
  45073. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45074. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45075. return false;
  45076. }
  45077. this.effectsReady = true;
  45078. }
  45079. var canvas = instanceInfo.owner.owner;
  45080. var engine = canvas.engine;
  45081. var depthFunction = 0;
  45082. if (this.effectFill && this.effectBorder) {
  45083. depthFunction = engine.getDepthFunction();
  45084. engine.setDepthFunctionToLessOrEqual();
  45085. }
  45086. var curAlphaMode = engine.getAlphaMode();
  45087. if (this.effectFill) {
  45088. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45089. var pid = context.groupInfoPartData[partIndex];
  45090. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45092. }
  45093. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45094. engine.enableEffect(effect);
  45095. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45096. if (context.useInstancing) {
  45097. if (!this.instancingFillAttributes) {
  45098. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45099. }
  45100. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45101. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45102. canvas._addDrawCallCount(1, context.renderMode);
  45103. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45104. engine.draw(true, 0, this.fillIndicesCount, count);
  45105. engine.unbindInstanceAttributes();
  45106. }
  45107. else {
  45108. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45109. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45110. this.setupUniforms(effect, partIndex, pid._partData, i);
  45111. engine.draw(true, 0, this.fillIndicesCount);
  45112. }
  45113. }
  45114. }
  45115. if (this.effectBorder) {
  45116. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45117. var pid = context.groupInfoPartData[partIndex];
  45118. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45119. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45120. }
  45121. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45122. engine.enableEffect(effect);
  45123. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45124. if (context.useInstancing) {
  45125. if (!this.instancingBorderAttributes) {
  45126. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45127. }
  45128. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45129. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45130. canvas._addDrawCallCount(1, context.renderMode);
  45131. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45132. engine.draw(true, 0, this.borderIndicesCount, count);
  45133. engine.unbindInstanceAttributes();
  45134. }
  45135. else {
  45136. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45137. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45138. this.setupUniforms(effect, partIndex, pid._partData, i);
  45139. engine.draw(true, 0, this.borderIndicesCount);
  45140. }
  45141. }
  45142. }
  45143. engine.setAlphaMode(curAlphaMode, true);
  45144. if (this.effectFill && this.effectBorder) {
  45145. engine.setDepthFunction(depthFunction);
  45146. }
  45147. return true;
  45148. };
  45149. Rectangle2DRenderCache.prototype.dispose = function () {
  45150. if (!_super.prototype.dispose.call(this)) {
  45151. return false;
  45152. }
  45153. if (this.fillVB) {
  45154. this._engine._releaseBuffer(this.fillVB);
  45155. this.fillVB = null;
  45156. }
  45157. if (this.fillIB) {
  45158. this._engine._releaseBuffer(this.fillIB);
  45159. this.fillIB = null;
  45160. }
  45161. this.effectFill = null;
  45162. this.effectFillInstanced = null;
  45163. this.effectBorder = null;
  45164. this.effectBorderInstanced = null;
  45165. if (this.borderVB) {
  45166. this._engine._releaseBuffer(this.borderVB);
  45167. this.borderVB = null;
  45168. }
  45169. if (this.borderIB) {
  45170. this._engine._releaseBuffer(this.borderIB);
  45171. this.borderIB = null;
  45172. }
  45173. return true;
  45174. };
  45175. return Rectangle2DRenderCache;
  45176. }(BABYLON.ModelRenderCache));
  45177. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  45178. var Rectangle2DInstanceData = (function (_super) {
  45179. __extends(Rectangle2DInstanceData, _super);
  45180. function Rectangle2DInstanceData(partId) {
  45181. _super.call(this, partId, 1);
  45182. }
  45183. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  45184. get: function () {
  45185. return null;
  45186. },
  45187. set: function (value) {
  45188. },
  45189. enumerable: true,
  45190. configurable: true
  45191. });
  45192. __decorate([
  45193. BABYLON.instanceData()
  45194. ], Rectangle2DInstanceData.prototype, "properties", null);
  45195. return Rectangle2DInstanceData;
  45196. }(BABYLON.Shape2DInstanceData));
  45197. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  45198. var Rectangle2D = (function (_super) {
  45199. __extends(Rectangle2D, _super);
  45200. /**
  45201. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  45202. * @param settings a combination of settings, possible ones are
  45203. * - 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)
  45204. * - children: an array of direct children
  45205. * - id a text identifier, for information purpose
  45206. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  45207. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45208. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45209. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45210. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45211. * - zOrder: override the zOrder with the specified value
  45212. * - origin: define the normalized origin point location, default [0.5;0.5]
  45213. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  45214. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  45215. * - 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)
  45216. * - 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)
  45217. * - borderThickness: the thickness of the drawn border, default is 1.
  45218. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  45219. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45220. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45221. * - 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!
  45222. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45223. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45224. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45225. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45226. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45227. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45228. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45229. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45230. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45231. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45232. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45233. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45234. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45235. */
  45236. function Rectangle2D(settings) {
  45237. // Avoid checking every time if the object exists
  45238. if (settings == null) {
  45239. settings = {};
  45240. }
  45241. _super.call(this, settings);
  45242. if (settings.size != null) {
  45243. this.size = settings.size;
  45244. }
  45245. else if (settings.width || settings.height) {
  45246. var size = new BABYLON.Size(settings.width, settings.height);
  45247. this.size = size;
  45248. }
  45249. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  45250. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  45251. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  45252. //this.size = size;
  45253. this.roundRadius = roundRadius;
  45254. this.borderThickness = borderThickness;
  45255. }
  45256. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  45257. get: function () {
  45258. if (this._actualSize) {
  45259. return this._actualSize;
  45260. }
  45261. return this.size;
  45262. },
  45263. set: function (value) {
  45264. this._actualSize = value;
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  45270. get: function () {
  45271. return this._notRounded;
  45272. },
  45273. set: function (value) {
  45274. this._notRounded = value;
  45275. },
  45276. enumerable: true,
  45277. configurable: true
  45278. });
  45279. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  45280. get: function () {
  45281. return this._roundRadius;
  45282. },
  45283. set: function (value) {
  45284. this._roundRadius = value;
  45285. this.notRounded = value === 0;
  45286. this._positioningDirty();
  45287. },
  45288. enumerable: true,
  45289. configurable: true
  45290. });
  45291. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  45292. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  45293. if (this.notRounded) {
  45294. return true;
  45295. }
  45296. // 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.
  45297. // 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)
  45298. // 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.
  45299. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  45300. var size = this.size;
  45301. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  45302. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  45303. var rr = this.roundRadius;
  45304. var rrs = rr * rr;
  45305. // Check if the point is in the bottom/left quarter area
  45306. Rectangle2D._i1.x = rr;
  45307. Rectangle2D._i1.y = rr;
  45308. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45309. // Compute the intersection point in the quarter local space
  45310. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45311. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45312. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45313. return Rectangle2D._i2.lengthSquared() <= rrs;
  45314. }
  45315. // Check if the point is in the top/left quarter area
  45316. Rectangle2D._i1.x = rr;
  45317. Rectangle2D._i1.y = size.height - rr;
  45318. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45319. // Compute the intersection point in the quarter local space
  45320. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45321. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45322. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45323. return Rectangle2D._i2.lengthSquared() <= rrs;
  45324. }
  45325. // Check if the point is in the top/right quarter area
  45326. Rectangle2D._i1.x = size.width - rr;
  45327. Rectangle2D._i1.y = size.height - rr;
  45328. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  45329. // Compute the intersection point in the quarter local space
  45330. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45331. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45332. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45333. return Rectangle2D._i2.lengthSquared() <= rrs;
  45334. }
  45335. // Check if the point is in the bottom/right quarter area
  45336. Rectangle2D._i1.x = size.width - rr;
  45337. Rectangle2D._i1.y = rr;
  45338. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  45339. // Compute the intersection point in the quarter local space
  45340. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  45341. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  45342. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  45343. return Rectangle2D._i2.lengthSquared() <= rrs;
  45344. }
  45345. // At any other locations the point is guarantied to be inside
  45346. return true;
  45347. };
  45348. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  45349. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45350. };
  45351. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  45352. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  45353. return renderCache;
  45354. };
  45355. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45356. var renderCache = modelRenderCache;
  45357. var engine = this.owner.engine;
  45358. // Need to create WebGL resources for fill part?
  45359. if (this.fill) {
  45360. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  45361. var vb = new Float32Array(vbSize);
  45362. for (var i = 0; i < vbSize; i++) {
  45363. vb[i] = i;
  45364. }
  45365. renderCache.fillVB = engine.createVertexBuffer(vb);
  45366. var triCount = vbSize - 1;
  45367. var ib = new Float32Array(triCount * 3);
  45368. for (var i = 0; i < triCount; i++) {
  45369. ib[i * 3 + 0] = 0;
  45370. ib[i * 3 + 2] = i + 1;
  45371. ib[i * 3 + 1] = i + 2;
  45372. }
  45373. ib[triCount * 3 - 2] = 1;
  45374. renderCache.fillIB = engine.createIndexBuffer(ib);
  45375. renderCache.fillIndicesCount = triCount * 3;
  45376. // 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
  45377. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45378. if (ei) {
  45379. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45380. }
  45381. // Get the non instanced version
  45382. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45383. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45384. }
  45385. // Need to create WebGL resource for border part?
  45386. if (this.border) {
  45387. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  45388. var vb = new Float32Array(vbSize);
  45389. for (var i = 0; i < vbSize; i++) {
  45390. vb[i] = i;
  45391. }
  45392. renderCache.borderVB = engine.createVertexBuffer(vb);
  45393. var triCount = vbSize;
  45394. var rs = triCount / 2;
  45395. var ib = new Float32Array(triCount * 3);
  45396. for (var i = 0; i < rs; i++) {
  45397. var r0 = i;
  45398. var r1 = (i + 1) % rs;
  45399. ib[i * 6 + 0] = rs + r1;
  45400. ib[i * 6 + 1] = rs + r0;
  45401. ib[i * 6 + 2] = r0;
  45402. ib[i * 6 + 3] = r1;
  45403. ib[i * 6 + 4] = rs + r1;
  45404. ib[i * 6 + 5] = r0;
  45405. }
  45406. renderCache.borderIB = engine.createIndexBuffer(ib);
  45407. renderCache.borderIndicesCount = triCount * 3;
  45408. // 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
  45409. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45410. if (ei) {
  45411. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45412. }
  45413. // Get the non instanced version
  45414. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45415. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45416. }
  45417. return renderCache;
  45418. };
  45419. // 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
  45420. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  45421. // Fall back to default implementation if there's no round Radius
  45422. if (this._notRounded) {
  45423. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  45424. }
  45425. else {
  45426. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45427. initialContentPosition.x = initialContentPosition.y = rr;
  45428. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  45429. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  45430. }
  45431. };
  45432. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  45433. // Fall back to default implementation if there's no round Radius
  45434. if (this._notRounded) {
  45435. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  45436. }
  45437. else {
  45438. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45439. newPrimSize.copyFrom(primSize);
  45440. newPrimSize.width += rr * 2;
  45441. newPrimSize.height += rr * 2;
  45442. }
  45443. };
  45444. Rectangle2D.prototype.createInstanceDataParts = function () {
  45445. var res = new Array();
  45446. if (this.border) {
  45447. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45448. }
  45449. if (this.fill) {
  45450. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45451. }
  45452. return res;
  45453. };
  45454. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  45455. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45456. return false;
  45457. }
  45458. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45459. var d = part;
  45460. var size = this.actualSize;
  45461. var s = this.actualScale;
  45462. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45463. }
  45464. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45465. var d = part;
  45466. var size = this.actualSize;
  45467. var s = this.actualScale;
  45468. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45469. }
  45470. return true;
  45471. };
  45472. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  45473. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  45474. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  45475. Rectangle2D.roundSubdivisions = 16;
  45476. __decorate([
  45477. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  45478. ], Rectangle2D.prototype, "actualSize", null);
  45479. __decorate([
  45480. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  45481. ], Rectangle2D.prototype, "notRounded", null);
  45482. __decorate([
  45483. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  45484. ], Rectangle2D.prototype, "roundRadius", null);
  45485. Rectangle2D = __decorate([
  45486. BABYLON.className("Rectangle2D")
  45487. ], Rectangle2D);
  45488. return Rectangle2D;
  45489. }(BABYLON.Shape2D));
  45490. BABYLON.Rectangle2D = Rectangle2D;
  45491. })(BABYLON || (BABYLON = {}));
  45492. var BABYLON;
  45493. (function (BABYLON) {
  45494. var Ellipse2DRenderCache = (function (_super) {
  45495. __extends(Ellipse2DRenderCache, _super);
  45496. function Ellipse2DRenderCache(engine, modelKey) {
  45497. _super.call(this, engine, modelKey);
  45498. this.effectsReady = false;
  45499. this.fillVB = null;
  45500. this.fillIB = null;
  45501. this.fillIndicesCount = 0;
  45502. this.instancingFillAttributes = null;
  45503. this.effectFillInstanced = null;
  45504. this.effectFill = null;
  45505. this.borderVB = null;
  45506. this.borderIB = null;
  45507. this.borderIndicesCount = 0;
  45508. this.instancingBorderAttributes = null;
  45509. this.effectBorderInstanced = null;
  45510. this.effectBorder = null;
  45511. }
  45512. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  45513. // Do nothing if the shader is still loading/preparing
  45514. if (!this.effectsReady) {
  45515. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45516. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45517. return false;
  45518. }
  45519. this.effectsReady = true;
  45520. }
  45521. var canvas = instanceInfo.owner.owner;
  45522. var engine = canvas.engine;
  45523. var depthFunction = 0;
  45524. if (this.effectFill && this.effectBorder) {
  45525. depthFunction = engine.getDepthFunction();
  45526. engine.setDepthFunctionToLessOrEqual();
  45527. }
  45528. var curAlphaMode = engine.getAlphaMode();
  45529. if (this.effectFill) {
  45530. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45531. var pid = context.groupInfoPartData[partIndex];
  45532. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45533. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45534. }
  45535. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45536. engine.enableEffect(effect);
  45537. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45538. if (context.useInstancing) {
  45539. if (!this.instancingFillAttributes) {
  45540. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45541. }
  45542. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45543. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45544. canvas._addDrawCallCount(1, context.renderMode);
  45545. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45546. engine.draw(true, 0, this.fillIndicesCount, count);
  45547. engine.unbindInstanceAttributes();
  45548. }
  45549. else {
  45550. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45551. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45552. this.setupUniforms(effect, partIndex, pid._partData, i);
  45553. engine.draw(true, 0, this.fillIndicesCount);
  45554. }
  45555. }
  45556. }
  45557. if (this.effectBorder) {
  45558. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45559. var pid = context.groupInfoPartData[partIndex];
  45560. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45562. }
  45563. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45564. engine.enableEffect(effect);
  45565. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45566. if (context.useInstancing) {
  45567. if (!this.instancingBorderAttributes) {
  45568. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45569. }
  45570. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45571. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45572. canvas._addDrawCallCount(1, context.renderMode);
  45573. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45574. engine.draw(true, 0, this.borderIndicesCount, count);
  45575. engine.unbindInstanceAttributes();
  45576. }
  45577. else {
  45578. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45579. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45580. this.setupUniforms(effect, partIndex, pid._partData, i);
  45581. engine.draw(true, 0, this.borderIndicesCount);
  45582. }
  45583. }
  45584. }
  45585. engine.setAlphaMode(curAlphaMode, true);
  45586. if (this.effectFill && this.effectBorder) {
  45587. engine.setDepthFunction(depthFunction);
  45588. }
  45589. return true;
  45590. };
  45591. Ellipse2DRenderCache.prototype.dispose = function () {
  45592. if (!_super.prototype.dispose.call(this)) {
  45593. return false;
  45594. }
  45595. if (this.fillVB) {
  45596. this._engine._releaseBuffer(this.fillVB);
  45597. this.fillVB = null;
  45598. }
  45599. if (this.fillIB) {
  45600. this._engine._releaseBuffer(this.fillIB);
  45601. this.fillIB = null;
  45602. }
  45603. this.effectFill = null;
  45604. this.effectFillInstanced = null;
  45605. this.effectBorder = null;
  45606. this.effectBorderInstanced = null;
  45607. if (this.borderVB) {
  45608. this._engine._releaseBuffer(this.borderVB);
  45609. this.borderVB = null;
  45610. }
  45611. if (this.borderIB) {
  45612. this._engine._releaseBuffer(this.borderIB);
  45613. this.borderIB = null;
  45614. }
  45615. return true;
  45616. };
  45617. return Ellipse2DRenderCache;
  45618. }(BABYLON.ModelRenderCache));
  45619. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  45620. var Ellipse2DInstanceData = (function (_super) {
  45621. __extends(Ellipse2DInstanceData, _super);
  45622. function Ellipse2DInstanceData(partId) {
  45623. _super.call(this, partId, 1);
  45624. }
  45625. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  45626. get: function () {
  45627. return null;
  45628. },
  45629. set: function (value) {
  45630. },
  45631. enumerable: true,
  45632. configurable: true
  45633. });
  45634. __decorate([
  45635. BABYLON.instanceData()
  45636. ], Ellipse2DInstanceData.prototype, "properties", null);
  45637. return Ellipse2DInstanceData;
  45638. }(BABYLON.Shape2DInstanceData));
  45639. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  45640. var Ellipse2D = (function (_super) {
  45641. __extends(Ellipse2D, _super);
  45642. /**
  45643. * Create an Ellipse 2D Shape primitive
  45644. * @param settings a combination of settings, possible ones are
  45645. * - 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)
  45646. * - children: an array of direct children
  45647. * - id: a text identifier, for information purpose
  45648. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45649. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45650. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45651. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45652. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45653. * - zOrder: override the zOrder with the specified value
  45654. * - origin: define the normalized origin point location, default [0.5;0.5]
  45655. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  45656. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  45657. * - 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)
  45658. * - 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)
  45659. * - borderThickness: the thickness of the drawn border, default is 1.
  45660. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  45661. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45662. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45663. * - 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!
  45664. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45665. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45666. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45667. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45668. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45669. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45670. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45671. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45672. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45673. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45674. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45675. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45676. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45677. */
  45678. function Ellipse2D(settings) {
  45679. // Avoid checking every time if the object exists
  45680. if (settings == null) {
  45681. settings = {};
  45682. }
  45683. _super.call(this, settings);
  45684. if (settings.size != null) {
  45685. this.size = settings.size;
  45686. }
  45687. else if (settings.width || settings.height) {
  45688. var size = new BABYLON.Size(settings.width, settings.height);
  45689. this.size = size;
  45690. }
  45691. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  45692. this.subdivisions = sub;
  45693. }
  45694. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  45695. get: function () {
  45696. if (this._actualSize) {
  45697. return this._actualSize;
  45698. }
  45699. return this.size;
  45700. },
  45701. set: function (value) {
  45702. this._actualSize = value;
  45703. },
  45704. enumerable: true,
  45705. configurable: true
  45706. });
  45707. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  45708. get: function () {
  45709. return this._subdivisions;
  45710. },
  45711. set: function (value) {
  45712. this._subdivisions = value;
  45713. },
  45714. enumerable: true,
  45715. configurable: true
  45716. });
  45717. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  45718. var w = this.size.width / 2;
  45719. var h = this.size.height / 2;
  45720. var x = intersectInfo._localPickPosition.x - w;
  45721. var y = intersectInfo._localPickPosition.y - h;
  45722. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  45723. };
  45724. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  45725. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45726. };
  45727. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  45728. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  45729. return renderCache;
  45730. };
  45731. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45732. var renderCache = modelRenderCache;
  45733. var engine = this.owner.engine;
  45734. // Need to create WebGL resources for fill part?
  45735. if (this.fill) {
  45736. var vbSize = this.subdivisions + 1;
  45737. var vb = new Float32Array(vbSize);
  45738. for (var i = 0; i < vbSize; i++) {
  45739. vb[i] = i;
  45740. }
  45741. renderCache.fillVB = engine.createVertexBuffer(vb);
  45742. var triCount = vbSize - 1;
  45743. var ib = new Float32Array(triCount * 3);
  45744. for (var i = 0; i < triCount; i++) {
  45745. ib[i * 3 + 0] = 0;
  45746. ib[i * 3 + 2] = i + 1;
  45747. ib[i * 3 + 1] = i + 2;
  45748. }
  45749. ib[triCount * 3 - 2] = 1;
  45750. renderCache.fillIB = engine.createIndexBuffer(ib);
  45751. renderCache.fillIndicesCount = triCount * 3;
  45752. // 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
  45753. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45754. if (ei) {
  45755. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45756. }
  45757. // Get the non instanced version
  45758. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45759. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45760. }
  45761. // Need to create WebGL resource for border part?
  45762. if (this.border) {
  45763. var vbSize = this.subdivisions * 2;
  45764. var vb = new Float32Array(vbSize);
  45765. for (var i = 0; i < vbSize; i++) {
  45766. vb[i] = i;
  45767. }
  45768. renderCache.borderVB = engine.createVertexBuffer(vb);
  45769. var triCount = vbSize;
  45770. var rs = triCount / 2;
  45771. var ib = new Float32Array(triCount * 3);
  45772. for (var i = 0; i < rs; i++) {
  45773. var r0 = i;
  45774. var r1 = (i + 1) % rs;
  45775. ib[i * 6 + 0] = rs + r1;
  45776. ib[i * 6 + 1] = rs + r0;
  45777. ib[i * 6 + 2] = r0;
  45778. ib[i * 6 + 3] = r1;
  45779. ib[i * 6 + 4] = rs + r1;
  45780. ib[i * 6 + 5] = r0;
  45781. }
  45782. renderCache.borderIB = engine.createIndexBuffer(ib);
  45783. renderCache.borderIndicesCount = (triCount * 3);
  45784. // 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
  45785. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45786. if (ei) {
  45787. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45788. }
  45789. // Get the non instanced version
  45790. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45791. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45792. }
  45793. return renderCache;
  45794. };
  45795. Ellipse2D.prototype.createInstanceDataParts = function () {
  45796. var res = new Array();
  45797. if (this.border) {
  45798. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45799. }
  45800. if (this.fill) {
  45801. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45802. }
  45803. return res;
  45804. };
  45805. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  45806. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45807. return false;
  45808. }
  45809. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45810. var d = part;
  45811. var size = this.actualSize;
  45812. var s = this.actualScale;
  45813. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45814. }
  45815. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45816. var d = part;
  45817. var size = this.actualSize;
  45818. var s = this.actualScale;
  45819. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45820. }
  45821. return true;
  45822. };
  45823. __decorate([
  45824. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  45825. ], Ellipse2D.prototype, "actualSize", null);
  45826. __decorate([
  45827. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  45828. ], Ellipse2D.prototype, "subdivisions", null);
  45829. Ellipse2D = __decorate([
  45830. BABYLON.className("Ellipse2D")
  45831. ], Ellipse2D);
  45832. return Ellipse2D;
  45833. }(BABYLON.Shape2D));
  45834. BABYLON.Ellipse2D = Ellipse2D;
  45835. })(BABYLON || (BABYLON = {}));
  45836. var BABYLON;
  45837. (function (BABYLON) {
  45838. var Sprite2DRenderCache = (function (_super) {
  45839. __extends(Sprite2DRenderCache, _super);
  45840. function Sprite2DRenderCache() {
  45841. _super.apply(this, arguments);
  45842. this.effectsReady = false;
  45843. this.vb = null;
  45844. this.ib = null;
  45845. this.instancingAttributes = null;
  45846. this.texture = null;
  45847. this.effect = null;
  45848. this.effectInstanced = null;
  45849. }
  45850. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  45851. // Do nothing if the shader is still loading/preparing
  45852. if (!this.effectsReady) {
  45853. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45854. return false;
  45855. }
  45856. this.effectsReady = true;
  45857. }
  45858. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  45859. var canvas = instanceInfo.owner.owner;
  45860. var engine = canvas.engine;
  45861. var cur = engine.getAlphaMode();
  45862. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45863. engine.enableEffect(effect);
  45864. effect.setTexture("diffuseSampler", this.texture);
  45865. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45866. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45867. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45868. }
  45869. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45870. var pid = context.groupInfoPartData[0];
  45871. if (context.useInstancing) {
  45872. if (!this.instancingAttributes) {
  45873. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45874. }
  45875. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45876. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45877. canvas._addDrawCallCount(1, context.renderMode);
  45878. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45879. engine.draw(true, 0, 6, count);
  45880. engine.unbindInstanceAttributes();
  45881. }
  45882. else {
  45883. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45884. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45885. this.setupUniforms(effect, 0, pid._partData, i);
  45886. engine.draw(true, 0, 6);
  45887. }
  45888. }
  45889. engine.setAlphaMode(cur, true);
  45890. return true;
  45891. };
  45892. Sprite2DRenderCache.prototype.dispose = function () {
  45893. if (!_super.prototype.dispose.call(this)) {
  45894. return false;
  45895. }
  45896. if (this.vb) {
  45897. this._engine._releaseBuffer(this.vb);
  45898. this.vb = null;
  45899. }
  45900. if (this.ib) {
  45901. this._engine._releaseBuffer(this.ib);
  45902. this.ib = null;
  45903. }
  45904. //if (this.texture) {
  45905. // this.texture.dispose();
  45906. // this.texture = null;
  45907. //}
  45908. this.effect = null;
  45909. this.effectInstanced = null;
  45910. return true;
  45911. };
  45912. return Sprite2DRenderCache;
  45913. }(BABYLON.ModelRenderCache));
  45914. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45915. var Sprite2DInstanceData = (function (_super) {
  45916. __extends(Sprite2DInstanceData, _super);
  45917. function Sprite2DInstanceData(partId) {
  45918. _super.call(this, partId, 1);
  45919. }
  45920. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45921. get: function () {
  45922. return null;
  45923. },
  45924. set: function (value) {
  45925. },
  45926. enumerable: true,
  45927. configurable: true
  45928. });
  45929. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45930. get: function () {
  45931. return null;
  45932. },
  45933. set: function (value) {
  45934. },
  45935. enumerable: true,
  45936. configurable: true
  45937. });
  45938. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45939. get: function () {
  45940. return null;
  45941. },
  45942. set: function (value) {
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45948. get: function () {
  45949. return null;
  45950. },
  45951. set: function (value) {
  45952. },
  45953. enumerable: true,
  45954. configurable: true
  45955. });
  45956. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45957. // 3 floats being:
  45958. // - x: frame number to display
  45959. // - y: invertY setting
  45960. // - z: alignToPixel setting
  45961. get: function () {
  45962. return null;
  45963. },
  45964. set: function (value) {
  45965. },
  45966. enumerable: true,
  45967. configurable: true
  45968. });
  45969. __decorate([
  45970. BABYLON.instanceData()
  45971. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45972. __decorate([
  45973. BABYLON.instanceData()
  45974. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45975. __decorate([
  45976. BABYLON.instanceData()
  45977. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45978. __decorate([
  45979. BABYLON.instanceData()
  45980. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45981. __decorate([
  45982. BABYLON.instanceData()
  45983. ], Sprite2DInstanceData.prototype, "properties", null);
  45984. return Sprite2DInstanceData;
  45985. }(BABYLON.InstanceDataBase));
  45986. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45987. var Sprite2D = (function (_super) {
  45988. __extends(Sprite2D, _super);
  45989. /**
  45990. * Create an 2D Sprite primitive
  45991. * @param texture the texture that stores the sprite to render
  45992. * @param settings a combination of settings, possible ones are
  45993. * - 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)
  45994. * - children: an array of direct children
  45995. * - id a text identifier, for information purpose
  45996. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45997. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45998. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45999. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46000. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46001. * - zOrder: override the zOrder with the specified value
  46002. * - origin: define the normalized origin point location, default [0.5;0.5]
  46003. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  46004. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  46005. * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  46006. * - invertY: if true the texture Y will be inverted, default is false.
  46007. * - 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.
  46008. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  46009. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46010. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46011. * - 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!
  46012. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46013. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46014. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46015. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46016. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46017. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46018. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46019. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46020. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46021. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46022. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46023. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46024. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46025. */
  46026. function Sprite2D(texture, settings) {
  46027. var _this = this;
  46028. if (!settings) {
  46029. settings = {};
  46030. }
  46031. _super.call(this, settings);
  46032. this.texture = texture;
  46033. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46034. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46035. this.size = settings.spriteSize;
  46036. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  46037. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  46038. this.spriteFrame = 0;
  46039. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  46040. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  46041. this.useAlphaFromTexture = true;
  46042. if (settings.spriteSize == null || !texture.isReady()) {
  46043. if (texture.isReady()) {
  46044. this.size = texture.getBaseSize();
  46045. }
  46046. else {
  46047. texture.onLoadObservable.add(function () {
  46048. if (settings.spriteSize == null) {
  46049. _this.size = texture.getBaseSize();
  46050. }
  46051. _this._positioningDirty();
  46052. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  46053. });
  46054. }
  46055. }
  46056. }
  46057. Object.defineProperty(Sprite2D.prototype, "texture", {
  46058. get: function () {
  46059. return this._texture;
  46060. },
  46061. set: function (value) {
  46062. this._texture = value;
  46063. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  46064. },
  46065. enumerable: true,
  46066. configurable: true
  46067. });
  46068. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  46069. get: function () {
  46070. return this._useAlphaFromTexture;
  46071. },
  46072. set: function (value) {
  46073. if (this._useAlphaFromTexture === value) {
  46074. return;
  46075. }
  46076. this._useAlphaFromTexture = value;
  46077. this._updateRenderMode();
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  46083. get: function () {
  46084. if (this._actualSize) {
  46085. return this._actualSize;
  46086. }
  46087. return this.size;
  46088. },
  46089. set: function (value) {
  46090. this._actualSize = value;
  46091. },
  46092. enumerable: true,
  46093. configurable: true
  46094. });
  46095. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  46096. get: function () {
  46097. return this._location;
  46098. },
  46099. set: function (value) {
  46100. this._location = value;
  46101. },
  46102. enumerable: true,
  46103. configurable: true
  46104. });
  46105. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  46106. get: function () {
  46107. return this._spriteFrame;
  46108. },
  46109. set: function (value) {
  46110. this._spriteFrame = value;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(Sprite2D.prototype, "invertY", {
  46116. get: function () {
  46117. return this._invertY;
  46118. },
  46119. set: function (value) {
  46120. this._invertY = value;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  46126. get: function () {
  46127. return this._spriteScaleFactor;
  46128. },
  46129. set: function (value) {
  46130. this._spriteScaleFactor = value;
  46131. },
  46132. enumerable: true,
  46133. configurable: true
  46134. });
  46135. /**
  46136. * Sets the scale of the sprite using a BABYLON.Size(w,h).
  46137. * Keeps proportion by taking the maximum of the two scale for x and y.
  46138. * @param {Size} size Size(width,height)
  46139. */
  46140. Sprite2D.prototype.scaleToSize = function (size) {
  46141. var baseSize = this.size;
  46142. if (baseSize == null || !this.texture.isReady()) {
  46143. // we're probably at initiation of the scene, size is not set
  46144. if (this.texture.isReady()) {
  46145. baseSize = this.texture.getBaseSize();
  46146. }
  46147. else {
  46148. // the texture is not ready, wait for it to load before calling scaleToSize again
  46149. var thisObject = this;
  46150. this.texture.onLoadObservable.add(function () {
  46151. thisObject.scaleToSize(size);
  46152. });
  46153. return;
  46154. }
  46155. }
  46156. this.scale = Math.max(size.height / baseSize.height, size.width / baseSize.width);
  46157. };
  46158. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  46159. /**
  46160. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  46161. */
  46162. get: function () {
  46163. return this._alignToPixel;
  46164. },
  46165. set: function (value) {
  46166. this._alignToPixel = value;
  46167. },
  46168. enumerable: true,
  46169. configurable: true
  46170. });
  46171. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  46172. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  46173. };
  46174. /**
  46175. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  46176. */
  46177. Sprite2D.prototype.getAnimatables = function () {
  46178. var res = new Array();
  46179. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  46180. res.push(this.texture);
  46181. }
  46182. return res;
  46183. };
  46184. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  46185. // 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
  46186. return true;
  46187. };
  46188. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  46189. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  46190. return sprite;
  46191. };
  46192. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  46193. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  46194. return renderCache;
  46195. };
  46196. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46197. var renderCache = modelRenderCache;
  46198. var engine = this.owner.engine;
  46199. var vb = new Float32Array(4);
  46200. for (var i = 0; i < 4; i++) {
  46201. vb[i] = i;
  46202. }
  46203. renderCache.vb = engine.createVertexBuffer(vb);
  46204. var ib = new Float32Array(6);
  46205. ib[0] = 0;
  46206. ib[1] = 2;
  46207. ib[2] = 1;
  46208. ib[3] = 0;
  46209. ib[4] = 3;
  46210. ib[5] = 2;
  46211. renderCache.ib = engine.createIndexBuffer(ib);
  46212. renderCache.texture = this.texture;
  46213. // 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
  46214. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  46215. if (ei) {
  46216. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46217. }
  46218. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  46219. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46220. return renderCache;
  46221. };
  46222. Sprite2D.prototype.createInstanceDataParts = function () {
  46223. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  46224. };
  46225. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46226. Sprite2D.layoutConstructMode = true;
  46227. };
  46228. // if obj contains something, we restore the _text property
  46229. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46230. Sprite2D.layoutConstructMode = false;
  46231. };
  46232. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  46233. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46234. return false;
  46235. }
  46236. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  46237. return false;
  46238. }
  46239. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  46240. var d = this._instanceDataParts[0];
  46241. if (Sprite2D.layoutConstructMode) {
  46242. d.topLeftUV = BABYLON.Vector2.Zero();
  46243. d.sizeUV = BABYLON.Vector2.Zero();
  46244. d.properties = BABYLON.Vector3.Zero();
  46245. d.textureSize = BABYLON.Vector2.Zero();
  46246. d.scaleFactor = BABYLON.Vector2.Zero();
  46247. }
  46248. else {
  46249. var ts = this.texture.getBaseSize();
  46250. var sl = this.spriteLocation;
  46251. var ss = this.actualSize;
  46252. var ssf = this.spriteScaleFactor;
  46253. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  46254. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  46255. d.sizeUV = suv;
  46256. d.scaleFactor = ssf;
  46257. Sprite2D._prop.x = this.spriteFrame;
  46258. Sprite2D._prop.y = this.invertY ? 1 : 0;
  46259. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  46260. d.properties = Sprite2D._prop;
  46261. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46262. }
  46263. }
  46264. return true;
  46265. };
  46266. Sprite2D.prototype._mustUpdateInstance = function () {
  46267. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  46268. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  46269. if (res) {
  46270. this._updateRenderMode();
  46271. }
  46272. return res;
  46273. };
  46274. Sprite2D.prototype._useTextureAlpha = function () {
  46275. return this.texture != null && this.texture.hasAlpha;
  46276. };
  46277. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  46278. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  46279. };
  46280. Sprite2D.SPRITE2D_MAINPARTID = 1;
  46281. Sprite2D._prop = BABYLON.Vector3.Zero();
  46282. Sprite2D.layoutConstructMode = false;
  46283. __decorate([
  46284. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  46285. ], Sprite2D.prototype, "texture", null);
  46286. __decorate([
  46287. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  46288. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  46289. __decorate([
  46290. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  46291. ], Sprite2D.prototype, "actualSize", null);
  46292. __decorate([
  46293. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  46294. ], Sprite2D.prototype, "spriteLocation", null);
  46295. __decorate([
  46296. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  46297. ], Sprite2D.prototype, "spriteFrame", null);
  46298. __decorate([
  46299. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  46300. ], Sprite2D.prototype, "invertY", null);
  46301. __decorate([
  46302. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  46303. ], Sprite2D.prototype, "spriteScaleFactor", null);
  46304. Sprite2D = __decorate([
  46305. BABYLON.className("Sprite2D")
  46306. ], Sprite2D);
  46307. return Sprite2D;
  46308. }(BABYLON.RenderablePrim2D));
  46309. BABYLON.Sprite2D = Sprite2D;
  46310. })(BABYLON || (BABYLON = {}));
  46311. var BABYLON;
  46312. (function (BABYLON) {
  46313. var Text2DRenderCache = (function (_super) {
  46314. __extends(Text2DRenderCache, _super);
  46315. function Text2DRenderCache() {
  46316. _super.apply(this, arguments);
  46317. this.effectsReady = false;
  46318. this.vb = null;
  46319. this.ib = null;
  46320. this.instancingAttributes = null;
  46321. this.fontTexture = null;
  46322. this.effect = null;
  46323. this.effectInstanced = null;
  46324. }
  46325. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  46326. // Do nothing if the shader is still loading/preparing
  46327. if (!this.effectsReady) {
  46328. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  46329. return false;
  46330. }
  46331. this.effectsReady = true;
  46332. }
  46333. var canvas = instanceInfo.owner.owner;
  46334. var engine = canvas.engine;
  46335. this.fontTexture.update();
  46336. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  46337. engine.enableEffect(effect);
  46338. effect.setTexture("diffuseSampler", this.fontTexture);
  46339. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  46340. var curAlphaMode = engine.getAlphaMode();
  46341. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46342. var pid = context.groupInfoPartData[0];
  46343. if (context.useInstancing) {
  46344. if (!this.instancingAttributes) {
  46345. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  46346. }
  46347. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  46348. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46349. canvas._addDrawCallCount(1, context.renderMode);
  46350. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  46351. engine.draw(true, 0, 6, count);
  46352. engine.unbindInstanceAttributes();
  46353. }
  46354. else {
  46355. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46356. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46357. this.setupUniforms(effect, 0, pid._partData, i);
  46358. engine.draw(true, 0, 6);
  46359. }
  46360. }
  46361. engine.setAlphaMode(curAlphaMode, true);
  46362. return true;
  46363. };
  46364. Text2DRenderCache.prototype.dispose = function () {
  46365. if (!_super.prototype.dispose.call(this)) {
  46366. return false;
  46367. }
  46368. if (this.vb) {
  46369. this._engine._releaseBuffer(this.vb);
  46370. this.vb = null;
  46371. }
  46372. if (this.ib) {
  46373. this._engine._releaseBuffer(this.ib);
  46374. this.ib = null;
  46375. }
  46376. if (this.fontTexture) {
  46377. this.fontTexture.decCachedFontTextureCounter();
  46378. this.fontTexture = null;
  46379. }
  46380. this.effect = null;
  46381. this.effectInstanced = null;
  46382. return true;
  46383. };
  46384. return Text2DRenderCache;
  46385. }(BABYLON.ModelRenderCache));
  46386. BABYLON.Text2DRenderCache = Text2DRenderCache;
  46387. var Text2DInstanceData = (function (_super) {
  46388. __extends(Text2DInstanceData, _super);
  46389. function Text2DInstanceData(partId, dataElementCount) {
  46390. _super.call(this, partId, dataElementCount);
  46391. }
  46392. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  46393. get: function () {
  46394. return null;
  46395. },
  46396. set: function (value) {
  46397. },
  46398. enumerable: true,
  46399. configurable: true
  46400. });
  46401. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  46402. get: function () {
  46403. return null;
  46404. },
  46405. set: function (value) {
  46406. },
  46407. enumerable: true,
  46408. configurable: true
  46409. });
  46410. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  46411. get: function () {
  46412. return null;
  46413. },
  46414. set: function (value) {
  46415. },
  46416. enumerable: true,
  46417. configurable: true
  46418. });
  46419. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  46420. get: function () {
  46421. return null;
  46422. },
  46423. set: function (value) {
  46424. },
  46425. enumerable: true,
  46426. configurable: true
  46427. });
  46428. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  46429. get: function () {
  46430. return null;
  46431. },
  46432. set: function (value) {
  46433. },
  46434. enumerable: true,
  46435. configurable: true
  46436. });
  46437. __decorate([
  46438. BABYLON.instanceData()
  46439. ], Text2DInstanceData.prototype, "topLeftUV", null);
  46440. __decorate([
  46441. BABYLON.instanceData()
  46442. ], Text2DInstanceData.prototype, "sizeUV", null);
  46443. __decorate([
  46444. BABYLON.instanceData()
  46445. ], Text2DInstanceData.prototype, "textureSize", null);
  46446. __decorate([
  46447. BABYLON.instanceData()
  46448. ], Text2DInstanceData.prototype, "color", null);
  46449. __decorate([
  46450. BABYLON.instanceData()
  46451. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  46452. return Text2DInstanceData;
  46453. }(BABYLON.InstanceDataBase));
  46454. BABYLON.Text2DInstanceData = Text2DInstanceData;
  46455. var Text2D = (function (_super) {
  46456. __extends(Text2D, _super);
  46457. /**
  46458. * Create a Text primitive
  46459. * @param text the text to display
  46460. * @param settings a combination of settings, possible ones are
  46461. * - 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)
  46462. * - children: an array of direct children
  46463. * - id a text identifier, for information purpose
  46464. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46465. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46466. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46467. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46468. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46469. * - zOrder: override the zOrder with the specified value
  46470. * - origin: define the normalized origin point location, default [0.5;0.5]
  46471. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  46472. * - 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.
  46473. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  46474. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  46475. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  46476. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  46477. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46478. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46479. * - 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!
  46480. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46481. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46482. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46483. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46484. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46485. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46486. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46487. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46488. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46489. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46490. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46491. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46492. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46493. */
  46494. function Text2D(text, settings) {
  46495. if (!settings) {
  46496. settings = {};
  46497. }
  46498. _super.call(this, settings);
  46499. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  46500. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  46501. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  46502. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  46503. this._textSize = null;
  46504. this.text = text;
  46505. this.size = (settings.size == null) ? null : settings.size;
  46506. this._updateRenderMode();
  46507. }
  46508. Object.defineProperty(Text2D.prototype, "fontName", {
  46509. get: function () {
  46510. return this._fontName;
  46511. },
  46512. set: function (value) {
  46513. if (this._fontName) {
  46514. throw new Error("Font Name change is not supported right now.");
  46515. }
  46516. this._fontName = value;
  46517. },
  46518. enumerable: true,
  46519. configurable: true
  46520. });
  46521. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  46522. get: function () {
  46523. return this._defaultFontColor;
  46524. },
  46525. set: function (value) {
  46526. this._defaultFontColor = value;
  46527. },
  46528. enumerable: true,
  46529. configurable: true
  46530. });
  46531. Object.defineProperty(Text2D.prototype, "text", {
  46532. get: function () {
  46533. return this._text;
  46534. },
  46535. set: function (value) {
  46536. this._text = value;
  46537. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  46538. this._size = null;
  46539. this._updateCharCount();
  46540. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  46541. var s = this.textSize;
  46542. },
  46543. enumerable: true,
  46544. configurable: true
  46545. });
  46546. Object.defineProperty(Text2D.prototype, "size", {
  46547. get: function () {
  46548. if (this._size != null) {
  46549. return this._size;
  46550. }
  46551. return this.textSize;
  46552. },
  46553. set: function (value) {
  46554. this._size = value;
  46555. },
  46556. enumerable: true,
  46557. configurable: true
  46558. });
  46559. Object.defineProperty(Text2D.prototype, "actualSize", {
  46560. /**
  46561. * Get the actual size of the Text2D primitive
  46562. */
  46563. get: function () {
  46564. if (this._actualSize) {
  46565. return this._actualSize;
  46566. }
  46567. return this.size;
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. Object.defineProperty(Text2D.prototype, "textSize", {
  46573. /**
  46574. * Get the area that bounds the text associated to the primitive
  46575. */
  46576. get: function () {
  46577. if (!this._textSize) {
  46578. if (this.owner) {
  46579. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  46580. if (!newSize.equals(this._textSize)) {
  46581. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  46582. this._positioningDirty();
  46583. }
  46584. this._textSize = newSize;
  46585. }
  46586. else {
  46587. return Text2D.nullSize;
  46588. }
  46589. }
  46590. return this._textSize;
  46591. },
  46592. enumerable: true,
  46593. configurable: true
  46594. });
  46595. Object.defineProperty(Text2D.prototype, "fontTexture", {
  46596. get: function () {
  46597. if (this._fontTexture) {
  46598. return this._fontTexture;
  46599. }
  46600. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  46601. return null;
  46602. }
  46603. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46604. return this._fontTexture;
  46605. },
  46606. enumerable: true,
  46607. configurable: true
  46608. });
  46609. /**
  46610. * Dispose the primitive, remove it from its parent
  46611. */
  46612. Text2D.prototype.dispose = function () {
  46613. if (!_super.prototype.dispose.call(this)) {
  46614. return false;
  46615. }
  46616. if (this._fontTexture) {
  46617. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46618. this._fontTexture = null;
  46619. }
  46620. return true;
  46621. };
  46622. Text2D.prototype.updateLevelBoundingInfo = function () {
  46623. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  46624. };
  46625. Text2D.prototype.levelIntersect = function (intersectInfo) {
  46626. // 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...
  46627. return true;
  46628. };
  46629. Text2D.prototype.createModelRenderCache = function (modelKey) {
  46630. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  46631. return renderCache;
  46632. };
  46633. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46634. var renderCache = modelRenderCache;
  46635. var engine = this.owner.engine;
  46636. renderCache.fontTexture = this.fontTexture;
  46637. renderCache.fontTexture.incCachedFontTextureCounter();
  46638. var vb = new Float32Array(4);
  46639. for (var i = 0; i < 4; i++) {
  46640. vb[i] = i;
  46641. }
  46642. renderCache.vb = engine.createVertexBuffer(vb);
  46643. var ib = new Float32Array(6);
  46644. ib[0] = 0;
  46645. ib[1] = 2;
  46646. ib[2] = 1;
  46647. ib[3] = 0;
  46648. ib[4] = 3;
  46649. ib[5] = 2;
  46650. renderCache.ib = engine.createIndexBuffer(ib);
  46651. // 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
  46652. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  46653. if (ei) {
  46654. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46655. }
  46656. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  46657. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46658. return renderCache;
  46659. };
  46660. Text2D.prototype.createInstanceDataParts = function () {
  46661. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  46662. };
  46663. // Looks like a hack!? Yes! Because that's what it is!
  46664. // 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
  46665. // 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)
  46666. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46667. if (!this._charCount) {
  46668. var curText = this._text;
  46669. this.text = "A";
  46670. return curText;
  46671. }
  46672. };
  46673. // if obj contains something, we restore the _text property
  46674. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46675. if (obj !== undefined) {
  46676. this.text = obj;
  46677. }
  46678. };
  46679. Text2D.prototype.refreshInstanceDataPart = function (part) {
  46680. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46681. return false;
  46682. }
  46683. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  46684. var d = part;
  46685. var texture = this.fontTexture;
  46686. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  46687. var ts = texture.getSize();
  46688. var offset = BABYLON.Vector2.Zero();
  46689. var lh = this.fontTexture.lineHeight;
  46690. 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
  46691. var charxpos = 0;
  46692. d.dataElementCount = this._charCount;
  46693. d.curElement = 0;
  46694. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  46695. var char = _a[_i];
  46696. // Line feed
  46697. if (char === "\n") {
  46698. offset.x = 0;
  46699. offset.y -= texture.lineHeight;
  46700. }
  46701. // Tabulation ?
  46702. if (char === "\t") {
  46703. var nextPos = charxpos + this._tabulationSize;
  46704. nextPos = nextPos - (nextPos % this._tabulationSize);
  46705. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  46706. charxpos = nextPos;
  46707. continue;
  46708. }
  46709. if (char < " ") {
  46710. continue;
  46711. }
  46712. this.updateInstanceDataPart(d, offset);
  46713. var ci = texture.getChar(char);
  46714. offset.x += ci.charWidth;
  46715. d.topLeftUV = ci.topLeftUV;
  46716. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  46717. d.sizeUV = suv;
  46718. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46719. d.color = this.defaultFontColor;
  46720. d.superSampleFactor = superSampleFactor;
  46721. ++d.curElement;
  46722. }
  46723. }
  46724. return true;
  46725. };
  46726. Text2D.prototype._updateCharCount = function () {
  46727. var count = 0;
  46728. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  46729. var char = _a[_i];
  46730. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  46731. continue;
  46732. }
  46733. ++count;
  46734. }
  46735. this._charCount = count;
  46736. };
  46737. Text2D.prototype._useTextureAlpha = function () {
  46738. return this.fontTexture != null && this.fontTexture.hasAlpha;
  46739. };
  46740. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  46741. return true;
  46742. };
  46743. Text2D.TEXT2D_MAINPARTID = 1;
  46744. __decorate([
  46745. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  46746. ], Text2D.prototype, "fontName", null);
  46747. __decorate([
  46748. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  46749. ], Text2D.prototype, "defaultFontColor", null);
  46750. __decorate([
  46751. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  46752. ], Text2D.prototype, "text", null);
  46753. __decorate([
  46754. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  46755. ], Text2D.prototype, "size", null);
  46756. Text2D = __decorate([
  46757. BABYLON.className("Text2D")
  46758. ], Text2D);
  46759. return Text2D;
  46760. }(BABYLON.RenderablePrim2D));
  46761. BABYLON.Text2D = Text2D;
  46762. })(BABYLON || (BABYLON = {}));
  46763. var BABYLON;
  46764. (function (BABYLON) {
  46765. var Lines2DRenderCache = (function (_super) {
  46766. __extends(Lines2DRenderCache, _super);
  46767. function Lines2DRenderCache(engine, modelKey) {
  46768. _super.call(this, engine, modelKey);
  46769. this.effectsReady = false;
  46770. this.fillVB = null;
  46771. this.fillIB = null;
  46772. this.fillIndicesCount = 0;
  46773. this.instancingFillAttributes = null;
  46774. this.effectFill = null;
  46775. this.effectFillInstanced = null;
  46776. this.borderVB = null;
  46777. this.borderIB = null;
  46778. this.borderIndicesCount = 0;
  46779. this.instancingBorderAttributes = null;
  46780. this.effectBorder = null;
  46781. this.effectBorderInstanced = null;
  46782. }
  46783. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  46784. // Do nothing if the shader is still loading/preparing
  46785. if (!this.effectsReady) {
  46786. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  46787. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  46788. return false;
  46789. }
  46790. this.effectsReady = true;
  46791. }
  46792. var canvas = instanceInfo.owner.owner;
  46793. var engine = canvas.engine;
  46794. var depthFunction = 0;
  46795. if (this.effectFill && this.effectBorder) {
  46796. depthFunction = engine.getDepthFunction();
  46797. engine.setDepthFunctionToLessOrEqual();
  46798. }
  46799. var curAlphaMode = engine.getAlphaMode();
  46800. if (this.effectFill) {
  46801. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  46802. var pid = context.groupInfoPartData[partIndex];
  46803. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46804. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46805. }
  46806. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  46807. engine.enableEffect(effect);
  46808. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  46809. if (context.useInstancing) {
  46810. if (!this.instancingFillAttributes) {
  46811. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  46812. }
  46813. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46814. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46815. canvas._addDrawCallCount(1, context.renderMode);
  46816. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  46817. engine.draw(true, 0, this.fillIndicesCount, count);
  46818. engine.unbindInstanceAttributes();
  46819. }
  46820. else {
  46821. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46822. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46823. this.setupUniforms(effect, partIndex, pid._partData, i);
  46824. engine.draw(true, 0, this.fillIndicesCount);
  46825. }
  46826. }
  46827. }
  46828. if (this.effectBorder) {
  46829. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  46830. var pid = context.groupInfoPartData[partIndex];
  46831. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46832. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46833. }
  46834. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  46835. engine.enableEffect(effect);
  46836. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  46837. if (context.useInstancing) {
  46838. if (!this.instancingBorderAttributes) {
  46839. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  46840. }
  46841. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46842. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46843. canvas._addDrawCallCount(1, context.renderMode);
  46844. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  46845. engine.draw(true, 0, this.borderIndicesCount, count);
  46846. engine.unbindInstanceAttributes();
  46847. }
  46848. else {
  46849. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46850. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46851. this.setupUniforms(effect, partIndex, pid._partData, i);
  46852. engine.draw(true, 0, this.borderIndicesCount);
  46853. }
  46854. }
  46855. }
  46856. engine.setAlphaMode(curAlphaMode, true);
  46857. if (this.effectFill && this.effectBorder) {
  46858. engine.setDepthFunction(depthFunction);
  46859. }
  46860. return true;
  46861. };
  46862. Lines2DRenderCache.prototype.dispose = function () {
  46863. if (!_super.prototype.dispose.call(this)) {
  46864. return false;
  46865. }
  46866. if (this.fillVB) {
  46867. this._engine._releaseBuffer(this.fillVB);
  46868. this.fillVB = null;
  46869. }
  46870. if (this.fillIB) {
  46871. this._engine._releaseBuffer(this.fillIB);
  46872. this.fillIB = null;
  46873. }
  46874. this.effectFill = null;
  46875. this.effectFillInstanced = null;
  46876. this.effectBorder = null;
  46877. this.effectBorderInstanced = null;
  46878. if (this.borderVB) {
  46879. this._engine._releaseBuffer(this.borderVB);
  46880. this.borderVB = null;
  46881. }
  46882. if (this.borderIB) {
  46883. this._engine._releaseBuffer(this.borderIB);
  46884. this.borderIB = null;
  46885. }
  46886. return true;
  46887. };
  46888. return Lines2DRenderCache;
  46889. }(BABYLON.ModelRenderCache));
  46890. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  46891. var Lines2DInstanceData = (function (_super) {
  46892. __extends(Lines2DInstanceData, _super);
  46893. function Lines2DInstanceData(partId) {
  46894. _super.call(this, partId, 1);
  46895. }
  46896. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  46897. get: function () {
  46898. return null;
  46899. },
  46900. set: function (value) {
  46901. },
  46902. enumerable: true,
  46903. configurable: true
  46904. });
  46905. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  46906. get: function () {
  46907. return null;
  46908. },
  46909. set: function (value) {
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. __decorate([
  46915. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46916. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46917. __decorate([
  46918. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46919. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46920. return Lines2DInstanceData;
  46921. }(BABYLON.Shape2DInstanceData));
  46922. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46923. var Lines2D = (function (_super) {
  46924. __extends(Lines2D, _super);
  46925. /**
  46926. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46927. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46928. * @param settings a combination of settings, possible ones are
  46929. * - 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)
  46930. * - children: an array of direct children
  46931. * - id a text identifier, for information purpose
  46932. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46933. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46934. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46935. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46936. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46937. * - zOrder: override the zOrder with the specified value
  46938. * - origin: define the normalized origin point location, default [0.5;0.5]
  46939. * - 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.
  46940. * - 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.
  46941. * - 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.
  46942. * - 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.
  46943. * - 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)
  46944. * - 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)
  46945. * - borderThickness: the thickness of the drawn border, default is 1.
  46946. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46947. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46948. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46949. * - 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!
  46950. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46951. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46952. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46953. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46954. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46955. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46956. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46957. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46958. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46959. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46960. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46961. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46962. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46963. */
  46964. function Lines2D(points, settings) {
  46965. if (!settings) {
  46966. settings = {};
  46967. }
  46968. _super.call(this, settings);
  46969. this._fillVB = null;
  46970. this._fillIB = null;
  46971. this._borderVB = null;
  46972. this._borderIB = null;
  46973. this._size = BABYLON.Size.Zero();
  46974. this._boundingMin = null;
  46975. this._boundingMax = null;
  46976. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46977. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46978. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46979. var closed = (settings.closed == null) ? false : settings.closed;
  46980. this.points = points;
  46981. this.fillThickness = fillThickness;
  46982. this.startCap = startCap;
  46983. this.endCap = endCap;
  46984. this.closed = closed;
  46985. }
  46986. Object.defineProperty(Lines2D, "NoCap", {
  46987. /**
  46988. * No Cap to apply on the extremity
  46989. */
  46990. get: function () { return Lines2D._noCap; },
  46991. enumerable: true,
  46992. configurable: true
  46993. });
  46994. Object.defineProperty(Lines2D, "RoundCap", {
  46995. /**
  46996. * A round cap, will use the line thickness as diameter
  46997. */
  46998. get: function () { return Lines2D._roundCap; },
  46999. enumerable: true,
  47000. configurable: true
  47001. });
  47002. Object.defineProperty(Lines2D, "TriangleCap", {
  47003. /**
  47004. * Creates a triangle at the extremity.
  47005. */
  47006. get: function () { return Lines2D._triangleCap; },
  47007. enumerable: true,
  47008. configurable: true
  47009. });
  47010. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  47011. /**
  47012. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  47013. */
  47014. get: function () { return Lines2D._squareAnchorCap; },
  47015. enumerable: true,
  47016. configurable: true
  47017. });
  47018. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  47019. /**
  47020. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  47021. */
  47022. get: function () { return Lines2D._roundAnchorCap; },
  47023. enumerable: true,
  47024. configurable: true
  47025. });
  47026. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  47027. /**
  47028. * Creates a diamond anchor at the extremity.
  47029. */
  47030. get: function () { return Lines2D._diamondAnchorCap; },
  47031. enumerable: true,
  47032. configurable: true
  47033. });
  47034. Object.defineProperty(Lines2D, "ArrowCap", {
  47035. /**
  47036. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  47037. */
  47038. get: function () { return Lines2D._arrowCap; },
  47039. enumerable: true,
  47040. configurable: true
  47041. });
  47042. Object.defineProperty(Lines2D.prototype, "points", {
  47043. get: function () {
  47044. return this._points;
  47045. },
  47046. set: function (value) {
  47047. this._points = value;
  47048. this._contour = null;
  47049. this._boundingBoxDirty();
  47050. },
  47051. enumerable: true,
  47052. configurable: true
  47053. });
  47054. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  47055. get: function () {
  47056. return this._fillThickness;
  47057. },
  47058. set: function (value) {
  47059. this._fillThickness = value;
  47060. },
  47061. enumerable: true,
  47062. configurable: true
  47063. });
  47064. Object.defineProperty(Lines2D.prototype, "closed", {
  47065. get: function () {
  47066. return this._closed;
  47067. },
  47068. set: function (value) {
  47069. this._closed = value;
  47070. },
  47071. enumerable: true,
  47072. configurable: true
  47073. });
  47074. Object.defineProperty(Lines2D.prototype, "startCap", {
  47075. get: function () {
  47076. return this._startCap;
  47077. },
  47078. set: function (value) {
  47079. this._startCap = value;
  47080. },
  47081. enumerable: true,
  47082. configurable: true
  47083. });
  47084. Object.defineProperty(Lines2D.prototype, "endCap", {
  47085. get: function () {
  47086. return this._endCap;
  47087. },
  47088. set: function (value) {
  47089. this._endCap = value;
  47090. },
  47091. enumerable: true,
  47092. configurable: true
  47093. });
  47094. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  47095. var _this = this;
  47096. if (this._contour == null) {
  47097. this._computeLines2D();
  47098. }
  47099. var pl = this.points.length;
  47100. var l = this.closed ? pl + 1 : pl;
  47101. var p = intersectInfo._localPickPosition;
  47102. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  47103. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  47104. for (var i = 1; i < l; i++) {
  47105. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  47106. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  47107. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  47108. return true;
  47109. }
  47110. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  47111. return true;
  47112. }
  47113. Lines2D._prevA.x = Lines2D._curA.x;
  47114. Lines2D._prevA.y = Lines2D._curA.y;
  47115. Lines2D._prevB.x = Lines2D._curB.x;
  47116. Lines2D._prevB.y = Lines2D._curB.y;
  47117. }
  47118. var capIntersect = function (tri, points) {
  47119. var l = tri.length;
  47120. for (var i = 0; i < l; i += 3) {
  47121. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  47122. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  47123. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  47124. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  47125. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  47126. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  47127. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  47128. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  47129. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  47130. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  47131. return true;
  47132. }
  47133. }
  47134. return false;
  47135. };
  47136. if (this._startCapTriIndices) {
  47137. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  47138. return true;
  47139. }
  47140. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  47141. return true;
  47142. }
  47143. }
  47144. return false;
  47145. };
  47146. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  47147. get: function () {
  47148. if (!this._boundingMin) {
  47149. this._computeLines2D();
  47150. }
  47151. return this._boundingMin;
  47152. },
  47153. enumerable: true,
  47154. configurable: true
  47155. });
  47156. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  47157. get: function () {
  47158. if (!this._boundingMax) {
  47159. this._computeLines2D();
  47160. }
  47161. return this._boundingMax;
  47162. },
  47163. enumerable: true,
  47164. configurable: true
  47165. });
  47166. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  47167. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  47168. // Remove the BORDER category, we don't use it in the VertexShader
  47169. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  47170. if (i !== -1) {
  47171. res.splice(i, 1);
  47172. }
  47173. return res;
  47174. };
  47175. Lines2D.prototype.updateLevelBoundingInfo = function () {
  47176. if (!this._boundingMin) {
  47177. this._computeLines2D();
  47178. }
  47179. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  47180. };
  47181. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  47182. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  47183. return renderCache;
  47184. };
  47185. ///////////////////////////////////////////////////////////////////////////////////
  47186. // Methods for Lines building
  47187. Lines2D.prototype._perp = function (v, res) {
  47188. res.x = v.y;
  47189. res.y = -v.x;
  47190. };
  47191. ;
  47192. Lines2D.prototype._direction = function (a, b, res) {
  47193. a.subtractToRef(b, res);
  47194. res.normalize();
  47195. };
  47196. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  47197. a.addToRef(b, tangent);
  47198. tangent.normalize();
  47199. miter.x = -tangent.y;
  47200. miter.y = tangent.x;
  47201. Lines2D._miterTps.x = -a.y;
  47202. Lines2D._miterTps.y = a.x;
  47203. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  47204. };
  47205. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  47206. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  47207. if (d === 0)
  47208. return false;
  47209. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  47210. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  47211. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  47212. return false;
  47213. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  47214. return false;
  47215. return true;
  47216. };
  47217. Lines2D.prototype._updateMinMax = function (array, offset) {
  47218. if (offset >= array.length) {
  47219. return;
  47220. }
  47221. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  47222. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  47223. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  47224. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  47225. };
  47226. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  47227. var borderMode = borderThickness != null && !isNaN(borderThickness);
  47228. var off = index * (borderMode ? 8 : 4);
  47229. // 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)
  47230. if (off >= array.length) {
  47231. return;
  47232. }
  47233. // Store start/end normal, we need it for the cap construction
  47234. if (index === 0) {
  47235. this._perp(n, Lines2D._startDir);
  47236. }
  47237. else if (index === max - 1) {
  47238. this._perp(n, Lines2D._endDir);
  47239. Lines2D._endDir.x *= -1;
  47240. Lines2D._endDir.y *= -1;
  47241. }
  47242. var swap = false;
  47243. array[off + 0] = p.x + n.x * halfThickness;
  47244. array[off + 1] = p.y + n.y * halfThickness;
  47245. array[off + 2] = p.x + n.x * -halfThickness;
  47246. array[off + 3] = p.y + n.y * -halfThickness;
  47247. this._updateMinMax(array, off);
  47248. this._updateMinMax(array, off + 2);
  47249. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  47250. // 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
  47251. if (detectFlip !== undefined) {
  47252. // Flip if intersect
  47253. var flipOff = detectFlip * (borderMode ? 8 : 4);
  47254. 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])) {
  47255. swap = true;
  47256. var tps = array[off + 0];
  47257. array[off + 0] = array[off + 2];
  47258. array[off + 2] = tps;
  47259. tps = array[off + 1];
  47260. array[off + 1] = array[off + 3];
  47261. array[off + 3] = tps;
  47262. }
  47263. }
  47264. if (borderMode) {
  47265. var t = halfThickness + borderThickness;
  47266. array[off + 4] = p.x + n.x * (swap ? -t : t);
  47267. array[off + 5] = p.y + n.y * (swap ? -t : t);
  47268. array[off + 6] = p.x + n.x * (swap ? t : -t);
  47269. array[off + 7] = p.y + n.y * (swap ? t : -t);
  47270. this._updateMinMax(array, off + 4);
  47271. this._updateMinMax(array, off + 6);
  47272. }
  47273. if (contour) {
  47274. off += borderMode ? 4 : 0;
  47275. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  47276. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  47277. }
  47278. };
  47279. Lines2D.prototype._getCapSize = function (type, border) {
  47280. if (border === void 0) { border = false; }
  47281. var sd = Lines2D._roundCapSubDiv;
  47282. // If no array given, we call this to get the size
  47283. var vbsize = 0, ibsize = 0;
  47284. switch (type) {
  47285. case Lines2D.NoCap:
  47286. {
  47287. // If the line is not close and we're computing border, we add the size to generate the edge border
  47288. if (!this.closed && border) {
  47289. vbsize = 4;
  47290. ibsize = 6;
  47291. }
  47292. else {
  47293. vbsize = ibsize = 0;
  47294. }
  47295. break;
  47296. }
  47297. case Lines2D.RoundCap:
  47298. {
  47299. if (border) {
  47300. vbsize = sd;
  47301. ibsize = (sd - 2) * 3;
  47302. }
  47303. else {
  47304. vbsize = (sd / 2) + 1;
  47305. ibsize = (sd / 2) * 3;
  47306. }
  47307. break;
  47308. }
  47309. case Lines2D.ArrowCap:
  47310. {
  47311. if (border) {
  47312. vbsize = 12;
  47313. ibsize = 24;
  47314. }
  47315. else {
  47316. vbsize = 3;
  47317. ibsize = 3;
  47318. }
  47319. break;
  47320. }
  47321. case Lines2D.TriangleCap:
  47322. {
  47323. if (border) {
  47324. vbsize = 6;
  47325. ibsize = 12;
  47326. }
  47327. else {
  47328. vbsize = 3;
  47329. ibsize = 3;
  47330. }
  47331. break;
  47332. }
  47333. case Lines2D.DiamondAnchorCap:
  47334. {
  47335. if (border) {
  47336. vbsize = 10;
  47337. ibsize = 24;
  47338. }
  47339. else {
  47340. vbsize = 5;
  47341. ibsize = 9;
  47342. }
  47343. break;
  47344. }
  47345. case Lines2D.SquareAnchorCap:
  47346. {
  47347. if (border) {
  47348. vbsize = 12;
  47349. ibsize = 30;
  47350. }
  47351. else {
  47352. vbsize = 4;
  47353. ibsize = 6;
  47354. }
  47355. break;
  47356. }
  47357. case Lines2D.RoundAnchorCap:
  47358. {
  47359. if (border) {
  47360. vbsize = sd * 2;
  47361. ibsize = (sd - 1) * 6;
  47362. }
  47363. else {
  47364. vbsize = sd + 1;
  47365. ibsize = (sd + 1) * 3;
  47366. }
  47367. break;
  47368. }
  47369. }
  47370. return { vbsize: vbsize * 2, ibsize: ibsize };
  47371. };
  47372. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  47373. var c = Math.cos(rotation);
  47374. var s = Math.sin(rotation);
  47375. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  47376. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  47377. var offset = baseOffset + (index * 2);
  47378. vb[offset + 0] = Lines2D._tpsV.x;
  47379. vb[offset + 1] = Lines2D._tpsV.y;
  47380. if (contour) {
  47381. contour.push(Lines2D._tpsV.x);
  47382. contour.push(Lines2D._tpsV.y);
  47383. }
  47384. this._updateMinMax(vb, offset);
  47385. return (baseOffset + index * 2) / 2;
  47386. };
  47387. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  47388. ib[baseOffset + index] = vertexIndex;
  47389. };
  47390. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  47391. // 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
  47392. var sd = Lines2D._roundCapSubDiv;
  47393. var dir = new BABYLON.Vector2(1, 0);
  47394. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  47395. var ht = thickness / 2;
  47396. var t = thickness;
  47397. var borderMode = borderThickness != null;
  47398. var bt = borderThickness;
  47399. switch (type) {
  47400. case Lines2D.NoCap:
  47401. if (borderMode && !this.closed) {
  47402. var vi = 0;
  47403. var ii = 0;
  47404. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  47405. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  47406. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  47407. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  47408. this._storeIndex(ib, ibi, ii++, v1);
  47409. this._storeIndex(ib, ibi, ii++, v2);
  47410. this._storeIndex(ib, ibi, ii++, v3);
  47411. this._storeIndex(ib, ibi, ii++, v1);
  47412. this._storeIndex(ib, ibi, ii++, v3);
  47413. this._storeIndex(ib, ibi, ii++, v4);
  47414. }
  47415. break;
  47416. case Lines2D.ArrowCap:
  47417. ht *= 2;
  47418. case Lines2D.TriangleCap:
  47419. {
  47420. if (borderMode) {
  47421. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  47422. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  47423. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  47424. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  47425. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  47426. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  47427. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  47428. var ii = 0;
  47429. this._storeIndex(ib, ibi, ii++, v1);
  47430. this._storeIndex(ib, ibi, ii++, v4);
  47431. this._storeIndex(ib, ibi, ii++, v5);
  47432. this._storeIndex(ib, ibi, ii++, v1);
  47433. this._storeIndex(ib, ibi, ii++, v5);
  47434. this._storeIndex(ib, ibi, ii++, v2);
  47435. this._storeIndex(ib, ibi, ii++, v6);
  47436. this._storeIndex(ib, ibi, ii++, v3);
  47437. this._storeIndex(ib, ibi, ii++, v2);
  47438. this._storeIndex(ib, ibi, ii++, v6);
  47439. this._storeIndex(ib, ibi, ii++, v2);
  47440. this._storeIndex(ib, ibi, ii++, v5);
  47441. if (type === Lines2D.ArrowCap) {
  47442. var rht = thickness / 2;
  47443. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  47444. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  47445. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  47446. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  47447. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  47448. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  47449. this._storeIndex(ib, ibi, ii++, v7);
  47450. this._storeIndex(ib, ibi, ii++, v8);
  47451. this._storeIndex(ib, ibi, ii++, v9);
  47452. this._storeIndex(ib, ibi, ii++, v7);
  47453. this._storeIndex(ib, ibi, ii++, v9);
  47454. this._storeIndex(ib, ibi, ii++, v4);
  47455. this._storeIndex(ib, ibi, ii++, v10);
  47456. this._storeIndex(ib, ibi, ii++, v12);
  47457. this._storeIndex(ib, ibi, ii++, v11);
  47458. this._storeIndex(ib, ibi, ii++, v10);
  47459. this._storeIndex(ib, ibi, ii++, v6);
  47460. this._storeIndex(ib, ibi, ii++, v12);
  47461. }
  47462. }
  47463. else {
  47464. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  47465. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  47466. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  47467. this._storeIndex(ib, ibi, 0, v1);
  47468. this._storeIndex(ib, ibi, 1, v2);
  47469. this._storeIndex(ib, ibi, 2, v3);
  47470. }
  47471. break;
  47472. }
  47473. case Lines2D.RoundCap:
  47474. {
  47475. if (borderMode) {
  47476. var curA = -Math.PI / 2;
  47477. var incA = Math.PI / (sd / 2 - 1);
  47478. var ii = 0;
  47479. for (var i = 0; i < (sd / 2); i++) {
  47480. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47481. 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);
  47482. if (i > 0) {
  47483. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47484. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47485. this._storeIndex(ib, ibi, ii++, v2);
  47486. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47487. this._storeIndex(ib, ibi, ii++, v2);
  47488. this._storeIndex(ib, ibi, ii++, v1);
  47489. }
  47490. curA += incA;
  47491. }
  47492. }
  47493. else {
  47494. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  47495. var curA = -Math.PI / 2;
  47496. var incA = Math.PI / (sd / 2 - 1);
  47497. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47498. curA += incA;
  47499. for (var i = 1; i < (sd / 2); i++) {
  47500. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  47501. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47502. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47503. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47504. curA += incA;
  47505. }
  47506. }
  47507. break;
  47508. }
  47509. case Lines2D.SquareAnchorCap:
  47510. {
  47511. var vi = 0;
  47512. var c = borderMode ? null : contour;
  47513. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  47514. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  47515. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  47516. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  47517. if (borderMode) {
  47518. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  47519. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  47520. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  47521. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  47522. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  47523. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  47524. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  47525. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  47526. var ii = 0;
  47527. this._storeIndex(ib, ibi, ii++, v6);
  47528. this._storeIndex(ib, ibi, ii++, v1);
  47529. this._storeIndex(ib, ibi, ii++, v5);
  47530. this._storeIndex(ib, ibi, ii++, v6);
  47531. this._storeIndex(ib, ibi, ii++, v7);
  47532. this._storeIndex(ib, ibi, ii++, v1);
  47533. this._storeIndex(ib, ibi, ii++, v1);
  47534. this._storeIndex(ib, ibi, ii++, v7);
  47535. this._storeIndex(ib, ibi, ii++, v8);
  47536. this._storeIndex(ib, ibi, ii++, v1);
  47537. this._storeIndex(ib, ibi, ii++, v8);
  47538. this._storeIndex(ib, ibi, ii++, v2);
  47539. this._storeIndex(ib, ibi, ii++, v2);
  47540. this._storeIndex(ib, ibi, ii++, v8);
  47541. this._storeIndex(ib, ibi, ii++, v9);
  47542. this._storeIndex(ib, ibi, ii++, v2);
  47543. this._storeIndex(ib, ibi, ii++, v9);
  47544. this._storeIndex(ib, ibi, ii++, v3);
  47545. this._storeIndex(ib, ibi, ii++, v3);
  47546. this._storeIndex(ib, ibi, ii++, v9);
  47547. this._storeIndex(ib, ibi, ii++, v10);
  47548. this._storeIndex(ib, ibi, ii++, v3);
  47549. this._storeIndex(ib, ibi, ii++, v10);
  47550. this._storeIndex(ib, ibi, ii++, v4);
  47551. this._storeIndex(ib, ibi, ii++, v10);
  47552. this._storeIndex(ib, ibi, ii++, v11);
  47553. this._storeIndex(ib, ibi, ii++, v4);
  47554. this._storeIndex(ib, ibi, ii++, v11);
  47555. this._storeIndex(ib, ibi, ii++, v12);
  47556. this._storeIndex(ib, ibi, ii++, v4);
  47557. }
  47558. else {
  47559. this._storeIndex(ib, ibi, 0, v1);
  47560. this._storeIndex(ib, ibi, 1, v2);
  47561. this._storeIndex(ib, ibi, 2, v3);
  47562. this._storeIndex(ib, ibi, 3, v1);
  47563. this._storeIndex(ib, ibi, 4, v3);
  47564. this._storeIndex(ib, ibi, 5, v4);
  47565. }
  47566. break;
  47567. }
  47568. case Lines2D.RoundAnchorCap:
  47569. {
  47570. var cpos = Math.sqrt(t * t - ht * ht);
  47571. var center = new BABYLON.Vector2(cpos, 0);
  47572. var curA = BABYLON.Tools.ToRadians(-150);
  47573. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  47574. if (borderMode) {
  47575. var ii = 0;
  47576. for (var i = 0; i < sd; i++) {
  47577. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47578. 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);
  47579. if (i > 0) {
  47580. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47581. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47582. this._storeIndex(ib, ibi, ii++, v2);
  47583. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47584. this._storeIndex(ib, ibi, ii++, v2);
  47585. this._storeIndex(ib, ibi, ii++, v1);
  47586. }
  47587. curA += incA;
  47588. }
  47589. }
  47590. else {
  47591. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  47592. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47593. curA += incA;
  47594. for (var i = 1; i < sd; i++) {
  47595. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  47596. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47597. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47598. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47599. curA += incA;
  47600. }
  47601. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  47602. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  47603. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  47604. }
  47605. break;
  47606. }
  47607. case Lines2D.DiamondAnchorCap:
  47608. {
  47609. var vi = 0;
  47610. var c = borderMode ? null : contour;
  47611. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  47612. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  47613. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  47614. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  47615. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  47616. if (borderMode) {
  47617. var f = Math.sqrt(bt * bt * 2);
  47618. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  47619. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  47620. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  47621. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  47622. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  47623. var ii = 0;
  47624. this._storeIndex(ib, ibi, ii++, v6);
  47625. this._storeIndex(ib, ibi, ii++, v7);
  47626. this._storeIndex(ib, ibi, ii++, v1);
  47627. this._storeIndex(ib, ibi, ii++, v1);
  47628. this._storeIndex(ib, ibi, ii++, v7);
  47629. this._storeIndex(ib, ibi, ii++, v2);
  47630. this._storeIndex(ib, ibi, ii++, v2);
  47631. this._storeIndex(ib, ibi, ii++, v7);
  47632. this._storeIndex(ib, ibi, ii++, v8);
  47633. this._storeIndex(ib, ibi, ii++, v2);
  47634. this._storeIndex(ib, ibi, ii++, v8);
  47635. this._storeIndex(ib, ibi, ii++, v3);
  47636. this._storeIndex(ib, ibi, ii++, v3);
  47637. this._storeIndex(ib, ibi, ii++, v8);
  47638. this._storeIndex(ib, ibi, ii++, v9);
  47639. this._storeIndex(ib, ibi, ii++, v3);
  47640. this._storeIndex(ib, ibi, ii++, v9);
  47641. this._storeIndex(ib, ibi, ii++, v4);
  47642. this._storeIndex(ib, ibi, ii++, v4);
  47643. this._storeIndex(ib, ibi, ii++, v9);
  47644. this._storeIndex(ib, ibi, ii++, v10);
  47645. this._storeIndex(ib, ibi, ii++, v4);
  47646. this._storeIndex(ib, ibi, ii++, v10);
  47647. this._storeIndex(ib, ibi, ii++, v5);
  47648. }
  47649. else {
  47650. this._storeIndex(ib, ibi, 0, v1);
  47651. this._storeIndex(ib, ibi, 1, v2);
  47652. this._storeIndex(ib, ibi, 2, v3);
  47653. this._storeIndex(ib, ibi, 3, v1);
  47654. this._storeIndex(ib, ibi, 4, v3);
  47655. this._storeIndex(ib, ibi, 5, v5);
  47656. this._storeIndex(ib, ibi, 6, v5);
  47657. this._storeIndex(ib, ibi, 7, v3);
  47658. this._storeIndex(ib, ibi, 8, v4);
  47659. }
  47660. break;
  47661. }
  47662. }
  47663. return null;
  47664. };
  47665. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  47666. var lineA = BABYLON.Vector2.Zero();
  47667. var lineB = BABYLON.Vector2.Zero();
  47668. var tangent = BABYLON.Vector2.Zero();
  47669. var miter = BABYLON.Vector2.Zero();
  47670. var curNormal = null;
  47671. if (this.closed) {
  47672. this.points.push(this.points[0]);
  47673. }
  47674. var total = this.points.length;
  47675. for (var i = 1; i < total; i++) {
  47676. var last = this.points[i - 1];
  47677. var cur = this.points[i];
  47678. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  47679. this._direction(cur, last, lineA);
  47680. if (!curNormal) {
  47681. curNormal = BABYLON.Vector2.Zero();
  47682. this._perp(lineA, curNormal);
  47683. }
  47684. if (i === 1) {
  47685. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  47686. }
  47687. if (!next) {
  47688. this._perp(lineA, curNormal);
  47689. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  47690. }
  47691. else {
  47692. this._direction(next, cur, lineB);
  47693. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  47694. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  47695. }
  47696. }
  47697. if (this.points.length > 2 && this.closed) {
  47698. var last2 = this.points[total - 2];
  47699. var cur2 = this.points[0];
  47700. var next2 = this.points[1];
  47701. this._direction(cur2, last2, lineA);
  47702. this._direction(next2, cur2, lineB);
  47703. this._perp(lineA, curNormal);
  47704. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  47705. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  47706. // Patch contour
  47707. if (contour) {
  47708. var off = (bt == null) ? 0 : 4;
  47709. contour[0].x = vb[off + 0];
  47710. contour[0].y = vb[off + 1];
  47711. contour[1].x = vb[off + 2];
  47712. contour[1].y = vb[off + 3];
  47713. }
  47714. }
  47715. // Remove the point we added at the beginning
  47716. if (this.closed) {
  47717. this.points.splice(total - 1);
  47718. }
  47719. };
  47720. // Methods for Lines building
  47721. ///////////////////////////////////////////////////////////////////////////////////
  47722. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  47723. var renderCache = modelRenderCache;
  47724. var engine = this.owner.engine;
  47725. if (this._fillVB === null) {
  47726. this._computeLines2D();
  47727. }
  47728. // Need to create WebGL resources for fill part?
  47729. if (this.fill) {
  47730. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  47731. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  47732. renderCache.fillIndicesCount = this._fillIB.length;
  47733. // 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
  47734. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  47735. if (ei) {
  47736. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47737. }
  47738. // Get the non instanced version
  47739. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  47740. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47741. }
  47742. // Need to create WebGL resources for border part?
  47743. if (this.border) {
  47744. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  47745. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  47746. renderCache.borderIndicesCount = this._borderIB.length;
  47747. // 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
  47748. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  47749. if (ei) {
  47750. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47751. }
  47752. // Get the non instanced version
  47753. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  47754. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47755. }
  47756. this._fillVB = null;
  47757. this._fillIB = null;
  47758. this._borderVB = null;
  47759. this._borderIB = null;
  47760. return renderCache;
  47761. };
  47762. Lines2D.prototype._computeLines2D = function () {
  47763. // Init min/max because their being computed here
  47764. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  47765. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  47766. var contour = new Array();
  47767. var startCapContour = new Array();
  47768. var endCapContour = new Array();
  47769. // Need to create WebGL resources for fill part?
  47770. if (this.fill) {
  47771. var startCapInfo = this._getCapSize(this.startCap);
  47772. var endCapInfo = this._getCapSize(this.endCap);
  47773. var count = this.points.length;
  47774. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47775. this._fillVB = new Float32Array(vbSize);
  47776. var vb = this._fillVB;
  47777. var ht = this.fillThickness / 2;
  47778. var total = this.points.length;
  47779. this._buildLine(vb, this.border ? null : contour, ht);
  47780. var max = total * 2;
  47781. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  47782. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47783. var ib = this._fillIB;
  47784. for (var i = 0; i < triCount; i += 2) {
  47785. ib[i * 3 + 0] = i + 0;
  47786. ib[i * 3 + 1] = i + 1;
  47787. ib[i * 3 + 2] = (i + 2) % max;
  47788. ib[i * 3 + 3] = i + 1;
  47789. ib[i * 3 + 4] = (i + 3) % max;
  47790. ib[i * 3 + 5] = (i + 2) % max;
  47791. }
  47792. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  47793. 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);
  47794. }
  47795. // Need to create WebGL resources for border part?
  47796. if (this.border) {
  47797. var startCapInfo = this._getCapSize(this.startCap, true);
  47798. var endCapInfo = this._getCapSize(this.endCap, true);
  47799. var count = this.points.length;
  47800. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47801. this._borderVB = new Float32Array(vbSize);
  47802. var vb = this._borderVB;
  47803. var ht = this.fillThickness / 2;
  47804. var bt = this.borderThickness;
  47805. var total = this.points.length;
  47806. this._buildLine(vb, contour, ht, bt);
  47807. var max = total * 2 * 2;
  47808. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  47809. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47810. var ib = this._borderIB;
  47811. for (var i = 0; i < triCount; i += 4) {
  47812. ib[i * 3 + 0] = i + 0;
  47813. ib[i * 3 + 1] = i + 2;
  47814. ib[i * 3 + 2] = (i + 6) % max;
  47815. ib[i * 3 + 3] = i + 0;
  47816. ib[i * 3 + 4] = (i + 6) % max;
  47817. ib[i * 3 + 5] = (i + 4) % max;
  47818. ib[i * 3 + 6] = i + 3;
  47819. ib[i * 3 + 7] = i + 1;
  47820. ib[i * 3 + 8] = (i + 5) % max;
  47821. ib[i * 3 + 9] = i + 3;
  47822. ib[i * 3 + 10] = (i + 5) % max;
  47823. ib[i * 3 + 11] = (i + 7) % max;
  47824. }
  47825. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  47826. 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);
  47827. }
  47828. this._contour = contour;
  47829. if (startCapContour.length > 0) {
  47830. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  47831. this._startCapTriIndices = startCapTri;
  47832. this._startCapContour = startCapContour;
  47833. }
  47834. else {
  47835. this._startCapTriIndices = null;
  47836. this._startCapContour = null;
  47837. }
  47838. if (endCapContour.length > 0) {
  47839. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  47840. this._endCapContour = endCapContour;
  47841. this._endCapTriIndices = endCapTri;
  47842. }
  47843. else {
  47844. this._endCapContour = null;
  47845. this._endCapTriIndices = null;
  47846. }
  47847. var bs = this._boundingMax.subtract(this._boundingMin);
  47848. this._size.width = bs.x;
  47849. this._size.height = bs.y;
  47850. };
  47851. Object.defineProperty(Lines2D.prototype, "size", {
  47852. get: function () {
  47853. if (this._size == null) {
  47854. this._computeLines2D();
  47855. }
  47856. return this._size;
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. Lines2D.prototype.createInstanceDataParts = function () {
  47862. var res = new Array();
  47863. if (this.border) {
  47864. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  47865. }
  47866. if (this.fill) {
  47867. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  47868. }
  47869. return res;
  47870. };
  47871. Lines2D.prototype.applyActualScaleOnTransform = function () {
  47872. return true;
  47873. };
  47874. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  47875. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  47876. return false;
  47877. }
  47878. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  47879. var d = part;
  47880. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  47881. d.boundingMin = this.boundingMin;
  47882. d.boundingMax = this.boundingMax;
  47883. }
  47884. }
  47885. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  47886. var d = part;
  47887. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  47888. d.boundingMin = this.boundingMin;
  47889. d.boundingMax = this.boundingMax;
  47890. }
  47891. }
  47892. return true;
  47893. };
  47894. Lines2D._prevA = BABYLON.Vector2.Zero();
  47895. Lines2D._prevB = BABYLON.Vector2.Zero();
  47896. Lines2D._curA = BABYLON.Vector2.Zero();
  47897. Lines2D._curB = BABYLON.Vector2.Zero();
  47898. Lines2D._miterTps = BABYLON.Vector2.Zero();
  47899. Lines2D._startDir = BABYLON.Vector2.Zero();
  47900. Lines2D._endDir = BABYLON.Vector2.Zero();
  47901. Lines2D._tpsV = BABYLON.Vector2.Zero();
  47902. Lines2D._noCap = 0;
  47903. Lines2D._roundCap = 1;
  47904. Lines2D._triangleCap = 2;
  47905. Lines2D._squareAnchorCap = 3;
  47906. Lines2D._roundAnchorCap = 4;
  47907. Lines2D._diamondAnchorCap = 5;
  47908. Lines2D._arrowCap = 6;
  47909. Lines2D._roundCapSubDiv = 36;
  47910. __decorate([
  47911. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  47912. ], Lines2D.prototype, "points", null);
  47913. __decorate([
  47914. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47915. ], Lines2D.prototype, "fillThickness", null);
  47916. __decorate([
  47917. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47918. ], Lines2D.prototype, "closed", null);
  47919. __decorate([
  47920. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47921. ], Lines2D.prototype, "startCap", null);
  47922. __decorate([
  47923. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47924. ], Lines2D.prototype, "endCap", null);
  47925. Lines2D = __decorate([
  47926. BABYLON.className("Lines2D")
  47927. ], Lines2D);
  47928. return Lines2D;
  47929. }(BABYLON.Shape2D));
  47930. BABYLON.Lines2D = Lines2D;
  47931. })(BABYLON || (BABYLON = {}));
  47932. var BABYLON;
  47933. (function (BABYLON) {
  47934. // This class contains data that lifetime is bounding to the Babylon Engine object
  47935. var Canvas2DEngineBoundData = (function () {
  47936. function Canvas2DEngineBoundData() {
  47937. this._modelCache = new BABYLON.StringDictionary();
  47938. }
  47939. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47940. return this._modelCache.getOrAddWithFactory(key, factory);
  47941. };
  47942. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47943. if (!modelRenderCache.isDisposed) {
  47944. return false;
  47945. }
  47946. this._modelCache.remove(modelRenderCache.modelKey);
  47947. return true;
  47948. };
  47949. return Canvas2DEngineBoundData;
  47950. }());
  47951. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47952. var Canvas2D = (function (_super) {
  47953. __extends(Canvas2D, _super);
  47954. function Canvas2D(scene, settings) {
  47955. var _this = this;
  47956. _super.call(this, settings);
  47957. /**
  47958. * 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.
  47959. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47960. */
  47961. this.worldSpaceToNodeLocal = function (worldPos) {
  47962. var node = _this._worldSpaceNode;
  47963. if (!node) {
  47964. return;
  47965. }
  47966. var mtx = node.getWorldMatrix().clone();
  47967. mtx.invert();
  47968. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47969. var res = new BABYLON.Vector2(v.x, v.y);
  47970. var size = _this.actualSize;
  47971. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47972. res.y += size.height * 0.5;
  47973. return res;
  47974. };
  47975. /**
  47976. * 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
  47977. */
  47978. this.worldSpaceCacheChanged = function () {
  47979. var plane = _this.worldSpaceCanvasNode;
  47980. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47981. vd.uvs = new Float32Array(8);
  47982. var material = plane.material;
  47983. var tex = _this._renderableData._cacheTexture;
  47984. if (material.diffuseTexture !== tex) {
  47985. material.diffuseTexture = tex;
  47986. tex.hasAlpha = true;
  47987. }
  47988. var nodeuv = _this._renderableData._cacheNodeUVs;
  47989. for (var i = 0; i < 4; i++) {
  47990. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47991. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47992. }
  47993. vd.applyToMesh(plane);
  47994. };
  47995. this._notifDebugMode = false;
  47996. this._mapCounter = 0;
  47997. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47998. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47999. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  48000. this._groupRenderCounter = new BABYLON.PerfCounter();
  48001. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  48002. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  48003. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  48004. this._updateLayoutCounter = new BABYLON.PerfCounter();
  48005. this._updatePositioningCounter = new BABYLON.PerfCounter();
  48006. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  48007. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  48008. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  48009. this._cachedCanvasGroup = null;
  48010. this._profileInfoText = null;
  48011. BABYLON.Prim2DBase._isCanvasInit = false;
  48012. if (!settings) {
  48013. settings = {};
  48014. }
  48015. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  48016. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  48017. this._background.zOrder = 1.0;
  48018. this._background.isPickable = false;
  48019. this._background.origin = BABYLON.Vector2.Zero();
  48020. this._background.levelVisible = false;
  48021. if (settings.backgroundRoundRadius != null) {
  48022. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  48023. }
  48024. if (settings.backgroundBorder != null) {
  48025. if (typeof (settings.backgroundBorder) === "string") {
  48026. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  48027. }
  48028. else {
  48029. this.backgroundBorder = settings.backgroundBorder;
  48030. }
  48031. }
  48032. if (settings.backgroundBorderThickNess != null) {
  48033. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  48034. }
  48035. if (settings.backgroundFill != null) {
  48036. if (typeof (settings.backgroundFill) === "string") {
  48037. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  48038. }
  48039. else {
  48040. this.backgroundFill = settings.backgroundFill;
  48041. }
  48042. }
  48043. // Put a handler to resize the background whenever the canvas is resizing
  48044. this.propertyChanged.add(function (e, s) {
  48045. if (e.propertyName === "size") {
  48046. _this._background.size = _this.size;
  48047. }
  48048. }, BABYLON.Group2D.sizeProperty.flagId);
  48049. this._background._patchHierarchy(this);
  48050. }
  48051. var engine = scene.getEngine();
  48052. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  48053. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  48054. this._capturedPointers = new BABYLON.StringDictionary();
  48055. this._pickStartingPosition = BABYLON.Vector2.Zero();
  48056. this._hierarchyLevelMaxSiblingCount = 50;
  48057. this._hierarchyDepth = 0;
  48058. this._zOrder = 0;
  48059. this._zMax = 1;
  48060. this._scene = scene;
  48061. this._engine = engine;
  48062. this._renderingSize = new BABYLON.Size(0, 0);
  48063. this._designSize = settings.designSize || null;
  48064. this._designUseHorizAxis = settings.designUseHorizAxis === true;
  48065. this._trackedGroups = new Array();
  48066. this._maxAdaptiveWorldSpaceCanvasSize = null;
  48067. this._groupCacheMaps = new BABYLON.StringDictionary();
  48068. this._patchHierarchy(this);
  48069. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  48070. this._fitRenderingDevice = !settings.size;
  48071. if (!settings.size) {
  48072. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  48073. }
  48074. // Register scene dispose to also dispose the canvas when it'll happens
  48075. scene.onDisposeObservable.add(function (d, s) {
  48076. _this.dispose();
  48077. });
  48078. if (this._isScreenSpace) {
  48079. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  48080. _this._engine.clear(null, false, true, true);
  48081. _this._render();
  48082. });
  48083. }
  48084. else {
  48085. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  48086. _this._render();
  48087. });
  48088. }
  48089. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  48090. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  48091. this._setupInteraction(enableInteraction);
  48092. }
  48093. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  48094. get: function () {
  48095. return this._drawCallsOpaqueCounter;
  48096. },
  48097. enumerable: true,
  48098. configurable: true
  48099. });
  48100. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  48101. get: function () {
  48102. return this._drawCallsAlphaTestCounter;
  48103. },
  48104. enumerable: true,
  48105. configurable: true
  48106. });
  48107. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  48108. get: function () {
  48109. return this._drawCallsTransparentCounter;
  48110. },
  48111. enumerable: true,
  48112. configurable: true
  48113. });
  48114. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  48115. get: function () {
  48116. return this._groupRenderCounter;
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  48122. get: function () {
  48123. return this._updateTransparentDataCounter;
  48124. },
  48125. enumerable: true,
  48126. configurable: true
  48127. });
  48128. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  48129. get: function () {
  48130. return this._cachedGroupRenderCounter;
  48131. },
  48132. enumerable: true,
  48133. configurable: true
  48134. });
  48135. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  48136. get: function () {
  48137. return this._updateCachedStateCounter;
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  48143. get: function () {
  48144. return this._updateLayoutCounter;
  48145. },
  48146. enumerable: true,
  48147. configurable: true
  48148. });
  48149. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  48150. get: function () {
  48151. return this._updatePositioningCounter;
  48152. },
  48153. enumerable: true,
  48154. configurable: true
  48155. });
  48156. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  48157. get: function () {
  48158. return this._updateLocalTransformCounter;
  48159. },
  48160. enumerable: true,
  48161. configurable: true
  48162. });
  48163. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  48164. get: function () {
  48165. return this._updateGlobalTransformCounter;
  48166. },
  48167. enumerable: true,
  48168. configurable: true
  48169. });
  48170. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  48171. get: function () {
  48172. return this._boundingInfoRecomputeCounter;
  48173. },
  48174. enumerable: true,
  48175. configurable: true
  48176. });
  48177. Canvas2D.prototype._canvasPreInit = function (settings) {
  48178. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  48179. this._cachingStrategy = cachingStrategy;
  48180. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  48181. };
  48182. Canvas2D.prototype._setupInteraction = function (enable) {
  48183. var _this = this;
  48184. // No change detection
  48185. if (enable === this._interactionEnabled) {
  48186. return;
  48187. }
  48188. // Set the new state
  48189. this._interactionEnabled = enable;
  48190. // ScreenSpace mode
  48191. if (this._isScreenSpace) {
  48192. // Disable interaction
  48193. if (!enable) {
  48194. if (this._scenePrePointerObserver) {
  48195. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  48196. this._scenePrePointerObserver = null;
  48197. }
  48198. return;
  48199. }
  48200. // Enable Interaction
  48201. // Register the observable
  48202. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  48203. if (_this.isVisible === false) {
  48204. return;
  48205. }
  48206. var hs = 1 / _this.engine.getHardwareScalingLevel();
  48207. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  48208. _this._handlePointerEventForInteraction(e, localPos, s);
  48209. });
  48210. }
  48211. else {
  48212. var scene = this.scene;
  48213. if (enable) {
  48214. scene.constantlyUpdateMeshUnderPointer = true;
  48215. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  48216. if (_this.isVisible === false) {
  48217. return;
  48218. }
  48219. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  48220. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  48221. _this._handlePointerEventForInteraction(e, localPos, s);
  48222. }
  48223. });
  48224. }
  48225. else {
  48226. if (this._scenePointerObserver) {
  48227. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  48228. this._scenePointerObserver = null;
  48229. }
  48230. }
  48231. }
  48232. };
  48233. /**
  48234. * Internal method, you should use the Prim2DBase version instead
  48235. */
  48236. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  48237. if (this.isPointerCaptured(pointerId)) {
  48238. return false;
  48239. }
  48240. // Try to capture the pointer on the HTML side
  48241. try {
  48242. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  48243. }
  48244. catch (e) {
  48245. }
  48246. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  48247. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  48248. this._capturedPointers.add(pointerId.toString(), primitive);
  48249. return true;
  48250. };
  48251. /**
  48252. * Internal method, you should use the Prim2DBase version instead
  48253. */
  48254. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  48255. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  48256. return false;
  48257. }
  48258. // Try to release the pointer on the HTML side
  48259. try {
  48260. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  48261. }
  48262. catch (e) {
  48263. }
  48264. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  48265. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  48266. this._capturedPointers.remove(pointerId.toString());
  48267. return true;
  48268. };
  48269. /**
  48270. * Determine if the given pointer is captured or not
  48271. * @param pointerId the Id of the pointer
  48272. * @return true if it's captured, false otherwise
  48273. */
  48274. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  48275. return this._capturedPointers.contains(pointerId.toString());
  48276. };
  48277. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  48278. // Avoid unnecessary lookup
  48279. if (this._capturedPointers.count === 0) {
  48280. return null;
  48281. }
  48282. return this._capturedPointers.get(pointerId.toString());
  48283. };
  48284. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  48285. // Dispose check
  48286. if (this.isDisposed) {
  48287. return;
  48288. }
  48289. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  48290. if (!this._updatePointerInfo(eventData, localPosition)) {
  48291. return;
  48292. }
  48293. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48294. // 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.
  48295. // 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.
  48296. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null, true);
  48297. // 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
  48298. this._updateOverStatus(true);
  48299. // Check if we have nothing to raise
  48300. if (!this._actualOverPrimitive && !capturedPrim) {
  48301. return;
  48302. }
  48303. // Update the relatedTarget info with the over primitive or the captured one (if any)
  48304. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  48305. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  48306. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  48307. // Analyze the pointer event type and fire proper events on the primitive
  48308. var skip = false;
  48309. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48310. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  48311. }
  48312. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48313. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  48314. }
  48315. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48316. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  48317. }
  48318. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  48319. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  48320. }
  48321. eventState.skipNextObservers = skip;
  48322. };
  48323. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  48324. var s = this.scale;
  48325. var pii = this._primPointerInfo;
  48326. if (!pii.canvasPointerPos) {
  48327. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  48328. }
  48329. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  48330. if (!camera || !camera.viewport) {
  48331. return false;
  48332. }
  48333. var engine = this._scene.getEngine();
  48334. if (this._isScreenSpace) {
  48335. var cameraViewport = camera.viewport;
  48336. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48337. // Moving coordinates to local viewport world
  48338. var x = localPosition.x - viewport.x;
  48339. var y = localPosition.y - viewport.y;
  48340. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  48341. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  48342. }
  48343. else {
  48344. pii.canvasPointerPos.x = localPosition.x / s;
  48345. pii.canvasPointerPos.y = localPosition.y / s;
  48346. }
  48347. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  48348. pii.mouseWheelDelta = 0;
  48349. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  48350. var event = eventData.event;
  48351. if (event.wheelDelta) {
  48352. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  48353. }
  48354. else if (event.detail) {
  48355. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  48356. }
  48357. }
  48358. else {
  48359. var pe = eventData.event;
  48360. pii.ctrlKey = pe.ctrlKey;
  48361. pii.altKey = pe.altKey;
  48362. pii.shiftKey = pe.shiftKey;
  48363. pii.metaKey = pe.metaKey;
  48364. pii.button = pe.button;
  48365. pii.buttons = pe.buttons;
  48366. pii.pointerId = pe.pointerId;
  48367. pii.width = pe.width;
  48368. pii.height = pe.height;
  48369. pii.presssure = pe.pressure;
  48370. pii.tilt.x = pe.tiltX;
  48371. pii.tilt.y = pe.tiltY;
  48372. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  48373. }
  48374. return true;
  48375. };
  48376. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  48377. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  48378. return;
  48379. }
  48380. // 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
  48381. if (!this._globalTransform) {
  48382. this.updateCachedStates(true);
  48383. }
  48384. var ii = Canvas2D._interInfo;
  48385. ii.pickPosition.x = mouseLocalPos.x;
  48386. ii.pickPosition.y = mouseLocalPos.y;
  48387. ii.findFirstOnly = false;
  48388. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  48389. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  48390. this._previousIntersectionList = this._actualIntersectionList;
  48391. this._actualIntersectionList = null;
  48392. this._previousOverPrimitive = this._actualOverPrimitive;
  48393. this._actualOverPrimitive = null;
  48394. return;
  48395. }
  48396. this.intersect(ii);
  48397. this._previousIntersectionList = this._actualIntersectionList;
  48398. this._actualIntersectionList = ii.intersectedPrimitives;
  48399. this._previousOverPrimitive = this._actualOverPrimitive;
  48400. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  48401. if (this._previousOverPrimitive && this._actualOverPrimitive && this._previousOverPrimitive.prim !== this._actualOverPrimitive.prim) {
  48402. console.log("changed");
  48403. }
  48404. this._intersectionRenderId = this.scene.getRenderId();
  48405. };
  48406. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  48407. Canvas2D.prototype._updateOverStatus = function (force) {
  48408. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._previousIntersectionList || !this._actualIntersectionList) {
  48409. return;
  48410. }
  48411. // Detect a change of over
  48412. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  48413. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  48414. if (prevPrim !== actualPrim) {
  48415. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  48416. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  48417. // Notify the previous "over" prim that the pointer is no longer over it
  48418. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  48419. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  48420. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  48421. }
  48422. // Notify the new "over" prim that the pointer is over it
  48423. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  48424. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  48425. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  48426. }
  48427. }
  48428. this._hoverStatusRenderId = this.scene.getRenderId();
  48429. };
  48430. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  48431. if (this._primPointerInfo.isCaptured) {
  48432. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  48433. }
  48434. else {
  48435. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  48436. var pii = _a[_i];
  48437. if (pii.prim === prim) {
  48438. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  48439. return;
  48440. }
  48441. }
  48442. }
  48443. };
  48444. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  48445. if (!this._notifDebugMode) {
  48446. return;
  48447. }
  48448. var debug = "";
  48449. for (var i = 0; i < prim.hierarchyDepth; i++) {
  48450. debug += " ";
  48451. }
  48452. var pii = this._primPointerInfo;
  48453. 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();
  48454. console.log(debug);
  48455. };
  48456. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  48457. var ppi = this._primPointerInfo;
  48458. var event = eventData ? eventData.event : null;
  48459. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  48460. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  48461. this._notifParents(prim, mask);
  48462. }
  48463. var bubbleCancelled = false;
  48464. var cur = prim;
  48465. while (cur) {
  48466. // Only trigger the observers if the primitive is intersected (except for out)
  48467. if (!bubbleCancelled) {
  48468. this._updatePrimPointerPos(cur);
  48469. // Exec the observers
  48470. this._debugExecObserver(cur, mask);
  48471. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  48472. eventData.skipOnPointerObservable = true;
  48473. return false;
  48474. }
  48475. this._triggerActionManager(cur, ppi, mask, event);
  48476. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  48477. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  48478. if (ppi.cancelBubble) {
  48479. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  48480. return false;
  48481. }
  48482. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  48483. bubbleCancelled = true;
  48484. }
  48485. }
  48486. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  48487. if (bubbleCancelled) {
  48488. this._updatePrimPointerPos(cur);
  48489. }
  48490. // Trigger a PointerEnter corresponding to the PointerOver
  48491. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48492. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  48493. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  48494. }
  48495. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48496. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  48497. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  48498. }
  48499. // Loop to the parent
  48500. cur = cur.parent;
  48501. }
  48502. return true;
  48503. };
  48504. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  48505. var _this = this;
  48506. // 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
  48507. if (!this._globalTransform) {
  48508. this.updateCachedStates(true);
  48509. }
  48510. // Process Trigger related to PointerDown
  48511. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  48512. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  48513. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  48514. this._pickStartingTime = new Date().getTime();
  48515. this._pickedDownPrim = null;
  48516. if (prim.actionManager) {
  48517. this._pickedDownPrim = prim;
  48518. if (prim.actionManager.hasPickTriggers) {
  48519. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48520. switch (eventData.button) {
  48521. case 0:
  48522. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  48523. break;
  48524. case 1:
  48525. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  48526. break;
  48527. case 2:
  48528. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  48529. break;
  48530. }
  48531. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  48532. }
  48533. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  48534. window.setTimeout(function () {
  48535. var ppi = _this._primPointerInfo;
  48536. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  48537. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  48538. _this._updateOverStatus(false);
  48539. var ii = new BABYLON.IntersectInfo2D();
  48540. ii.pickPosition = ppi.canvasPointerPos.clone();
  48541. ii.findFirstOnly = false;
  48542. _this.intersect(ii);
  48543. if (ii.isPrimIntersected(prim) !== null) {
  48544. if (prim.actionManager) {
  48545. 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)) {
  48546. _this._pickStartingTime = 0;
  48547. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  48548. }
  48549. }
  48550. }
  48551. }, BABYLON.ActionManager.LongPressDelay);
  48552. }
  48553. }
  48554. }
  48555. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  48556. this._pickStartingTime = 0;
  48557. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48558. if (prim.actionManager) {
  48559. // OnPickUpTrigger
  48560. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  48561. // OnPickTrigger
  48562. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  48563. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  48564. }
  48565. }
  48566. // OnPickOutTrigger
  48567. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  48568. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  48569. }
  48570. }
  48571. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  48572. if (prim.actionManager) {
  48573. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48574. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  48575. }
  48576. }
  48577. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  48578. if (prim.actionManager) {
  48579. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48580. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  48581. }
  48582. }
  48583. };
  48584. Canvas2D.prototype._notifParents = function (prim, mask) {
  48585. var pii = this._primPointerInfo;
  48586. var curPrim = this;
  48587. while (curPrim) {
  48588. this._updatePrimPointerPos(curPrim);
  48589. // Fire the proper notification
  48590. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48591. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  48592. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  48593. }
  48594. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48595. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  48596. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  48597. }
  48598. curPrim = curPrim.parent;
  48599. }
  48600. };
  48601. /**
  48602. * Don't forget to call the dispose method when you're done with the Canvas instance.
  48603. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  48604. */
  48605. Canvas2D.prototype.dispose = function () {
  48606. if (!_super.prototype.dispose.call(this)) {
  48607. return false;
  48608. }
  48609. if (this._profilingCanvas) {
  48610. this._profilingCanvas.dispose();
  48611. this._profilingCanvas = null;
  48612. }
  48613. if (this.interactionEnabled) {
  48614. this._setupInteraction(false);
  48615. }
  48616. if (this._beforeRenderObserver) {
  48617. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  48618. this._beforeRenderObserver = null;
  48619. }
  48620. if (this._afterRenderObserver) {
  48621. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  48622. this._afterRenderObserver = null;
  48623. }
  48624. if (this._groupCacheMaps) {
  48625. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  48626. this._groupCacheMaps = null;
  48627. }
  48628. };
  48629. Object.defineProperty(Canvas2D.prototype, "scene", {
  48630. /**
  48631. * Accessor to the Scene that owns the Canvas
  48632. * @returns The instance of the Scene object
  48633. */
  48634. get: function () {
  48635. return this._scene;
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(Canvas2D.prototype, "engine", {
  48641. /**
  48642. * Accessor to the Engine that drives the Scene used by this Canvas
  48643. * @returns The instance of the Engine object
  48644. */
  48645. get: function () {
  48646. return this._engine;
  48647. },
  48648. enumerable: true,
  48649. configurable: true
  48650. });
  48651. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  48652. /**
  48653. * Accessor of the Caching Strategy used by this Canvas.
  48654. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  48655. * @returns the value corresponding to the used strategy.
  48656. */
  48657. get: function () {
  48658. return this._cachingStrategy;
  48659. },
  48660. enumerable: true,
  48661. configurable: true
  48662. });
  48663. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  48664. /**
  48665. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  48666. * @returns {}
  48667. */
  48668. get: function () {
  48669. return this._isScreenSpace;
  48670. },
  48671. enumerable: true,
  48672. configurable: true
  48673. });
  48674. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  48675. /**
  48676. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  48677. */
  48678. get: function () {
  48679. return this._worldSpaceNode;
  48680. },
  48681. set: function (val) {
  48682. this._worldSpaceNode = val;
  48683. },
  48684. enumerable: true,
  48685. configurable: true
  48686. });
  48687. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  48688. /**
  48689. * Check if the WebGL Instanced Array extension is supported or not
  48690. */
  48691. get: function () {
  48692. return this._supprtInstancedArray;
  48693. },
  48694. enumerable: true,
  48695. configurable: true
  48696. });
  48697. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  48698. /**
  48699. * Property that defines the fill object used to draw the background of the Canvas.
  48700. * Note that Canvas with a Caching Strategy of
  48701. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  48702. */
  48703. get: function () {
  48704. if (!this._background || !this._background.isVisible) {
  48705. return null;
  48706. }
  48707. return this._background.fill;
  48708. },
  48709. set: function (value) {
  48710. this.checkBackgroundAvailability();
  48711. if (value === this._background.fill) {
  48712. return;
  48713. }
  48714. this._background.fill = value;
  48715. this._background.levelVisible = true;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  48721. /**
  48722. * Property that defines the border object used to draw the background of the Canvas.
  48723. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  48724. */
  48725. get: function () {
  48726. if (!this._background || !this._background.isVisible) {
  48727. return null;
  48728. }
  48729. return this._background.border;
  48730. },
  48731. set: function (value) {
  48732. this.checkBackgroundAvailability();
  48733. if (value === this._background.border) {
  48734. return;
  48735. }
  48736. this._background.border = value;
  48737. this._background.levelVisible = true;
  48738. },
  48739. enumerable: true,
  48740. configurable: true
  48741. });
  48742. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  48743. /**
  48744. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  48745. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  48746. */
  48747. get: function () {
  48748. if (!this._background || !this._background.isVisible) {
  48749. return null;
  48750. }
  48751. return this._background.borderThickness;
  48752. },
  48753. set: function (value) {
  48754. this.checkBackgroundAvailability();
  48755. if (value === this._background.borderThickness) {
  48756. return;
  48757. }
  48758. this._background.borderThickness = value;
  48759. },
  48760. enumerable: true,
  48761. configurable: true
  48762. });
  48763. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  48764. /**
  48765. * You can set the roundRadius of the background
  48766. * @returns The current roundRadius
  48767. */
  48768. get: function () {
  48769. if (!this._background || !this._background.isVisible) {
  48770. return null;
  48771. }
  48772. return this._background.roundRadius;
  48773. },
  48774. set: function (value) {
  48775. this.checkBackgroundAvailability();
  48776. if (value === this._background.roundRadius) {
  48777. return;
  48778. }
  48779. this._background.roundRadius = value;
  48780. this._background.levelVisible = true;
  48781. },
  48782. enumerable: true,
  48783. configurable: true
  48784. });
  48785. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  48786. /**
  48787. * Enable/Disable interaction for this Canvas
  48788. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  48789. */
  48790. get: function () {
  48791. return this._interactionEnabled;
  48792. },
  48793. set: function (enable) {
  48794. this._setupInteraction(enable);
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(Canvas2D.prototype, "designSize", {
  48800. get: function () {
  48801. return this._designSize;
  48802. },
  48803. enumerable: true,
  48804. configurable: true
  48805. });
  48806. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  48807. get: function () {
  48808. return this._designUseHorizAxis;
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  48814. /**
  48815. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  48816. * @returns {}
  48817. */
  48818. get: function () {
  48819. return this.__engineData;
  48820. },
  48821. enumerable: true,
  48822. configurable: true
  48823. });
  48824. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  48825. if (this._profilingCanvas) {
  48826. return this._profilingCanvas;
  48827. }
  48828. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  48829. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  48830. new BABYLON.Rectangle2D({
  48831. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  48832. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  48833. ]
  48834. })
  48835. ]
  48836. });
  48837. this._profileInfoText = canvas.findById("ProfileInfoText");
  48838. this._profilingCanvas = canvas;
  48839. return canvas;
  48840. };
  48841. Canvas2D.prototype.checkBackgroundAvailability = function () {
  48842. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  48843. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  48844. }
  48845. };
  48846. Canvas2D.prototype._initPerfMetrics = function () {
  48847. this._drawCallsOpaqueCounter.fetchNewFrame();
  48848. this._drawCallsAlphaTestCounter.fetchNewFrame();
  48849. this._drawCallsTransparentCounter.fetchNewFrame();
  48850. this._groupRenderCounter.fetchNewFrame();
  48851. this._updateTransparentDataCounter.fetchNewFrame();
  48852. this._cachedGroupRenderCounter.fetchNewFrame();
  48853. this._updateCachedStateCounter.fetchNewFrame();
  48854. this._updateLayoutCounter.fetchNewFrame();
  48855. this._updatePositioningCounter.fetchNewFrame();
  48856. this._updateLocalTransformCounter.fetchNewFrame();
  48857. this._updateGlobalTransformCounter.fetchNewFrame();
  48858. this._boundingInfoRecomputeCounter.fetchNewFrame();
  48859. };
  48860. Canvas2D.prototype._fetchPerfMetrics = function () {
  48861. this._drawCallsOpaqueCounter.addCount(0, true);
  48862. this._drawCallsAlphaTestCounter.addCount(0, true);
  48863. this._drawCallsTransparentCounter.addCount(0, true);
  48864. this._groupRenderCounter.addCount(0, true);
  48865. this._updateTransparentDataCounter.addCount(0, true);
  48866. this._cachedGroupRenderCounter.addCount(0, true);
  48867. this._updateCachedStateCounter.addCount(0, true);
  48868. this._updateLayoutCounter.addCount(0, true);
  48869. this._updatePositioningCounter.addCount(0, true);
  48870. this._updateLocalTransformCounter.addCount(0, true);
  48871. this._updateGlobalTransformCounter.addCount(0, true);
  48872. this._boundingInfoRecomputeCounter.addCount(0, true);
  48873. };
  48874. Canvas2D.prototype._updateProfileCanvas = function () {
  48875. if (this._profileInfoText == null) {
  48876. return;
  48877. }
  48878. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  48879. var p = "Draw Calls:\n" +
  48880. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  48881. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  48882. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  48883. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  48884. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  48885. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  48886. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  48887. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  48888. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  48889. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  48890. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  48891. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  48892. this._profileInfoText.text = p;
  48893. };
  48894. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  48895. switch (renderMode) {
  48896. case BABYLON.Render2DContext.RenderModeOpaque:
  48897. this._drawCallsOpaqueCounter.addCount(count, false);
  48898. return;
  48899. case BABYLON.Render2DContext.RenderModeAlphaTest:
  48900. this._drawCallsAlphaTestCounter.addCount(count, false);
  48901. return;
  48902. case BABYLON.Render2DContext.RenderModeTransparent:
  48903. this._drawCallsTransparentCounter.addCount(count, false);
  48904. return;
  48905. }
  48906. };
  48907. Canvas2D.prototype._addGroupRenderCount = function (count) {
  48908. this._groupRenderCounter.addCount(count, false);
  48909. };
  48910. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  48911. this._updateTransparentDataCounter.addCount(count, false);
  48912. };
  48913. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  48914. this._cachedGroupRenderCounter.addCount(count, false);
  48915. };
  48916. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  48917. this._updateCachedStateCounter.addCount(count, false);
  48918. };
  48919. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  48920. this._updateLayoutCounter.addCount(count, false);
  48921. };
  48922. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  48923. this._updatePositioningCounter.addCount(count, false);
  48924. };
  48925. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  48926. this._updateLocalTransformCounter.addCount(count, false);
  48927. };
  48928. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  48929. this._updateGlobalTransformCounter.addCount(count, false);
  48930. };
  48931. Canvas2D.prototype._updateTrackedNodes = function () {
  48932. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48933. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48934. var rh = this.engine.getRenderHeight();
  48935. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  48936. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  48937. var group = _a[_i];
  48938. if (group.isDisposed || !group.isVisible) {
  48939. continue;
  48940. }
  48941. var node = group.trackedNode;
  48942. var worldMtx = node.getWorldMatrix();
  48943. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  48944. var s = this.scale;
  48945. group.x = Math.round(proj.x / s);
  48946. group.y = Math.round((rh - proj.y) / s);
  48947. }
  48948. };
  48949. /**
  48950. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  48951. */
  48952. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  48953. this._updateCanvasState(forceRecompute);
  48954. };
  48955. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  48956. if (this._globalTransformStep < 2) {
  48957. return;
  48958. }
  48959. var n = this.worldSpaceCanvasNode;
  48960. var bi = n.getBoundingInfo().boundingBox;
  48961. var v = bi.vectorsWorld;
  48962. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48963. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48964. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48965. var projPoints = new Array(4);
  48966. for (var i = 0; i < 4; i++) {
  48967. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48968. }
  48969. var left = projPoints[3].subtract(projPoints[0]).length();
  48970. var top = projPoints[3].subtract(projPoints[1]).length();
  48971. var right = projPoints[1].subtract(projPoints[2]).length();
  48972. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48973. var w = Math.round(Math.max(top, bottom));
  48974. var h = Math.round(Math.max(right, left));
  48975. var isW = w > h;
  48976. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48977. var edge = Math.max(w, h);
  48978. if (edge < 256) {
  48979. edge = 256;
  48980. }
  48981. else {
  48982. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48983. }
  48984. // Clip values if needed
  48985. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48986. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48987. if (newScale !== this.scale) {
  48988. var scale = newScale;
  48989. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48990. this._setRenderingScale(scale);
  48991. }
  48992. };
  48993. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48994. // Check if the update has already been made for this render Frame
  48995. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48996. return;
  48997. }
  48998. // Detect a change of rendering size
  48999. var renderingSizeChanged = false;
  49000. var newWidth = this.engine.getRenderWidth();
  49001. if (newWidth !== this._renderingSize.width) {
  49002. renderingSizeChanged = true;
  49003. }
  49004. this._renderingSize.width = newWidth;
  49005. var newHeight = this.engine.getRenderHeight();
  49006. if (newHeight !== this._renderingSize.height) {
  49007. renderingSizeChanged = true;
  49008. }
  49009. this._renderingSize.height = newHeight;
  49010. // If the canvas fit the rendering size and it changed, update
  49011. if (renderingSizeChanged && this._fitRenderingDevice) {
  49012. this._actualSize = this._renderingSize.clone();
  49013. this._size = this._renderingSize.clone();
  49014. if (this._background) {
  49015. this._background.size = this.size;
  49016. }
  49017. // Dirty the Layout at the Canvas level to recompute as the size changed
  49018. this._setLayoutDirty();
  49019. }
  49020. // If there's a design size, update the scale according to the renderingSize
  49021. if (this._designSize) {
  49022. var scale = void 0;
  49023. if (this._designUseHorizAxis) {
  49024. scale = this._renderingSize.width / this._designSize.width;
  49025. }
  49026. else {
  49027. scale = this._renderingSize.height / this._designSize.height;
  49028. }
  49029. this.size = this._designSize.clone();
  49030. this.scale = scale;
  49031. }
  49032. var context = new BABYLON.PrepareRender2DContext();
  49033. ++this._globalTransformProcessStep;
  49034. this.updateCachedStates(false);
  49035. this._prepareGroupRender(context);
  49036. this._updateRenderId = this.scene.getRenderId();
  49037. };
  49038. /**
  49039. * Method that renders the Canvas, you should not invoke
  49040. */
  49041. Canvas2D.prototype._render = function () {
  49042. this._initPerfMetrics();
  49043. this._updateCanvasState(false);
  49044. this._updateTrackedNodes();
  49045. // Nothing to do is the Canvas is not visible
  49046. if (this.isVisible === false) {
  49047. return;
  49048. }
  49049. if (!this._isScreenSpace) {
  49050. this._updateAdaptiveSizeWorldCanvas();
  49051. }
  49052. this._updateCanvasState(false);
  49053. if (this._primPointerInfo.canvasPointerPos) {
  49054. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  49055. this._updateOverStatus(false); // TODO this._primPointerInfo may not be up to date!
  49056. }
  49057. this.engine.setState(false);
  49058. this._groupRender();
  49059. if (!this._isScreenSpace) {
  49060. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  49061. this.worldSpaceCacheChanged();
  49062. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  49063. }
  49064. }
  49065. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  49066. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  49067. this._cachedCanvasGroup._renderCachedCanvas();
  49068. }
  49069. this._fetchPerfMetrics();
  49070. this._updateProfileCanvas();
  49071. };
  49072. /**
  49073. * Internal method that allocate a cache for the given group.
  49074. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  49075. * @param group The group to allocate the cache of.
  49076. * @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.
  49077. */
  49078. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  49079. if (useMipMap === void 0) { useMipMap = false; }
  49080. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  49081. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  49082. var rd = group._renderableData;
  49083. var noResizeScale = rd._noResizeOnScale;
  49084. var isCanvas = parent == null;
  49085. var scale;
  49086. if (noResizeScale) {
  49087. scale = isCanvas ? Canvas2D._unS : group.parent.actualScale;
  49088. }
  49089. else {
  49090. scale = group.actualScale;
  49091. }
  49092. // Determine size
  49093. var size = group.actualSize;
  49094. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  49095. if (minSize) {
  49096. size.width = Math.max(minSize.width, size.width);
  49097. size.height = Math.max(minSize.height, size.height);
  49098. }
  49099. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  49100. // Try to find a spot in one of the cached texture
  49101. var res = null;
  49102. var map;
  49103. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  49104. var _map = mapArray_1[_i];
  49105. map = _map;
  49106. var node = map.allocateRect(size);
  49107. if (node) {
  49108. res = { node: node, texture: map };
  49109. break;
  49110. }
  49111. }
  49112. // Couldn't find a map that could fit the rect, create a new map for it
  49113. if (!res) {
  49114. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  49115. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  49116. if (size.width > mapSize.width || size.height > mapSize.height) {
  49117. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  49118. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  49119. }
  49120. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  49121. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  49122. map.hasAlpha = true;
  49123. map.anisotropicFilteringLevel = 4;
  49124. mapArray.splice(0, 0, map);
  49125. var node = map.allocateRect(size);
  49126. res = { node: node, texture: map };
  49127. }
  49128. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  49129. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  49130. if (group !== this || this._isScreenSpace) {
  49131. var node = res.node;
  49132. // 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
  49133. var sprite = void 0;
  49134. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  49135. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  49136. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  49137. sprite.zOrder = 1;
  49138. sprite.origin = BABYLON.Vector2.Zero();
  49139. }
  49140. else {
  49141. 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, dontInheritParentScale: true });
  49142. sprite.origin = group.origin.clone();
  49143. sprite.addExternalData("__cachedGroup__", group);
  49144. sprite.pointerEventObservable.add(function (e, s) {
  49145. if (group.pointerEventObservable !== null) {
  49146. group.pointerEventObservable.notifyObservers(e, s.mask);
  49147. }
  49148. });
  49149. res.sprite = sprite;
  49150. }
  49151. if (sprite && noResizeScale) {
  49152. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  49153. sprite.scaleX = relScale.x;
  49154. sprite.scaleY = relScale.y;
  49155. }
  49156. }
  49157. return res;
  49158. };
  49159. /**
  49160. * Internal method used to register a Scene Node to track position for the given group
  49161. * Do not invoke this method, for internal purpose only.
  49162. * @param group the group to track its associated Scene Node
  49163. */
  49164. Canvas2D.prototype._registerTrackedNode = function (group) {
  49165. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  49166. return;
  49167. }
  49168. this._trackedGroups.push(group);
  49169. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  49170. };
  49171. /**
  49172. * Internal method used to unregister a tracked Scene Node
  49173. * Do not invoke this method, it's for internal purpose only.
  49174. * @param group the group to unregister its tracked Scene Node from.
  49175. */
  49176. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  49177. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  49178. return;
  49179. }
  49180. var i = this._trackedGroups.indexOf(group);
  49181. if (i !== -1) {
  49182. this._trackedGroups.splice(i, 1);
  49183. }
  49184. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  49185. };
  49186. /**
  49187. * Get a Solid Color Brush instance matching the given color.
  49188. * @param color The color to retrieve
  49189. * @return A shared instance of the SolidColorBrush2D class that use the given color
  49190. */
  49191. Canvas2D.GetSolidColorBrush = function (color) {
  49192. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  49193. };
  49194. /**
  49195. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  49196. * @param color The color to retrieve
  49197. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  49198. */
  49199. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  49200. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  49201. };
  49202. /**
  49203. * Get a Gradient Color Brush
  49204. * @param color1 starting color
  49205. * @param color2 engine color
  49206. * @param translation translation vector to apply. default is [0;0]
  49207. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  49208. * @param scale scaling factor to apply. default is 1.
  49209. */
  49210. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  49211. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  49212. if (rotation === void 0) { rotation = 0; }
  49213. if (scale === void 0) { scale = 1; }
  49214. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  49215. };
  49216. /**
  49217. * Create a solid or gradient brush from a string value.
  49218. * @param brushString should be either
  49219. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  49220. * - "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.
  49221. */
  49222. Canvas2D.GetBrushFromString = function (brushString) {
  49223. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  49224. brushString = brushString.trim();
  49225. var split = brushString.split(",");
  49226. // Solid, formatted as: "[solid:]#FF808080"
  49227. if (split.length === 1) {
  49228. var value = null;
  49229. if (brushString.indexOf("solid:") === 0) {
  49230. value = brushString.substr(6).trim();
  49231. }
  49232. else if (brushString.indexOf("#") === 0) {
  49233. value = brushString;
  49234. }
  49235. else {
  49236. return null;
  49237. }
  49238. return Canvas2D.GetSolidColorBrushFromHex(value);
  49239. }
  49240. else {
  49241. if (split[0].indexOf("gradient:") === 0) {
  49242. split[0] = split[0].substr(9).trim();
  49243. }
  49244. try {
  49245. var start = BABYLON.Color4.FromHexString(split[0].trim());
  49246. var end = BABYLON.Color4.FromHexString(split[1].trim());
  49247. var t = BABYLON.Vector2.Zero();
  49248. if (split.length > 2) {
  49249. var v = split[2].trim();
  49250. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  49251. return null;
  49252. }
  49253. var sep = v.indexOf(":");
  49254. var x = parseFloat(v.substr(1, sep));
  49255. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  49256. t = new BABYLON.Vector2(x, y);
  49257. }
  49258. var r = 0;
  49259. if (split.length > 3) {
  49260. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  49261. }
  49262. var s = 1;
  49263. if (split.length > 4) {
  49264. s = parseFloat(split[4].trim());
  49265. }
  49266. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  49267. }
  49268. catch (e) {
  49269. return null;
  49270. }
  49271. }
  49272. };
  49273. /**
  49274. * 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.
  49275. * This strategy doesn't allow primitives added directly as children of the Canvas.
  49276. * 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.
  49277. */
  49278. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  49279. /**
  49280. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  49281. * 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.
  49282. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  49283. * 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.
  49284. */
  49285. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  49286. /**
  49287. * 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).
  49288. */
  49289. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  49290. /**
  49291. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  49292. * 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).
  49293. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  49294. */
  49295. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  49296. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  49297. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  49298. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  49299. Canvas2D._m = BABYLON.Matrix.Identity();
  49300. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  49301. Canvas2D._unS = new BABYLON.Vector2(1, 1);
  49302. /**
  49303. * Define the default size used for both the width and height of a MapTexture to allocate.
  49304. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  49305. */
  49306. Canvas2D._groupTextureCacheSize = 1024;
  49307. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  49308. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  49309. Canvas2D = __decorate([
  49310. BABYLON.className("Canvas2D")
  49311. ], Canvas2D);
  49312. return Canvas2D;
  49313. }(BABYLON.Group2D));
  49314. BABYLON.Canvas2D = Canvas2D;
  49315. var WorldSpaceCanvas2D = (function (_super) {
  49316. __extends(WorldSpaceCanvas2D, _super);
  49317. /**
  49318. * 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.
  49319. * 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.
  49320. * @param scene the Scene that owns the Canvas
  49321. * @param size the dimension of the Canvas in World Space
  49322. * @param settings a combination of settings, possible ones are
  49323. * - children: an array of direct children primitives
  49324. * - id: a text identifier, for information purpose only, default is null.
  49325. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  49326. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  49327. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  49328. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  49329. * - 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).
  49330. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49331. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49332. * - 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.
  49333. * - 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.
  49334. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49335. * - 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.
  49336. * - 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.
  49337. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49338. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49339. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49340. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  49341. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  49342. */
  49343. function WorldSpaceCanvas2D(scene, size, settings) {
  49344. var _this = this;
  49345. BABYLON.Prim2DBase._isCanvasInit = true;
  49346. var s = settings;
  49347. s.isScreenSpace = false;
  49348. s.size = size.clone();
  49349. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  49350. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  49351. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  49352. }
  49353. _super.call(this, scene, settings);
  49354. BABYLON.Prim2DBase._isCanvasInit = false;
  49355. this._renderableData._useMipMap = true;
  49356. this._renderableData._anisotropicLevel = 8;
  49357. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  49358. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  49359. //}
  49360. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  49361. var id = settings ? settings.id || null : null;
  49362. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  49363. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  49364. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  49365. if (settings.maxAdaptiveCanvasSize == null) {
  49366. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  49367. }
  49368. else {
  49369. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  49370. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  49371. }
  49372. if (createWorldSpaceNode) {
  49373. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  49374. var vertexData = BABYLON.VertexData.CreatePlane({
  49375. width: size.width,
  49376. height: size.height,
  49377. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  49378. });
  49379. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  49380. this.applyCachedTexture(vertexData, mtl);
  49381. vertexData.applyToMesh(plane, true);
  49382. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  49383. mtl.disableLighting = true;
  49384. mtl.useAlphaFromDiffuseTexture = true;
  49385. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  49386. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  49387. plane.material = mtl;
  49388. this._worldSpaceNode = plane;
  49389. }
  49390. else {
  49391. this._worldSpaceNode = settings.customWorldSpaceNode;
  49392. this.applyCachedTexture(null, null);
  49393. }
  49394. this.propertyChanged.add(function (e, st) {
  49395. var mesh = _this._worldSpaceNode;
  49396. if (mesh) {
  49397. mesh.isVisible = _this.isVisible;
  49398. }
  49399. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  49400. }
  49401. WorldSpaceCanvas2D = __decorate([
  49402. BABYLON.className("WorldSpaceCanvas2D")
  49403. ], WorldSpaceCanvas2D);
  49404. return WorldSpaceCanvas2D;
  49405. }(Canvas2D));
  49406. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  49407. var ScreenSpaceCanvas2D = (function (_super) {
  49408. __extends(ScreenSpaceCanvas2D, _super);
  49409. /**
  49410. * 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.
  49411. * 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.
  49412. * All caching strategies will be available.
  49413. * 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]
  49414. * @param scene the Scene that owns the Canvas
  49415. * @param settings a combination of settings, possible ones are
  49416. * - children: an array of direct children primitives
  49417. * - id: a text identifier, for information purpose only
  49418. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  49419. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  49420. * - 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]
  49421. * - width: the width of the Canvas. you can alternatively use the size setting.
  49422. * - height: the height of the Canvas. you can alternatively use the size setting.
  49423. * - 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
  49424. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  49425. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  49426. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  49427. * - 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.
  49428. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  49429. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  49430. * - 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.
  49431. * - 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.
  49432. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  49433. * - 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.
  49434. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49435. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49436. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49437. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  49438. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  49439. */
  49440. function ScreenSpaceCanvas2D(scene, settings) {
  49441. BABYLON.Prim2DBase._isCanvasInit = true;
  49442. _super.call(this, scene, settings);
  49443. }
  49444. ScreenSpaceCanvas2D = __decorate([
  49445. BABYLON.className("ScreenSpaceCanvas2D")
  49446. ], ScreenSpaceCanvas2D);
  49447. return ScreenSpaceCanvas2D;
  49448. }(Canvas2D));
  49449. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  49450. })(BABYLON || (BABYLON = {}));
  49451. var BABYLON;
  49452. (function (BABYLON) {
  49453. /**
  49454. * This is the class that is used to display a World Space Canvas into a 3D scene
  49455. */
  49456. var WorldSpaceCanvas2DNode = (function (_super) {
  49457. __extends(WorldSpaceCanvas2DNode, _super);
  49458. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  49459. _super.call(this, name, scene);
  49460. this._canvas = canvas;
  49461. }
  49462. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  49463. _super.prototype.dispose.call(this);
  49464. if (this._canvas) {
  49465. this._canvas.dispose();
  49466. this._canvas = null;
  49467. }
  49468. };
  49469. return WorldSpaceCanvas2DNode;
  49470. }(BABYLON.Mesh));
  49471. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  49472. })(BABYLON || (BABYLON = {}));
  49473. var BABYLON;
  49474. (function (BABYLON) {
  49475. var ShaderMaterial = (function (_super) {
  49476. __extends(ShaderMaterial, _super);
  49477. function ShaderMaterial(name, scene, shaderPath, options) {
  49478. _super.call(this, name, scene);
  49479. this._textures = {};
  49480. this._textureArrays = {};
  49481. this._floats = {};
  49482. this._floatsArrays = {};
  49483. this._colors3 = {};
  49484. this._colors4 = {};
  49485. this._vectors2 = {};
  49486. this._vectors3 = {};
  49487. this._vectors4 = {};
  49488. this._matrices = {};
  49489. this._matrices3x3 = {};
  49490. this._matrices2x2 = {};
  49491. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49492. this._shaderPath = shaderPath;
  49493. options.needAlphaBlending = options.needAlphaBlending || false;
  49494. options.needAlphaTesting = options.needAlphaTesting || false;
  49495. options.attributes = options.attributes || ["position", "normal", "uv"];
  49496. options.uniforms = options.uniforms || ["worldViewProjection"];
  49497. options.samplers = options.samplers || [];
  49498. options.defines = options.defines || [];
  49499. this._options = options;
  49500. }
  49501. ShaderMaterial.prototype.needAlphaBlending = function () {
  49502. return this._options.needAlphaBlending;
  49503. };
  49504. ShaderMaterial.prototype.needAlphaTesting = function () {
  49505. return this._options.needAlphaTesting;
  49506. };
  49507. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49508. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49509. this._options.uniforms.push(uniformName);
  49510. }
  49511. };
  49512. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49513. if (this._options.samplers.indexOf(name) === -1) {
  49514. this._options.samplers.push(name);
  49515. }
  49516. this._textures[name] = texture;
  49517. return this;
  49518. };
  49519. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49520. if (this._options.samplers.indexOf(name) === -1) {
  49521. this._options.samplers.push(name);
  49522. }
  49523. this._checkUniform(name);
  49524. this._textureArrays[name] = textures;
  49525. return this;
  49526. };
  49527. ShaderMaterial.prototype.setFloat = function (name, value) {
  49528. this._checkUniform(name);
  49529. this._floats[name] = value;
  49530. return this;
  49531. };
  49532. ShaderMaterial.prototype.setFloats = function (name, value) {
  49533. this._checkUniform(name);
  49534. this._floatsArrays[name] = value;
  49535. return this;
  49536. };
  49537. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49538. this._checkUniform(name);
  49539. this._colors3[name] = value;
  49540. return this;
  49541. };
  49542. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49543. this._checkUniform(name);
  49544. this._colors4[name] = value;
  49545. return this;
  49546. };
  49547. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49548. this._checkUniform(name);
  49549. this._vectors2[name] = value;
  49550. return this;
  49551. };
  49552. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49553. this._checkUniform(name);
  49554. this._vectors3[name] = value;
  49555. return this;
  49556. };
  49557. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49558. this._checkUniform(name);
  49559. this._vectors4[name] = value;
  49560. return this;
  49561. };
  49562. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49563. this._checkUniform(name);
  49564. this._matrices[name] = value;
  49565. return this;
  49566. };
  49567. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49568. this._checkUniform(name);
  49569. this._matrices3x3[name] = value;
  49570. return this;
  49571. };
  49572. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49573. this._checkUniform(name);
  49574. this._matrices2x2[name] = value;
  49575. return this;
  49576. };
  49577. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49578. var scene = this.getScene();
  49579. var engine = scene.getEngine();
  49580. if (!this.checkReadyOnEveryCall) {
  49581. if (this._renderId === scene.getRenderId()) {
  49582. return true;
  49583. }
  49584. }
  49585. // Instances
  49586. var defines = [];
  49587. var fallbacks = new BABYLON.EffectFallbacks();
  49588. if (useInstances) {
  49589. defines.push("#define INSTANCES");
  49590. }
  49591. for (var index = 0; index < this._options.defines.length; index++) {
  49592. defines.push(this._options.defines[index]);
  49593. }
  49594. // Bones
  49595. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49596. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49597. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49598. fallbacks.addCPUSkinningFallback(0, mesh);
  49599. }
  49600. // Alpha test
  49601. if (engine.getAlphaTesting()) {
  49602. defines.push("#define ALPHATEST");
  49603. }
  49604. var previousEffect = this._effect;
  49605. var join = defines.join("\n");
  49606. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  49607. if (!this._effect.isReady()) {
  49608. return false;
  49609. }
  49610. if (previousEffect !== this._effect) {
  49611. scene.resetCachedMaterial();
  49612. }
  49613. this._renderId = scene.getRenderId();
  49614. return true;
  49615. };
  49616. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49617. var scene = this.getScene();
  49618. if (this._options.uniforms.indexOf("world") !== -1) {
  49619. this._effect.setMatrix("world", world);
  49620. }
  49621. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49622. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49623. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49624. }
  49625. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49626. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49627. }
  49628. };
  49629. ShaderMaterial.prototype.bind = function (world, mesh) {
  49630. // Std values
  49631. this.bindOnlyWorldMatrix(world);
  49632. if (this.getScene().getCachedMaterial() !== this) {
  49633. if (this._options.uniforms.indexOf("view") !== -1) {
  49634. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49635. }
  49636. if (this._options.uniforms.indexOf("projection") !== -1) {
  49637. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49638. }
  49639. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49640. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49641. }
  49642. // Bones
  49643. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49644. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49645. }
  49646. var name;
  49647. // Texture
  49648. for (name in this._textures) {
  49649. this._effect.setTexture(name, this._textures[name]);
  49650. }
  49651. // Texture arrays
  49652. for (name in this._textureArrays) {
  49653. this._effect.setTextureArray(name, this._textureArrays[name]);
  49654. }
  49655. // Float
  49656. for (name in this._floats) {
  49657. this._effect.setFloat(name, this._floats[name]);
  49658. }
  49659. // Float s
  49660. for (name in this._floatsArrays) {
  49661. this._effect.setArray(name, this._floatsArrays[name]);
  49662. }
  49663. // Color3
  49664. for (name in this._colors3) {
  49665. this._effect.setColor3(name, this._colors3[name]);
  49666. }
  49667. // Color4
  49668. for (name in this._colors4) {
  49669. var color = this._colors4[name];
  49670. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49671. }
  49672. // Vector2
  49673. for (name in this._vectors2) {
  49674. this._effect.setVector2(name, this._vectors2[name]);
  49675. }
  49676. // Vector3
  49677. for (name in this._vectors3) {
  49678. this._effect.setVector3(name, this._vectors3[name]);
  49679. }
  49680. // Vector4
  49681. for (name in this._vectors4) {
  49682. this._effect.setVector4(name, this._vectors4[name]);
  49683. }
  49684. // Matrix
  49685. for (name in this._matrices) {
  49686. this._effect.setMatrix(name, this._matrices[name]);
  49687. }
  49688. // Matrix 3x3
  49689. for (name in this._matrices3x3) {
  49690. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49691. }
  49692. // Matrix 2x2
  49693. for (name in this._matrices2x2) {
  49694. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49695. }
  49696. }
  49697. _super.prototype.bind.call(this, world, mesh);
  49698. };
  49699. ShaderMaterial.prototype.clone = function (name) {
  49700. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49701. return newShaderMaterial;
  49702. };
  49703. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49704. if (forceDisposeTextures) {
  49705. var name;
  49706. for (name in this._textures) {
  49707. this._textures[name].dispose();
  49708. }
  49709. for (name in this._textureArrays) {
  49710. var array = this._textureArrays[name];
  49711. for (var index = 0; index < array.length; index++) {
  49712. array[index].dispose();
  49713. }
  49714. }
  49715. }
  49716. this._textures = {};
  49717. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49718. };
  49719. ShaderMaterial.prototype.serialize = function () {
  49720. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49721. serializationObject.customType = "BABYLON.ShaderMaterial";
  49722. serializationObject.options = this._options;
  49723. serializationObject.shaderPath = this._shaderPath;
  49724. var name;
  49725. // Texture
  49726. serializationObject.textures = {};
  49727. for (name in this._textures) {
  49728. serializationObject.textures[name] = this._textures[name].serialize();
  49729. }
  49730. // Texture arrays
  49731. serializationObject.textureArrays = {};
  49732. for (name in this._textureArrays) {
  49733. serializationObject.textureArrays[name] = [];
  49734. var array = this._textureArrays[name];
  49735. for (var index = 0; index < array.length; index++) {
  49736. serializationObject.textureArrays[name].push(array[index].serialize());
  49737. }
  49738. }
  49739. // Float
  49740. serializationObject.floats = {};
  49741. for (name in this._floats) {
  49742. serializationObject.floats[name] = this._floats[name];
  49743. }
  49744. // Float s
  49745. serializationObject.floatArrays = {};
  49746. for (name in this._floatsArrays) {
  49747. serializationObject.floatArrays[name] = this._floatsArrays[name];
  49748. }
  49749. // Color3
  49750. serializationObject.colors3 = {};
  49751. for (name in this._colors3) {
  49752. serializationObject.colors3[name] = this._colors3[name].asArray();
  49753. }
  49754. // Color4
  49755. serializationObject.colors4 = {};
  49756. for (name in this._colors4) {
  49757. serializationObject.colors4[name] = this._colors4[name].asArray();
  49758. }
  49759. // Vector2
  49760. serializationObject.vectors2 = {};
  49761. for (name in this._vectors2) {
  49762. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  49763. }
  49764. // Vector3
  49765. serializationObject.vectors3 = {};
  49766. for (name in this._vectors3) {
  49767. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  49768. }
  49769. // Vector4
  49770. serializationObject.vectors4 = {};
  49771. for (name in this._vectors4) {
  49772. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  49773. }
  49774. // Matrix
  49775. serializationObject.matrices = {};
  49776. for (name in this._matrices) {
  49777. serializationObject.matrices[name] = this._matrices[name].asArray();
  49778. }
  49779. // Matrix 3x3
  49780. serializationObject.matrices3x3 = {};
  49781. for (name in this._matrices3x3) {
  49782. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  49783. }
  49784. // Matrix 2x2
  49785. serializationObject.matrices2x2 = {};
  49786. for (name in this._matrices2x2) {
  49787. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  49788. }
  49789. return serializationObject;
  49790. };
  49791. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  49792. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  49793. var name;
  49794. // Texture
  49795. for (name in source.textures) {
  49796. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  49797. }
  49798. // Texture arrays
  49799. for (name in source.textureArrays) {
  49800. var array = source.textureArrays[name];
  49801. var textureArray = new Array();
  49802. for (var index = 0; index < array.length; index++) {
  49803. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  49804. }
  49805. material.setTextureArray(name, textureArray);
  49806. }
  49807. // Float
  49808. for (name in source.floats) {
  49809. material.setFloat(name, source.floats[name]);
  49810. }
  49811. // Float s
  49812. for (name in source.floatsArrays) {
  49813. material.setFloats(name, source.floatsArrays[name]);
  49814. }
  49815. // Color3
  49816. for (name in source.colors3) {
  49817. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49818. }
  49819. // Color4
  49820. for (name in source.colors4) {
  49821. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49822. }
  49823. // Vector2
  49824. for (name in source.vectors2) {
  49825. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49826. }
  49827. // Vector3
  49828. for (name in source.vectors3) {
  49829. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49830. }
  49831. // Vector4
  49832. for (name in source.vectors4) {
  49833. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49834. }
  49835. // Matrix
  49836. for (name in source.matrices) {
  49837. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49838. }
  49839. // Matrix 3x3
  49840. for (name in source.matrices3x3) {
  49841. material.setMatrix3x3(name, source.matrices3x3[name]);
  49842. }
  49843. // Matrix 2x2
  49844. for (name in source.matrices2x2) {
  49845. material.setMatrix2x2(name, source.matrices2x2[name]);
  49846. }
  49847. return material;
  49848. };
  49849. return ShaderMaterial;
  49850. }(BABYLON.Material));
  49851. BABYLON.ShaderMaterial = ShaderMaterial;
  49852. })(BABYLON || (BABYLON = {}));
  49853. var BABYLON;
  49854. (function (BABYLON) {
  49855. var Internals;
  49856. (function (Internals) {
  49857. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49858. // All values and structures referenced from:
  49859. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49860. var DDS_MAGIC = 0x20534444;
  49861. 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;
  49862. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49863. 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;
  49864. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49865. function FourCCToInt32(value) {
  49866. return value.charCodeAt(0) +
  49867. (value.charCodeAt(1) << 8) +
  49868. (value.charCodeAt(2) << 16) +
  49869. (value.charCodeAt(3) << 24);
  49870. }
  49871. function Int32ToFourCC(value) {
  49872. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49873. }
  49874. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49875. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49876. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49877. var headerLengthInt = 31; // The header length in 32 bit ints
  49878. // Offsets into the header array
  49879. var off_magic = 0;
  49880. var off_size = 1;
  49881. var off_flags = 2;
  49882. var off_height = 3;
  49883. var off_width = 4;
  49884. var off_mipmapCount = 7;
  49885. var off_pfFlags = 20;
  49886. var off_pfFourCC = 21;
  49887. var off_RGBbpp = 22;
  49888. var off_RMask = 23;
  49889. var off_GMask = 24;
  49890. var off_BMask = 25;
  49891. var off_AMask = 26;
  49892. var off_caps1 = 27;
  49893. var off_caps2 = 28;
  49894. ;
  49895. var DDSTools = (function () {
  49896. function DDSTools() {
  49897. }
  49898. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49899. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49900. var mipmapCount = 1;
  49901. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49902. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49903. }
  49904. return {
  49905. width: header[off_width],
  49906. height: header[off_height],
  49907. mipmapCount: mipmapCount,
  49908. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49909. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49910. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49911. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49912. };
  49913. };
  49914. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49915. var byteArray = new Uint8Array(dataLength);
  49916. var srcData = new Uint8Array(arrayBuffer);
  49917. var index = 0;
  49918. for (var y = height - 1; y >= 0; y--) {
  49919. for (var x = 0; x < width; x++) {
  49920. var srcPos = dataOffset + (x + y * width) * 4;
  49921. byteArray[index + 2] = srcData[srcPos];
  49922. byteArray[index + 1] = srcData[srcPos + 1];
  49923. byteArray[index] = srcData[srcPos + 2];
  49924. byteArray[index + 3] = srcData[srcPos + 3];
  49925. index += 4;
  49926. }
  49927. }
  49928. return byteArray;
  49929. };
  49930. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49931. var byteArray = new Uint8Array(dataLength);
  49932. var srcData = new Uint8Array(arrayBuffer);
  49933. var index = 0;
  49934. for (var y = height - 1; y >= 0; y--) {
  49935. for (var x = 0; x < width; x++) {
  49936. var srcPos = dataOffset + (x + y * width) * 3;
  49937. byteArray[index + 2] = srcData[srcPos];
  49938. byteArray[index + 1] = srcData[srcPos + 1];
  49939. byteArray[index] = srcData[srcPos + 2];
  49940. index += 3;
  49941. }
  49942. }
  49943. return byteArray;
  49944. };
  49945. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49946. var byteArray = new Uint8Array(dataLength);
  49947. var srcData = new Uint8Array(arrayBuffer);
  49948. var index = 0;
  49949. for (var y = height - 1; y >= 0; y--) {
  49950. for (var x = 0; x < width; x++) {
  49951. var srcPos = dataOffset + (x + y * width);
  49952. byteArray[index] = srcData[srcPos];
  49953. index++;
  49954. }
  49955. }
  49956. return byteArray;
  49957. };
  49958. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49959. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49960. if (header[off_magic] != DDS_MAGIC) {
  49961. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49962. return;
  49963. }
  49964. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49965. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49966. return;
  49967. }
  49968. if (info.isFourCC) {
  49969. fourCC = header[off_pfFourCC];
  49970. switch (fourCC) {
  49971. case FOURCC_DXT1:
  49972. blockBytes = 8;
  49973. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49974. break;
  49975. case FOURCC_DXT3:
  49976. blockBytes = 16;
  49977. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49978. break;
  49979. case FOURCC_DXT5:
  49980. blockBytes = 16;
  49981. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49982. break;
  49983. default:
  49984. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49985. return;
  49986. }
  49987. }
  49988. mipmapCount = 1;
  49989. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49990. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49991. }
  49992. var bpp = header[off_RGBbpp];
  49993. for (var face = 0; face < faces; face++) {
  49994. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49995. width = header[off_width];
  49996. height = header[off_height];
  49997. dataOffset = header[off_size] + 4;
  49998. for (i = 0; i < mipmapCount; ++i) {
  49999. if (info.isRGB) {
  50000. if (bpp === 24) {
  50001. dataLength = width * height * 3;
  50002. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  50003. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  50004. }
  50005. else {
  50006. dataLength = width * height * 4;
  50007. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  50008. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  50009. }
  50010. }
  50011. else if (info.isLuminance) {
  50012. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  50013. var unpaddedRowSize = width;
  50014. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  50015. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  50016. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  50017. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  50018. }
  50019. else {
  50020. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  50021. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  50022. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  50023. }
  50024. dataOffset += dataLength;
  50025. width *= 0.5;
  50026. height *= 0.5;
  50027. width = Math.max(1.0, width);
  50028. height = Math.max(1.0, height);
  50029. }
  50030. }
  50031. };
  50032. return DDSTools;
  50033. }());
  50034. Internals.DDSTools = DDSTools;
  50035. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50036. })(BABYLON || (BABYLON = {}));
  50037. var BABYLON;
  50038. (function (BABYLON) {
  50039. var CannonJSPlugin = (function () {
  50040. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  50041. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  50042. if (iterations === void 0) { iterations = 10; }
  50043. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  50044. this.name = "CannonJSPlugin";
  50045. this._physicsMaterials = [];
  50046. this._fixedTimeStep = 1 / 60;
  50047. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  50048. this._currentCollisionGroup = 2;
  50049. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  50050. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  50051. this._tmpPosition = BABYLON.Vector3.Zero();
  50052. this._tmpQuaternion = new BABYLON.Quaternion();
  50053. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  50054. this._tmpDeltaRotation = new BABYLON.Quaternion();
  50055. this._tmpUnityRotation = new BABYLON.Quaternion();
  50056. if (!this.isSupported()) {
  50057. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  50058. return;
  50059. }
  50060. this.world = new CANNON.World();
  50061. this.world.broadphase = new CANNON.NaiveBroadphase();
  50062. this.world.solver.iterations = iterations;
  50063. }
  50064. CannonJSPlugin.prototype.setGravity = function (gravity) {
  50065. this.world.gravity.copy(gravity);
  50066. };
  50067. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  50068. this._fixedTimeStep = timeStep;
  50069. };
  50070. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  50071. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  50072. };
  50073. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50074. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  50075. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  50076. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  50077. };
  50078. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  50079. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  50080. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  50081. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  50082. };
  50083. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  50084. //parent-child relationship. Does this impostor has a parent impostor?
  50085. if (impostor.parent) {
  50086. if (impostor.physicsBody) {
  50087. this.removePhysicsBody(impostor);
  50088. //TODO is that needed?
  50089. impostor.forceUpdate();
  50090. }
  50091. return;
  50092. }
  50093. //should a new body be created for this impostor?
  50094. if (impostor.isBodyInitRequired()) {
  50095. var shape = this._createShape(impostor);
  50096. //unregister events, if body is being changed
  50097. var oldBody = impostor.physicsBody;
  50098. if (oldBody) {
  50099. this.removePhysicsBody(impostor);
  50100. }
  50101. //create the body and material
  50102. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  50103. var bodyCreationObject = {
  50104. mass: impostor.getParam("mass"),
  50105. material: material
  50106. };
  50107. // A simple extend, in case native options were used.
  50108. var nativeOptions = impostor.getParam("nativeOptions");
  50109. for (var key in nativeOptions) {
  50110. if (nativeOptions.hasOwnProperty(key)) {
  50111. bodyCreationObject[key] = nativeOptions[key];
  50112. }
  50113. }
  50114. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  50115. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  50116. this.world.addEventListener("preStep", impostor.beforeStep);
  50117. this.world.addEventListener("postStep", impostor.afterStep);
  50118. impostor.physicsBody.addShape(shape);
  50119. this.world.add(impostor.physicsBody);
  50120. //try to keep the body moving in the right direction by taking old properties.
  50121. //Should be tested!
  50122. if (oldBody) {
  50123. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  50124. impostor.physicsBody[param].copy(oldBody[param]);
  50125. });
  50126. }
  50127. this._processChildMeshes(impostor);
  50128. }
  50129. //now update the body's transformation
  50130. this._updatePhysicsBodyTransformation(impostor);
  50131. };
  50132. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  50133. var _this = this;
  50134. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  50135. if (meshChildren.length) {
  50136. var processMesh = function (localPosition, mesh) {
  50137. var childImpostor = mesh.getPhysicsImpostor();
  50138. if (childImpostor) {
  50139. var parent = childImpostor.parent;
  50140. if (parent !== mainImpostor) {
  50141. var localPosition = mesh.position;
  50142. if (childImpostor.physicsBody) {
  50143. _this.removePhysicsBody(childImpostor);
  50144. childImpostor.physicsBody = null;
  50145. }
  50146. childImpostor.parent = mainImpostor;
  50147. childImpostor.resetUpdateFlags();
  50148. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  50149. //Add the mass of the children.
  50150. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  50151. }
  50152. }
  50153. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  50154. };
  50155. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  50156. }
  50157. };
  50158. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50159. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  50160. this.world.removeEventListener("preStep", impostor.beforeStep);
  50161. this.world.removeEventListener("postStep", impostor.afterStep);
  50162. this.world.remove(impostor.physicsBody);
  50163. };
  50164. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50165. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50166. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50167. if (!mainBody || !connectedBody) {
  50168. return;
  50169. }
  50170. var constraint;
  50171. var jointData = impostorJoint.joint.jointData;
  50172. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  50173. var constraintData = {
  50174. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  50175. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  50176. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  50177. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  50178. maxForce: jointData.nativeParams.maxForce,
  50179. collideConnected: !!jointData.collision
  50180. };
  50181. //Not needed, Cannon has a collideConnected flag
  50182. /*if (!jointData.collision) {
  50183. //add 1st body to a collision group of its own, if it is not in 1
  50184. if (mainBody.collisionFilterGroup === 1) {
  50185. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  50186. this._currentCollisionGroup <<= 1;
  50187. }
  50188. if (connectedBody.collisionFilterGroup === 1) {
  50189. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  50190. this._currentCollisionGroup <<= 1;
  50191. }
  50192. //add their mask to the collisionFilterMask of each other:
  50193. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  50194. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  50195. }*/
  50196. switch (impostorJoint.joint.type) {
  50197. case BABYLON.PhysicsJoint.HingeJoint:
  50198. case BABYLON.PhysicsJoint.Hinge2Joint:
  50199. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  50200. break;
  50201. case BABYLON.PhysicsJoint.DistanceJoint:
  50202. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  50203. break;
  50204. case BABYLON.PhysicsJoint.SpringJoint:
  50205. var springData = jointData;
  50206. constraint = new CANNON.Spring(mainBody, connectedBody, {
  50207. restLength: springData.length,
  50208. stiffness: springData.stiffness,
  50209. damping: springData.damping,
  50210. localAnchorA: constraintData.pivotA,
  50211. localAnchorB: constraintData.pivotB
  50212. });
  50213. break;
  50214. case BABYLON.PhysicsJoint.LockJoint:
  50215. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  50216. break;
  50217. case BABYLON.PhysicsJoint.PointToPointJoint:
  50218. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50219. default:
  50220. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  50221. break;
  50222. }
  50223. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  50224. constraint.collideConnected = !!jointData.collision;
  50225. impostorJoint.joint.physicsJoint = constraint;
  50226. //don't add spring as constraint, as it is not one.
  50227. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  50228. this.world.addConstraint(constraint);
  50229. }
  50230. else {
  50231. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  50232. constraint.applyForce();
  50233. });
  50234. }
  50235. };
  50236. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50237. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  50238. };
  50239. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  50240. var index;
  50241. var mat;
  50242. for (index = 0; index < this._physicsMaterials.length; index++) {
  50243. mat = this._physicsMaterials[index];
  50244. if (mat.friction === friction && mat.restitution === restitution) {
  50245. return mat;
  50246. }
  50247. }
  50248. var currentMat = new CANNON.Material(name);
  50249. currentMat.friction = friction;
  50250. currentMat.restitution = restitution;
  50251. this._physicsMaterials.push(currentMat);
  50252. return currentMat;
  50253. };
  50254. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  50255. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  50256. };
  50257. CannonJSPlugin.prototype._createShape = function (impostor) {
  50258. var object = impostor.object;
  50259. var returnValue;
  50260. var extendSize = impostor.getObjectExtendSize();
  50261. switch (impostor.type) {
  50262. case BABYLON.PhysicsEngine.SphereImpostor:
  50263. var radiusX = extendSize.x;
  50264. var radiusY = extendSize.y;
  50265. var radiusZ = extendSize.z;
  50266. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  50267. break;
  50268. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  50269. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50270. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  50271. break;
  50272. case BABYLON.PhysicsImpostor.BoxImpostor:
  50273. var box = extendSize.scale(0.5);
  50274. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  50275. break;
  50276. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50277. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  50278. returnValue = new CANNON.Plane();
  50279. break;
  50280. case BABYLON.PhysicsImpostor.MeshImpostor:
  50281. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  50282. var rawFaces = object.getIndices ? object.getIndices() : [];
  50283. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  50284. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  50285. break;
  50286. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  50287. returnValue = this._createHeightmap(object);
  50288. break;
  50289. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50290. returnValue = new CANNON.Particle();
  50291. break;
  50292. }
  50293. return returnValue;
  50294. };
  50295. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  50296. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50297. var matrix = [];
  50298. //For now pointDepth will not be used and will be automatically calculated.
  50299. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  50300. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  50301. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  50302. var elementSize = dim * 2 / arraySize;
  50303. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  50304. for (var i = 0; i < pos.length; i = i + 3) {
  50305. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  50306. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  50307. var y = pos[i + 1] + minY;
  50308. if (!matrix[x]) {
  50309. matrix[x] = [];
  50310. }
  50311. if (!matrix[x][z]) {
  50312. matrix[x][z] = y;
  50313. }
  50314. matrix[x][z] = Math.max(y, matrix[x][z]);
  50315. }
  50316. for (var x = 0; x <= arraySize; ++x) {
  50317. if (!matrix[x]) {
  50318. var loc = 1;
  50319. while (!matrix[(x + loc) % arraySize]) {
  50320. loc++;
  50321. }
  50322. matrix[x] = matrix[(x + loc) % arraySize].slice();
  50323. }
  50324. for (var z = 0; z <= arraySize; ++z) {
  50325. if (!matrix[x][z]) {
  50326. var loc = 1;
  50327. var newValue;
  50328. while (newValue === undefined) {
  50329. newValue = matrix[x][(z + loc++) % arraySize];
  50330. }
  50331. matrix[x][z] = newValue;
  50332. }
  50333. }
  50334. }
  50335. var shape = new CANNON.Heightfield(matrix, {
  50336. elementSize: elementSize
  50337. });
  50338. //For future reference, needed for body transformation
  50339. shape.minY = minY;
  50340. return shape;
  50341. };
  50342. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  50343. var object = impostor.object;
  50344. //make sure it is updated...
  50345. object.computeWorldMatrix && object.computeWorldMatrix(true);
  50346. // The delta between the mesh position and the mesh bounding box center
  50347. var center = impostor.getObjectCenter();
  50348. var extendSize = impostor.getObjectExtendSize();
  50349. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  50350. this._tmpPosition.copyFrom(center);
  50351. var quaternion = object.rotationQuaternion;
  50352. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  50353. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  50354. //-90 DEG in X, precalculated
  50355. quaternion = quaternion.multiply(this._minus90X);
  50356. //Invert! (Precalculated, 90 deg in X)
  50357. //No need to clone. this will never change.
  50358. impostor.setDeltaRotation(this._plus90X);
  50359. }
  50360. //If it is a heightfield, if should be centered.
  50361. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  50362. var mesh = object;
  50363. //calculate the correct body position:
  50364. var rotationQuaternion = mesh.rotationQuaternion;
  50365. mesh.rotationQuaternion = this._tmpUnityRotation;
  50366. mesh.computeWorldMatrix(true);
  50367. //get original center with no rotation
  50368. var c = center.clone();
  50369. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  50370. //rotation is back
  50371. mesh.rotationQuaternion = rotationQuaternion;
  50372. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  50373. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  50374. mesh.setPivotMatrix(p);
  50375. mesh.computeWorldMatrix(true);
  50376. //calculate the translation
  50377. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  50378. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  50379. //add it inverted to the delta
  50380. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  50381. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  50382. mesh.setPivotMatrix(oldPivot);
  50383. mesh.computeWorldMatrix(true);
  50384. }
  50385. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  50386. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  50387. this._tmpPosition.copyFrom(object.position);
  50388. }
  50389. impostor.setDeltaPosition(this._tmpDeltaPosition);
  50390. //Now update the impostor object
  50391. impostor.physicsBody.position.copy(this._tmpPosition);
  50392. impostor.physicsBody.quaternion.copy(quaternion);
  50393. };
  50394. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50395. impostor.object.position.copyFrom(impostor.physicsBody.position);
  50396. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  50397. };
  50398. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50399. impostor.physicsBody.position.copy(newPosition);
  50400. impostor.physicsBody.quaternion.copy(newRotation);
  50401. };
  50402. CannonJSPlugin.prototype.isSupported = function () {
  50403. return window.CANNON !== undefined;
  50404. };
  50405. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50406. impostor.physicsBody.velocity.copy(velocity);
  50407. };
  50408. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50409. impostor.physicsBody.angularVelocity.copy(velocity);
  50410. };
  50411. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50412. var v = impostor.physicsBody.velocity;
  50413. if (!v)
  50414. return null;
  50415. return new BABYLON.Vector3(v.x, v.y, v.z);
  50416. };
  50417. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50418. var v = impostor.physicsBody.angularVelocity;
  50419. if (!v)
  50420. return null;
  50421. return new BABYLON.Vector3(v.x, v.y, v.z);
  50422. };
  50423. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50424. impostor.physicsBody.mass = mass;
  50425. impostor.physicsBody.updateMassProperties();
  50426. };
  50427. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  50428. impostor.physicsBody.sleep();
  50429. };
  50430. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  50431. impostor.physicsBody.wakeUp();
  50432. };
  50433. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50434. joint.physicsJoint.distance = maxDistance;
  50435. };
  50436. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  50437. if (!motorIndex) {
  50438. joint.physicsJoint.enableMotor();
  50439. }
  50440. };
  50441. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  50442. if (!motorIndex) {
  50443. joint.physicsJoint.disableMotor();
  50444. }
  50445. };
  50446. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50447. if (!motorIndex) {
  50448. joint.physicsJoint.enableMotor();
  50449. joint.physicsJoint.setMotorSpeed(speed);
  50450. if (maxForce) {
  50451. this.setLimit(joint, maxForce);
  50452. }
  50453. }
  50454. };
  50455. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  50456. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  50457. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  50458. };
  50459. CannonJSPlugin.prototype.dispose = function () {
  50460. //nothing to do, actually.
  50461. };
  50462. return CannonJSPlugin;
  50463. }());
  50464. BABYLON.CannonJSPlugin = CannonJSPlugin;
  50465. })(BABYLON || (BABYLON = {}));
  50466. var BABYLON;
  50467. (function (BABYLON) {
  50468. var OimoJSPlugin = (function () {
  50469. function OimoJSPlugin(iterations) {
  50470. this.name = "OimoJSPlugin";
  50471. this._tmpImpostorsArray = [];
  50472. this._tmpPositionVector = BABYLON.Vector3.Zero();
  50473. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  50474. this.world.clear();
  50475. //making sure no stats are calculated
  50476. this.world.isNoStat = true;
  50477. }
  50478. OimoJSPlugin.prototype.setGravity = function (gravity) {
  50479. this.world.gravity.copy(gravity);
  50480. };
  50481. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  50482. this.world.timeStep = timeStep;
  50483. };
  50484. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  50485. var _this = this;
  50486. impostors.forEach(function (impostor) {
  50487. impostor.beforeStep();
  50488. });
  50489. this.world.step();
  50490. impostors.forEach(function (impostor) {
  50491. impostor.afterStep();
  50492. //update the ordered impostors array
  50493. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  50494. });
  50495. //check for collisions
  50496. var contact = this.world.contacts;
  50497. while (contact !== null) {
  50498. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  50499. contact = contact.next;
  50500. continue;
  50501. }
  50502. //is this body colliding with any other? get the impostor
  50503. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  50504. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  50505. if (!mainImpostor || !collidingImpostor) {
  50506. contact = contact.next;
  50507. continue;
  50508. }
  50509. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  50510. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  50511. contact = contact.next;
  50512. }
  50513. };
  50514. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50515. var mass = impostor.physicsBody.massInfo.mass;
  50516. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  50517. };
  50518. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  50519. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  50520. this.applyImpulse(impostor, force, contactPoint);
  50521. };
  50522. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  50523. var _this = this;
  50524. //parent-child relationship. Does this impostor has a parent impostor?
  50525. if (impostor.parent) {
  50526. if (impostor.physicsBody) {
  50527. this.removePhysicsBody(impostor);
  50528. //TODO is that needed?
  50529. impostor.forceUpdate();
  50530. }
  50531. return;
  50532. }
  50533. if (impostor.isBodyInitRequired()) {
  50534. var bodyConfig = {
  50535. name: impostor.uniqueId,
  50536. //Oimo must have mass, also for static objects.
  50537. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  50538. size: [],
  50539. type: [],
  50540. pos: [],
  50541. rot: [],
  50542. move: impostor.getParam("mass") !== 0,
  50543. //Supporting older versions of Oimo
  50544. world: this.world
  50545. };
  50546. var impostors = [impostor];
  50547. var addToArray = function (parent) {
  50548. if (!parent.getChildMeshes)
  50549. return;
  50550. parent.getChildMeshes().forEach(function (m) {
  50551. if (m.physicsImpostor) {
  50552. impostors.push(m.physicsImpostor);
  50553. m.physicsImpostor._init();
  50554. }
  50555. });
  50556. };
  50557. addToArray(impostor.object);
  50558. var checkWithEpsilon_1 = function (value) {
  50559. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  50560. };
  50561. impostors.forEach(function (i) {
  50562. //get the correct bounding box
  50563. var oldQuaternion = i.object.rotationQuaternion;
  50564. var rot = new OIMO.Euler().setFromQuaternion({
  50565. x: impostor.object.rotationQuaternion.x,
  50566. y: impostor.object.rotationQuaternion.y,
  50567. z: impostor.object.rotationQuaternion.z,
  50568. s: impostor.object.rotationQuaternion.w
  50569. });
  50570. var extendSize = i.getObjectExtendSize();
  50571. if (i === impostor) {
  50572. var center = impostor.getObjectCenter();
  50573. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  50574. //Can also use Array.prototype.push.apply
  50575. bodyConfig.pos.push(center.x);
  50576. bodyConfig.pos.push(center.y);
  50577. bodyConfig.pos.push(center.z);
  50578. //tmp solution
  50579. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  50580. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  50581. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  50582. }
  50583. else {
  50584. bodyConfig.pos.push(i.object.position.x);
  50585. bodyConfig.pos.push(i.object.position.y);
  50586. bodyConfig.pos.push(i.object.position.z);
  50587. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  50588. bodyConfig.rot.push(0);
  50589. bodyConfig.rot.push(0);
  50590. bodyConfig.rot.push(0);
  50591. }
  50592. // register mesh
  50593. switch (i.type) {
  50594. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50595. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  50596. case BABYLON.PhysicsImpostor.SphereImpostor:
  50597. var radiusX = extendSize.x;
  50598. var radiusY = extendSize.y;
  50599. var radiusZ = extendSize.z;
  50600. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  50601. bodyConfig.type.push('sphere');
  50602. //due to the way oimo works with compounds, add 3 times
  50603. bodyConfig.size.push(size);
  50604. bodyConfig.size.push(size);
  50605. bodyConfig.size.push(size);
  50606. break;
  50607. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50608. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  50609. var sizeY = checkWithEpsilon_1(extendSize.y);
  50610. bodyConfig.type.push('cylinder');
  50611. bodyConfig.size.push(sizeX);
  50612. bodyConfig.size.push(sizeY);
  50613. //due to the way oimo works with compounds, add one more value.
  50614. bodyConfig.size.push(sizeY);
  50615. break;
  50616. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50617. case BABYLON.PhysicsImpostor.BoxImpostor:
  50618. default:
  50619. var sizeX = checkWithEpsilon_1(extendSize.x);
  50620. var sizeY = checkWithEpsilon_1(extendSize.y);
  50621. var sizeZ = checkWithEpsilon_1(extendSize.z);
  50622. bodyConfig.type.push('box');
  50623. bodyConfig.size.push(sizeX);
  50624. bodyConfig.size.push(sizeY);
  50625. bodyConfig.size.push(sizeZ);
  50626. break;
  50627. }
  50628. //actually not needed, but hey...
  50629. i.object.rotationQuaternion = oldQuaternion;
  50630. });
  50631. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  50632. }
  50633. else {
  50634. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  50635. }
  50636. impostor.setDeltaPosition(this._tmpPositionVector);
  50637. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  50638. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  50639. };
  50640. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50641. //impostor.physicsBody.dispose();
  50642. //Same as : (older oimo versions)
  50643. this.world.removeRigidBody(impostor.physicsBody);
  50644. };
  50645. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50646. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50647. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50648. if (!mainBody || !connectedBody) {
  50649. return;
  50650. }
  50651. var jointData = impostorJoint.joint.jointData;
  50652. var options = jointData.nativeParams || {};
  50653. var type;
  50654. var nativeJointData = {
  50655. body1: mainBody,
  50656. body2: connectedBody,
  50657. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  50658. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  50659. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  50660. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  50661. min: options.min,
  50662. max: options.max,
  50663. collision: options.collision || jointData.collision,
  50664. spring: options.spring,
  50665. //supporting older version of Oimo
  50666. world: this.world
  50667. };
  50668. switch (impostorJoint.joint.type) {
  50669. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50670. type = "jointBall";
  50671. break;
  50672. case BABYLON.PhysicsJoint.SpringJoint:
  50673. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  50674. var springData = jointData;
  50675. nativeJointData.min = springData.length || nativeJointData.min;
  50676. //Max should also be set, just make sure it is at least min
  50677. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  50678. case BABYLON.PhysicsJoint.DistanceJoint:
  50679. type = "jointDistance";
  50680. nativeJointData.max = jointData.maxDistance;
  50681. break;
  50682. case BABYLON.PhysicsJoint.PrismaticJoint:
  50683. type = "jointPrisme";
  50684. break;
  50685. case BABYLON.PhysicsJoint.SliderJoint:
  50686. type = "jointSlide";
  50687. break;
  50688. case BABYLON.PhysicsJoint.WheelJoint:
  50689. type = "jointWheel";
  50690. break;
  50691. case BABYLON.PhysicsJoint.HingeJoint:
  50692. default:
  50693. type = "jointHinge";
  50694. break;
  50695. }
  50696. nativeJointData.type = type;
  50697. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  50698. };
  50699. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50700. //Bug in Oimo prevents us from disposing a joint in the playground
  50701. //joint.joint.physicsJoint.dispose();
  50702. //So we will bruteforce it!
  50703. try {
  50704. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  50705. }
  50706. catch (e) {
  50707. BABYLON.Tools.Warn(e);
  50708. }
  50709. };
  50710. OimoJSPlugin.prototype.isSupported = function () {
  50711. return OIMO !== undefined;
  50712. };
  50713. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50714. if (!impostor.physicsBody.sleeping) {
  50715. //TODO check that
  50716. if (impostor.physicsBody.shapes.next) {
  50717. var parentShape = this._getLastShape(impostor.physicsBody);
  50718. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  50719. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  50720. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  50721. }
  50722. else {
  50723. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  50724. }
  50725. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  50726. impostor.object.rotationQuaternion.normalize();
  50727. }
  50728. };
  50729. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50730. var body = impostor.physicsBody;
  50731. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  50732. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  50733. body.syncShapes();
  50734. body.awake();
  50735. };
  50736. OimoJSPlugin.prototype._getLastShape = function (body) {
  50737. var lastShape = body.shapes;
  50738. while (lastShape.next) {
  50739. lastShape = lastShape.next;
  50740. }
  50741. return lastShape;
  50742. };
  50743. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50744. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  50745. };
  50746. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50747. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  50748. };
  50749. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50750. var v = impostor.physicsBody.linearVelocity;
  50751. if (!v)
  50752. return null;
  50753. return new BABYLON.Vector3(v.x, v.y, v.z);
  50754. };
  50755. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50756. var v = impostor.physicsBody.angularVelocity;
  50757. if (!v)
  50758. return null;
  50759. return new BABYLON.Vector3(v.x, v.y, v.z);
  50760. };
  50761. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50762. var staticBody = mass === 0;
  50763. //this will actually set the body's density and not its mass.
  50764. //But this is how oimo treats the mass variable.
  50765. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  50766. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  50767. };
  50768. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  50769. impostor.physicsBody.sleep();
  50770. };
  50771. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  50772. impostor.physicsBody.awake();
  50773. };
  50774. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50775. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  50776. if (minDistance !== void 0) {
  50777. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  50778. }
  50779. };
  50780. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50781. //TODO separate rotational and transational motors.
  50782. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50783. if (motor) {
  50784. motor.setMotor(speed, maxForce);
  50785. }
  50786. };
  50787. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  50788. //TODO separate rotational and transational motors.
  50789. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50790. if (motor) {
  50791. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  50792. }
  50793. };
  50794. OimoJSPlugin.prototype.dispose = function () {
  50795. this.world.clear();
  50796. };
  50797. return OimoJSPlugin;
  50798. }());
  50799. BABYLON.OimoJSPlugin = OimoJSPlugin;
  50800. })(BABYLON || (BABYLON = {}));
  50801. var BABYLON;
  50802. (function (BABYLON) {
  50803. var DisplayPassPostProcess = (function (_super) {
  50804. __extends(DisplayPassPostProcess, _super);
  50805. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50806. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  50807. }
  50808. return DisplayPassPostProcess;
  50809. }(BABYLON.PostProcess));
  50810. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50811. })(BABYLON || (BABYLON = {}));
  50812. var BABYLON;
  50813. (function (BABYLON) {
  50814. var SimplificationSettings = (function () {
  50815. function SimplificationSettings(quality, distance, optimizeMesh) {
  50816. this.quality = quality;
  50817. this.distance = distance;
  50818. this.optimizeMesh = optimizeMesh;
  50819. }
  50820. return SimplificationSettings;
  50821. }());
  50822. BABYLON.SimplificationSettings = SimplificationSettings;
  50823. var SimplificationQueue = (function () {
  50824. function SimplificationQueue() {
  50825. this.running = false;
  50826. this._simplificationArray = [];
  50827. }
  50828. SimplificationQueue.prototype.addTask = function (task) {
  50829. this._simplificationArray.push(task);
  50830. };
  50831. SimplificationQueue.prototype.executeNext = function () {
  50832. var task = this._simplificationArray.pop();
  50833. if (task) {
  50834. this.running = true;
  50835. this.runSimplification(task);
  50836. }
  50837. else {
  50838. this.running = false;
  50839. }
  50840. };
  50841. SimplificationQueue.prototype.runSimplification = function (task) {
  50842. var _this = this;
  50843. if (task.parallelProcessing) {
  50844. //parallel simplifier
  50845. task.settings.forEach(function (setting) {
  50846. var simplifier = _this.getSimplifier(task);
  50847. simplifier.simplify(setting, function (newMesh) {
  50848. task.mesh.addLODLevel(setting.distance, newMesh);
  50849. newMesh.isVisible = true;
  50850. //check if it is the last
  50851. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50852. //all done, run the success callback.
  50853. task.successCallback();
  50854. }
  50855. _this.executeNext();
  50856. });
  50857. });
  50858. }
  50859. else {
  50860. //single simplifier.
  50861. var simplifier = this.getSimplifier(task);
  50862. var runDecimation = function (setting, callback) {
  50863. simplifier.simplify(setting, function (newMesh) {
  50864. task.mesh.addLODLevel(setting.distance, newMesh);
  50865. newMesh.isVisible = true;
  50866. //run the next quality level
  50867. callback();
  50868. });
  50869. };
  50870. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50871. runDecimation(task.settings[loop.index], function () {
  50872. loop.executeNext();
  50873. });
  50874. }, function () {
  50875. //execution ended, run the success callback.
  50876. if (task.successCallback) {
  50877. task.successCallback();
  50878. }
  50879. _this.executeNext();
  50880. });
  50881. }
  50882. };
  50883. SimplificationQueue.prototype.getSimplifier = function (task) {
  50884. switch (task.simplificationType) {
  50885. case SimplificationType.QUADRATIC:
  50886. default:
  50887. return new QuadraticErrorSimplification(task.mesh);
  50888. }
  50889. };
  50890. return SimplificationQueue;
  50891. }());
  50892. BABYLON.SimplificationQueue = SimplificationQueue;
  50893. /**
  50894. * The implemented types of simplification.
  50895. * At the moment only Quadratic Error Decimation is implemented.
  50896. */
  50897. (function (SimplificationType) {
  50898. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50899. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50900. var SimplificationType = BABYLON.SimplificationType;
  50901. var DecimationTriangle = (function () {
  50902. function DecimationTriangle(vertices) {
  50903. this.vertices = vertices;
  50904. this.error = new Array(4);
  50905. this.deleted = false;
  50906. this.isDirty = false;
  50907. this.deletePending = false;
  50908. this.borderFactor = 0;
  50909. }
  50910. return DecimationTriangle;
  50911. }());
  50912. BABYLON.DecimationTriangle = DecimationTriangle;
  50913. var DecimationVertex = (function () {
  50914. function DecimationVertex(position, id) {
  50915. this.position = position;
  50916. this.id = id;
  50917. this.isBorder = true;
  50918. this.q = new QuadraticMatrix();
  50919. this.triangleCount = 0;
  50920. this.triangleStart = 0;
  50921. this.originalOffsets = [];
  50922. }
  50923. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50924. this.position.copyFrom(newPosition);
  50925. };
  50926. return DecimationVertex;
  50927. }());
  50928. BABYLON.DecimationVertex = DecimationVertex;
  50929. var QuadraticMatrix = (function () {
  50930. function QuadraticMatrix(data) {
  50931. this.data = new Array(10);
  50932. for (var i = 0; i < 10; ++i) {
  50933. if (data && data[i]) {
  50934. this.data[i] = data[i];
  50935. }
  50936. else {
  50937. this.data[i] = 0;
  50938. }
  50939. }
  50940. }
  50941. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50942. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50943. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50944. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50945. return det;
  50946. };
  50947. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50948. for (var i = 0; i < 10; ++i) {
  50949. this.data[i] += matrix.data[i];
  50950. }
  50951. };
  50952. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50953. for (var i = 0; i < 10; ++i) {
  50954. this.data[i] += data[i];
  50955. }
  50956. };
  50957. QuadraticMatrix.prototype.add = function (matrix) {
  50958. var m = new QuadraticMatrix();
  50959. for (var i = 0; i < 10; ++i) {
  50960. m.data[i] = this.data[i] + matrix.data[i];
  50961. }
  50962. return m;
  50963. };
  50964. QuadraticMatrix.FromData = function (a, b, c, d) {
  50965. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50966. };
  50967. //returning an array to avoid garbage collection
  50968. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50969. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50970. };
  50971. return QuadraticMatrix;
  50972. }());
  50973. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50974. var Reference = (function () {
  50975. function Reference(vertexId, triangleId) {
  50976. this.vertexId = vertexId;
  50977. this.triangleId = triangleId;
  50978. }
  50979. return Reference;
  50980. }());
  50981. BABYLON.Reference = Reference;
  50982. /**
  50983. * An implementation of the Quadratic Error simplification algorithm.
  50984. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50985. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50986. * @author RaananW
  50987. */
  50988. var QuadraticErrorSimplification = (function () {
  50989. function QuadraticErrorSimplification(_mesh) {
  50990. this._mesh = _mesh;
  50991. this.initialized = false;
  50992. this.syncIterations = 5000;
  50993. this.aggressiveness = 7;
  50994. this.decimationIterations = 100;
  50995. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50996. }
  50997. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50998. var _this = this;
  50999. this.initDecimatedMesh();
  51000. //iterating through the submeshes array, one after the other.
  51001. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  51002. _this.initWithMesh(loop.index, function () {
  51003. _this.runDecimation(settings, loop.index, function () {
  51004. loop.executeNext();
  51005. });
  51006. }, settings.optimizeMesh);
  51007. }, function () {
  51008. setTimeout(function () {
  51009. successCallback(_this._reconstructedMesh);
  51010. }, 0);
  51011. });
  51012. };
  51013. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  51014. var _this = this;
  51015. var gCount = 0;
  51016. triangle.vertices.forEach(function (vertex) {
  51017. var count = 0;
  51018. var vPos = vertex.position;
  51019. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  51020. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  51021. ++count;
  51022. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  51023. ++count;
  51024. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  51025. ++count;
  51026. if (count > 1) {
  51027. ++gCount;
  51028. }
  51029. ;
  51030. });
  51031. if (gCount > 1) {
  51032. console.log(triangle, gCount);
  51033. }
  51034. return gCount > 1;
  51035. };
  51036. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  51037. var _this = this;
  51038. var targetCount = ~~(this.triangles.length * settings.quality);
  51039. var deletedTriangles = 0;
  51040. var triangleCount = this.triangles.length;
  51041. var iterationFunction = function (iteration, callback) {
  51042. setTimeout(function () {
  51043. if (iteration % 5 === 0) {
  51044. _this.updateMesh(iteration === 0);
  51045. }
  51046. for (var i = 0; i < _this.triangles.length; ++i) {
  51047. _this.triangles[i].isDirty = false;
  51048. }
  51049. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  51050. var trianglesIterator = function (i) {
  51051. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  51052. var t = _this.triangles[tIdx];
  51053. if (!t)
  51054. return;
  51055. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  51056. return;
  51057. }
  51058. for (var j = 0; j < 3; ++j) {
  51059. if (t.error[j] < threshold) {
  51060. var deleted0 = [];
  51061. var deleted1 = [];
  51062. var v0 = t.vertices[j];
  51063. var v1 = t.vertices[(j + 1) % 3];
  51064. if (v0.isBorder || v1.isBorder)
  51065. continue;
  51066. var p = BABYLON.Vector3.Zero();
  51067. var n = BABYLON.Vector3.Zero();
  51068. var uv = BABYLON.Vector2.Zero();
  51069. var color = new BABYLON.Color4(0, 0, 0, 1);
  51070. _this.calculateError(v0, v1, p, n, uv, color);
  51071. var delTr = [];
  51072. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  51073. continue;
  51074. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  51075. continue;
  51076. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  51077. continue;
  51078. var uniqueArray = [];
  51079. delTr.forEach(function (deletedT) {
  51080. if (uniqueArray.indexOf(deletedT) === -1) {
  51081. deletedT.deletePending = true;
  51082. uniqueArray.push(deletedT);
  51083. }
  51084. });
  51085. if (uniqueArray.length % 2 !== 0) {
  51086. continue;
  51087. }
  51088. v0.q = v1.q.add(v0.q);
  51089. v0.updatePosition(p);
  51090. var tStart = _this.references.length;
  51091. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  51092. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  51093. var tCount = _this.references.length - tStart;
  51094. if (tCount <= v0.triangleCount) {
  51095. if (tCount) {
  51096. for (var c = 0; c < tCount; c++) {
  51097. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  51098. }
  51099. }
  51100. }
  51101. else {
  51102. v0.triangleStart = tStart;
  51103. }
  51104. v0.triangleCount = tCount;
  51105. break;
  51106. }
  51107. }
  51108. };
  51109. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  51110. }, 0);
  51111. };
  51112. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  51113. if (triangleCount - deletedTriangles <= targetCount)
  51114. loop.breakLoop();
  51115. else {
  51116. iterationFunction(loop.index, function () {
  51117. loop.executeNext();
  51118. });
  51119. }
  51120. }, function () {
  51121. setTimeout(function () {
  51122. //reconstruct this part of the mesh
  51123. _this.reconstructMesh(submeshIndex);
  51124. successCallback();
  51125. }, 0);
  51126. });
  51127. };
  51128. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  51129. var _this = this;
  51130. this.vertices = [];
  51131. this.triangles = [];
  51132. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51133. var indices = this._mesh.getIndices();
  51134. var submesh = this._mesh.subMeshes[submeshIndex];
  51135. var findInVertices = function (positionToSearch) {
  51136. if (optimizeMesh) {
  51137. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  51138. if (_this.vertices[ii].position.equals(positionToSearch)) {
  51139. return _this.vertices[ii];
  51140. }
  51141. }
  51142. }
  51143. return null;
  51144. };
  51145. var vertexReferences = [];
  51146. var vertexInit = function (i) {
  51147. var offset = i + submesh.verticesStart;
  51148. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  51149. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  51150. vertex.originalOffsets.push(offset);
  51151. if (vertex.id === _this.vertices.length) {
  51152. _this.vertices.push(vertex);
  51153. }
  51154. vertexReferences.push(vertex.id);
  51155. };
  51156. //var totalVertices = mesh.getTotalVertices();
  51157. var totalVertices = submesh.verticesCount;
  51158. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  51159. var indicesInit = function (i) {
  51160. var offset = (submesh.indexStart / 3) + i;
  51161. var pos = (offset * 3);
  51162. var i0 = indices[pos + 0];
  51163. var i1 = indices[pos + 1];
  51164. var i2 = indices[pos + 2];
  51165. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  51166. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  51167. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  51168. var triangle = new DecimationTriangle([v0, v1, v2]);
  51169. triangle.originalOffset = pos;
  51170. _this.triangles.push(triangle);
  51171. };
  51172. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  51173. _this.init(callback);
  51174. });
  51175. });
  51176. };
  51177. QuadraticErrorSimplification.prototype.init = function (callback) {
  51178. var _this = this;
  51179. var triangleInit1 = function (i) {
  51180. var t = _this.triangles[i];
  51181. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  51182. for (var j = 0; j < 3; j++) {
  51183. 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))));
  51184. }
  51185. };
  51186. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  51187. var triangleInit2 = function (i) {
  51188. var t = _this.triangles[i];
  51189. for (var j = 0; j < 3; ++j) {
  51190. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  51191. }
  51192. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51193. };
  51194. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  51195. _this.initialized = true;
  51196. callback();
  51197. });
  51198. });
  51199. };
  51200. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  51201. var newTriangles = [];
  51202. var i;
  51203. for (i = 0; i < this.vertices.length; ++i) {
  51204. this.vertices[i].triangleCount = 0;
  51205. }
  51206. var t;
  51207. var j;
  51208. for (i = 0; i < this.triangles.length; ++i) {
  51209. if (!this.triangles[i].deleted) {
  51210. t = this.triangles[i];
  51211. for (j = 0; j < 3; ++j) {
  51212. t.vertices[j].triangleCount = 1;
  51213. }
  51214. newTriangles.push(t);
  51215. }
  51216. }
  51217. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  51218. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  51219. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  51220. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  51221. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51222. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51223. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51224. var vertexCount = 0;
  51225. for (i = 0; i < this.vertices.length; ++i) {
  51226. var vertex = this.vertices[i];
  51227. vertex.id = vertexCount;
  51228. if (vertex.triangleCount) {
  51229. vertex.originalOffsets.forEach(function (originalOffset) {
  51230. newPositionData.push(vertex.position.x);
  51231. newPositionData.push(vertex.position.y);
  51232. newPositionData.push(vertex.position.z);
  51233. newNormalData.push(normalData[originalOffset * 3]);
  51234. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  51235. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  51236. if (uvs && uvs.length) {
  51237. newUVsData.push(uvs[(originalOffset * 2)]);
  51238. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  51239. }
  51240. else if (colorsData && colorsData.length) {
  51241. newColorsData.push(colorsData[(originalOffset * 4)]);
  51242. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  51243. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  51244. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  51245. }
  51246. ++vertexCount;
  51247. });
  51248. }
  51249. }
  51250. var startingIndex = this._reconstructedMesh.getTotalIndices();
  51251. var startingVertex = this._reconstructedMesh.getTotalVertices();
  51252. var submeshesArray = this._reconstructedMesh.subMeshes;
  51253. this._reconstructedMesh.subMeshes = [];
  51254. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  51255. var originalIndices = this._mesh.getIndices();
  51256. for (i = 0; i < newTriangles.length; ++i) {
  51257. t = newTriangles[i]; //now get the new referencing point for each vertex
  51258. [0, 1, 2].forEach(function (idx) {
  51259. var id = originalIndices[t.originalOffset + idx];
  51260. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  51261. if (offset < 0)
  51262. offset = 0;
  51263. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  51264. });
  51265. }
  51266. //overwriting the old vertex buffers and indices.
  51267. this._reconstructedMesh.setIndices(newIndicesArray);
  51268. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  51269. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  51270. if (newUVsData.length > 0)
  51271. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  51272. if (newColorsData.length > 0)
  51273. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  51274. //create submesh
  51275. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  51276. if (submeshIndex > 0) {
  51277. this._reconstructedMesh.subMeshes = [];
  51278. submeshesArray.forEach(function (submesh) {
  51279. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  51280. });
  51281. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  51282. }
  51283. };
  51284. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  51285. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  51286. this._reconstructedMesh.material = this._mesh.material;
  51287. this._reconstructedMesh.parent = this._mesh.parent;
  51288. this._reconstructedMesh.isVisible = false;
  51289. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  51290. };
  51291. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  51292. for (var i = 0; i < vertex1.triangleCount; ++i) {
  51293. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  51294. if (t.deleted)
  51295. continue;
  51296. var s = this.references[vertex1.triangleStart + i].vertexId;
  51297. var v1 = t.vertices[(s + 1) % 3];
  51298. var v2 = t.vertices[(s + 2) % 3];
  51299. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  51300. deletedArray[i] = true;
  51301. delTr.push(t);
  51302. continue;
  51303. }
  51304. var d1 = v1.position.subtract(point);
  51305. d1 = d1.normalize();
  51306. var d2 = v2.position.subtract(point);
  51307. d2 = d2.normalize();
  51308. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  51309. return true;
  51310. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  51311. deletedArray[i] = false;
  51312. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  51313. return true;
  51314. }
  51315. return false;
  51316. };
  51317. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  51318. var newDeleted = deletedTriangles;
  51319. for (var i = 0; i < vertex.triangleCount; ++i) {
  51320. var ref = this.references[vertex.triangleStart + i];
  51321. var t = this.triangles[ref.triangleId];
  51322. if (t.deleted)
  51323. continue;
  51324. if (deletedArray[i] && t.deletePending) {
  51325. t.deleted = true;
  51326. newDeleted++;
  51327. continue;
  51328. }
  51329. t.vertices[ref.vertexId] = origVertex;
  51330. t.isDirty = true;
  51331. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  51332. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  51333. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  51334. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51335. this.references.push(ref);
  51336. }
  51337. return newDeleted;
  51338. };
  51339. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  51340. for (var i = 0; i < this.vertices.length; ++i) {
  51341. var vCount = [];
  51342. var vId = [];
  51343. var v = this.vertices[i];
  51344. var j;
  51345. for (j = 0; j < v.triangleCount; ++j) {
  51346. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  51347. for (var ii = 0; ii < 3; ii++) {
  51348. var ofs = 0;
  51349. var vv = triangle.vertices[ii];
  51350. while (ofs < vCount.length) {
  51351. if (vId[ofs] === vv.id)
  51352. break;
  51353. ++ofs;
  51354. }
  51355. if (ofs === vCount.length) {
  51356. vCount.push(1);
  51357. vId.push(vv.id);
  51358. }
  51359. else {
  51360. vCount[ofs]++;
  51361. }
  51362. }
  51363. }
  51364. for (j = 0; j < vCount.length; ++j) {
  51365. if (vCount[j] === 1) {
  51366. this.vertices[vId[j]].isBorder = true;
  51367. }
  51368. else {
  51369. this.vertices[vId[j]].isBorder = false;
  51370. }
  51371. }
  51372. }
  51373. };
  51374. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  51375. if (identifyBorders === void 0) { identifyBorders = false; }
  51376. var i;
  51377. if (!identifyBorders) {
  51378. var newTrianglesVector = [];
  51379. for (i = 0; i < this.triangles.length; ++i) {
  51380. if (!this.triangles[i].deleted) {
  51381. newTrianglesVector.push(this.triangles[i]);
  51382. }
  51383. }
  51384. this.triangles = newTrianglesVector;
  51385. }
  51386. for (i = 0; i < this.vertices.length; ++i) {
  51387. this.vertices[i].triangleCount = 0;
  51388. this.vertices[i].triangleStart = 0;
  51389. }
  51390. var t;
  51391. var j;
  51392. var v;
  51393. for (i = 0; i < this.triangles.length; ++i) {
  51394. t = this.triangles[i];
  51395. for (j = 0; j < 3; ++j) {
  51396. v = t.vertices[j];
  51397. v.triangleCount++;
  51398. }
  51399. }
  51400. var tStart = 0;
  51401. for (i = 0; i < this.vertices.length; ++i) {
  51402. this.vertices[i].triangleStart = tStart;
  51403. tStart += this.vertices[i].triangleCount;
  51404. this.vertices[i].triangleCount = 0;
  51405. }
  51406. var newReferences = new Array(this.triangles.length * 3);
  51407. for (i = 0; i < this.triangles.length; ++i) {
  51408. t = this.triangles[i];
  51409. for (j = 0; j < 3; ++j) {
  51410. v = t.vertices[j];
  51411. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  51412. v.triangleCount++;
  51413. }
  51414. }
  51415. this.references = newReferences;
  51416. if (identifyBorders) {
  51417. this.identifyBorder();
  51418. }
  51419. };
  51420. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  51421. var x = point.x;
  51422. var y = point.y;
  51423. var z = point.z;
  51424. 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
  51425. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  51426. };
  51427. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  51428. var q = vertex1.q.add(vertex2.q);
  51429. var border = vertex1.isBorder && vertex2.isBorder;
  51430. var error = 0;
  51431. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  51432. if (qDet !== 0 && !border) {
  51433. if (!pointResult) {
  51434. pointResult = BABYLON.Vector3.Zero();
  51435. }
  51436. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  51437. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  51438. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  51439. error = this.vertexError(q, pointResult);
  51440. }
  51441. else {
  51442. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  51443. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  51444. var error1 = this.vertexError(q, vertex1.position);
  51445. var error2 = this.vertexError(q, vertex2.position);
  51446. var error3 = this.vertexError(q, p3);
  51447. error = Math.min(error1, error2, error3);
  51448. if (error === error1) {
  51449. if (pointResult) {
  51450. pointResult.copyFrom(vertex1.position);
  51451. }
  51452. }
  51453. else if (error === error2) {
  51454. if (pointResult) {
  51455. pointResult.copyFrom(vertex2.position);
  51456. }
  51457. }
  51458. else {
  51459. if (pointResult) {
  51460. pointResult.copyFrom(p3);
  51461. }
  51462. }
  51463. }
  51464. return error;
  51465. };
  51466. return QuadraticErrorSimplification;
  51467. }());
  51468. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  51469. })(BABYLON || (BABYLON = {}));
  51470. var BABYLON;
  51471. (function (BABYLON) {
  51472. var serializedGeometries = [];
  51473. var serializeGeometry = function (geometry, serializationGeometries) {
  51474. if (serializedGeometries[geometry.id]) {
  51475. return;
  51476. }
  51477. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  51478. serializationGeometries.boxes.push(geometry.serialize());
  51479. }
  51480. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  51481. serializationGeometries.spheres.push(geometry.serialize());
  51482. }
  51483. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  51484. serializationGeometries.cylinders.push(geometry.serialize());
  51485. }
  51486. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  51487. serializationGeometries.toruses.push(geometry.serialize());
  51488. }
  51489. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  51490. serializationGeometries.grounds.push(geometry.serialize());
  51491. }
  51492. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  51493. serializationGeometries.planes.push(geometry.serialize());
  51494. }
  51495. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  51496. serializationGeometries.torusKnots.push(geometry.serialize());
  51497. }
  51498. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  51499. throw new Error("Unknown primitive type");
  51500. }
  51501. else {
  51502. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  51503. }
  51504. serializedGeometries[geometry.id] = true;
  51505. };
  51506. var serializeMesh = function (mesh, serializationScene) {
  51507. var serializationObject = {};
  51508. serializationObject.name = mesh.name;
  51509. serializationObject.id = mesh.id;
  51510. if (BABYLON.Tags.HasTags(mesh)) {
  51511. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  51512. }
  51513. serializationObject.position = mesh.position.asArray();
  51514. if (mesh.rotationQuaternion) {
  51515. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  51516. }
  51517. else if (mesh.rotation) {
  51518. serializationObject.rotation = mesh.rotation.asArray();
  51519. }
  51520. serializationObject.scaling = mesh.scaling.asArray();
  51521. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  51522. serializationObject.isEnabled = mesh.isEnabled();
  51523. serializationObject.isVisible = mesh.isVisible;
  51524. serializationObject.infiniteDistance = mesh.infiniteDistance;
  51525. serializationObject.pickable = mesh.isPickable;
  51526. serializationObject.receiveShadows = mesh.receiveShadows;
  51527. serializationObject.billboardMode = mesh.billboardMode;
  51528. serializationObject.visibility = mesh.visibility;
  51529. serializationObject.checkCollisions = mesh.checkCollisions;
  51530. // Parent
  51531. if (mesh.parent) {
  51532. serializationObject.parentId = mesh.parent.id;
  51533. }
  51534. // Geometry
  51535. var geometry = mesh._geometry;
  51536. if (geometry) {
  51537. var geometryId = geometry.id;
  51538. serializationObject.geometryId = geometryId;
  51539. if (!mesh.getScene().getGeometryByID(geometryId)) {
  51540. // 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
  51541. serializeGeometry(geometry, serializationScene.geometries);
  51542. }
  51543. // SubMeshes
  51544. serializationObject.subMeshes = [];
  51545. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51546. var subMesh = mesh.subMeshes[subIndex];
  51547. serializationObject.subMeshes.push({
  51548. materialIndex: subMesh.materialIndex,
  51549. verticesStart: subMesh.verticesStart,
  51550. verticesCount: subMesh.verticesCount,
  51551. indexStart: subMesh.indexStart,
  51552. indexCount: subMesh.indexCount
  51553. });
  51554. }
  51555. }
  51556. // Material
  51557. if (mesh.material) {
  51558. serializationObject.materialId = mesh.material.id;
  51559. }
  51560. else {
  51561. mesh.material = null;
  51562. }
  51563. // Skeleton
  51564. if (mesh.skeleton) {
  51565. serializationObject.skeletonId = mesh.skeleton.id;
  51566. }
  51567. // Physics
  51568. //TODO implement correct serialization for physics impostors.
  51569. if (mesh.getPhysicsImpostor()) {
  51570. serializationObject.physicsMass = mesh.getPhysicsMass();
  51571. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  51572. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  51573. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  51574. }
  51575. // Instances
  51576. serializationObject.instances = [];
  51577. for (var index = 0; index < mesh.instances.length; index++) {
  51578. var instance = mesh.instances[index];
  51579. var serializationInstance = {
  51580. name: instance.name,
  51581. position: instance.position.asArray(),
  51582. scaling: instance.scaling.asArray()
  51583. };
  51584. if (instance.rotationQuaternion) {
  51585. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  51586. }
  51587. else if (instance.rotation) {
  51588. serializationInstance.rotation = instance.rotation.asArray();
  51589. }
  51590. serializationObject.instances.push(serializationInstance);
  51591. // Animations
  51592. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  51593. serializationInstance.ranges = instance.serializeAnimationRanges();
  51594. }
  51595. // Animations
  51596. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  51597. serializationObject.ranges = mesh.serializeAnimationRanges();
  51598. // Layer mask
  51599. serializationObject.layerMask = mesh.layerMask;
  51600. // Action Manager
  51601. if (mesh.actionManager) {
  51602. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  51603. }
  51604. return serializationObject;
  51605. };
  51606. var finalizeSingleMesh = function (mesh, serializationObject) {
  51607. //only works if the mesh is already loaded
  51608. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51609. //serialize material
  51610. if (mesh.material) {
  51611. if (mesh.material instanceof BABYLON.StandardMaterial) {
  51612. serializationObject.materials = serializationObject.materials || [];
  51613. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51614. serializationObject.materials.push(mesh.material.serialize());
  51615. }
  51616. }
  51617. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  51618. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  51619. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51620. serializationObject.multiMaterials.push(mesh.material.serialize());
  51621. }
  51622. }
  51623. }
  51624. //serialize geometry
  51625. var geometry = mesh._geometry;
  51626. if (geometry) {
  51627. if (!serializationObject.geometries) {
  51628. serializationObject.geometries = {};
  51629. serializationObject.geometries.boxes = [];
  51630. serializationObject.geometries.spheres = [];
  51631. serializationObject.geometries.cylinders = [];
  51632. serializationObject.geometries.toruses = [];
  51633. serializationObject.geometries.grounds = [];
  51634. serializationObject.geometries.planes = [];
  51635. serializationObject.geometries.torusKnots = [];
  51636. serializationObject.geometries.vertexData = [];
  51637. }
  51638. serializeGeometry(geometry, serializationObject.geometries);
  51639. }
  51640. // Skeletons
  51641. if (mesh.skeleton) {
  51642. serializationObject.skeletons = serializationObject.skeletons || [];
  51643. serializationObject.skeletons.push(mesh.skeleton.serialize());
  51644. }
  51645. //serialize the actual mesh
  51646. serializationObject.meshes = serializationObject.meshes || [];
  51647. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51648. }
  51649. };
  51650. var SceneSerializer = (function () {
  51651. function SceneSerializer() {
  51652. }
  51653. SceneSerializer.ClearCache = function () {
  51654. serializedGeometries = [];
  51655. };
  51656. SceneSerializer.Serialize = function (scene) {
  51657. var serializationObject = {};
  51658. // Scene
  51659. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  51660. serializationObject.autoClear = scene.autoClear;
  51661. serializationObject.clearColor = scene.clearColor.asArray();
  51662. serializationObject.ambientColor = scene.ambientColor.asArray();
  51663. serializationObject.gravity = scene.gravity.asArray();
  51664. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  51665. serializationObject.workerCollisions = scene.workerCollisions;
  51666. // Fog
  51667. if (scene.fogMode && scene.fogMode !== 0) {
  51668. serializationObject.fogMode = scene.fogMode;
  51669. serializationObject.fogColor = scene.fogColor.asArray();
  51670. serializationObject.fogStart = scene.fogStart;
  51671. serializationObject.fogEnd = scene.fogEnd;
  51672. serializationObject.fogDensity = scene.fogDensity;
  51673. }
  51674. //Physics
  51675. if (scene.isPhysicsEnabled()) {
  51676. serializationObject.physicsEnabled = true;
  51677. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  51678. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  51679. }
  51680. // Lights
  51681. serializationObject.lights = [];
  51682. var index;
  51683. var light;
  51684. for (index = 0; index < scene.lights.length; index++) {
  51685. light = scene.lights[index];
  51686. serializationObject.lights.push(light.serialize());
  51687. }
  51688. // Cameras
  51689. serializationObject.cameras = [];
  51690. for (index = 0; index < scene.cameras.length; index++) {
  51691. var camera = scene.cameras[index];
  51692. serializationObject.cameras.push(camera.serialize());
  51693. }
  51694. if (scene.activeCamera) {
  51695. serializationObject.activeCameraID = scene.activeCamera.id;
  51696. }
  51697. // Animations
  51698. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  51699. // Materials
  51700. serializationObject.materials = [];
  51701. serializationObject.multiMaterials = [];
  51702. var material;
  51703. for (index = 0; index < scene.materials.length; index++) {
  51704. material = scene.materials[index];
  51705. serializationObject.materials.push(material.serialize());
  51706. }
  51707. // MultiMaterials
  51708. serializationObject.multiMaterials = [];
  51709. for (index = 0; index < scene.multiMaterials.length; index++) {
  51710. var multiMaterial = scene.multiMaterials[index];
  51711. serializationObject.multiMaterials.push(multiMaterial.serialize());
  51712. }
  51713. // Skeletons
  51714. serializationObject.skeletons = [];
  51715. for (index = 0; index < scene.skeletons.length; index++) {
  51716. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  51717. }
  51718. // Geometries
  51719. serializationObject.geometries = {};
  51720. serializationObject.geometries.boxes = [];
  51721. serializationObject.geometries.spheres = [];
  51722. serializationObject.geometries.cylinders = [];
  51723. serializationObject.geometries.toruses = [];
  51724. serializationObject.geometries.grounds = [];
  51725. serializationObject.geometries.planes = [];
  51726. serializationObject.geometries.torusKnots = [];
  51727. serializationObject.geometries.vertexData = [];
  51728. serializedGeometries = [];
  51729. var geometries = scene.getGeometries();
  51730. for (index = 0; index < geometries.length; index++) {
  51731. var geometry = geometries[index];
  51732. if (geometry.isReady()) {
  51733. serializeGeometry(geometry, serializationObject.geometries);
  51734. }
  51735. }
  51736. // Meshes
  51737. serializationObject.meshes = [];
  51738. for (index = 0; index < scene.meshes.length; index++) {
  51739. var abstractMesh = scene.meshes[index];
  51740. if (abstractMesh instanceof BABYLON.Mesh) {
  51741. var mesh = abstractMesh;
  51742. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51743. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51744. }
  51745. }
  51746. }
  51747. // Particles Systems
  51748. serializationObject.particleSystems = [];
  51749. for (index = 0; index < scene.particleSystems.length; index++) {
  51750. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  51751. }
  51752. // Lens flares
  51753. serializationObject.lensFlareSystems = [];
  51754. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  51755. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  51756. }
  51757. // Shadows
  51758. serializationObject.shadowGenerators = [];
  51759. for (index = 0; index < scene.lights.length; index++) {
  51760. light = scene.lights[index];
  51761. var shadowGenerator = light.getShadowGenerator();
  51762. // Only support serialization for official generator so far.
  51763. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  51764. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  51765. }
  51766. }
  51767. // Action Manager
  51768. if (scene.actionManager) {
  51769. serializationObject.actions = scene.actionManager.serialize("scene");
  51770. }
  51771. // Audio
  51772. serializationObject.sounds = [];
  51773. for (index = 0; index < scene.soundTracks.length; index++) {
  51774. var soundtrack = scene.soundTracks[index];
  51775. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  51776. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  51777. }
  51778. }
  51779. return serializationObject;
  51780. };
  51781. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  51782. if (withParents === void 0) { withParents = false; }
  51783. if (withChildren === void 0) { withChildren = false; }
  51784. var serializationObject = {};
  51785. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  51786. if (withParents || withChildren) {
  51787. //deliberate for loop! not for each, appended should be processed as well.
  51788. for (var i = 0; i < toSerialize.length; ++i) {
  51789. if (withChildren) {
  51790. toSerialize[i].getDescendants().forEach(function (node) {
  51791. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  51792. toSerialize.push(node);
  51793. }
  51794. });
  51795. }
  51796. //make sure the array doesn't contain the object already
  51797. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  51798. toSerialize.push(toSerialize[i].parent);
  51799. }
  51800. }
  51801. }
  51802. toSerialize.forEach(function (mesh) {
  51803. finalizeSingleMesh(mesh, serializationObject);
  51804. });
  51805. return serializationObject;
  51806. };
  51807. return SceneSerializer;
  51808. }());
  51809. BABYLON.SceneSerializer = SceneSerializer;
  51810. })(BABYLON || (BABYLON = {}));
  51811. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51812. // Huge respect for a such great lib.
  51813. // Earcut license:
  51814. // Copyright (c) 2016, Mapbox
  51815. //
  51816. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51817. // with or without fee is hereby granted, provided that the above copyright notice
  51818. // and this permission notice appear in all copies.
  51819. //
  51820. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51821. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51822. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51823. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51824. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51825. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51826. // THIS SOFTWARE.
  51827. var Earcut;
  51828. (function (Earcut) {
  51829. /**
  51830. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51831. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51832. * @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).
  51833. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51834. */
  51835. function earcut(data, holeIndices, dim) {
  51836. dim = dim || 2;
  51837. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51838. if (!outerNode)
  51839. return triangles;
  51840. var minX, minY, maxX, maxY, x, y, size;
  51841. if (hasHoles)
  51842. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51843. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51844. if (data.length > 80 * dim) {
  51845. minX = maxX = data[0];
  51846. minY = maxY = data[1];
  51847. for (var i = dim; i < outerLen; i += dim) {
  51848. x = data[i];
  51849. y = data[i + 1];
  51850. if (x < minX)
  51851. minX = x;
  51852. if (y < minY)
  51853. minY = y;
  51854. if (x > maxX)
  51855. maxX = x;
  51856. if (y > maxY)
  51857. maxY = y;
  51858. }
  51859. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51860. size = Math.max(maxX - minX, maxY - minY);
  51861. }
  51862. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51863. return triangles;
  51864. }
  51865. Earcut.earcut = earcut;
  51866. // create a circular doubly linked list from polygon points in the specified winding order
  51867. function linkedList(data, start, end, dim, clockwise) {
  51868. var i, last;
  51869. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51870. for (i = start; i < end; i += dim)
  51871. last = insertNode(i, data[i], data[i + 1], last);
  51872. }
  51873. else {
  51874. for (i = end - dim; i >= start; i -= dim)
  51875. last = insertNode(i, data[i], data[i + 1], last);
  51876. }
  51877. if (last && equals(last, last.next)) {
  51878. removeNode(last);
  51879. last = last.next;
  51880. }
  51881. return last;
  51882. }
  51883. // eliminate colinear or duplicate points
  51884. function filterPoints(start, end) {
  51885. if (!start)
  51886. return start;
  51887. if (!end)
  51888. end = start;
  51889. var p = start, again;
  51890. do {
  51891. again = false;
  51892. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51893. removeNode(p);
  51894. p = end = p.prev;
  51895. if (p === p.next)
  51896. return null;
  51897. again = true;
  51898. }
  51899. else {
  51900. p = p.next;
  51901. }
  51902. } while (again || p !== end);
  51903. return end;
  51904. }
  51905. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51906. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51907. if (!ear)
  51908. return;
  51909. // interlink polygon nodes in z-order
  51910. if (!pass && size)
  51911. indexCurve(ear, minX, minY, size);
  51912. var stop = ear, prev, next;
  51913. // iterate through ears, slicing them one by one
  51914. while (ear.prev !== ear.next) {
  51915. prev = ear.prev;
  51916. next = ear.next;
  51917. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51918. // cut off the triangle
  51919. triangles.push(prev.i / dim);
  51920. triangles.push(ear.i / dim);
  51921. triangles.push(next.i / dim);
  51922. removeNode(ear);
  51923. // skipping the next vertice leads to less sliver triangles
  51924. ear = next.next;
  51925. stop = next.next;
  51926. continue;
  51927. }
  51928. ear = next;
  51929. // if we looped through the whole remaining polygon and can't find any more ears
  51930. if (ear === stop) {
  51931. // try filtering points and slicing again
  51932. if (!pass) {
  51933. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51934. }
  51935. else if (pass === 1) {
  51936. ear = cureLocalIntersections(ear, triangles, dim);
  51937. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51938. }
  51939. else if (pass === 2) {
  51940. splitEarcut(ear, triangles, dim, minX, minY, size);
  51941. }
  51942. break;
  51943. }
  51944. }
  51945. }
  51946. // check whether a polygon node forms a valid ear with adjacent nodes
  51947. function isEar(ear) {
  51948. var a = ear.prev, b = ear, c = ear.next;
  51949. if (area(a, b, c) >= 0)
  51950. return false; // reflex, can't be an ear
  51951. // now make sure we don't have other points inside the potential ear
  51952. var p = ear.next.next;
  51953. while (p !== ear.prev) {
  51954. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51955. area(p.prev, p, p.next) >= 0)
  51956. return false;
  51957. p = p.next;
  51958. }
  51959. return true;
  51960. }
  51961. function isEarHashed(ear, minX, minY, size) {
  51962. var a = ear.prev, b = ear, c = ear.next;
  51963. if (area(a, b, c) >= 0)
  51964. return false; // reflex, can't be an ear
  51965. // triangle bbox; min & max are calculated like this for speed
  51966. 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);
  51967. // z-order range for the current triangle bbox;
  51968. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51969. // first look for points inside the triangle in increasing z-order
  51970. var p = ear.nextZ;
  51971. while (p && p.z <= maxZ) {
  51972. if (p !== ear.prev &&
  51973. p !== ear.next &&
  51974. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51975. area(p.prev, p, p.next) >= 0)
  51976. return false;
  51977. p = p.nextZ;
  51978. }
  51979. // then look for points in decreasing z-order
  51980. p = ear.prevZ;
  51981. while (p && p.z >= minZ) {
  51982. if (p !== ear.prev &&
  51983. p !== ear.next &&
  51984. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51985. area(p.prev, p, p.next) >= 0)
  51986. return false;
  51987. p = p.prevZ;
  51988. }
  51989. return true;
  51990. }
  51991. // go through all polygon nodes and cure small local self-intersections
  51992. function cureLocalIntersections(start, triangles, dim) {
  51993. var p = start;
  51994. do {
  51995. var a = p.prev, b = p.next.next;
  51996. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51997. triangles.push(a.i / dim);
  51998. triangles.push(p.i / dim);
  51999. triangles.push(b.i / dim);
  52000. // remove two nodes involved
  52001. removeNode(p);
  52002. removeNode(p.next);
  52003. p = start = b;
  52004. }
  52005. p = p.next;
  52006. } while (p !== start);
  52007. return p;
  52008. }
  52009. // try splitting polygon into two and triangulate them independently
  52010. function splitEarcut(start, triangles, dim, minX, minY, size) {
  52011. // look for a valid diagonal that divides the polygon into two
  52012. var a = start;
  52013. do {
  52014. var b = a.next.next;
  52015. while (b !== a.prev) {
  52016. if (a.i !== b.i && isValidDiagonal(a, b)) {
  52017. // split the polygon in two by the diagonal
  52018. var c = splitPolygon(a, b);
  52019. // filter colinear points around the cuts
  52020. a = filterPoints(a, a.next);
  52021. c = filterPoints(c, c.next);
  52022. // run earcut on each half
  52023. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  52024. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  52025. return;
  52026. }
  52027. b = b.next;
  52028. }
  52029. a = a.next;
  52030. } while (a !== start);
  52031. }
  52032. // link every hole into the outer loop, producing a single-ring polygon without holes
  52033. function eliminateHoles(data, holeIndices, outerNode, dim) {
  52034. var queue = [], i, len, start, end, list;
  52035. for (i = 0, len = holeIndices.length; i < len; i++) {
  52036. start = holeIndices[i] * dim;
  52037. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52038. list = linkedList(data, start, end, dim, false);
  52039. if (list === list.next)
  52040. list.steiner = true;
  52041. queue.push(getLeftmost(list));
  52042. }
  52043. queue.sort(compareX);
  52044. // process holes from left to right
  52045. for (i = 0; i < queue.length; i++) {
  52046. eliminateHole(queue[i], outerNode);
  52047. outerNode = filterPoints(outerNode, outerNode.next);
  52048. }
  52049. return outerNode;
  52050. }
  52051. function compareX(a, b) {
  52052. return a.x - b.x;
  52053. }
  52054. // find a bridge between vertices that connects hole with an outer ring and and link it
  52055. function eliminateHole(hole, outerNode) {
  52056. outerNode = findHoleBridge(hole, outerNode);
  52057. if (outerNode) {
  52058. var b = splitPolygon(outerNode, hole);
  52059. filterPoints(b, b.next);
  52060. }
  52061. }
  52062. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  52063. function findHoleBridge(hole, outerNode) {
  52064. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  52065. // find a segment intersected by a ray from the hole's leftmost point to the left;
  52066. // segment's endpoint with lesser x will be potential connection point
  52067. do {
  52068. if (hy <= p.y && hy >= p.next.y) {
  52069. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  52070. if (x <= hx && x > qx) {
  52071. qx = x;
  52072. if (x === hx) {
  52073. if (hy === p.y)
  52074. return p;
  52075. if (hy === p.next.y)
  52076. return p.next;
  52077. }
  52078. m = p.x < p.next.x ? p : p.next;
  52079. }
  52080. }
  52081. p = p.next;
  52082. } while (p !== outerNode);
  52083. if (!m)
  52084. return null;
  52085. if (hx === qx)
  52086. return m.prev; // hole touches outer segment; pick lower endpoint
  52087. // look for points inside the triangle of hole point, segment intersection and endpoint;
  52088. // if there are no points found, we have a valid connection;
  52089. // otherwise choose the point of the minimum angle with the ray as connection point
  52090. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  52091. p = m.next;
  52092. while (p !== stop) {
  52093. if (hx >= p.x &&
  52094. p.x >= mx &&
  52095. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  52096. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  52097. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  52098. m = p;
  52099. tanMin = tan;
  52100. }
  52101. }
  52102. p = p.next;
  52103. }
  52104. return m;
  52105. }
  52106. // interlink polygon nodes in z-order
  52107. function indexCurve(start, minX, minY, size) {
  52108. var p = start;
  52109. do {
  52110. if (p.z === null)
  52111. p.z = zOrder(p.x, p.y, minX, minY, size);
  52112. p.prevZ = p.prev;
  52113. p.nextZ = p.next;
  52114. p = p.next;
  52115. } while (p !== start);
  52116. p.prevZ.nextZ = null;
  52117. p.prevZ = null;
  52118. sortLinked(p);
  52119. }
  52120. // Simon Tatham's linked list merge sort algorithm
  52121. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52122. function sortLinked(list) {
  52123. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52124. do {
  52125. p = list;
  52126. list = null;
  52127. tail = null;
  52128. numMerges = 0;
  52129. while (p) {
  52130. numMerges++;
  52131. q = p;
  52132. pSize = 0;
  52133. for (i = 0; i < inSize; i++) {
  52134. pSize++;
  52135. q = q.nextZ;
  52136. if (!q)
  52137. break;
  52138. }
  52139. qSize = inSize;
  52140. while (pSize > 0 || (qSize > 0 && q)) {
  52141. if (pSize === 0) {
  52142. e = q;
  52143. q = q.nextZ;
  52144. qSize--;
  52145. }
  52146. else if (qSize === 0 || !q) {
  52147. e = p;
  52148. p = p.nextZ;
  52149. pSize--;
  52150. }
  52151. else if (p.z <= q.z) {
  52152. e = p;
  52153. p = p.nextZ;
  52154. pSize--;
  52155. }
  52156. else {
  52157. e = q;
  52158. q = q.nextZ;
  52159. qSize--;
  52160. }
  52161. if (tail)
  52162. tail.nextZ = e;
  52163. else
  52164. list = e;
  52165. e.prevZ = tail;
  52166. tail = e;
  52167. }
  52168. p = q;
  52169. }
  52170. tail.nextZ = null;
  52171. inSize *= 2;
  52172. } while (numMerges > 1);
  52173. return list;
  52174. }
  52175. // z-order of a point given coords and size of the data bounding box
  52176. function zOrder(x, y, minX, minY, size) {
  52177. // coords are transformed into non-negative 15-bit integer range
  52178. x = 32767 * (x - minX) / size;
  52179. y = 32767 * (y - minY) / size;
  52180. x = (x | (x << 8)) & 0x00FF00FF;
  52181. x = (x | (x << 4)) & 0x0F0F0F0F;
  52182. x = (x | (x << 2)) & 0x33333333;
  52183. x = (x | (x << 1)) & 0x55555555;
  52184. y = (y | (y << 8)) & 0x00FF00FF;
  52185. y = (y | (y << 4)) & 0x0F0F0F0F;
  52186. y = (y | (y << 2)) & 0x33333333;
  52187. y = (y | (y << 1)) & 0x55555555;
  52188. return x | (y << 1);
  52189. }
  52190. // find the leftmost node of a polygon ring
  52191. function getLeftmost(start) {
  52192. var p = start, leftmost = start;
  52193. do {
  52194. if (p.x < leftmost.x)
  52195. leftmost = p;
  52196. p = p.next;
  52197. } while (p !== start);
  52198. return leftmost;
  52199. }
  52200. // check if a point lies within a convex triangle
  52201. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  52202. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  52203. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  52204. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  52205. }
  52206. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  52207. function isValidDiagonal(a, b) {
  52208. return a.next.i !== b.i &&
  52209. a.prev.i !== b.i &&
  52210. !intersectsPolygon(a, b) &&
  52211. locallyInside(a, b) &&
  52212. locallyInside(b, a) &&
  52213. middleInside(a, b);
  52214. }
  52215. // signed area of a triangle
  52216. function area(p, q, r) {
  52217. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  52218. }
  52219. // check if two points are equal
  52220. function equals(p1, p2) {
  52221. return p1.x === p2.x && p1.y === p2.y;
  52222. }
  52223. // check if two segments intersect
  52224. function intersects(p1, q1, p2, q2) {
  52225. if ((equals(p1, q1) && equals(p2, q2)) ||
  52226. (equals(p1, q2) && equals(p2, q1)))
  52227. return true;
  52228. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  52229. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  52230. }
  52231. // check if a polygon diagonal intersects any polygon segments
  52232. function intersectsPolygon(a, b) {
  52233. var p = a;
  52234. do {
  52235. if (p.i !== a.i &&
  52236. p.next.i !== a.i &&
  52237. p.i !== b.i &&
  52238. p.next.i !== b.i &&
  52239. intersects(p, p.next, a, b))
  52240. return true;
  52241. p = p.next;
  52242. } while (p !== a);
  52243. return false;
  52244. }
  52245. // check if a polygon diagonal is locally inside the polygon
  52246. function locallyInside(a, b) {
  52247. return area(a.prev, a, a.next) < 0
  52248. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  52249. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  52250. }
  52251. // check if the middle point of a polygon diagonal is inside the polygon
  52252. function middleInside(a, b) {
  52253. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  52254. do {
  52255. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  52256. inside = !inside;
  52257. p = p.next;
  52258. } while (p !== a);
  52259. return inside;
  52260. }
  52261. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52262. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52263. function splitPolygon(a, b) {
  52264. 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;
  52265. a.next = b;
  52266. b.prev = a;
  52267. a2.next = an;
  52268. an.prev = a2;
  52269. b2.next = a2;
  52270. a2.prev = b2;
  52271. bp.next = b2;
  52272. b2.prev = bp;
  52273. return b2;
  52274. }
  52275. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52276. function insertNode(i, x, y, last) {
  52277. var p = new Node(i, x, y);
  52278. if (!last) {
  52279. p.prev = p;
  52280. p.next = p;
  52281. }
  52282. else {
  52283. p.next = last.next;
  52284. p.prev = last;
  52285. last.next.prev = p;
  52286. last.next = p;
  52287. }
  52288. return p;
  52289. }
  52290. function removeNode(p) {
  52291. p.next.prev = p.prev;
  52292. p.prev.next = p.next;
  52293. if (p.prevZ)
  52294. p.prevZ.nextZ = p.nextZ;
  52295. if (p.nextZ)
  52296. p.nextZ.prevZ = p.prevZ;
  52297. }
  52298. function Node(i, x, y) {
  52299. // vertice index in coordinates array
  52300. this.i = i;
  52301. // vertex coordinates
  52302. this.x = x;
  52303. this.y = y;
  52304. // previous and next vertice nodes in a polygon ring
  52305. this.prev = null;
  52306. this.next = null;
  52307. // z-order curve value
  52308. this.z = null;
  52309. // previous and next nodes in z-order
  52310. this.prevZ = null;
  52311. this.nextZ = null;
  52312. // indicates whether this is a steiner point
  52313. this.steiner = false;
  52314. }
  52315. /**
  52316. * return a percentage difference between the polygon area and its triangulation area;
  52317. * used to verify correctness of triangulation
  52318. */
  52319. function deviation(data, holeIndices, dim, triangles) {
  52320. var hasHoles = holeIndices && holeIndices.length;
  52321. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52322. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52323. if (hasHoles) {
  52324. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52325. var start = holeIndices[i] * dim;
  52326. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52327. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52328. }
  52329. }
  52330. var trianglesArea = 0;
  52331. for (i = 0; i < triangles.length; i += 3) {
  52332. var a = triangles[i] * dim;
  52333. var b = triangles[i + 1] * dim;
  52334. var c = triangles[i + 2] * dim;
  52335. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52336. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52337. }
  52338. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52339. }
  52340. Earcut.deviation = deviation;
  52341. ;
  52342. function signedArea(data, start, end, dim) {
  52343. var sum = 0;
  52344. for (var i = start, j = end - dim; i < end; i += dim) {
  52345. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52346. j = i;
  52347. }
  52348. return sum;
  52349. }
  52350. /**
  52351. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52352. */
  52353. function flatten(data) {
  52354. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52355. for (var i = 0; i < data.length; i++) {
  52356. for (var j = 0; j < data[i].length; j++) {
  52357. for (var d = 0; d < dim; d++)
  52358. result.vertices.push(data[i][j][d]);
  52359. }
  52360. if (i > 0) {
  52361. holeIndex += data[i - 1].length;
  52362. result.holes.push(holeIndex);
  52363. }
  52364. }
  52365. return result;
  52366. }
  52367. Earcut.flatten = flatten;
  52368. ;
  52369. })(Earcut || (Earcut = {}));
  52370. var BABYLON;
  52371. (function (BABYLON) {
  52372. // Unique ID when we import meshes from Babylon to CSG
  52373. var currentCSGMeshId = 0;
  52374. // # class Vertex
  52375. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52376. // one to provide additional features like texture coordinates and vertex
  52377. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52378. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52379. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52380. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52381. // is not used anywhere else.
  52382. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52383. var Vertex = (function () {
  52384. function Vertex(pos, normal, uv) {
  52385. this.pos = pos;
  52386. this.normal = normal;
  52387. this.uv = uv;
  52388. }
  52389. Vertex.prototype.clone = function () {
  52390. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52391. };
  52392. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52393. // orientation of a polygon is flipped.
  52394. Vertex.prototype.flip = function () {
  52395. this.normal = this.normal.scale(-1);
  52396. };
  52397. // Create a new vertex between this vertex and `other` by linearly
  52398. // interpolating all properties using a parameter of `t`. Subclasses should
  52399. // override this to interpolate additional properties.
  52400. Vertex.prototype.interpolate = function (other, t) {
  52401. 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));
  52402. };
  52403. return Vertex;
  52404. }());
  52405. // # class Plane
  52406. // Represents a plane in 3D space.
  52407. var Plane = (function () {
  52408. function Plane(normal, w) {
  52409. this.normal = normal;
  52410. this.w = w;
  52411. }
  52412. Plane.FromPoints = function (a, b, c) {
  52413. var v0 = c.subtract(a);
  52414. var v1 = b.subtract(a);
  52415. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52416. return null;
  52417. }
  52418. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52419. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52420. };
  52421. Plane.prototype.clone = function () {
  52422. return new Plane(this.normal.clone(), this.w);
  52423. };
  52424. Plane.prototype.flip = function () {
  52425. this.normal.scaleInPlace(-1);
  52426. this.w = -this.w;
  52427. };
  52428. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52429. // fragments in the appropriate lists. Coplanar polygons go into either
  52430. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52431. // respect to this plane. Polygons in front or in back of this plane go into
  52432. // either `front` or `back`.
  52433. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52434. var COPLANAR = 0;
  52435. var FRONT = 1;
  52436. var BACK = 2;
  52437. var SPANNING = 3;
  52438. // Classify each point as well as the entire polygon into one of the above
  52439. // four classes.
  52440. var polygonType = 0;
  52441. var types = [];
  52442. var i;
  52443. var t;
  52444. for (i = 0; i < polygon.vertices.length; i++) {
  52445. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52446. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52447. polygonType |= type;
  52448. types.push(type);
  52449. }
  52450. // Put the polygon in the correct list, splitting it when necessary.
  52451. switch (polygonType) {
  52452. case COPLANAR:
  52453. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52454. break;
  52455. case FRONT:
  52456. front.push(polygon);
  52457. break;
  52458. case BACK:
  52459. back.push(polygon);
  52460. break;
  52461. case SPANNING:
  52462. var f = [], b = [];
  52463. for (i = 0; i < polygon.vertices.length; i++) {
  52464. var j = (i + 1) % polygon.vertices.length;
  52465. var ti = types[i], tj = types[j];
  52466. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52467. if (ti !== BACK)
  52468. f.push(vi);
  52469. if (ti !== FRONT)
  52470. b.push(ti !== BACK ? vi.clone() : vi);
  52471. if ((ti | tj) === SPANNING) {
  52472. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52473. var v = vi.interpolate(vj, t);
  52474. f.push(v);
  52475. b.push(v.clone());
  52476. }
  52477. }
  52478. var poly;
  52479. if (f.length >= 3) {
  52480. poly = new Polygon(f, polygon.shared);
  52481. if (poly.plane)
  52482. front.push(poly);
  52483. }
  52484. if (b.length >= 3) {
  52485. poly = new Polygon(b, polygon.shared);
  52486. if (poly.plane)
  52487. back.push(poly);
  52488. }
  52489. break;
  52490. }
  52491. };
  52492. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52493. // point is on the plane.
  52494. Plane.EPSILON = 1e-5;
  52495. return Plane;
  52496. }());
  52497. // # class Polygon
  52498. // Represents a convex polygon. The vertices used to initialize a polygon must
  52499. // be coplanar and form a convex loop.
  52500. //
  52501. // Each convex polygon has a `shared` property, which is shared between all
  52502. // polygons that are clones of each other or were split from the same polygon.
  52503. // This can be used to define per-polygon properties (such as surface color).
  52504. var Polygon = (function () {
  52505. function Polygon(vertices, shared) {
  52506. this.vertices = vertices;
  52507. this.shared = shared;
  52508. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52509. }
  52510. Polygon.prototype.clone = function () {
  52511. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52512. return new Polygon(vertices, this.shared);
  52513. };
  52514. Polygon.prototype.flip = function () {
  52515. this.vertices.reverse().map(function (v) { v.flip(); });
  52516. this.plane.flip();
  52517. };
  52518. return Polygon;
  52519. }());
  52520. // # class Node
  52521. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52522. // by picking a polygon to split along. That polygon (and all other coplanar
  52523. // polygons) are added directly to that node and the other polygons are added to
  52524. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52525. // no distinction between internal and leaf nodes.
  52526. var Node = (function () {
  52527. function Node(polygons) {
  52528. this.plane = null;
  52529. this.front = null;
  52530. this.back = null;
  52531. this.polygons = [];
  52532. if (polygons) {
  52533. this.build(polygons);
  52534. }
  52535. }
  52536. Node.prototype.clone = function () {
  52537. var node = new Node();
  52538. node.plane = this.plane && this.plane.clone();
  52539. node.front = this.front && this.front.clone();
  52540. node.back = this.back && this.back.clone();
  52541. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52542. return node;
  52543. };
  52544. // Convert solid space to empty space and empty space to solid space.
  52545. Node.prototype.invert = function () {
  52546. for (var i = 0; i < this.polygons.length; i++) {
  52547. this.polygons[i].flip();
  52548. }
  52549. if (this.plane) {
  52550. this.plane.flip();
  52551. }
  52552. if (this.front) {
  52553. this.front.invert();
  52554. }
  52555. if (this.back) {
  52556. this.back.invert();
  52557. }
  52558. var temp = this.front;
  52559. this.front = this.back;
  52560. this.back = temp;
  52561. };
  52562. // Recursively remove all polygons in `polygons` that are inside this BSP
  52563. // tree.
  52564. Node.prototype.clipPolygons = function (polygons) {
  52565. if (!this.plane)
  52566. return polygons.slice();
  52567. var front = [], back = [];
  52568. for (var i = 0; i < polygons.length; i++) {
  52569. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52570. }
  52571. if (this.front) {
  52572. front = this.front.clipPolygons(front);
  52573. }
  52574. if (this.back) {
  52575. back = this.back.clipPolygons(back);
  52576. }
  52577. else {
  52578. back = [];
  52579. }
  52580. return front.concat(back);
  52581. };
  52582. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52583. // `bsp`.
  52584. Node.prototype.clipTo = function (bsp) {
  52585. this.polygons = bsp.clipPolygons(this.polygons);
  52586. if (this.front)
  52587. this.front.clipTo(bsp);
  52588. if (this.back)
  52589. this.back.clipTo(bsp);
  52590. };
  52591. // Return a list of all polygons in this BSP tree.
  52592. Node.prototype.allPolygons = function () {
  52593. var polygons = this.polygons.slice();
  52594. if (this.front)
  52595. polygons = polygons.concat(this.front.allPolygons());
  52596. if (this.back)
  52597. polygons = polygons.concat(this.back.allPolygons());
  52598. return polygons;
  52599. };
  52600. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52601. // new polygons are filtered down to the bottom of the tree and become new
  52602. // nodes there. Each set of polygons is partitioned using the first polygon
  52603. // (no heuristic is used to pick a good split).
  52604. Node.prototype.build = function (polygons) {
  52605. if (!polygons.length)
  52606. return;
  52607. if (!this.plane)
  52608. this.plane = polygons[0].plane.clone();
  52609. var front = [], back = [];
  52610. for (var i = 0; i < polygons.length; i++) {
  52611. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52612. }
  52613. if (front.length) {
  52614. if (!this.front)
  52615. this.front = new Node();
  52616. this.front.build(front);
  52617. }
  52618. if (back.length) {
  52619. if (!this.back)
  52620. this.back = new Node();
  52621. this.back.build(back);
  52622. }
  52623. };
  52624. return Node;
  52625. }());
  52626. var CSG = (function () {
  52627. function CSG() {
  52628. this.polygons = new Array();
  52629. }
  52630. // Convert BABYLON.Mesh to BABYLON.CSG
  52631. CSG.FromMesh = function (mesh) {
  52632. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52633. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52634. if (mesh instanceof BABYLON.Mesh) {
  52635. mesh.computeWorldMatrix(true);
  52636. matrix = mesh.getWorldMatrix();
  52637. meshPosition = mesh.position.clone();
  52638. meshRotation = mesh.rotation.clone();
  52639. if (mesh.rotationQuaternion) {
  52640. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52641. }
  52642. meshScaling = mesh.scaling.clone();
  52643. }
  52644. else {
  52645. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52646. }
  52647. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52648. var subMeshes = mesh.subMeshes;
  52649. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52650. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52651. vertices = [];
  52652. for (var j = 0; j < 3; j++) {
  52653. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52654. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52655. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52656. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52657. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52658. vertex = new Vertex(position, normal, uv);
  52659. vertices.push(vertex);
  52660. }
  52661. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52662. // To handle the case of degenerated triangle
  52663. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52664. if (polygon.plane)
  52665. polygons.push(polygon);
  52666. }
  52667. }
  52668. var csg = CSG.FromPolygons(polygons);
  52669. csg.matrix = matrix;
  52670. csg.position = meshPosition;
  52671. csg.rotation = meshRotation;
  52672. csg.scaling = meshScaling;
  52673. csg.rotationQuaternion = meshRotationQuaternion;
  52674. currentCSGMeshId++;
  52675. return csg;
  52676. };
  52677. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52678. CSG.FromPolygons = function (polygons) {
  52679. var csg = new CSG();
  52680. csg.polygons = polygons;
  52681. return csg;
  52682. };
  52683. CSG.prototype.clone = function () {
  52684. var csg = new CSG();
  52685. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52686. csg.copyTransformAttributes(this);
  52687. return csg;
  52688. };
  52689. CSG.prototype.toPolygons = function () {
  52690. return this.polygons;
  52691. };
  52692. CSG.prototype.union = function (csg) {
  52693. var a = new Node(this.clone().polygons);
  52694. var b = new Node(csg.clone().polygons);
  52695. a.clipTo(b);
  52696. b.clipTo(a);
  52697. b.invert();
  52698. b.clipTo(a);
  52699. b.invert();
  52700. a.build(b.allPolygons());
  52701. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52702. };
  52703. CSG.prototype.unionInPlace = function (csg) {
  52704. var a = new Node(this.polygons);
  52705. var b = new Node(csg.polygons);
  52706. a.clipTo(b);
  52707. b.clipTo(a);
  52708. b.invert();
  52709. b.clipTo(a);
  52710. b.invert();
  52711. a.build(b.allPolygons());
  52712. this.polygons = a.allPolygons();
  52713. };
  52714. CSG.prototype.subtract = function (csg) {
  52715. var a = new Node(this.clone().polygons);
  52716. var b = new Node(csg.clone().polygons);
  52717. a.invert();
  52718. a.clipTo(b);
  52719. b.clipTo(a);
  52720. b.invert();
  52721. b.clipTo(a);
  52722. b.invert();
  52723. a.build(b.allPolygons());
  52724. a.invert();
  52725. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52726. };
  52727. CSG.prototype.subtractInPlace = function (csg) {
  52728. var a = new Node(this.polygons);
  52729. var b = new Node(csg.polygons);
  52730. a.invert();
  52731. a.clipTo(b);
  52732. b.clipTo(a);
  52733. b.invert();
  52734. b.clipTo(a);
  52735. b.invert();
  52736. a.build(b.allPolygons());
  52737. a.invert();
  52738. this.polygons = a.allPolygons();
  52739. };
  52740. CSG.prototype.intersect = function (csg) {
  52741. var a = new Node(this.clone().polygons);
  52742. var b = new Node(csg.clone().polygons);
  52743. a.invert();
  52744. b.clipTo(a);
  52745. b.invert();
  52746. a.clipTo(b);
  52747. b.clipTo(a);
  52748. a.build(b.allPolygons());
  52749. a.invert();
  52750. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52751. };
  52752. CSG.prototype.intersectInPlace = function (csg) {
  52753. var a = new Node(this.polygons);
  52754. var b = new Node(csg.polygons);
  52755. a.invert();
  52756. b.clipTo(a);
  52757. b.invert();
  52758. a.clipTo(b);
  52759. b.clipTo(a);
  52760. a.build(b.allPolygons());
  52761. a.invert();
  52762. this.polygons = a.allPolygons();
  52763. };
  52764. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52765. // not modified.
  52766. CSG.prototype.inverse = function () {
  52767. var csg = this.clone();
  52768. csg.inverseInPlace();
  52769. return csg;
  52770. };
  52771. CSG.prototype.inverseInPlace = function () {
  52772. this.polygons.map(function (p) { p.flip(); });
  52773. };
  52774. // This is used to keep meshes transformations so they can be restored
  52775. // when we build back a Babylon Mesh
  52776. // NB : All CSG operations are performed in world coordinates
  52777. CSG.prototype.copyTransformAttributes = function (csg) {
  52778. this.matrix = csg.matrix;
  52779. this.position = csg.position;
  52780. this.rotation = csg.rotation;
  52781. this.scaling = csg.scaling;
  52782. this.rotationQuaternion = csg.rotationQuaternion;
  52783. return this;
  52784. };
  52785. // Build Raw mesh from CSG
  52786. // Coordinates here are in world space
  52787. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52788. var matrix = this.matrix.clone();
  52789. matrix.invert();
  52790. 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;
  52791. if (keepSubMeshes) {
  52792. // Sort Polygons, since subMeshes are indices range
  52793. polygons.sort(function (a, b) {
  52794. if (a.shared.meshId === b.shared.meshId) {
  52795. return a.shared.subMeshId - b.shared.subMeshId;
  52796. }
  52797. else {
  52798. return a.shared.meshId - b.shared.meshId;
  52799. }
  52800. });
  52801. }
  52802. for (var i = 0, il = polygons.length; i < il; i++) {
  52803. polygon = polygons[i];
  52804. // Building SubMeshes
  52805. if (!subMesh_dict[polygon.shared.meshId]) {
  52806. subMesh_dict[polygon.shared.meshId] = {};
  52807. }
  52808. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52809. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52810. indexStart: +Infinity,
  52811. indexEnd: -Infinity,
  52812. materialIndex: polygon.shared.materialIndex
  52813. };
  52814. }
  52815. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52816. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52817. polygonIndices[0] = 0;
  52818. polygonIndices[1] = j - 1;
  52819. polygonIndices[2] = j;
  52820. for (var k = 0; k < 3; k++) {
  52821. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52822. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52823. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52824. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52825. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52826. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52827. // Check if 2 points can be merged
  52828. if (!(typeof vertex_idx !== 'undefined' &&
  52829. normals[vertex_idx * 3] === localNormal.x &&
  52830. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52831. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52832. uvs[vertex_idx * 2] === uv.x &&
  52833. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52834. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52835. uvs.push(uv.x, uv.y);
  52836. normals.push(normal.x, normal.y, normal.z);
  52837. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52838. }
  52839. indices.push(vertex_idx);
  52840. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52841. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52842. currentIndex++;
  52843. }
  52844. }
  52845. }
  52846. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52847. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52848. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52849. mesh.setIndices(indices);
  52850. if (keepSubMeshes) {
  52851. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52852. var materialIndexOffset = 0, materialMaxIndex;
  52853. mesh.subMeshes = new Array();
  52854. for (var m in subMesh_dict) {
  52855. materialMaxIndex = -1;
  52856. for (var sm in subMesh_dict[m]) {
  52857. subMesh_obj = subMesh_dict[m][sm];
  52858. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52859. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52860. }
  52861. materialIndexOffset += ++materialMaxIndex;
  52862. }
  52863. }
  52864. return mesh;
  52865. };
  52866. // Build Mesh from CSG taking material and transforms into account
  52867. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52868. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52869. mesh.material = material;
  52870. mesh.position.copyFrom(this.position);
  52871. mesh.rotation.copyFrom(this.rotation);
  52872. if (this.rotationQuaternion) {
  52873. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52874. }
  52875. mesh.scaling.copyFrom(this.scaling);
  52876. mesh.computeWorldMatrix(true);
  52877. return mesh;
  52878. };
  52879. return CSG;
  52880. }());
  52881. BABYLON.CSG = CSG;
  52882. })(BABYLON || (BABYLON = {}));
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. var VRDistortionCorrectionPostProcess = (function (_super) {
  52886. __extends(VRDistortionCorrectionPostProcess, _super);
  52887. //ANY
  52888. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52889. var _this = this;
  52890. _super.call(this, name, "vrDistortionCorrection", [
  52891. 'LensCenter',
  52892. 'Scale',
  52893. 'ScaleIn',
  52894. 'HmdWarpParam'
  52895. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52896. this._isRightEye = isRightEye;
  52897. this._distortionFactors = vrMetrics.distortionK;
  52898. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52899. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52900. this.onSizeChangedObservable.add(function () {
  52901. _this.aspectRatio = _this.width * .5 / _this.height;
  52902. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52903. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52904. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52905. });
  52906. this.onApplyObservable.add(function (effect) {
  52907. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52908. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52909. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52910. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52911. });
  52912. }
  52913. return VRDistortionCorrectionPostProcess;
  52914. }(BABYLON.PostProcess));
  52915. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52916. })(BABYLON || (BABYLON = {}));
  52917. // Mainly based on these 2 articles :
  52918. // 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
  52919. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52920. var BABYLON;
  52921. (function (BABYLON) {
  52922. (function (JoystickAxis) {
  52923. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52924. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52925. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52926. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52927. var JoystickAxis = BABYLON.JoystickAxis;
  52928. var VirtualJoystick = (function () {
  52929. function VirtualJoystick(leftJoystick) {
  52930. var _this = this;
  52931. if (leftJoystick) {
  52932. this._leftJoystick = true;
  52933. }
  52934. else {
  52935. this._leftJoystick = false;
  52936. }
  52937. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52938. VirtualJoystick._globalJoystickIndex++;
  52939. // By default left & right arrow keys are moving the X
  52940. // and up & down keys are moving the Y
  52941. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52942. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52943. this.reverseLeftRight = false;
  52944. this.reverseUpDown = false;
  52945. // collections of pointers
  52946. this._touches = new BABYLON.StringDictionary();
  52947. this.deltaPosition = BABYLON.Vector3.Zero();
  52948. this._joystickSensibility = 25;
  52949. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52950. this._rotationSpeed = 25;
  52951. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52952. this._rotateOnAxisRelativeToMesh = false;
  52953. this._onResize = function (evt) {
  52954. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52955. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52956. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52957. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52958. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52959. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52960. };
  52961. // injecting a canvas element on top of the canvas 3D game
  52962. if (!VirtualJoystick.vjCanvas) {
  52963. window.addEventListener("resize", this._onResize, false);
  52964. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52965. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52966. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52967. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52968. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52969. VirtualJoystick.vjCanvas.style.width = "100%";
  52970. VirtualJoystick.vjCanvas.style.height = "100%";
  52971. VirtualJoystick.vjCanvas.style.position = "absolute";
  52972. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52973. VirtualJoystick.vjCanvas.style.top = "0px";
  52974. VirtualJoystick.vjCanvas.style.left = "0px";
  52975. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52976. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52977. // Support for jQuery PEP polyfill
  52978. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52979. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52980. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52981. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52982. document.body.appendChild(VirtualJoystick.vjCanvas);
  52983. }
  52984. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52985. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52986. this.pressed = false;
  52987. // default joystick color
  52988. this._joystickColor = "cyan";
  52989. this._joystickPointerID = -1;
  52990. // current joystick position
  52991. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52992. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52993. // origin joystick position
  52994. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52995. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52996. this._onPointerDownHandlerRef = function (evt) {
  52997. _this._onPointerDown(evt);
  52998. };
  52999. this._onPointerMoveHandlerRef = function (evt) {
  53000. _this._onPointerMove(evt);
  53001. };
  53002. this._onPointerOutHandlerRef = function (evt) {
  53003. _this._onPointerUp(evt);
  53004. };
  53005. this._onPointerUpHandlerRef = function (evt) {
  53006. _this._onPointerUp(evt);
  53007. };
  53008. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  53009. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  53010. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  53011. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  53012. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  53013. evt.preventDefault(); // Disables system menu
  53014. }, false);
  53015. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  53016. }
  53017. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  53018. this._joystickSensibility = newJoystickSensibility;
  53019. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  53020. };
  53021. VirtualJoystick.prototype._onPointerDown = function (e) {
  53022. var positionOnScreenCondition;
  53023. e.preventDefault();
  53024. if (this._leftJoystick === true) {
  53025. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  53026. }
  53027. else {
  53028. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  53029. }
  53030. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  53031. // First contact will be dedicated to the virtual joystick
  53032. this._joystickPointerID = e.pointerId;
  53033. this._joystickPointerStartPos.x = e.clientX;
  53034. this._joystickPointerStartPos.y = e.clientY;
  53035. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  53036. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  53037. this._deltaJoystickVector.x = 0;
  53038. this._deltaJoystickVector.y = 0;
  53039. this.pressed = true;
  53040. this._touches.add(e.pointerId.toString(), e);
  53041. }
  53042. else {
  53043. // You can only trigger the action buttons with a joystick declared
  53044. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  53045. this._action();
  53046. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  53047. }
  53048. }
  53049. };
  53050. VirtualJoystick.prototype._onPointerMove = function (e) {
  53051. // If the current pointer is the one associated to the joystick (first touch contact)
  53052. if (this._joystickPointerID == e.pointerId) {
  53053. this._joystickPointerPos.x = e.clientX;
  53054. this._joystickPointerPos.y = e.clientY;
  53055. this._deltaJoystickVector = this._joystickPointerPos.clone();
  53056. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  53057. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  53058. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  53059. switch (this._axisTargetedByLeftAndRight) {
  53060. case JoystickAxis.X:
  53061. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  53062. break;
  53063. case JoystickAxis.Y:
  53064. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  53065. break;
  53066. case JoystickAxis.Z:
  53067. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  53068. break;
  53069. }
  53070. var directionUpDown = this.reverseUpDown ? 1 : -1;
  53071. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  53072. switch (this._axisTargetedByUpAndDown) {
  53073. case JoystickAxis.X:
  53074. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  53075. break;
  53076. case JoystickAxis.Y:
  53077. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  53078. break;
  53079. case JoystickAxis.Z:
  53080. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  53081. break;
  53082. }
  53083. }
  53084. else {
  53085. var data = this._touches.get(e.pointerId.toString());
  53086. if (data) {
  53087. data.x = e.clientX;
  53088. data.y = e.clientY;
  53089. }
  53090. }
  53091. };
  53092. VirtualJoystick.prototype._onPointerUp = function (e) {
  53093. if (this._joystickPointerID == e.pointerId) {
  53094. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  53095. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  53096. this._joystickPointerID = -1;
  53097. this.pressed = false;
  53098. }
  53099. else {
  53100. var touch = this._touches.get(e.pointerId.toString());
  53101. if (touch) {
  53102. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53103. }
  53104. }
  53105. this._deltaJoystickVector.x = 0;
  53106. this._deltaJoystickVector.y = 0;
  53107. this._touches.remove(e.pointerId.toString());
  53108. };
  53109. /**
  53110. * Change the color of the virtual joystick
  53111. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  53112. */
  53113. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  53114. this._joystickColor = newColor;
  53115. };
  53116. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  53117. this._action = action;
  53118. };
  53119. // Define which axis you'd like to control for left & right
  53120. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  53121. switch (axis) {
  53122. case JoystickAxis.X:
  53123. case JoystickAxis.Y:
  53124. case JoystickAxis.Z:
  53125. this._axisTargetedByLeftAndRight = axis;
  53126. break;
  53127. default:
  53128. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  53129. break;
  53130. }
  53131. };
  53132. // Define which axis you'd like to control for up & down
  53133. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  53134. switch (axis) {
  53135. case JoystickAxis.X:
  53136. case JoystickAxis.Y:
  53137. case JoystickAxis.Z:
  53138. this._axisTargetedByUpAndDown = axis;
  53139. break;
  53140. default:
  53141. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  53142. break;
  53143. }
  53144. };
  53145. VirtualJoystick.prototype._clearCanvas = function () {
  53146. if (this._leftJoystick) {
  53147. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  53148. }
  53149. else {
  53150. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  53151. }
  53152. };
  53153. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  53154. var _this = this;
  53155. if (this.pressed) {
  53156. this._touches.forEach(function (touch) {
  53157. if (touch.pointerId === _this._joystickPointerID) {
  53158. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  53159. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  53160. VirtualJoystick.vjCanvasContext.beginPath();
  53161. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53162. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53163. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  53164. VirtualJoystick.vjCanvasContext.stroke();
  53165. VirtualJoystick.vjCanvasContext.closePath();
  53166. VirtualJoystick.vjCanvasContext.beginPath();
  53167. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53168. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  53169. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  53170. VirtualJoystick.vjCanvasContext.stroke();
  53171. VirtualJoystick.vjCanvasContext.closePath();
  53172. VirtualJoystick.vjCanvasContext.beginPath();
  53173. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  53174. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  53175. VirtualJoystick.vjCanvasContext.stroke();
  53176. VirtualJoystick.vjCanvasContext.closePath();
  53177. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  53178. }
  53179. else {
  53180. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  53181. VirtualJoystick.vjCanvasContext.beginPath();
  53182. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  53183. VirtualJoystick.vjCanvasContext.beginPath();
  53184. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  53185. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  53186. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  53187. VirtualJoystick.vjCanvasContext.stroke();
  53188. VirtualJoystick.vjCanvasContext.closePath();
  53189. touch.prevX = touch.x;
  53190. touch.prevY = touch.y;
  53191. }
  53192. ;
  53193. });
  53194. }
  53195. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  53196. };
  53197. VirtualJoystick.prototype.releaseCanvas = function () {
  53198. if (VirtualJoystick.vjCanvas) {
  53199. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  53200. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  53201. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  53202. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  53203. window.removeEventListener("resize", this._onResize);
  53204. document.body.removeChild(VirtualJoystick.vjCanvas);
  53205. VirtualJoystick.vjCanvas = null;
  53206. }
  53207. };
  53208. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  53209. VirtualJoystick._globalJoystickIndex = 0;
  53210. return VirtualJoystick;
  53211. }());
  53212. BABYLON.VirtualJoystick = VirtualJoystick;
  53213. })(BABYLON || (BABYLON = {}));
  53214. var BABYLON;
  53215. (function (BABYLON) {
  53216. // We're mainly based on the logic defined into the FreeCamera code
  53217. var VirtualJoysticksCamera = (function (_super) {
  53218. __extends(VirtualJoysticksCamera, _super);
  53219. function VirtualJoysticksCamera(name, position, scene) {
  53220. _super.call(this, name, position, scene);
  53221. this.inputs.addVirtualJoystick();
  53222. }
  53223. return VirtualJoysticksCamera;
  53224. }(BABYLON.FreeCamera));
  53225. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  53226. })(BABYLON || (BABYLON = {}));
  53227. var BABYLON;
  53228. (function (BABYLON) {
  53229. var FreeCameraVirtualJoystickInput = (function () {
  53230. function FreeCameraVirtualJoystickInput() {
  53231. }
  53232. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  53233. return this._leftjoystick;
  53234. };
  53235. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  53236. return this._rightjoystick;
  53237. };
  53238. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  53239. if (this._leftjoystick) {
  53240. var camera = this.camera;
  53241. var speed = camera._computeLocalCameraSpeed() * 50;
  53242. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  53243. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  53244. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  53245. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  53246. if (!this._leftjoystick.pressed) {
  53247. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  53248. }
  53249. if (!this._rightjoystick.pressed) {
  53250. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  53251. }
  53252. }
  53253. };
  53254. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  53255. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  53256. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  53257. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  53258. this._leftjoystick.setJoystickSensibility(0.15);
  53259. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  53260. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  53261. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  53262. this._rightjoystick.reverseUpDown = true;
  53263. this._rightjoystick.setJoystickSensibility(0.05);
  53264. this._rightjoystick.setJoystickColor("yellow");
  53265. };
  53266. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  53267. this._leftjoystick.releaseCanvas();
  53268. this._rightjoystick.releaseCanvas();
  53269. };
  53270. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  53271. return "FreeCameraVirtualJoystickInput";
  53272. };
  53273. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  53274. return "virtualJoystick";
  53275. };
  53276. return FreeCameraVirtualJoystickInput;
  53277. }());
  53278. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  53279. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  53280. })(BABYLON || (BABYLON = {}));
  53281. var BABYLON;
  53282. (function (BABYLON) {
  53283. var AnaglyphPostProcess = (function (_super) {
  53284. __extends(AnaglyphPostProcess, _super);
  53285. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  53286. var _this = this;
  53287. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  53288. this._passedProcess = rigCameras[0]._rigPostProcess;
  53289. this.onApplyObservable.add(function (effect) {
  53290. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  53291. });
  53292. }
  53293. return AnaglyphPostProcess;
  53294. }(BABYLON.PostProcess));
  53295. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  53296. })(BABYLON || (BABYLON = {}));
  53297. var BABYLON;
  53298. (function (BABYLON) {
  53299. var OutlineRenderer = (function () {
  53300. function OutlineRenderer(scene) {
  53301. this._scene = scene;
  53302. }
  53303. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  53304. var _this = this;
  53305. if (useOverlay === void 0) { useOverlay = false; }
  53306. var scene = this._scene;
  53307. var engine = this._scene.getEngine();
  53308. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53309. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  53310. return;
  53311. }
  53312. var mesh = subMesh.getRenderingMesh();
  53313. var material = subMesh.getMaterial();
  53314. engine.enableEffect(this._effect);
  53315. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  53316. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  53317. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53318. // Bones
  53319. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53320. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53321. }
  53322. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53323. // Alpha test
  53324. if (material && material.needAlphaTesting()) {
  53325. var alphaTexture = material.getAlphaTestTexture();
  53326. this._effect.setTexture("diffuseSampler", alphaTexture);
  53327. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53328. }
  53329. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  53330. };
  53331. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  53332. var defines = [];
  53333. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53334. var mesh = subMesh.getMesh();
  53335. var material = subMesh.getMaterial();
  53336. // Alpha test
  53337. if (material && material.needAlphaTesting()) {
  53338. defines.push("#define ALPHATEST");
  53339. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53340. attribs.push(BABYLON.VertexBuffer.UVKind);
  53341. defines.push("#define UV1");
  53342. }
  53343. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53344. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53345. defines.push("#define UV2");
  53346. }
  53347. }
  53348. // Bones
  53349. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53350. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53351. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53352. if (mesh.numBoneInfluencers > 4) {
  53353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53355. }
  53356. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53357. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53358. }
  53359. else {
  53360. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53361. }
  53362. // Instances
  53363. if (useInstances) {
  53364. defines.push("#define INSTANCES");
  53365. attribs.push("world0");
  53366. attribs.push("world1");
  53367. attribs.push("world2");
  53368. attribs.push("world3");
  53369. }
  53370. // Get correct effect
  53371. var join = defines.join("\n");
  53372. if (this._cachedDefines !== join) {
  53373. this._cachedDefines = join;
  53374. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  53375. }
  53376. return this._effect.isReady();
  53377. };
  53378. return OutlineRenderer;
  53379. }());
  53380. BABYLON.OutlineRenderer = OutlineRenderer;
  53381. })(BABYLON || (BABYLON = {}));
  53382. var BABYLON;
  53383. (function (BABYLON) {
  53384. var MeshAssetTask = (function () {
  53385. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  53386. this.name = name;
  53387. this.meshesNames = meshesNames;
  53388. this.rootUrl = rootUrl;
  53389. this.sceneFilename = sceneFilename;
  53390. this.isCompleted = false;
  53391. }
  53392. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53393. var _this = this;
  53394. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  53395. _this.loadedMeshes = meshes;
  53396. _this.loadedParticleSystems = particleSystems;
  53397. _this.loadedSkeletons = skeletons;
  53398. _this.isCompleted = true;
  53399. if (_this.onSuccess) {
  53400. _this.onSuccess(_this);
  53401. }
  53402. onSuccess();
  53403. }, null, function () {
  53404. if (_this.onError) {
  53405. _this.onError(_this);
  53406. }
  53407. onError();
  53408. });
  53409. };
  53410. return MeshAssetTask;
  53411. }());
  53412. BABYLON.MeshAssetTask = MeshAssetTask;
  53413. var TextFileAssetTask = (function () {
  53414. function TextFileAssetTask(name, url) {
  53415. this.name = name;
  53416. this.url = url;
  53417. this.isCompleted = false;
  53418. }
  53419. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53420. var _this = this;
  53421. BABYLON.Tools.LoadFile(this.url, function (data) {
  53422. _this.text = data;
  53423. _this.isCompleted = true;
  53424. if (_this.onSuccess) {
  53425. _this.onSuccess(_this);
  53426. }
  53427. onSuccess();
  53428. }, null, scene.database, false, function () {
  53429. if (_this.onError) {
  53430. _this.onError(_this);
  53431. }
  53432. onError();
  53433. });
  53434. };
  53435. return TextFileAssetTask;
  53436. }());
  53437. BABYLON.TextFileAssetTask = TextFileAssetTask;
  53438. var BinaryFileAssetTask = (function () {
  53439. function BinaryFileAssetTask(name, url) {
  53440. this.name = name;
  53441. this.url = url;
  53442. this.isCompleted = false;
  53443. }
  53444. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53445. var _this = this;
  53446. BABYLON.Tools.LoadFile(this.url, function (data) {
  53447. _this.data = data;
  53448. _this.isCompleted = true;
  53449. if (_this.onSuccess) {
  53450. _this.onSuccess(_this);
  53451. }
  53452. onSuccess();
  53453. }, null, scene.database, true, function () {
  53454. if (_this.onError) {
  53455. _this.onError(_this);
  53456. }
  53457. onError();
  53458. });
  53459. };
  53460. return BinaryFileAssetTask;
  53461. }());
  53462. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  53463. var ImageAssetTask = (function () {
  53464. function ImageAssetTask(name, url) {
  53465. this.name = name;
  53466. this.url = url;
  53467. this.isCompleted = false;
  53468. }
  53469. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53470. var _this = this;
  53471. var img = new Image();
  53472. BABYLON.Tools.SetCorsBehavior(this.url, img);
  53473. img.onload = function () {
  53474. _this.image = img;
  53475. _this.isCompleted = true;
  53476. if (_this.onSuccess) {
  53477. _this.onSuccess(_this);
  53478. }
  53479. onSuccess();
  53480. };
  53481. img.onerror = function () {
  53482. if (_this.onError) {
  53483. _this.onError(_this);
  53484. }
  53485. onError();
  53486. };
  53487. img.src = this.url;
  53488. };
  53489. return ImageAssetTask;
  53490. }());
  53491. BABYLON.ImageAssetTask = ImageAssetTask;
  53492. var TextureAssetTask = (function () {
  53493. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  53494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53495. this.name = name;
  53496. this.url = url;
  53497. this.noMipmap = noMipmap;
  53498. this.invertY = invertY;
  53499. this.samplingMode = samplingMode;
  53500. this.isCompleted = false;
  53501. }
  53502. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53503. var _this = this;
  53504. var onload = function () {
  53505. _this.isCompleted = true;
  53506. if (_this.onSuccess) {
  53507. _this.onSuccess(_this);
  53508. }
  53509. onSuccess();
  53510. };
  53511. var onerror = function () {
  53512. if (_this.onError) {
  53513. _this.onError(_this);
  53514. }
  53515. onError();
  53516. };
  53517. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  53518. };
  53519. return TextureAssetTask;
  53520. }());
  53521. BABYLON.TextureAssetTask = TextureAssetTask;
  53522. var CubeTextureAssetTask = (function () {
  53523. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  53524. this.name = name;
  53525. this.url = url;
  53526. this.extensions = extensions;
  53527. this.noMipmap = noMipmap;
  53528. this.files = files;
  53529. this.isCompleted = false;
  53530. }
  53531. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53532. var _this = this;
  53533. var onload = function () {
  53534. _this.isCompleted = true;
  53535. if (_this.onSuccess) {
  53536. _this.onSuccess(_this);
  53537. }
  53538. onSuccess();
  53539. };
  53540. var onerror = function () {
  53541. if (_this.onError) {
  53542. _this.onError(_this);
  53543. }
  53544. onError();
  53545. };
  53546. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  53547. };
  53548. return CubeTextureAssetTask;
  53549. }());
  53550. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  53551. var AssetsManager = (function () {
  53552. function AssetsManager(scene) {
  53553. this.tasks = new Array();
  53554. this.waitingTasksCount = 0;
  53555. this.useDefaultLoadingScreen = true;
  53556. this._scene = scene;
  53557. }
  53558. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  53559. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  53560. this.tasks.push(task);
  53561. return task;
  53562. };
  53563. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  53564. var task = new TextFileAssetTask(taskName, url);
  53565. this.tasks.push(task);
  53566. return task;
  53567. };
  53568. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  53569. var task = new BinaryFileAssetTask(taskName, url);
  53570. this.tasks.push(task);
  53571. return task;
  53572. };
  53573. AssetsManager.prototype.addImageTask = function (taskName, url) {
  53574. var task = new ImageAssetTask(taskName, url);
  53575. this.tasks.push(task);
  53576. return task;
  53577. };
  53578. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  53579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53580. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  53581. this.tasks.push(task);
  53582. return task;
  53583. };
  53584. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  53585. this.waitingTasksCount--;
  53586. if (this.waitingTasksCount === 0) {
  53587. if (this.onFinish) {
  53588. this.onFinish(this.tasks);
  53589. }
  53590. this._scene.getEngine().hideLoadingUI();
  53591. }
  53592. };
  53593. AssetsManager.prototype._runTask = function (task) {
  53594. var _this = this;
  53595. task.run(this._scene, function () {
  53596. if (_this.onTaskSuccess) {
  53597. _this.onTaskSuccess(task);
  53598. }
  53599. _this._decreaseWaitingTasksCount();
  53600. }, function () {
  53601. if (_this.onTaskError) {
  53602. _this.onTaskError(task);
  53603. }
  53604. _this._decreaseWaitingTasksCount();
  53605. });
  53606. };
  53607. AssetsManager.prototype.reset = function () {
  53608. this.tasks = new Array();
  53609. return this;
  53610. };
  53611. AssetsManager.prototype.load = function () {
  53612. this.waitingTasksCount = this.tasks.length;
  53613. if (this.waitingTasksCount === 0) {
  53614. if (this.onFinish) {
  53615. this.onFinish(this.tasks);
  53616. }
  53617. return this;
  53618. }
  53619. if (this.useDefaultLoadingScreen) {
  53620. this._scene.getEngine().displayLoadingUI();
  53621. }
  53622. for (var index = 0; index < this.tasks.length; index++) {
  53623. var task = this.tasks[index];
  53624. this._runTask(task);
  53625. }
  53626. return this;
  53627. };
  53628. return AssetsManager;
  53629. }());
  53630. BABYLON.AssetsManager = AssetsManager;
  53631. })(BABYLON || (BABYLON = {}));
  53632. var BABYLON;
  53633. (function (BABYLON) {
  53634. var VRCameraMetrics = (function () {
  53635. function VRCameraMetrics() {
  53636. this.compensateDistortion = true;
  53637. }
  53638. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  53639. get: function () {
  53640. return this.hResolution / (2 * this.vResolution);
  53641. },
  53642. enumerable: true,
  53643. configurable: true
  53644. });
  53645. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  53646. get: function () {
  53647. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  53648. },
  53649. enumerable: true,
  53650. configurable: true
  53651. });
  53652. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  53653. get: function () {
  53654. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53655. var h = (4 * meters) / this.hScreenSize;
  53656. return BABYLON.Matrix.Translation(h, 0, 0);
  53657. },
  53658. enumerable: true,
  53659. configurable: true
  53660. });
  53661. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  53662. get: function () {
  53663. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53664. var h = (4 * meters) / this.hScreenSize;
  53665. return BABYLON.Matrix.Translation(-h, 0, 0);
  53666. },
  53667. enumerable: true,
  53668. configurable: true
  53669. });
  53670. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  53671. get: function () {
  53672. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  53673. },
  53674. enumerable: true,
  53675. configurable: true
  53676. });
  53677. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  53678. get: function () {
  53679. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  53680. },
  53681. enumerable: true,
  53682. configurable: true
  53683. });
  53684. VRCameraMetrics.GetDefault = function () {
  53685. var result = new VRCameraMetrics();
  53686. result.hResolution = 1280;
  53687. result.vResolution = 800;
  53688. result.hScreenSize = 0.149759993;
  53689. result.vScreenSize = 0.0935999975;
  53690. result.vScreenCenter = 0.0467999987,
  53691. result.eyeToScreenDistance = 0.0410000011;
  53692. result.lensSeparationDistance = 0.0635000020;
  53693. result.interpupillaryDistance = 0.0640000030;
  53694. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  53695. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  53696. result.postProcessScaleFactor = 1.714605507808412;
  53697. result.lensCenterOffset = 0.151976421;
  53698. return result;
  53699. };
  53700. return VRCameraMetrics;
  53701. }());
  53702. BABYLON.VRCameraMetrics = VRCameraMetrics;
  53703. })(BABYLON || (BABYLON = {}));
  53704. var BABYLON;
  53705. (function (BABYLON) {
  53706. var WebVRFreeCamera = (function (_super) {
  53707. __extends(WebVRFreeCamera, _super);
  53708. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  53709. var _this = this;
  53710. if (compensateDistortion === void 0) { compensateDistortion = false; }
  53711. if (webVROptions === void 0) { webVROptions = {}; }
  53712. _super.call(this, name, position, scene);
  53713. this.webVROptions = webVROptions;
  53714. this._vrDevice = null;
  53715. this._cacheState = null;
  53716. this._vrEnabled = false;
  53717. //enable VR
  53718. this.getEngine().initWebVR();
  53719. if (!this.getEngine().vrDisplaysPromise) {
  53720. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  53721. }
  53722. else {
  53723. //TODO get the metrics updated using the device's eye parameters!
  53724. //TODO also check that the device has the right capabilities!
  53725. this.getEngine().vrDisplaysPromise.then(function (devices) {
  53726. if (devices.length > 0) {
  53727. _this._vrEnabled = true;
  53728. if (_this.webVROptions.displayName) {
  53729. var found = devices.some(function (device) {
  53730. if (device.displayName === _this.webVROptions.displayName) {
  53731. _this._vrDevice = device;
  53732. return true;
  53733. }
  53734. else {
  53735. return false;
  53736. }
  53737. });
  53738. if (!found) {
  53739. _this._vrDevice = devices[0];
  53740. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  53741. }
  53742. }
  53743. else {
  53744. //choose the first one
  53745. _this._vrDevice = devices[0];
  53746. }
  53747. //reset the rig parameters.
  53748. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  53749. }
  53750. else {
  53751. BABYLON.Tools.Error("No WebVR devices found!");
  53752. }
  53753. });
  53754. }
  53755. this.rotationQuaternion = new BABYLON.Quaternion();
  53756. this._quaternionCache = new BABYLON.Quaternion();
  53757. }
  53758. WebVRFreeCamera.prototype._checkInputs = function () {
  53759. if (this._vrEnabled) {
  53760. var currentPost = this._vrDevice.getPose();
  53761. //make sure we have data
  53762. if (currentPost && currentPost.orientation) {
  53763. this._cacheState = currentPost;
  53764. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  53765. if (this.webVROptions.trackPosition && this._cacheState.position) {
  53766. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  53767. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  53768. }
  53769. //Flip in XY plane
  53770. this.rotationQuaternion.z *= -1;
  53771. this.rotationQuaternion.w *= -1;
  53772. }
  53773. }
  53774. _super.prototype._checkInputs.call(this);
  53775. };
  53776. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  53777. _super.prototype.attachControl.call(this, element, noPreventDefault);
  53778. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  53779. if (this._vrEnabled) {
  53780. this.getEngine().enableVR(this._vrDevice);
  53781. }
  53782. };
  53783. WebVRFreeCamera.prototype.detachControl = function (element) {
  53784. _super.prototype.detachControl.call(this, element);
  53785. this._vrEnabled = false;
  53786. this.getEngine().disableVR();
  53787. };
  53788. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  53789. //Backwards comp.
  53790. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  53791. //this.getEngine().switchFullscreen(requestPointerlock);
  53792. };
  53793. WebVRFreeCamera.prototype.getTypeName = function () {
  53794. return "WebVRFreeCamera";
  53795. };
  53796. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  53797. //uses the vrDisplay's "resetPose()".
  53798. //pitch and roll won't be affected.
  53799. this._vrDevice.resetPose();
  53800. };
  53801. return WebVRFreeCamera;
  53802. }(BABYLON.FreeCamera));
  53803. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  53804. })(BABYLON || (BABYLON = {}));
  53805. var BABYLON;
  53806. (function (BABYLON) {
  53807. // Standard optimizations
  53808. var SceneOptimization = (function () {
  53809. function SceneOptimization(priority) {
  53810. if (priority === void 0) { priority = 0; }
  53811. this.priority = priority;
  53812. this.apply = function (scene) {
  53813. return true; // Return true if everything that can be done was applied
  53814. };
  53815. }
  53816. return SceneOptimization;
  53817. }());
  53818. BABYLON.SceneOptimization = SceneOptimization;
  53819. var TextureOptimization = (function (_super) {
  53820. __extends(TextureOptimization, _super);
  53821. function TextureOptimization(priority, maximumSize) {
  53822. var _this = this;
  53823. if (priority === void 0) { priority = 0; }
  53824. if (maximumSize === void 0) { maximumSize = 1024; }
  53825. _super.call(this, priority);
  53826. this.priority = priority;
  53827. this.maximumSize = maximumSize;
  53828. this.apply = function (scene) {
  53829. var allDone = true;
  53830. for (var index = 0; index < scene.textures.length; index++) {
  53831. var texture = scene.textures[index];
  53832. if (!texture.canRescale) {
  53833. continue;
  53834. }
  53835. var currentSize = texture.getSize();
  53836. var maxDimension = Math.max(currentSize.width, currentSize.height);
  53837. if (maxDimension > _this.maximumSize) {
  53838. texture.scale(0.5);
  53839. allDone = false;
  53840. }
  53841. }
  53842. return allDone;
  53843. };
  53844. }
  53845. return TextureOptimization;
  53846. }(SceneOptimization));
  53847. BABYLON.TextureOptimization = TextureOptimization;
  53848. var HardwareScalingOptimization = (function (_super) {
  53849. __extends(HardwareScalingOptimization, _super);
  53850. function HardwareScalingOptimization(priority, maximumScale) {
  53851. var _this = this;
  53852. if (priority === void 0) { priority = 0; }
  53853. if (maximumScale === void 0) { maximumScale = 2; }
  53854. _super.call(this, priority);
  53855. this.priority = priority;
  53856. this.maximumScale = maximumScale;
  53857. this._currentScale = 1;
  53858. this.apply = function (scene) {
  53859. _this._currentScale++;
  53860. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  53861. return _this._currentScale >= _this.maximumScale;
  53862. };
  53863. }
  53864. return HardwareScalingOptimization;
  53865. }(SceneOptimization));
  53866. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53867. var ShadowsOptimization = (function (_super) {
  53868. __extends(ShadowsOptimization, _super);
  53869. function ShadowsOptimization() {
  53870. _super.apply(this, arguments);
  53871. this.apply = function (scene) {
  53872. scene.shadowsEnabled = false;
  53873. return true;
  53874. };
  53875. }
  53876. return ShadowsOptimization;
  53877. }(SceneOptimization));
  53878. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53879. var PostProcessesOptimization = (function (_super) {
  53880. __extends(PostProcessesOptimization, _super);
  53881. function PostProcessesOptimization() {
  53882. _super.apply(this, arguments);
  53883. this.apply = function (scene) {
  53884. scene.postProcessesEnabled = false;
  53885. return true;
  53886. };
  53887. }
  53888. return PostProcessesOptimization;
  53889. }(SceneOptimization));
  53890. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53891. var LensFlaresOptimization = (function (_super) {
  53892. __extends(LensFlaresOptimization, _super);
  53893. function LensFlaresOptimization() {
  53894. _super.apply(this, arguments);
  53895. this.apply = function (scene) {
  53896. scene.lensFlaresEnabled = false;
  53897. return true;
  53898. };
  53899. }
  53900. return LensFlaresOptimization;
  53901. }(SceneOptimization));
  53902. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53903. var ParticlesOptimization = (function (_super) {
  53904. __extends(ParticlesOptimization, _super);
  53905. function ParticlesOptimization() {
  53906. _super.apply(this, arguments);
  53907. this.apply = function (scene) {
  53908. scene.particlesEnabled = false;
  53909. return true;
  53910. };
  53911. }
  53912. return ParticlesOptimization;
  53913. }(SceneOptimization));
  53914. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53915. var RenderTargetsOptimization = (function (_super) {
  53916. __extends(RenderTargetsOptimization, _super);
  53917. function RenderTargetsOptimization() {
  53918. _super.apply(this, arguments);
  53919. this.apply = function (scene) {
  53920. scene.renderTargetsEnabled = false;
  53921. return true;
  53922. };
  53923. }
  53924. return RenderTargetsOptimization;
  53925. }(SceneOptimization));
  53926. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53927. var MergeMeshesOptimization = (function (_super) {
  53928. __extends(MergeMeshesOptimization, _super);
  53929. function MergeMeshesOptimization() {
  53930. var _this = this;
  53931. _super.apply(this, arguments);
  53932. this._canBeMerged = function (abstractMesh) {
  53933. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53934. return false;
  53935. }
  53936. var mesh = abstractMesh;
  53937. if (!mesh.isVisible || !mesh.isEnabled()) {
  53938. return false;
  53939. }
  53940. if (mesh.instances.length > 0) {
  53941. return false;
  53942. }
  53943. if (mesh.skeleton || mesh.hasLODLevels) {
  53944. return false;
  53945. }
  53946. if (mesh.parent) {
  53947. return false;
  53948. }
  53949. return true;
  53950. };
  53951. this.apply = function (scene, updateSelectionTree) {
  53952. var globalPool = scene.meshes.slice(0);
  53953. var globalLength = globalPool.length;
  53954. for (var index = 0; index < globalLength; index++) {
  53955. var currentPool = new Array();
  53956. var current = globalPool[index];
  53957. // Checks
  53958. if (!_this._canBeMerged(current)) {
  53959. continue;
  53960. }
  53961. currentPool.push(current);
  53962. // Find compatible meshes
  53963. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53964. var otherMesh = globalPool[subIndex];
  53965. if (!_this._canBeMerged(otherMesh)) {
  53966. continue;
  53967. }
  53968. if (otherMesh.material !== current.material) {
  53969. continue;
  53970. }
  53971. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53972. continue;
  53973. }
  53974. currentPool.push(otherMesh);
  53975. globalLength--;
  53976. globalPool.splice(subIndex, 1);
  53977. subIndex--;
  53978. }
  53979. if (currentPool.length < 2) {
  53980. continue;
  53981. }
  53982. // Merge meshes
  53983. BABYLON.Mesh.MergeMeshes(currentPool);
  53984. }
  53985. if (updateSelectionTree != undefined) {
  53986. if (updateSelectionTree) {
  53987. scene.createOrUpdateSelectionOctree();
  53988. }
  53989. }
  53990. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53991. scene.createOrUpdateSelectionOctree();
  53992. }
  53993. return true;
  53994. };
  53995. }
  53996. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53997. get: function () {
  53998. return MergeMeshesOptimization._UpdateSelectionTree;
  53999. },
  54000. set: function (value) {
  54001. MergeMeshesOptimization._UpdateSelectionTree = value;
  54002. },
  54003. enumerable: true,
  54004. configurable: true
  54005. });
  54006. MergeMeshesOptimization._UpdateSelectionTree = false;
  54007. return MergeMeshesOptimization;
  54008. }(SceneOptimization));
  54009. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  54010. // Options
  54011. var SceneOptimizerOptions = (function () {
  54012. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  54013. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  54014. if (trackerDuration === void 0) { trackerDuration = 2000; }
  54015. this.targetFrameRate = targetFrameRate;
  54016. this.trackerDuration = trackerDuration;
  54017. this.optimizations = new Array();
  54018. }
  54019. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  54020. var result = new SceneOptimizerOptions(targetFrameRate);
  54021. var priority = 0;
  54022. result.optimizations.push(new MergeMeshesOptimization(priority));
  54023. result.optimizations.push(new ShadowsOptimization(priority));
  54024. result.optimizations.push(new LensFlaresOptimization(priority));
  54025. // Next priority
  54026. priority++;
  54027. result.optimizations.push(new PostProcessesOptimization(priority));
  54028. result.optimizations.push(new ParticlesOptimization(priority));
  54029. // Next priority
  54030. priority++;
  54031. result.optimizations.push(new TextureOptimization(priority, 1024));
  54032. return result;
  54033. };
  54034. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  54035. var result = new SceneOptimizerOptions(targetFrameRate);
  54036. var priority = 0;
  54037. result.optimizations.push(new MergeMeshesOptimization(priority));
  54038. result.optimizations.push(new ShadowsOptimization(priority));
  54039. result.optimizations.push(new LensFlaresOptimization(priority));
  54040. // Next priority
  54041. priority++;
  54042. result.optimizations.push(new PostProcessesOptimization(priority));
  54043. result.optimizations.push(new ParticlesOptimization(priority));
  54044. // Next priority
  54045. priority++;
  54046. result.optimizations.push(new TextureOptimization(priority, 512));
  54047. // Next priority
  54048. priority++;
  54049. result.optimizations.push(new RenderTargetsOptimization(priority));
  54050. // Next priority
  54051. priority++;
  54052. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  54053. return result;
  54054. };
  54055. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  54056. var result = new SceneOptimizerOptions(targetFrameRate);
  54057. var priority = 0;
  54058. result.optimizations.push(new MergeMeshesOptimization(priority));
  54059. result.optimizations.push(new ShadowsOptimization(priority));
  54060. result.optimizations.push(new LensFlaresOptimization(priority));
  54061. // Next priority
  54062. priority++;
  54063. result.optimizations.push(new PostProcessesOptimization(priority));
  54064. result.optimizations.push(new ParticlesOptimization(priority));
  54065. // Next priority
  54066. priority++;
  54067. result.optimizations.push(new TextureOptimization(priority, 256));
  54068. // Next priority
  54069. priority++;
  54070. result.optimizations.push(new RenderTargetsOptimization(priority));
  54071. // Next priority
  54072. priority++;
  54073. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  54074. return result;
  54075. };
  54076. return SceneOptimizerOptions;
  54077. }());
  54078. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  54079. // Scene optimizer tool
  54080. var SceneOptimizer = (function () {
  54081. function SceneOptimizer() {
  54082. }
  54083. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  54084. // TODO: add an epsilon
  54085. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  54086. if (onSuccess) {
  54087. onSuccess();
  54088. }
  54089. return;
  54090. }
  54091. // Apply current level of optimizations
  54092. var allDone = true;
  54093. var noOptimizationApplied = true;
  54094. for (var index = 0; index < options.optimizations.length; index++) {
  54095. var optimization = options.optimizations[index];
  54096. if (optimization.priority === currentPriorityLevel) {
  54097. noOptimizationApplied = false;
  54098. allDone = allDone && optimization.apply(scene);
  54099. }
  54100. }
  54101. // If no optimization was applied, this is a failure :(
  54102. if (noOptimizationApplied) {
  54103. if (onFailure) {
  54104. onFailure();
  54105. }
  54106. return;
  54107. }
  54108. // If all optimizations were done, move to next level
  54109. if (allDone) {
  54110. currentPriorityLevel++;
  54111. }
  54112. // Let's the system running for a specific amount of time before checking FPS
  54113. scene.executeWhenReady(function () {
  54114. setTimeout(function () {
  54115. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  54116. }, options.trackerDuration);
  54117. });
  54118. };
  54119. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  54120. if (!options) {
  54121. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  54122. }
  54123. // Let's the system running for a specific amount of time before checking FPS
  54124. scene.executeWhenReady(function () {
  54125. setTimeout(function () {
  54126. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  54127. }, options.trackerDuration);
  54128. });
  54129. };
  54130. return SceneOptimizer;
  54131. }());
  54132. BABYLON.SceneOptimizer = SceneOptimizer;
  54133. })(BABYLON || (BABYLON = {}));
  54134. var BABYLON;
  54135. (function (BABYLON) {
  54136. var Internals;
  54137. (function (Internals) {
  54138. var MeshLODLevel = (function () {
  54139. function MeshLODLevel(distance, mesh) {
  54140. this.distance = distance;
  54141. this.mesh = mesh;
  54142. }
  54143. return MeshLODLevel;
  54144. }());
  54145. Internals.MeshLODLevel = MeshLODLevel;
  54146. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54147. })(BABYLON || (BABYLON = {}));
  54148. var BABYLON;
  54149. (function (BABYLON) {
  54150. var RawTexture = (function (_super) {
  54151. __extends(RawTexture, _super);
  54152. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  54153. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54154. if (invertY === void 0) { invertY = false; }
  54155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54156. _super.call(this, null, scene, !generateMipMaps, invertY);
  54157. this.format = format;
  54158. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  54159. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54160. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54161. }
  54162. RawTexture.prototype.update = function (data) {
  54163. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  54164. };
  54165. // Statics
  54166. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54168. if (invertY === void 0) { invertY = false; }
  54169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54170. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54171. };
  54172. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54173. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54174. if (invertY === void 0) { invertY = false; }
  54175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54176. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54177. };
  54178. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54179. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54180. if (invertY === void 0) { invertY = false; }
  54181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54182. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54183. };
  54184. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54185. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54186. if (invertY === void 0) { invertY = false; }
  54187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54188. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  54189. };
  54190. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54191. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54192. if (invertY === void 0) { invertY = false; }
  54193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54194. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  54195. };
  54196. return RawTexture;
  54197. }(BABYLON.Texture));
  54198. BABYLON.RawTexture = RawTexture;
  54199. })(BABYLON || (BABYLON = {}));
  54200. var BABYLON;
  54201. (function (BABYLON) {
  54202. var IndexedVector2 = (function (_super) {
  54203. __extends(IndexedVector2, _super);
  54204. function IndexedVector2(original, index) {
  54205. _super.call(this, original.x, original.y);
  54206. this.index = index;
  54207. }
  54208. return IndexedVector2;
  54209. }(BABYLON.Vector2));
  54210. var PolygonPoints = (function () {
  54211. function PolygonPoints() {
  54212. this.elements = new Array();
  54213. }
  54214. PolygonPoints.prototype.add = function (originalPoints) {
  54215. var _this = this;
  54216. var result = new Array();
  54217. originalPoints.forEach(function (point) {
  54218. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  54219. var newPoint = new IndexedVector2(point, _this.elements.length);
  54220. result.push(newPoint);
  54221. _this.elements.push(newPoint);
  54222. }
  54223. });
  54224. return result;
  54225. };
  54226. PolygonPoints.prototype.computeBounds = function () {
  54227. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54228. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  54229. this.elements.forEach(function (point) {
  54230. // x
  54231. if (point.x < lmin.x) {
  54232. lmin.x = point.x;
  54233. }
  54234. else if (point.x > lmax.x) {
  54235. lmax.x = point.x;
  54236. }
  54237. // y
  54238. if (point.y < lmin.y) {
  54239. lmin.y = point.y;
  54240. }
  54241. else if (point.y > lmax.y) {
  54242. lmax.y = point.y;
  54243. }
  54244. });
  54245. return {
  54246. min: lmin,
  54247. max: lmax,
  54248. width: lmax.x - lmin.x,
  54249. height: lmax.y - lmin.y
  54250. };
  54251. };
  54252. return PolygonPoints;
  54253. }());
  54254. var Polygon = (function () {
  54255. function Polygon() {
  54256. }
  54257. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  54258. return [
  54259. new BABYLON.Vector2(xmin, ymin),
  54260. new BABYLON.Vector2(xmax, ymin),
  54261. new BABYLON.Vector2(xmax, ymax),
  54262. new BABYLON.Vector2(xmin, ymax)
  54263. ];
  54264. };
  54265. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  54266. if (cx === void 0) { cx = 0; }
  54267. if (cy === void 0) { cy = 0; }
  54268. if (numberOfSides === void 0) { numberOfSides = 32; }
  54269. var result = new Array();
  54270. var angle = 0;
  54271. var increment = (Math.PI * 2) / numberOfSides;
  54272. for (var i = 0; i < numberOfSides; i++) {
  54273. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  54274. angle -= increment;
  54275. }
  54276. return result;
  54277. };
  54278. Polygon.Parse = function (input) {
  54279. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  54280. var i, result = [];
  54281. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  54282. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  54283. }
  54284. return result;
  54285. };
  54286. Polygon.StartingAt = function (x, y) {
  54287. return BABYLON.Path2.StartingAt(x, y);
  54288. };
  54289. return Polygon;
  54290. }());
  54291. BABYLON.Polygon = Polygon;
  54292. var PolygonMeshBuilder = (function () {
  54293. function PolygonMeshBuilder(name, contours, scene) {
  54294. this._points = new PolygonPoints();
  54295. this._outlinepoints = new PolygonPoints();
  54296. this._holes = [];
  54297. this._epoints = new Array();
  54298. this._eholes = new Array();
  54299. this._name = name;
  54300. this._scene = scene;
  54301. var points;
  54302. if (contours instanceof BABYLON.Path2) {
  54303. points = contours.getPoints();
  54304. }
  54305. else {
  54306. points = contours;
  54307. }
  54308. this._addToepoint(points);
  54309. this._points.add(points);
  54310. this._outlinepoints.add(points);
  54311. }
  54312. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  54313. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  54314. var p = points_1[_i];
  54315. this._epoints.push(p.x, p.y);
  54316. }
  54317. };
  54318. PolygonMeshBuilder.prototype.addHole = function (hole) {
  54319. this._points.add(hole);
  54320. var holepoints = new PolygonPoints();
  54321. holepoints.add(hole);
  54322. this._holes.push(holepoints);
  54323. this._eholes.push(this._epoints.length / 2);
  54324. this._addToepoint(hole);
  54325. return this;
  54326. };
  54327. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  54328. var _this = this;
  54329. if (updatable === void 0) { updatable = false; }
  54330. var result = new BABYLON.Mesh(this._name, this._scene);
  54331. var normals = [];
  54332. var positions = [];
  54333. var uvs = [];
  54334. var bounds = this._points.computeBounds();
  54335. this._points.elements.forEach(function (p) {
  54336. normals.push(0, 1.0, 0);
  54337. positions.push(p.x, 0, p.y);
  54338. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  54339. });
  54340. var indices = [];
  54341. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  54342. for (var i = 0; i < res.length; i++) {
  54343. indices.push(res[i]);
  54344. }
  54345. if (depth > 0) {
  54346. var positionscount = (positions.length / 3); //get the current pointcount
  54347. this._points.elements.forEach(function (p) {
  54348. normals.push(0, -1.0, 0);
  54349. positions.push(p.x, -depth, p.y);
  54350. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  54351. });
  54352. var totalCount = indices.length;
  54353. for (var i = 0; i < totalCount; i += 3) {
  54354. var i0 = indices[i + 0];
  54355. var i1 = indices[i + 1];
  54356. var i2 = indices[i + 2];
  54357. indices.push(i2 + positionscount);
  54358. indices.push(i1 + positionscount);
  54359. indices.push(i0 + positionscount);
  54360. }
  54361. //Add the sides
  54362. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  54363. this._holes.forEach(function (hole) {
  54364. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  54365. });
  54366. }
  54367. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  54368. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  54369. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  54370. result.setIndices(indices);
  54371. return result;
  54372. };
  54373. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  54374. var StartIndex = positions.length / 3;
  54375. var ulength = 0;
  54376. for (var i = 0; i < points.elements.length; i++) {
  54377. var p = points.elements[i];
  54378. var p1;
  54379. if ((i + 1) > points.elements.length - 1) {
  54380. p1 = points.elements[0];
  54381. }
  54382. else {
  54383. p1 = points.elements[i + 1];
  54384. }
  54385. positions.push(p.x, 0, p.y);
  54386. positions.push(p.x, -depth, p.y);
  54387. positions.push(p1.x, 0, p1.y);
  54388. positions.push(p1.x, -depth, p1.y);
  54389. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  54390. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  54391. var v3 = v2.subtract(v1);
  54392. var v4 = new BABYLON.Vector3(0, 1, 0);
  54393. var vn = BABYLON.Vector3.Cross(v3, v4);
  54394. vn = vn.normalize();
  54395. uvs.push(ulength / bounds.width, 0);
  54396. uvs.push(ulength / bounds.width, 1);
  54397. ulength += v3.length();
  54398. uvs.push((ulength / bounds.width), 0);
  54399. uvs.push((ulength / bounds.width), 1);
  54400. if (!flip) {
  54401. normals.push(-vn.x, -vn.y, -vn.z);
  54402. normals.push(-vn.x, -vn.y, -vn.z);
  54403. normals.push(-vn.x, -vn.y, -vn.z);
  54404. normals.push(-vn.x, -vn.y, -vn.z);
  54405. indices.push(StartIndex);
  54406. indices.push(StartIndex + 1);
  54407. indices.push(StartIndex + 2);
  54408. indices.push(StartIndex + 1);
  54409. indices.push(StartIndex + 3);
  54410. indices.push(StartIndex + 2);
  54411. }
  54412. else {
  54413. normals.push(vn.x, vn.y, vn.z);
  54414. normals.push(vn.x, vn.y, vn.z);
  54415. normals.push(vn.x, vn.y, vn.z);
  54416. normals.push(vn.x, vn.y, vn.z);
  54417. indices.push(StartIndex);
  54418. indices.push(StartIndex + 2);
  54419. indices.push(StartIndex + 1);
  54420. indices.push(StartIndex + 1);
  54421. indices.push(StartIndex + 2);
  54422. indices.push(StartIndex + 3);
  54423. }
  54424. StartIndex += 4;
  54425. }
  54426. ;
  54427. };
  54428. return PolygonMeshBuilder;
  54429. }());
  54430. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  54431. })(BABYLON || (BABYLON = {}));
  54432. var BABYLON;
  54433. (function (BABYLON) {
  54434. var Octree = (function () {
  54435. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  54436. if (maxDepth === void 0) { maxDepth = 2; }
  54437. this.maxDepth = maxDepth;
  54438. this.dynamicContent = new Array();
  54439. this._maxBlockCapacity = maxBlockCapacity || 64;
  54440. this._selectionContent = new BABYLON.SmartArray(1024);
  54441. this._creationFunc = creationFunc;
  54442. }
  54443. // Methods
  54444. Octree.prototype.update = function (worldMin, worldMax, entries) {
  54445. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  54446. };
  54447. Octree.prototype.addMesh = function (entry) {
  54448. for (var index = 0; index < this.blocks.length; index++) {
  54449. var block = this.blocks[index];
  54450. block.addEntry(entry);
  54451. }
  54452. };
  54453. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  54454. this._selectionContent.reset();
  54455. for (var index = 0; index < this.blocks.length; index++) {
  54456. var block = this.blocks[index];
  54457. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  54458. }
  54459. if (allowDuplicate) {
  54460. this._selectionContent.concat(this.dynamicContent);
  54461. }
  54462. else {
  54463. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54464. }
  54465. return this._selectionContent;
  54466. };
  54467. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  54468. this._selectionContent.reset();
  54469. for (var index = 0; index < this.blocks.length; index++) {
  54470. var block = this.blocks[index];
  54471. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  54472. }
  54473. if (allowDuplicate) {
  54474. this._selectionContent.concat(this.dynamicContent);
  54475. }
  54476. else {
  54477. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54478. }
  54479. return this._selectionContent;
  54480. };
  54481. Octree.prototype.intersectsRay = function (ray) {
  54482. this._selectionContent.reset();
  54483. for (var index = 0; index < this.blocks.length; index++) {
  54484. var block = this.blocks[index];
  54485. block.intersectsRay(ray, this._selectionContent);
  54486. }
  54487. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54488. return this._selectionContent;
  54489. };
  54490. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  54491. target.blocks = new Array();
  54492. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  54493. // Segmenting space
  54494. for (var x = 0; x < 2; x++) {
  54495. for (var y = 0; y < 2; y++) {
  54496. for (var z = 0; z < 2; z++) {
  54497. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  54498. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  54499. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  54500. block.addEntries(entries);
  54501. target.blocks.push(block);
  54502. }
  54503. }
  54504. }
  54505. };
  54506. Octree.CreationFuncForMeshes = function (entry, block) {
  54507. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54508. block.entries.push(entry);
  54509. }
  54510. };
  54511. Octree.CreationFuncForSubMeshes = function (entry, block) {
  54512. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54513. block.entries.push(entry);
  54514. }
  54515. };
  54516. return Octree;
  54517. }());
  54518. BABYLON.Octree = Octree;
  54519. })(BABYLON || (BABYLON = {}));
  54520. var BABYLON;
  54521. (function (BABYLON) {
  54522. var OctreeBlock = (function () {
  54523. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  54524. this.entries = new Array();
  54525. this._boundingVectors = new Array();
  54526. this._capacity = capacity;
  54527. this._depth = depth;
  54528. this._maxDepth = maxDepth;
  54529. this._creationFunc = creationFunc;
  54530. this._minPoint = minPoint;
  54531. this._maxPoint = maxPoint;
  54532. this._boundingVectors.push(minPoint.clone());
  54533. this._boundingVectors.push(maxPoint.clone());
  54534. this._boundingVectors.push(minPoint.clone());
  54535. this._boundingVectors[2].x = maxPoint.x;
  54536. this._boundingVectors.push(minPoint.clone());
  54537. this._boundingVectors[3].y = maxPoint.y;
  54538. this._boundingVectors.push(minPoint.clone());
  54539. this._boundingVectors[4].z = maxPoint.z;
  54540. this._boundingVectors.push(maxPoint.clone());
  54541. this._boundingVectors[5].z = minPoint.z;
  54542. this._boundingVectors.push(maxPoint.clone());
  54543. this._boundingVectors[6].x = minPoint.x;
  54544. this._boundingVectors.push(maxPoint.clone());
  54545. this._boundingVectors[7].y = minPoint.y;
  54546. }
  54547. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  54548. // Property
  54549. get: function () {
  54550. return this._capacity;
  54551. },
  54552. enumerable: true,
  54553. configurable: true
  54554. });
  54555. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  54556. get: function () {
  54557. return this._minPoint;
  54558. },
  54559. enumerable: true,
  54560. configurable: true
  54561. });
  54562. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  54563. get: function () {
  54564. return this._maxPoint;
  54565. },
  54566. enumerable: true,
  54567. configurable: true
  54568. });
  54569. // Methods
  54570. OctreeBlock.prototype.addEntry = function (entry) {
  54571. if (this.blocks) {
  54572. for (var index = 0; index < this.blocks.length; index++) {
  54573. var block = this.blocks[index];
  54574. block.addEntry(entry);
  54575. }
  54576. return;
  54577. }
  54578. this._creationFunc(entry, this);
  54579. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  54580. this.createInnerBlocks();
  54581. }
  54582. };
  54583. OctreeBlock.prototype.addEntries = function (entries) {
  54584. for (var index = 0; index < entries.length; index++) {
  54585. var mesh = entries[index];
  54586. this.addEntry(mesh);
  54587. }
  54588. };
  54589. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  54590. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  54591. if (this.blocks) {
  54592. for (var index = 0; index < this.blocks.length; index++) {
  54593. var block = this.blocks[index];
  54594. block.select(frustumPlanes, selection, allowDuplicate);
  54595. }
  54596. return;
  54597. }
  54598. if (allowDuplicate) {
  54599. selection.concat(this.entries);
  54600. }
  54601. else {
  54602. selection.concatWithNoDuplicate(this.entries);
  54603. }
  54604. }
  54605. };
  54606. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  54607. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  54608. if (this.blocks) {
  54609. for (var index = 0; index < this.blocks.length; index++) {
  54610. var block = this.blocks[index];
  54611. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  54612. }
  54613. return;
  54614. }
  54615. if (allowDuplicate) {
  54616. selection.concat(this.entries);
  54617. }
  54618. else {
  54619. selection.concatWithNoDuplicate(this.entries);
  54620. }
  54621. }
  54622. };
  54623. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  54624. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  54625. if (this.blocks) {
  54626. for (var index = 0; index < this.blocks.length; index++) {
  54627. var block = this.blocks[index];
  54628. block.intersectsRay(ray, selection);
  54629. }
  54630. return;
  54631. }
  54632. selection.concatWithNoDuplicate(this.entries);
  54633. }
  54634. };
  54635. OctreeBlock.prototype.createInnerBlocks = function () {
  54636. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  54637. };
  54638. return OctreeBlock;
  54639. }());
  54640. BABYLON.OctreeBlock = OctreeBlock;
  54641. })(BABYLON || (BABYLON = {}));
  54642. var BABYLON;
  54643. (function (BABYLON) {
  54644. var BlurPostProcess = (function (_super) {
  54645. __extends(BlurPostProcess, _super);
  54646. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  54647. var _this = this;
  54648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54649. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  54650. this.direction = direction;
  54651. this.blurWidth = blurWidth;
  54652. this.onApplyObservable.add(function (effect) {
  54653. effect.setFloat2("screenSize", _this.width, _this.height);
  54654. effect.setVector2("direction", _this.direction);
  54655. effect.setFloat("blurWidth", _this.blurWidth);
  54656. });
  54657. }
  54658. return BlurPostProcess;
  54659. }(BABYLON.PostProcess));
  54660. BABYLON.BlurPostProcess = BlurPostProcess;
  54661. })(BABYLON || (BABYLON = {}));
  54662. var BABYLON;
  54663. (function (BABYLON) {
  54664. var RefractionPostProcess = (function (_super) {
  54665. __extends(RefractionPostProcess, _super);
  54666. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54667. var _this = this;
  54668. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  54669. this.color = color;
  54670. this.depth = depth;
  54671. this.colorLevel = colorLevel;
  54672. this.onActivateObservable.add(function (cam) {
  54673. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54674. });
  54675. this.onApplyObservable.add(function (effect) {
  54676. effect.setColor3("baseColor", _this.color);
  54677. effect.setFloat("depth", _this.depth);
  54678. effect.setFloat("colorLevel", _this.colorLevel);
  54679. effect.setTexture("refractionSampler", _this._refRexture);
  54680. });
  54681. }
  54682. // Methods
  54683. RefractionPostProcess.prototype.dispose = function (camera) {
  54684. if (this._refRexture) {
  54685. this._refRexture.dispose();
  54686. }
  54687. _super.prototype.dispose.call(this, camera);
  54688. };
  54689. return RefractionPostProcess;
  54690. }(BABYLON.PostProcess));
  54691. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54692. })(BABYLON || (BABYLON = {}));
  54693. var BABYLON;
  54694. (function (BABYLON) {
  54695. var BlackAndWhitePostProcess = (function (_super) {
  54696. __extends(BlackAndWhitePostProcess, _super);
  54697. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54698. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  54699. }
  54700. return BlackAndWhitePostProcess;
  54701. }(BABYLON.PostProcess));
  54702. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54703. })(BABYLON || (BABYLON = {}));
  54704. var BABYLON;
  54705. (function (BABYLON) {
  54706. var ConvolutionPostProcess = (function (_super) {
  54707. __extends(ConvolutionPostProcess, _super);
  54708. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54709. var _this = this;
  54710. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  54711. this.kernel = kernel;
  54712. this.onApply = function (effect) {
  54713. effect.setFloat2("screenSize", _this.width, _this.height);
  54714. effect.setArray("kernel", _this.kernel);
  54715. };
  54716. }
  54717. // Statics
  54718. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54719. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54720. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54721. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54722. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54723. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54724. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54725. return ConvolutionPostProcess;
  54726. }(BABYLON.PostProcess));
  54727. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54728. })(BABYLON || (BABYLON = {}));
  54729. var BABYLON;
  54730. (function (BABYLON) {
  54731. var FilterPostProcess = (function (_super) {
  54732. __extends(FilterPostProcess, _super);
  54733. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54734. var _this = this;
  54735. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  54736. this.kernelMatrix = kernelMatrix;
  54737. this.onApply = function (effect) {
  54738. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54739. };
  54740. }
  54741. return FilterPostProcess;
  54742. }(BABYLON.PostProcess));
  54743. BABYLON.FilterPostProcess = FilterPostProcess;
  54744. })(BABYLON || (BABYLON = {}));
  54745. var BABYLON;
  54746. (function (BABYLON) {
  54747. var FxaaPostProcess = (function (_super) {
  54748. __extends(FxaaPostProcess, _super);
  54749. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54750. var _this = this;
  54751. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  54752. this.onSizeChangedObservable.add(function () {
  54753. _this.texelWidth = 1.0 / _this.width;
  54754. _this.texelHeight = 1.0 / _this.height;
  54755. });
  54756. this.onApplyObservable.add(function (effect) {
  54757. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  54758. });
  54759. }
  54760. return FxaaPostProcess;
  54761. }(BABYLON.PostProcess));
  54762. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54763. })(BABYLON || (BABYLON = {}));
  54764. var BABYLON;
  54765. (function (BABYLON) {
  54766. var StereoscopicInterlacePostProcess = (function (_super) {
  54767. __extends(StereoscopicInterlacePostProcess, _super);
  54768. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  54769. var _this = this;
  54770. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  54771. this._passedProcess = rigCameras[0]._rigPostProcess;
  54772. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  54773. this.onSizeChangedObservable.add(function () {
  54774. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  54775. });
  54776. this.onApplyObservable.add(function (effect) {
  54777. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  54778. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  54779. });
  54780. }
  54781. return StereoscopicInterlacePostProcess;
  54782. }(BABYLON.PostProcess));
  54783. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  54784. })(BABYLON || (BABYLON = {}));
  54785. var BABYLON;
  54786. (function (BABYLON) {
  54787. var LensFlare = (function () {
  54788. function LensFlare(size, position, color, imgUrl, system) {
  54789. this.size = size;
  54790. this.position = position;
  54791. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54792. this.dispose = function () {
  54793. if (this.texture) {
  54794. this.texture.dispose();
  54795. }
  54796. // Remove from scene
  54797. var index = this._system.lensFlares.indexOf(this);
  54798. this._system.lensFlares.splice(index, 1);
  54799. };
  54800. this.color = color || new BABYLON.Color3(1, 1, 1);
  54801. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54802. this._system = system;
  54803. system.lensFlares.push(this);
  54804. }
  54805. return LensFlare;
  54806. }());
  54807. BABYLON.LensFlare = LensFlare;
  54808. })(BABYLON || (BABYLON = {}));
  54809. var BABYLON;
  54810. (function (BABYLON) {
  54811. var LensFlareSystem = (function () {
  54812. function LensFlareSystem(name, emitter, scene) {
  54813. this.name = name;
  54814. this.lensFlares = new Array();
  54815. this.borderLimit = 300;
  54816. this.viewportBorder = 0;
  54817. this.layerMask = 0x0FFFFFFF;
  54818. this._vertexBuffers = {};
  54819. this._isEnabled = true;
  54820. this._scene = scene;
  54821. this._emitter = emitter;
  54822. this.id = name;
  54823. scene.lensFlareSystems.push(this);
  54824. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54825. var engine = scene.getEngine();
  54826. // VBO
  54827. var vertices = [];
  54828. vertices.push(1, 1);
  54829. vertices.push(-1, 1);
  54830. vertices.push(-1, -1);
  54831. vertices.push(1, -1);
  54832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54833. // Indices
  54834. var indices = [];
  54835. indices.push(0);
  54836. indices.push(1);
  54837. indices.push(2);
  54838. indices.push(0);
  54839. indices.push(2);
  54840. indices.push(3);
  54841. this._indexBuffer = engine.createIndexBuffer(indices);
  54842. // Effects
  54843. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54844. }
  54845. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54846. get: function () {
  54847. return this._isEnabled;
  54848. },
  54849. set: function (value) {
  54850. this._isEnabled = value;
  54851. },
  54852. enumerable: true,
  54853. configurable: true
  54854. });
  54855. LensFlareSystem.prototype.getScene = function () {
  54856. return this._scene;
  54857. };
  54858. LensFlareSystem.prototype.getEmitter = function () {
  54859. return this._emitter;
  54860. };
  54861. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54862. this._emitter = newEmitter;
  54863. };
  54864. LensFlareSystem.prototype.getEmitterPosition = function () {
  54865. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54866. };
  54867. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54868. var position = this.getEmitterPosition();
  54869. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54870. this._positionX = position.x;
  54871. this._positionY = position.y;
  54872. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54873. if (this.viewportBorder > 0) {
  54874. globalViewport.x -= this.viewportBorder;
  54875. globalViewport.y -= this.viewportBorder;
  54876. globalViewport.width += this.viewportBorder * 2;
  54877. globalViewport.height += this.viewportBorder * 2;
  54878. position.x += this.viewportBorder;
  54879. position.y += this.viewportBorder;
  54880. this._positionX += this.viewportBorder;
  54881. this._positionY += this.viewportBorder;
  54882. }
  54883. if (position.z > 0) {
  54884. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54885. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54886. return true;
  54887. }
  54888. return true;
  54889. }
  54890. return false;
  54891. };
  54892. LensFlareSystem.prototype._isVisible = function () {
  54893. if (!this._isEnabled) {
  54894. return false;
  54895. }
  54896. var emitterPosition = this.getEmitterPosition();
  54897. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54898. var distance = direction.length();
  54899. direction.normalize();
  54900. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54901. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54902. return !pickInfo.hit || pickInfo.distance > distance;
  54903. };
  54904. LensFlareSystem.prototype.render = function () {
  54905. if (!this._effect.isReady())
  54906. return false;
  54907. var engine = this._scene.getEngine();
  54908. var viewport = this._scene.activeCamera.viewport;
  54909. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54910. // Position
  54911. if (!this.computeEffectivePosition(globalViewport)) {
  54912. return false;
  54913. }
  54914. // Visibility
  54915. if (!this._isVisible()) {
  54916. return false;
  54917. }
  54918. // Intensity
  54919. var awayX;
  54920. var awayY;
  54921. if (this._positionX < this.borderLimit + globalViewport.x) {
  54922. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54923. }
  54924. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54925. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54926. }
  54927. else {
  54928. awayX = 0;
  54929. }
  54930. if (this._positionY < this.borderLimit + globalViewport.y) {
  54931. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54932. }
  54933. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54934. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54935. }
  54936. else {
  54937. awayY = 0;
  54938. }
  54939. var away = (awayX > awayY) ? awayX : awayY;
  54940. away -= this.viewportBorder;
  54941. if (away > this.borderLimit) {
  54942. away = this.borderLimit;
  54943. }
  54944. var intensity = 1.0 - (away / this.borderLimit);
  54945. if (intensity < 0) {
  54946. return false;
  54947. }
  54948. if (intensity > 1.0) {
  54949. intensity = 1.0;
  54950. }
  54951. if (this.viewportBorder > 0) {
  54952. globalViewport.x += this.viewportBorder;
  54953. globalViewport.y += this.viewportBorder;
  54954. globalViewport.width -= this.viewportBorder * 2;
  54955. globalViewport.height -= this.viewportBorder * 2;
  54956. this._positionX -= this.viewportBorder;
  54957. this._positionY -= this.viewportBorder;
  54958. }
  54959. // Position
  54960. var centerX = globalViewport.x + globalViewport.width / 2;
  54961. var centerY = globalViewport.y + globalViewport.height / 2;
  54962. var distX = centerX - this._positionX;
  54963. var distY = centerY - this._positionY;
  54964. // Effects
  54965. engine.enableEffect(this._effect);
  54966. engine.setState(false);
  54967. engine.setDepthBuffer(false);
  54968. // VBOs
  54969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54970. // Flares
  54971. for (var index = 0; index < this.lensFlares.length; index++) {
  54972. var flare = this.lensFlares[index];
  54973. engine.setAlphaMode(flare.alphaMode);
  54974. var x = centerX - (distX * flare.position);
  54975. var y = centerY - (distY * flare.position);
  54976. var cw = flare.size;
  54977. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54978. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54979. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54980. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54981. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54982. // Texture
  54983. this._effect.setTexture("textureSampler", flare.texture);
  54984. // Color
  54985. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54986. // Draw order
  54987. engine.draw(true, 0, 6);
  54988. }
  54989. engine.setDepthBuffer(true);
  54990. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54991. return true;
  54992. };
  54993. LensFlareSystem.prototype.dispose = function () {
  54994. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54995. if (vertexBuffer) {
  54996. vertexBuffer.dispose();
  54997. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54998. }
  54999. if (this._indexBuffer) {
  55000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55001. this._indexBuffer = null;
  55002. }
  55003. while (this.lensFlares.length) {
  55004. this.lensFlares[0].dispose();
  55005. }
  55006. // Remove from scene
  55007. var index = this._scene.lensFlareSystems.indexOf(this);
  55008. this._scene.lensFlareSystems.splice(index, 1);
  55009. };
  55010. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  55011. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  55012. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  55013. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  55014. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  55015. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  55016. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  55017. var parsedFlare = parsedLensFlareSystem.flares[index];
  55018. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  55019. }
  55020. return lensFlareSystem;
  55021. };
  55022. LensFlareSystem.prototype.serialize = function () {
  55023. var serializationObject = {};
  55024. serializationObject.id = this.id;
  55025. serializationObject.name = this.name;
  55026. serializationObject.emitterId = this.getEmitter().id;
  55027. serializationObject.borderLimit = this.borderLimit;
  55028. serializationObject.flares = [];
  55029. for (var index = 0; index < this.lensFlares.length; index++) {
  55030. var flare = this.lensFlares[index];
  55031. serializationObject.flares.push({
  55032. size: flare.size,
  55033. position: flare.position,
  55034. color: flare.color.asArray(),
  55035. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  55036. });
  55037. }
  55038. return serializationObject;
  55039. };
  55040. return LensFlareSystem;
  55041. }());
  55042. BABYLON.LensFlareSystem = LensFlareSystem;
  55043. })(BABYLON || (BABYLON = {}));
  55044. var BABYLON;
  55045. (function (BABYLON) {
  55046. // We're mainly based on the logic defined into the FreeCamera code
  55047. var DeviceOrientationCamera = (function (_super) {
  55048. __extends(DeviceOrientationCamera, _super);
  55049. function DeviceOrientationCamera(name, position, scene) {
  55050. _super.call(this, name, position, scene);
  55051. this._quaternionCache = new BABYLON.Quaternion();
  55052. this.inputs.addDeviceOrientation();
  55053. }
  55054. DeviceOrientationCamera.prototype.getTypeName = function () {
  55055. return "DeviceOrientationCamera";
  55056. };
  55057. DeviceOrientationCamera.prototype._checkInputs = function () {
  55058. _super.prototype._checkInputs.call(this);
  55059. this._quaternionCache.copyFrom(this.rotationQuaternion);
  55060. if (this._initialQuaternion) {
  55061. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  55062. }
  55063. };
  55064. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  55065. var _this = this;
  55066. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  55067. //can only work if this camera has a rotation quaternion already.
  55068. if (!this.rotationQuaternion)
  55069. return;
  55070. if (!this._initialQuaternion) {
  55071. this._initialQuaternion = new BABYLON.Quaternion();
  55072. }
  55073. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  55074. ['x', 'y', 'z'].forEach(function (axisName) {
  55075. if (!axis[axisName]) {
  55076. _this._initialQuaternion[axisName] = 0;
  55077. }
  55078. else {
  55079. _this._initialQuaternion[axisName] *= -1;
  55080. }
  55081. });
  55082. this._initialQuaternion.normalize();
  55083. //force rotation update
  55084. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  55085. };
  55086. return DeviceOrientationCamera;
  55087. }(BABYLON.FreeCamera));
  55088. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  55089. })(BABYLON || (BABYLON = {}));
  55090. var BABYLON;
  55091. (function (BABYLON) {
  55092. var VRDeviceOrientationFreeCamera = (function (_super) {
  55093. __extends(VRDeviceOrientationFreeCamera, _super);
  55094. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  55095. if (compensateDistortion === void 0) { compensateDistortion = true; }
  55096. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  55097. _super.call(this, name, position, scene);
  55098. vrCameraMetrics.compensateDistortion = compensateDistortion;
  55099. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  55100. }
  55101. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  55102. return "VRDeviceOrientationFreeCamera";
  55103. };
  55104. return VRDeviceOrientationFreeCamera;
  55105. }(BABYLON.DeviceOrientationCamera));
  55106. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  55107. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  55108. __extends(VRDeviceOrientationArcRotateCamera, _super);
  55109. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  55110. if (compensateDistortion === void 0) { compensateDistortion = true; }
  55111. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  55112. _super.call(this, name, alpha, beta, radius, target, scene);
  55113. vrCameraMetrics.compensateDistortion = compensateDistortion;
  55114. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  55115. this.inputs.addVRDeviceOrientation();
  55116. }
  55117. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  55118. return "VRDeviceOrientationArcRotateCamera";
  55119. };
  55120. return VRDeviceOrientationArcRotateCamera;
  55121. }(BABYLON.ArcRotateCamera));
  55122. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  55123. })(BABYLON || (BABYLON = {}));
  55124. var BABYLON;
  55125. (function (BABYLON) {
  55126. // We're mainly based on the logic defined into the FreeCamera code
  55127. var UniversalCamera = (function (_super) {
  55128. __extends(UniversalCamera, _super);
  55129. //-- end properties for backward compatibility for inputs
  55130. function UniversalCamera(name, position, scene) {
  55131. _super.call(this, name, position, scene);
  55132. this.inputs.addGamepad();
  55133. }
  55134. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  55135. //-- Begin properties for backward compatibility for inputs
  55136. get: function () {
  55137. var gamepad = this.inputs.attached["gamepad"];
  55138. if (gamepad)
  55139. return gamepad.gamepadAngularSensibility;
  55140. },
  55141. set: function (value) {
  55142. var gamepad = this.inputs.attached["gamepad"];
  55143. if (gamepad)
  55144. gamepad.gamepadAngularSensibility = value;
  55145. },
  55146. enumerable: true,
  55147. configurable: true
  55148. });
  55149. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  55150. get: function () {
  55151. var gamepad = this.inputs.attached["gamepad"];
  55152. if (gamepad)
  55153. return gamepad.gamepadMoveSensibility;
  55154. },
  55155. set: function (value) {
  55156. var gamepad = this.inputs.attached["gamepad"];
  55157. if (gamepad)
  55158. gamepad.gamepadMoveSensibility = value;
  55159. },
  55160. enumerable: true,
  55161. configurable: true
  55162. });
  55163. UniversalCamera.prototype.getTypeName = function () {
  55164. return "UniversalCamera";
  55165. };
  55166. return UniversalCamera;
  55167. }(BABYLON.TouchCamera));
  55168. BABYLON.UniversalCamera = UniversalCamera;
  55169. })(BABYLON || (BABYLON = {}));
  55170. var BABYLON;
  55171. (function (BABYLON) {
  55172. var Gamepads = (function () {
  55173. function Gamepads(ongamedpadconnected) {
  55174. var _this = this;
  55175. this.babylonGamepads = [];
  55176. this.oneGamepadConnected = false;
  55177. this.isMonitoring = false;
  55178. this.gamepadEventSupported = 'GamepadEvent' in window;
  55179. this.gamepadSupportAvailable = (navigator.getGamepads ||
  55180. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  55181. this._callbackGamepadConnected = ongamedpadconnected;
  55182. if (this.gamepadSupportAvailable) {
  55183. // Checking if the gamepad connected event is supported (like in Firefox)
  55184. if (this.gamepadEventSupported) {
  55185. this._onGamepadConnectedEvent = function (evt) {
  55186. _this._onGamepadConnected(evt);
  55187. };
  55188. this._onGamepadDisonnectedEvent = function (evt) {
  55189. _this._onGamepadDisconnected(evt);
  55190. };
  55191. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55192. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55193. }
  55194. else {
  55195. this._startMonitoringGamepads();
  55196. }
  55197. }
  55198. }
  55199. Gamepads.prototype.dispose = function () {
  55200. if (Gamepads.gamepadDOMInfo) {
  55201. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55202. }
  55203. if (this._onGamepadConnectedEvent) {
  55204. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55205. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  55206. this._onGamepadConnectedEvent = null;
  55207. this._onGamepadDisonnectedEvent = null;
  55208. }
  55209. };
  55210. Gamepads.prototype._onGamepadConnected = function (evt) {
  55211. var newGamepad = this._addNewGamepad(evt.gamepad);
  55212. if (this._callbackGamepadConnected)
  55213. this._callbackGamepadConnected(newGamepad);
  55214. this._startMonitoringGamepads();
  55215. };
  55216. Gamepads.prototype._addNewGamepad = function (gamepad) {
  55217. if (!this.oneGamepadConnected) {
  55218. this.oneGamepadConnected = true;
  55219. if (Gamepads.gamepadDOMInfo) {
  55220. document.body.removeChild(Gamepads.gamepadDOMInfo);
  55221. Gamepads.gamepadDOMInfo = null;
  55222. }
  55223. }
  55224. var newGamepad;
  55225. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55226. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  55227. }
  55228. else {
  55229. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  55230. }
  55231. this.babylonGamepads.push(newGamepad);
  55232. return newGamepad;
  55233. };
  55234. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  55235. // Remove the gamepad from the list of gamepads to monitor.
  55236. for (var i in this.babylonGamepads) {
  55237. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  55238. this.babylonGamepads.splice(+i, 1);
  55239. break;
  55240. }
  55241. }
  55242. // If no gamepads are left, stop the polling loop.
  55243. if (this.babylonGamepads.length == 0) {
  55244. this._stopMonitoringGamepads();
  55245. }
  55246. };
  55247. Gamepads.prototype._startMonitoringGamepads = function () {
  55248. if (!this.isMonitoring) {
  55249. this.isMonitoring = true;
  55250. this._checkGamepadsStatus();
  55251. }
  55252. };
  55253. Gamepads.prototype._stopMonitoringGamepads = function () {
  55254. this.isMonitoring = false;
  55255. };
  55256. Gamepads.prototype._checkGamepadsStatus = function () {
  55257. var _this = this;
  55258. // updating gamepad objects
  55259. this._updateGamepadObjects();
  55260. for (var i in this.babylonGamepads) {
  55261. this.babylonGamepads[i].update();
  55262. }
  55263. if (this.isMonitoring) {
  55264. if (window.requestAnimationFrame) {
  55265. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55266. }
  55267. else if (window.mozRequestAnimationFrame) {
  55268. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55269. }
  55270. else if (window.webkitRequestAnimationFrame) {
  55271. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  55272. }
  55273. }
  55274. };
  55275. // This function is called only on Chrome, which does not yet support
  55276. // connection/disconnection events, but requires you to monitor
  55277. // an array for changes.
  55278. Gamepads.prototype._updateGamepadObjects = function () {
  55279. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55280. for (var i = 0; i < gamepads.length; i++) {
  55281. if (gamepads[i]) {
  55282. if (!(gamepads[i].index in this.babylonGamepads)) {
  55283. var newGamepad = this._addNewGamepad(gamepads[i]);
  55284. if (this._callbackGamepadConnected) {
  55285. this._callbackGamepadConnected(newGamepad);
  55286. }
  55287. }
  55288. else {
  55289. this.babylonGamepads[i].browserGamepad = gamepads[i];
  55290. }
  55291. }
  55292. }
  55293. };
  55294. return Gamepads;
  55295. }());
  55296. BABYLON.Gamepads = Gamepads;
  55297. var StickValues = (function () {
  55298. function StickValues(x, y) {
  55299. this.x = x;
  55300. this.y = y;
  55301. }
  55302. return StickValues;
  55303. }());
  55304. BABYLON.StickValues = StickValues;
  55305. var Gamepad = (function () {
  55306. function Gamepad(id, index, browserGamepad) {
  55307. this.id = id;
  55308. this.index = index;
  55309. this.browserGamepad = browserGamepad;
  55310. if (this.browserGamepad.axes.length >= 2) {
  55311. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55312. }
  55313. if (this.browserGamepad.axes.length >= 4) {
  55314. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55315. }
  55316. }
  55317. Gamepad.prototype.onleftstickchanged = function (callback) {
  55318. this._onleftstickchanged = callback;
  55319. };
  55320. Gamepad.prototype.onrightstickchanged = function (callback) {
  55321. this._onrightstickchanged = callback;
  55322. };
  55323. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55324. get: function () {
  55325. return this._leftStick;
  55326. },
  55327. set: function (newValues) {
  55328. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55329. this._onleftstickchanged(newValues);
  55330. }
  55331. this._leftStick = newValues;
  55332. },
  55333. enumerable: true,
  55334. configurable: true
  55335. });
  55336. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55337. get: function () {
  55338. return this._rightStick;
  55339. },
  55340. set: function (newValues) {
  55341. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55342. this._onrightstickchanged(newValues);
  55343. }
  55344. this._rightStick = newValues;
  55345. },
  55346. enumerable: true,
  55347. configurable: true
  55348. });
  55349. Gamepad.prototype.update = function () {
  55350. if (this._leftStick) {
  55351. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  55352. }
  55353. if (this._rightStick) {
  55354. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  55355. }
  55356. };
  55357. return Gamepad;
  55358. }());
  55359. BABYLON.Gamepad = Gamepad;
  55360. var GenericPad = (function (_super) {
  55361. __extends(GenericPad, _super);
  55362. function GenericPad(id, index, gamepad) {
  55363. _super.call(this, id, index, gamepad);
  55364. this.id = id;
  55365. this.index = index;
  55366. this.gamepad = gamepad;
  55367. this._buttons = new Array(gamepad.buttons.length);
  55368. }
  55369. GenericPad.prototype.onbuttondown = function (callback) {
  55370. this._onbuttondown = callback;
  55371. };
  55372. GenericPad.prototype.onbuttonup = function (callback) {
  55373. this._onbuttonup = callback;
  55374. };
  55375. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55376. if (newValue !== currentValue) {
  55377. if (this._onbuttondown && newValue === 1) {
  55378. this._onbuttondown(buttonIndex);
  55379. }
  55380. if (this._onbuttonup && newValue === 0) {
  55381. this._onbuttonup(buttonIndex);
  55382. }
  55383. }
  55384. return newValue;
  55385. };
  55386. GenericPad.prototype.update = function () {
  55387. _super.prototype.update.call(this);
  55388. for (var index = 0; index < this._buttons.length; index++) {
  55389. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  55390. }
  55391. };
  55392. return GenericPad;
  55393. }(Gamepad));
  55394. BABYLON.GenericPad = GenericPad;
  55395. (function (Xbox360Button) {
  55396. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55397. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55398. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55399. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55400. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55401. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55402. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55403. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55404. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55405. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55406. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55407. var Xbox360Button = BABYLON.Xbox360Button;
  55408. (function (Xbox360Dpad) {
  55409. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55410. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55411. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55412. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55413. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55414. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  55415. var Xbox360Pad = (function (_super) {
  55416. __extends(Xbox360Pad, _super);
  55417. function Xbox360Pad() {
  55418. _super.apply(this, arguments);
  55419. this._leftTrigger = 0;
  55420. this._rightTrigger = 0;
  55421. this._buttonA = 0;
  55422. this._buttonB = 0;
  55423. this._buttonX = 0;
  55424. this._buttonY = 0;
  55425. this._buttonBack = 0;
  55426. this._buttonStart = 0;
  55427. this._buttonLB = 0;
  55428. this._buttonRB = 0;
  55429. this._buttonLeftStick = 0;
  55430. this._buttonRightStick = 0;
  55431. this._dPadUp = 0;
  55432. this._dPadDown = 0;
  55433. this._dPadLeft = 0;
  55434. this._dPadRight = 0;
  55435. }
  55436. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55437. this._onlefttriggerchanged = callback;
  55438. };
  55439. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55440. this._onrighttriggerchanged = callback;
  55441. };
  55442. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55443. get: function () {
  55444. return this._leftTrigger;
  55445. },
  55446. set: function (newValue) {
  55447. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55448. this._onlefttriggerchanged(newValue);
  55449. }
  55450. this._leftTrigger = newValue;
  55451. },
  55452. enumerable: true,
  55453. configurable: true
  55454. });
  55455. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55456. get: function () {
  55457. return this._rightTrigger;
  55458. },
  55459. set: function (newValue) {
  55460. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55461. this._onrighttriggerchanged(newValue);
  55462. }
  55463. this._rightTrigger = newValue;
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55469. this._onbuttondown = callback;
  55470. };
  55471. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55472. this._onbuttonup = callback;
  55473. };
  55474. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55475. this._ondpaddown = callback;
  55476. };
  55477. Xbox360Pad.prototype.ondpadup = function (callback) {
  55478. this._ondpadup = callback;
  55479. };
  55480. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55481. if (newValue !== currentValue) {
  55482. if (this._onbuttondown && newValue === 1) {
  55483. this._onbuttondown(buttonType);
  55484. }
  55485. if (this._onbuttonup && newValue === 0) {
  55486. this._onbuttonup(buttonType);
  55487. }
  55488. }
  55489. return newValue;
  55490. };
  55491. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55492. if (newValue !== currentValue) {
  55493. if (this._ondpaddown && newValue === 1) {
  55494. this._ondpaddown(buttonType);
  55495. }
  55496. if (this._ondpadup && newValue === 0) {
  55497. this._ondpadup(buttonType);
  55498. }
  55499. }
  55500. return newValue;
  55501. };
  55502. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55503. get: function () {
  55504. return this._buttonA;
  55505. },
  55506. set: function (value) {
  55507. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55508. },
  55509. enumerable: true,
  55510. configurable: true
  55511. });
  55512. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55513. get: function () {
  55514. return this._buttonB;
  55515. },
  55516. set: function (value) {
  55517. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55518. },
  55519. enumerable: true,
  55520. configurable: true
  55521. });
  55522. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55523. get: function () {
  55524. return this._buttonX;
  55525. },
  55526. set: function (value) {
  55527. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55528. },
  55529. enumerable: true,
  55530. configurable: true
  55531. });
  55532. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55533. get: function () {
  55534. return this._buttonY;
  55535. },
  55536. set: function (value) {
  55537. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55538. },
  55539. enumerable: true,
  55540. configurable: true
  55541. });
  55542. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55543. get: function () {
  55544. return this._buttonStart;
  55545. },
  55546. set: function (value) {
  55547. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55548. },
  55549. enumerable: true,
  55550. configurable: true
  55551. });
  55552. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55553. get: function () {
  55554. return this._buttonBack;
  55555. },
  55556. set: function (value) {
  55557. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55558. },
  55559. enumerable: true,
  55560. configurable: true
  55561. });
  55562. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55563. get: function () {
  55564. return this._buttonLB;
  55565. },
  55566. set: function (value) {
  55567. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55568. },
  55569. enumerable: true,
  55570. configurable: true
  55571. });
  55572. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55573. get: function () {
  55574. return this._buttonRB;
  55575. },
  55576. set: function (value) {
  55577. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55578. },
  55579. enumerable: true,
  55580. configurable: true
  55581. });
  55582. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55583. get: function () {
  55584. return this._buttonLeftStick;
  55585. },
  55586. set: function (value) {
  55587. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55588. },
  55589. enumerable: true,
  55590. configurable: true
  55591. });
  55592. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55593. get: function () {
  55594. return this._buttonRightStick;
  55595. },
  55596. set: function (value) {
  55597. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55598. },
  55599. enumerable: true,
  55600. configurable: true
  55601. });
  55602. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55603. get: function () {
  55604. return this._dPadUp;
  55605. },
  55606. set: function (value) {
  55607. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55608. },
  55609. enumerable: true,
  55610. configurable: true
  55611. });
  55612. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55613. get: function () {
  55614. return this._dPadDown;
  55615. },
  55616. set: function (value) {
  55617. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55618. },
  55619. enumerable: true,
  55620. configurable: true
  55621. });
  55622. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55623. get: function () {
  55624. return this._dPadLeft;
  55625. },
  55626. set: function (value) {
  55627. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55628. },
  55629. enumerable: true,
  55630. configurable: true
  55631. });
  55632. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55633. get: function () {
  55634. return this._dPadRight;
  55635. },
  55636. set: function (value) {
  55637. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55638. },
  55639. enumerable: true,
  55640. configurable: true
  55641. });
  55642. Xbox360Pad.prototype.update = function () {
  55643. _super.prototype.update.call(this);
  55644. this.buttonA = this.browserGamepad.buttons[0].value;
  55645. this.buttonB = this.browserGamepad.buttons[1].value;
  55646. this.buttonX = this.browserGamepad.buttons[2].value;
  55647. this.buttonY = this.browserGamepad.buttons[3].value;
  55648. this.buttonLB = this.browserGamepad.buttons[4].value;
  55649. this.buttonRB = this.browserGamepad.buttons[5].value;
  55650. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55651. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55652. this.buttonBack = this.browserGamepad.buttons[8].value;
  55653. this.buttonStart = this.browserGamepad.buttons[9].value;
  55654. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55655. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55656. this.dPadUp = this.browserGamepad.buttons[12].value;
  55657. this.dPadDown = this.browserGamepad.buttons[13].value;
  55658. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55659. this.dPadRight = this.browserGamepad.buttons[15].value;
  55660. };
  55661. return Xbox360Pad;
  55662. }(Gamepad));
  55663. BABYLON.Xbox360Pad = Xbox360Pad;
  55664. })(BABYLON || (BABYLON = {}));
  55665. var BABYLON;
  55666. (function (BABYLON) {
  55667. // We're mainly based on the logic defined into the FreeCamera code
  55668. var GamepadCamera = (function (_super) {
  55669. __extends(GamepadCamera, _super);
  55670. //-- end properties for backward compatibility for inputs
  55671. function GamepadCamera(name, position, scene) {
  55672. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  55673. _super.call(this, name, position, scene);
  55674. }
  55675. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  55676. //-- Begin properties for backward compatibility for inputs
  55677. get: function () {
  55678. var gamepad = this.inputs.attached["gamepad"];
  55679. if (gamepad)
  55680. return gamepad.gamepadAngularSensibility;
  55681. },
  55682. set: function (value) {
  55683. var gamepad = this.inputs.attached["gamepad"];
  55684. if (gamepad)
  55685. gamepad.gamepadAngularSensibility = value;
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  55691. get: function () {
  55692. var gamepad = this.inputs.attached["gamepad"];
  55693. if (gamepad)
  55694. return gamepad.gamepadMoveSensibility;
  55695. },
  55696. set: function (value) {
  55697. var gamepad = this.inputs.attached["gamepad"];
  55698. if (gamepad)
  55699. gamepad.gamepadMoveSensibility = value;
  55700. },
  55701. enumerable: true,
  55702. configurable: true
  55703. });
  55704. GamepadCamera.prototype.getTypeName = function () {
  55705. return "GamepadCamera";
  55706. };
  55707. return GamepadCamera;
  55708. }(BABYLON.UniversalCamera));
  55709. BABYLON.GamepadCamera = GamepadCamera;
  55710. })(BABYLON || (BABYLON = {}));
  55711. var BABYLON;
  55712. (function (BABYLON) {
  55713. var Analyser = (function () {
  55714. function Analyser(scene) {
  55715. this.SMOOTHING = 0.75;
  55716. this.FFT_SIZE = 512;
  55717. this.BARGRAPHAMPLITUDE = 256;
  55718. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55719. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55720. this._scene = scene;
  55721. this._audioEngine = BABYLON.Engine.audioEngine;
  55722. if (this._audioEngine.canUseWebAudio) {
  55723. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55724. this._webAudioAnalyser.minDecibels = -140;
  55725. this._webAudioAnalyser.maxDecibels = 0;
  55726. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55727. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55728. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55729. }
  55730. }
  55731. Analyser.prototype.getFrequencyBinCount = function () {
  55732. if (this._audioEngine.canUseWebAudio) {
  55733. return this._webAudioAnalyser.frequencyBinCount;
  55734. }
  55735. else {
  55736. return 0;
  55737. }
  55738. };
  55739. Analyser.prototype.getByteFrequencyData = function () {
  55740. if (this._audioEngine.canUseWebAudio) {
  55741. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55742. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55743. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55744. }
  55745. return this._byteFreqs;
  55746. };
  55747. Analyser.prototype.getByteTimeDomainData = function () {
  55748. if (this._audioEngine.canUseWebAudio) {
  55749. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55750. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55751. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55752. }
  55753. return this._byteTime;
  55754. };
  55755. Analyser.prototype.getFloatFrequencyData = function () {
  55756. if (this._audioEngine.canUseWebAudio) {
  55757. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55758. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55759. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55760. }
  55761. return this._floatFreqs;
  55762. };
  55763. Analyser.prototype.drawDebugCanvas = function () {
  55764. var _this = this;
  55765. if (this._audioEngine.canUseWebAudio) {
  55766. if (!this._debugCanvas) {
  55767. this._debugCanvas = document.createElement("canvas");
  55768. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55769. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55770. this._debugCanvas.style.position = "absolute";
  55771. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55772. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55773. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55774. document.body.appendChild(this._debugCanvas);
  55775. this._registerFunc = function () {
  55776. _this.drawDebugCanvas();
  55777. };
  55778. this._scene.registerBeforeRender(this._registerFunc);
  55779. }
  55780. if (this._registerFunc) {
  55781. var workingArray = this.getByteFrequencyData();
  55782. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55783. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55784. // Draw the frequency domain chart.
  55785. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55786. var value = workingArray[i];
  55787. var percent = value / this.BARGRAPHAMPLITUDE;
  55788. var height = this.DEBUGCANVASSIZE.height * percent;
  55789. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55790. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55791. var hue = i / this.getFrequencyBinCount() * 360;
  55792. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55793. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55794. }
  55795. }
  55796. }
  55797. };
  55798. Analyser.prototype.stopDebugCanvas = function () {
  55799. if (this._debugCanvas) {
  55800. this._scene.unregisterBeforeRender(this._registerFunc);
  55801. this._registerFunc = null;
  55802. document.body.removeChild(this._debugCanvas);
  55803. this._debugCanvas = null;
  55804. this._debugCanvasContext = null;
  55805. }
  55806. };
  55807. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55808. if (this._audioEngine.canUseWebAudio) {
  55809. inputAudioNode.connect(this._webAudioAnalyser);
  55810. this._webAudioAnalyser.connect(outputAudioNode);
  55811. }
  55812. };
  55813. Analyser.prototype.dispose = function () {
  55814. if (this._audioEngine.canUseWebAudio) {
  55815. this._webAudioAnalyser.disconnect();
  55816. }
  55817. };
  55818. return Analyser;
  55819. }());
  55820. BABYLON.Analyser = Analyser;
  55821. })(BABYLON || (BABYLON = {}));
  55822. var BABYLON;
  55823. (function (BABYLON) {
  55824. var DepthRenderer = (function () {
  55825. function DepthRenderer(scene, type) {
  55826. var _this = this;
  55827. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55828. this._viewMatrix = BABYLON.Matrix.Zero();
  55829. this._projectionMatrix = BABYLON.Matrix.Zero();
  55830. this._transformMatrix = BABYLON.Matrix.Zero();
  55831. this._worldViewProjection = BABYLON.Matrix.Zero();
  55832. this._scene = scene;
  55833. var engine = scene.getEngine();
  55834. // Render target
  55835. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55836. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55837. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55838. this._depthMap.refreshRate = 1;
  55839. this._depthMap.renderParticles = false;
  55840. this._depthMap.renderList = null;
  55841. // set default depth value to 1.0 (far away)
  55842. this._depthMap.onClearObservable.add(function (engine) {
  55843. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55844. });
  55845. // Custom render function
  55846. var renderSubMesh = function (subMesh) {
  55847. var mesh = subMesh.getRenderingMesh();
  55848. var scene = _this._scene;
  55849. var engine = scene.getEngine();
  55850. // Culling
  55851. engine.setState(subMesh.getMaterial().backFaceCulling);
  55852. // Managing instances
  55853. var batch = mesh._getInstancesRenderList(subMesh._id);
  55854. if (batch.mustReturn) {
  55855. return;
  55856. }
  55857. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55858. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55859. engine.enableEffect(_this._effect);
  55860. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55861. var material = subMesh.getMaterial();
  55862. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55863. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  55864. // Alpha test
  55865. if (material && material.needAlphaTesting()) {
  55866. var alphaTexture = material.getAlphaTestTexture();
  55867. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55868. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55869. }
  55870. // Bones
  55871. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55872. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55873. }
  55874. // Draw
  55875. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55876. }
  55877. };
  55878. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  55879. var index;
  55880. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55881. renderSubMesh(opaqueSubMeshes.data[index]);
  55882. }
  55883. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55884. renderSubMesh(alphaTestSubMeshes.data[index]);
  55885. }
  55886. };
  55887. }
  55888. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55889. var material = subMesh.getMaterial();
  55890. if (material.disableDepthWrite) {
  55891. return false;
  55892. }
  55893. var defines = [];
  55894. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55895. var mesh = subMesh.getMesh();
  55896. var scene = mesh.getScene();
  55897. // Alpha test
  55898. if (material && material.needAlphaTesting()) {
  55899. defines.push("#define ALPHATEST");
  55900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55901. attribs.push(BABYLON.VertexBuffer.UVKind);
  55902. defines.push("#define UV1");
  55903. }
  55904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55905. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55906. defines.push("#define UV2");
  55907. }
  55908. }
  55909. // Bones
  55910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55913. if (mesh.numBoneInfluencers > 4) {
  55914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55916. }
  55917. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55918. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55919. }
  55920. else {
  55921. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55922. }
  55923. // Instances
  55924. if (useInstances) {
  55925. defines.push("#define INSTANCES");
  55926. attribs.push("world0");
  55927. attribs.push("world1");
  55928. attribs.push("world2");
  55929. attribs.push("world3");
  55930. }
  55931. // Get correct effect
  55932. var join = defines.join("\n");
  55933. if (this._cachedDefines !== join) {
  55934. this._cachedDefines = join;
  55935. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55936. }
  55937. return this._effect.isReady();
  55938. };
  55939. DepthRenderer.prototype.getDepthMap = function () {
  55940. return this._depthMap;
  55941. };
  55942. // Methods
  55943. DepthRenderer.prototype.dispose = function () {
  55944. this._depthMap.dispose();
  55945. };
  55946. return DepthRenderer;
  55947. }());
  55948. BABYLON.DepthRenderer = DepthRenderer;
  55949. })(BABYLON || (BABYLON = {}));
  55950. var BABYLON;
  55951. (function (BABYLON) {
  55952. var SSAORenderingPipeline = (function (_super) {
  55953. __extends(SSAORenderingPipeline, _super);
  55954. /**
  55955. * @constructor
  55956. * @param {string} name - The rendering pipeline name
  55957. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55958. * @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 }
  55959. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55960. */
  55961. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55962. var _this = this;
  55963. _super.call(this, scene.getEngine(), name);
  55964. // Members
  55965. /**
  55966. * The PassPostProcess id in the pipeline that contains the original scene color
  55967. * @type {string}
  55968. */
  55969. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55970. /**
  55971. * The SSAO PostProcess id in the pipeline
  55972. * @type {string}
  55973. */
  55974. this.SSAORenderEffect = "SSAORenderEffect";
  55975. /**
  55976. * The horizontal blur PostProcess id in the pipeline
  55977. * @type {string}
  55978. */
  55979. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55980. /**
  55981. * The vertical blur PostProcess id in the pipeline
  55982. * @type {string}
  55983. */
  55984. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55985. /**
  55986. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55987. * @type {string}
  55988. */
  55989. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55990. /**
  55991. * The output strength of the SSAO post-process. Default value is 1.0.
  55992. * @type {number}
  55993. */
  55994. this.totalStrength = 1.0;
  55995. /**
  55996. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55997. * @type {number}
  55998. */
  55999. this.radius = 0.0001;
  56000. /**
  56001. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56002. * Must not be equal to fallOff and superior to fallOff.
  56003. * Default value is 0.975
  56004. * @type {number}
  56005. */
  56006. this.area = 0.0075;
  56007. /**
  56008. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56009. * Must not be equal to area and inferior to area.
  56010. * Default value is 0.0
  56011. * @type {number}
  56012. */
  56013. this.fallOff = 0.000001;
  56014. /**
  56015. * The base color of the SSAO post-process
  56016. * The final result is "base + ssao" between [0, 1]
  56017. * @type {number}
  56018. */
  56019. this.base = 0.5;
  56020. this._firstUpdate = true;
  56021. this._scene = scene;
  56022. // Set up assets
  56023. this._createRandomTexture();
  56024. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56025. var ssaoRatio = ratio.ssaoRatio || ratio;
  56026. var combineRatio = ratio.combineRatio || ratio;
  56027. this._ratio = {
  56028. ssaoRatio: ssaoRatio,
  56029. combineRatio: combineRatio
  56030. };
  56031. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56032. this._createSSAOPostProcess(ssaoRatio);
  56033. this._createBlurPostProcess(ssaoRatio);
  56034. this._createSSAOCombinePostProcess(combineRatio);
  56035. // Set up pipeline
  56036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  56037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  56038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  56039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  56040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  56041. // Finish
  56042. scene.postProcessRenderPipelineManager.addPipeline(this);
  56043. if (cameras)
  56044. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56045. }
  56046. // Public Methods
  56047. /**
  56048. * Returns the horizontal blur PostProcess
  56049. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  56050. */
  56051. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  56052. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  56053. return null;
  56054. };
  56055. /**
  56056. * Returns the vertical blur PostProcess
  56057. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  56058. */
  56059. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  56060. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  56061. return null;
  56062. };
  56063. /**
  56064. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  56065. */
  56066. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56067. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56068. for (var i = 0; i < this._scene.cameras.length; i++) {
  56069. var camera = this._scene.cameras[i];
  56070. this._originalColorPostProcess.dispose(camera);
  56071. this._ssaoPostProcess.dispose(camera);
  56072. this._blurHPostProcess.dispose(camera);
  56073. this._blurVPostProcess.dispose(camera);
  56074. this._ssaoCombinePostProcess.dispose(camera);
  56075. }
  56076. this._randomTexture.dispose();
  56077. if (disableDepthRender)
  56078. this._scene.disableDepthRenderer();
  56079. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56080. };
  56081. // Private Methods
  56082. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  56083. var _this = this;
  56084. /*
  56085. var samplerOffsets = [
  56086. -8.0, -6.0, -4.0, -2.0,
  56087. 0.0,
  56088. 2.0, 4.0, 6.0, 8.0
  56089. ];
  56090. */
  56091. var samples = 16;
  56092. var samplerOffsets = [];
  56093. for (var i = -8; i < 8; i++) {
  56094. samplerOffsets.push(i * 2);
  56095. }
  56096. 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");
  56097. this._blurHPostProcess.onApply = function (effect) {
  56098. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  56099. effect.setTexture("depthSampler", _this._depthTexture);
  56100. if (_this._firstUpdate) {
  56101. effect.setArray("samplerOffsets", samplerOffsets);
  56102. }
  56103. };
  56104. 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");
  56105. this._blurVPostProcess.onApply = function (effect) {
  56106. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  56107. effect.setTexture("depthSampler", _this._depthTexture);
  56108. if (_this._firstUpdate) {
  56109. effect.setArray("samplerOffsets", samplerOffsets);
  56110. _this._firstUpdate = false;
  56111. }
  56112. };
  56113. };
  56114. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56115. var _this = this;
  56116. var numSamples = 16;
  56117. var sampleSphere = [
  56118. 0.5381, 0.1856, -0.4319,
  56119. 0.1379, 0.2486, 0.4430,
  56120. 0.3371, 0.5679, -0.0057,
  56121. -0.6999, -0.0451, -0.0019,
  56122. 0.0689, -0.1598, -0.8547,
  56123. 0.0560, 0.0069, -0.1843,
  56124. -0.0146, 0.1402, 0.0762,
  56125. 0.0100, -0.1924, -0.0344,
  56126. -0.3577, -0.5301, -0.4358,
  56127. -0.3169, 0.1063, 0.0158,
  56128. 0.0103, -0.5869, 0.0046,
  56129. -0.0897, -0.4940, 0.3287,
  56130. 0.7119, -0.0154, -0.0918,
  56131. -0.0533, 0.0596, -0.5411,
  56132. 0.0352, -0.0631, 0.5460,
  56133. -0.4776, 0.2847, -0.0271
  56134. ];
  56135. var samplesFactor = 1.0 / numSamples;
  56136. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  56137. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56138. "area", "fallOff", "base", "range", "viewport"
  56139. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56140. var viewport = new BABYLON.Vector2(0, 0);
  56141. this._ssaoPostProcess.onApply = function (effect) {
  56142. if (_this._firstUpdate) {
  56143. effect.setArray3("sampleSphere", sampleSphere);
  56144. effect.setFloat("samplesFactor", samplesFactor);
  56145. effect.setFloat("randTextureTiles", 4.0);
  56146. }
  56147. effect.setFloat("totalStrength", _this.totalStrength);
  56148. effect.setFloat("radius", _this.radius);
  56149. effect.setFloat("area", _this.area);
  56150. effect.setFloat("fallOff", _this.fallOff);
  56151. effect.setFloat("base", _this.base);
  56152. effect.setTexture("textureSampler", _this._depthTexture);
  56153. effect.setTexture("randomSampler", _this._randomTexture);
  56154. };
  56155. };
  56156. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56157. var _this = this;
  56158. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56159. this._ssaoCombinePostProcess.onApply = function (effect) {
  56160. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56161. };
  56162. };
  56163. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  56164. var size = 512;
  56165. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56166. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56167. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56168. var context = this._randomTexture.getContext();
  56169. var rand = function (min, max) {
  56170. return Math.random() * (max - min) + min;
  56171. };
  56172. var randVector = BABYLON.Vector3.Zero();
  56173. for (var x = 0; x < size; x++) {
  56174. for (var y = 0; y < size; y++) {
  56175. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  56176. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  56177. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  56178. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56179. context.fillRect(x, y, 1, 1);
  56180. }
  56181. }
  56182. this._randomTexture.update(false);
  56183. };
  56184. __decorate([
  56185. BABYLON.serialize()
  56186. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  56187. __decorate([
  56188. BABYLON.serialize()
  56189. ], SSAORenderingPipeline.prototype, "radius", void 0);
  56190. __decorate([
  56191. BABYLON.serialize()
  56192. ], SSAORenderingPipeline.prototype, "area", void 0);
  56193. __decorate([
  56194. BABYLON.serialize()
  56195. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  56196. __decorate([
  56197. BABYLON.serialize()
  56198. ], SSAORenderingPipeline.prototype, "base", void 0);
  56199. __decorate([
  56200. BABYLON.serialize()
  56201. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  56202. return SSAORenderingPipeline;
  56203. }(BABYLON.PostProcessRenderPipeline));
  56204. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  56205. })(BABYLON || (BABYLON = {}));
  56206. var BABYLON;
  56207. (function (BABYLON) {
  56208. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  56209. var VolumetricLightScatteringPostProcess = (function (_super) {
  56210. __extends(VolumetricLightScatteringPostProcess, _super);
  56211. /**
  56212. * @constructor
  56213. * @param {string} name - The post-process name
  56214. * @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)
  56215. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  56216. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  56217. * @param {number} samples - The post-process quality, default 100
  56218. * @param {number} samplingMode - The post-process filtering mode
  56219. * @param {BABYLON.Engine} engine - The babylon engine
  56220. * @param {boolean} reusable - If the post-process is reusable
  56221. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  56222. */
  56223. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  56224. var _this = this;
  56225. if (samples === void 0) { samples = 100; }
  56226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56227. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  56228. this._screenCoordinates = BABYLON.Vector2.Zero();
  56229. /**
  56230. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  56231. * @type {Vector3}
  56232. */
  56233. this.customMeshPosition = BABYLON.Vector3.Zero();
  56234. /**
  56235. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  56236. * @type {boolean}
  56237. */
  56238. this.useCustomMeshPosition = false;
  56239. /**
  56240. * If the post-process should inverse the light scattering direction
  56241. * @type {boolean}
  56242. */
  56243. this.invert = true;
  56244. /**
  56245. * Array containing the excluded meshes not rendered in the internal pass
  56246. */
  56247. this.excludedMeshes = new Array();
  56248. /**
  56249. * Controls the overall intensity of the post-process
  56250. * @type {number}
  56251. */
  56252. this.exposure = 0.3;
  56253. /**
  56254. * Dissipates each sample's contribution in range [0, 1]
  56255. * @type {number}
  56256. */
  56257. this.decay = 0.96815;
  56258. /**
  56259. * Controls the overall intensity of each sample
  56260. * @type {number}
  56261. */
  56262. this.weight = 0.58767;
  56263. /**
  56264. * Controls the density of each sample
  56265. * @type {number}
  56266. */
  56267. this.density = 0.926;
  56268. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  56269. var engine = scene.getEngine();
  56270. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  56271. // Configure mesh
  56272. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  56273. // Configure
  56274. this._createPass(scene, ratio.passRatio || ratio);
  56275. this.onActivate = function (camera) {
  56276. if (!_this.isSupported) {
  56277. _this.dispose(camera);
  56278. }
  56279. _this.onActivate = null;
  56280. };
  56281. this.onApplyObservable.add(function (effect) {
  56282. _this._updateMeshScreenCoordinates(scene);
  56283. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  56284. effect.setFloat("exposure", _this.exposure);
  56285. effect.setFloat("decay", _this.decay);
  56286. effect.setFloat("weight", _this.weight);
  56287. effect.setFloat("density", _this.density);
  56288. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  56289. });
  56290. }
  56291. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  56292. get: function () {
  56293. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56294. return false;
  56295. },
  56296. set: function (useDiffuseColor) {
  56297. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56298. },
  56299. enumerable: true,
  56300. configurable: true
  56301. });
  56302. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  56303. var mesh = subMesh.getMesh();
  56304. // Render this.mesh as default
  56305. if (mesh === this.mesh) {
  56306. return mesh.material.isReady(mesh);
  56307. }
  56308. var defines = [];
  56309. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56310. var material = subMesh.getMaterial();
  56311. var needUV = false;
  56312. // Alpha test
  56313. if (material) {
  56314. if (material.needAlphaTesting()) {
  56315. defines.push("#define ALPHATEST");
  56316. }
  56317. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56318. attribs.push(BABYLON.VertexBuffer.UVKind);
  56319. defines.push("#define UV1");
  56320. }
  56321. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56322. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56323. defines.push("#define UV2");
  56324. }
  56325. }
  56326. // Bones
  56327. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56330. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56331. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56332. }
  56333. else {
  56334. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56335. }
  56336. // Instances
  56337. if (useInstances) {
  56338. defines.push("#define INSTANCES");
  56339. attribs.push("world0");
  56340. attribs.push("world1");
  56341. attribs.push("world2");
  56342. attribs.push("world3");
  56343. }
  56344. // Get correct effect
  56345. var join = defines.join("\n");
  56346. if (this._cachedDefines !== join) {
  56347. this._cachedDefines = join;
  56348. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  56349. }
  56350. return this._volumetricLightScatteringPass.isReady();
  56351. };
  56352. /**
  56353. * Sets the new light position for light scattering effect
  56354. * @param {BABYLON.Vector3} The new custom light position
  56355. */
  56356. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  56357. this.customMeshPosition = position;
  56358. };
  56359. /**
  56360. * Returns the light position for light scattering effect
  56361. * @return {BABYLON.Vector3} The custom light position
  56362. */
  56363. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  56364. return this.customMeshPosition;
  56365. };
  56366. /**
  56367. * Disposes the internal assets and detaches the post-process from the camera
  56368. */
  56369. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56370. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56371. if (rttIndex !== -1) {
  56372. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56373. }
  56374. this._volumetricLightScatteringRTT.dispose();
  56375. _super.prototype.dispose.call(this, camera);
  56376. };
  56377. /**
  56378. * Returns the render target texture used by the post-process
  56379. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56380. */
  56381. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56382. return this._volumetricLightScatteringRTT;
  56383. };
  56384. // Private methods
  56385. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56386. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56387. return true;
  56388. }
  56389. return false;
  56390. };
  56391. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56392. var _this = this;
  56393. var engine = scene.getEngine();
  56394. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56395. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56396. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56397. this._volumetricLightScatteringRTT.renderList = null;
  56398. this._volumetricLightScatteringRTT.renderParticles = false;
  56399. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56400. // Custom render function for submeshes
  56401. var renderSubMesh = function (subMesh) {
  56402. var mesh = subMesh.getRenderingMesh();
  56403. if (_this._meshExcluded(mesh)) {
  56404. return;
  56405. }
  56406. var scene = mesh.getScene();
  56407. var engine = scene.getEngine();
  56408. // Culling
  56409. engine.setState(subMesh.getMaterial().backFaceCulling);
  56410. // Managing instances
  56411. var batch = mesh._getInstancesRenderList(subMesh._id);
  56412. if (batch.mustReturn) {
  56413. return;
  56414. }
  56415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  56416. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56417. var effect = _this._volumetricLightScatteringPass;
  56418. if (mesh === _this.mesh) {
  56419. effect = subMesh.getMaterial().getEffect();
  56420. }
  56421. engine.enableEffect(effect);
  56422. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56423. if (mesh === _this.mesh) {
  56424. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56425. }
  56426. else {
  56427. var material = subMesh.getMaterial();
  56428. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56429. // Alpha test
  56430. if (material && material.needAlphaTesting()) {
  56431. var alphaTexture = material.getAlphaTestTexture();
  56432. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56433. if (alphaTexture) {
  56434. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56435. }
  56436. }
  56437. // Bones
  56438. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56439. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56440. }
  56441. }
  56442. // Draw
  56443. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56444. }
  56445. };
  56446. // Render target texture callbacks
  56447. var savedSceneClearColor;
  56448. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56449. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56450. savedSceneClearColor = scene.clearColor;
  56451. scene.clearColor = sceneClearColor;
  56452. });
  56453. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56454. scene.clearColor = savedSceneClearColor;
  56455. });
  56456. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  56457. var engine = scene.getEngine();
  56458. var index;
  56459. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56460. renderSubMesh(opaqueSubMeshes.data[index]);
  56461. }
  56462. engine.setAlphaTesting(true);
  56463. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56464. renderSubMesh(alphaTestSubMeshes.data[index]);
  56465. }
  56466. engine.setAlphaTesting(false);
  56467. if (transparentSubMeshes.length) {
  56468. // Sort sub meshes
  56469. for (index = 0; index < transparentSubMeshes.length; index++) {
  56470. var submesh = transparentSubMeshes.data[index];
  56471. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56472. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56473. }
  56474. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56475. sortedArray.sort(function (a, b) {
  56476. // Alpha index first
  56477. if (a._alphaIndex > b._alphaIndex) {
  56478. return 1;
  56479. }
  56480. if (a._alphaIndex < b._alphaIndex) {
  56481. return -1;
  56482. }
  56483. // Then distance to camera
  56484. if (a._distanceToCamera < b._distanceToCamera) {
  56485. return 1;
  56486. }
  56487. if (a._distanceToCamera > b._distanceToCamera) {
  56488. return -1;
  56489. }
  56490. return 0;
  56491. });
  56492. // Render sub meshes
  56493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56494. for (index = 0; index < sortedArray.length; index++) {
  56495. renderSubMesh(sortedArray[index]);
  56496. }
  56497. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56498. }
  56499. };
  56500. };
  56501. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56502. var transform = scene.getTransformMatrix();
  56503. var meshPosition;
  56504. if (this.useCustomMeshPosition) {
  56505. meshPosition = this.customMeshPosition;
  56506. }
  56507. else if (this.attachedNode) {
  56508. meshPosition = this.attachedNode.position;
  56509. }
  56510. else {
  56511. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56512. }
  56513. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56514. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56515. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56516. if (this.invert)
  56517. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56518. };
  56519. // Static methods
  56520. /**
  56521. * Creates a default mesh for the Volumeric Light Scattering post-process
  56522. * @param {string} The mesh name
  56523. * @param {BABYLON.Scene} The scene where to create the mesh
  56524. * @return {BABYLON.Mesh} the default mesh
  56525. */
  56526. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56527. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56528. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56529. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56530. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56531. mesh.material = material;
  56532. return mesh;
  56533. };
  56534. __decorate([
  56535. BABYLON.serializeAsVector3()
  56536. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56537. __decorate([
  56538. BABYLON.serialize()
  56539. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56540. __decorate([
  56541. BABYLON.serialize()
  56542. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56543. __decorate([
  56544. BABYLON.serializeAsMeshReference()
  56545. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56546. __decorate([
  56547. BABYLON.serialize()
  56548. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56549. __decorate([
  56550. BABYLON.serialize()
  56551. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56552. __decorate([
  56553. BABYLON.serialize()
  56554. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56555. __decorate([
  56556. BABYLON.serialize()
  56557. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56558. __decorate([
  56559. BABYLON.serialize()
  56560. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56561. return VolumetricLightScatteringPostProcess;
  56562. }(BABYLON.PostProcess));
  56563. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56564. })(BABYLON || (BABYLON = {}));
  56565. // BABYLON.JS Chromatic Aberration GLSL Shader
  56566. // Author: Olivier Guyot
  56567. // Separates very slightly R, G and B colors on the edges of the screen
  56568. // Inspired by Francois Tarlier & Martins Upitis
  56569. var BABYLON;
  56570. (function (BABYLON) {
  56571. var LensRenderingPipeline = (function (_super) {
  56572. __extends(LensRenderingPipeline, _super);
  56573. /**
  56574. * @constructor
  56575. *
  56576. * Effect parameters are as follow:
  56577. * {
  56578. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56579. * edge_blur: number; // from 0 to x (1 for realism)
  56580. * distortion: number; // from 0 to x (1 for realism)
  56581. * grain_amount: number; // from 0 to 1
  56582. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56583. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56584. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56585. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56586. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56587. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56588. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56589. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56590. * }
  56591. * Note: if an effect parameter is unset, effect is disabled
  56592. *
  56593. * @param {string} name - The rendering pipeline name
  56594. * @param {object} parameters - An object containing all parameters (see above)
  56595. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56596. * @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)
  56597. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56598. */
  56599. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56600. var _this = this;
  56601. if (ratio === void 0) { ratio = 1.0; }
  56602. _super.call(this, scene.getEngine(), name);
  56603. // Lens effects can be of the following:
  56604. // - chromatic aberration (slight shift of RGB colors)
  56605. // - blur on the edge of the lens
  56606. // - lens distortion
  56607. // - depth-of-field blur & highlights enhancing
  56608. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56609. // - grain effect (noise or custom texture)
  56610. // Two additional texture samplers are needed:
  56611. // - depth map (for depth-of-field)
  56612. // - grain texture
  56613. /**
  56614. * The chromatic aberration PostProcess id in the pipeline
  56615. * @type {string}
  56616. */
  56617. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56618. /**
  56619. * The highlights enhancing PostProcess id in the pipeline
  56620. * @type {string}
  56621. */
  56622. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56623. /**
  56624. * The depth-of-field PostProcess id in the pipeline
  56625. * @type {string}
  56626. */
  56627. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56628. this._scene = scene;
  56629. // Fetch texture samplers
  56630. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56631. if (parameters.grain_texture) {
  56632. this._grainTexture = parameters.grain_texture;
  56633. }
  56634. else {
  56635. this._createGrainTexture();
  56636. }
  56637. // save parameters
  56638. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56639. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56640. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56641. this._distortion = parameters.distortion ? parameters.distortion : 0;
  56642. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56643. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56644. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56645. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56646. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56647. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56648. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56649. // Create effects
  56650. this._createChromaticAberrationPostProcess(ratio);
  56651. this._createHighlightsPostProcess(ratio);
  56652. this._createDepthOfFieldPostProcess(ratio / 4);
  56653. // Set up pipeline
  56654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56657. if (this._highlightsGain === -1) {
  56658. this._disableEffect(this.HighlightsEnhancingEffect, null);
  56659. }
  56660. // Finish
  56661. scene.postProcessRenderPipelineManager.addPipeline(this);
  56662. if (cameras) {
  56663. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56664. }
  56665. }
  56666. // public methods (self explanatory)
  56667. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56668. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56669. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56670. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56671. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56672. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56673. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56674. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56675. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56676. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56677. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56678. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56679. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56680. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56681. };
  56682. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56683. this._highlightsPostProcess.updateEffect();
  56684. };
  56685. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56686. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56687. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56688. this._highlightsGain = amount;
  56689. };
  56690. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56691. if (this._highlightsGain === -1) {
  56692. this._highlightsGain = 1.0;
  56693. }
  56694. this._highlightsThreshold = amount;
  56695. };
  56696. LensRenderingPipeline.prototype.disableHighlights = function () {
  56697. this._highlightsGain = -1;
  56698. };
  56699. /**
  56700. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56701. */
  56702. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56703. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56704. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56705. this._chromaticAberrationPostProcess = undefined;
  56706. this._highlightsPostProcess = undefined;
  56707. this._depthOfFieldPostProcess = undefined;
  56708. this._grainTexture.dispose();
  56709. if (disableDepthRender)
  56710. this._scene.disableDepthRenderer();
  56711. };
  56712. // colors shifting and distortion
  56713. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56714. var _this = this;
  56715. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56716. [], // samplers
  56717. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56718. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56719. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56720. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56721. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56722. };
  56723. };
  56724. // highlights enhancing
  56725. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56726. var _this = this;
  56727. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56728. [], // samplers
  56729. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56730. this._highlightsPostProcess.onApply = function (effect) {
  56731. effect.setFloat('gain', _this._highlightsGain);
  56732. effect.setFloat('threshold', _this._highlightsThreshold);
  56733. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56734. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56735. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56736. };
  56737. };
  56738. // colors shifting and distortion
  56739. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56740. var _this = this;
  56741. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56742. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56743. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56744. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56745. this._depthOfFieldPostProcess.onApply = function (effect) {
  56746. effect.setTexture("depthSampler", _this._depthTexture);
  56747. effect.setTexture("grainSampler", _this._grainTexture);
  56748. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56749. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56750. effect.setFloat('grain_amount', _this._grainAmount);
  56751. effect.setBool('blur_noise', _this._blurNoise);
  56752. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56753. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56754. effect.setFloat('distortion', _this._distortion);
  56755. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56756. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56757. effect.setFloat('aperture', _this._dofAperture);
  56758. effect.setFloat('darken', _this._dofDarken);
  56759. effect.setFloat('edge_blur', _this._edgeBlur);
  56760. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56761. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56762. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56763. };
  56764. };
  56765. // creates a black and white random noise texture, 512x512
  56766. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56767. var size = 512;
  56768. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56769. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56770. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56771. var context = this._grainTexture.getContext();
  56772. var rand = function (min, max) {
  56773. return Math.random() * (max - min) + min;
  56774. };
  56775. var value;
  56776. for (var x = 0; x < size; x++) {
  56777. for (var y = 0; y < size; y++) {
  56778. value = Math.floor(rand(0.42, 0.58) * 255);
  56779. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56780. context.fillRect(x, y, 1, 1);
  56781. }
  56782. }
  56783. this._grainTexture.update(false);
  56784. };
  56785. return LensRenderingPipeline;
  56786. }(BABYLON.PostProcessRenderPipeline));
  56787. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56788. })(BABYLON || (BABYLON = {}));
  56789. //
  56790. // This post-process allows the modification of rendered colors by using
  56791. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56792. //
  56793. // The object needs to be provided an url to a texture containing the color
  56794. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56795. // Use an image editing software to tweak the LUT to match your needs.
  56796. //
  56797. // For an example of a color LUT, see here:
  56798. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56799. // For explanations on color grading, see here:
  56800. // http://udn.epicgames.com/Three/ColorGrading.html
  56801. //
  56802. var BABYLON;
  56803. (function (BABYLON) {
  56804. var ColorCorrectionPostProcess = (function (_super) {
  56805. __extends(ColorCorrectionPostProcess, _super);
  56806. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56807. var _this = this;
  56808. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  56809. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56810. this._colorTableTexture.anisotropicFilteringLevel = 1;
  56811. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56812. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56813. this.onApply = function (effect) {
  56814. effect.setTexture("colorTable", _this._colorTableTexture);
  56815. };
  56816. }
  56817. return ColorCorrectionPostProcess;
  56818. }(BABYLON.PostProcess));
  56819. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56820. })(BABYLON || (BABYLON = {}));
  56821. var BABYLON;
  56822. (function (BABYLON) {
  56823. var AnaglyphFreeCamera = (function (_super) {
  56824. __extends(AnaglyphFreeCamera, _super);
  56825. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  56826. _super.call(this, name, position, scene);
  56827. this.interaxialDistance = interaxialDistance;
  56828. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56829. }
  56830. AnaglyphFreeCamera.prototype.getTypeName = function () {
  56831. return "AnaglyphFreeCamera";
  56832. };
  56833. return AnaglyphFreeCamera;
  56834. }(BABYLON.FreeCamera));
  56835. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  56836. var AnaglyphArcRotateCamera = (function (_super) {
  56837. __extends(AnaglyphArcRotateCamera, _super);
  56838. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  56839. _super.call(this, name, alpha, beta, radius, target, scene);
  56840. this.interaxialDistance = interaxialDistance;
  56841. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56842. }
  56843. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  56844. return "AnaglyphArcRotateCamera";
  56845. };
  56846. return AnaglyphArcRotateCamera;
  56847. }(BABYLON.ArcRotateCamera));
  56848. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  56849. var AnaglyphGamepadCamera = (function (_super) {
  56850. __extends(AnaglyphGamepadCamera, _super);
  56851. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  56852. _super.call(this, name, position, scene);
  56853. this.interaxialDistance = interaxialDistance;
  56854. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56855. }
  56856. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  56857. return "AnaglyphGamepadCamera";
  56858. };
  56859. return AnaglyphGamepadCamera;
  56860. }(BABYLON.GamepadCamera));
  56861. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  56862. var AnaglyphUniversalCamera = (function (_super) {
  56863. __extends(AnaglyphUniversalCamera, _super);
  56864. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  56865. _super.call(this, name, position, scene);
  56866. this.interaxialDistance = interaxialDistance;
  56867. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56868. }
  56869. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  56870. return "AnaglyphUniversalCamera";
  56871. };
  56872. return AnaglyphUniversalCamera;
  56873. }(BABYLON.UniversalCamera));
  56874. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  56875. var StereoscopicFreeCamera = (function (_super) {
  56876. __extends(StereoscopicFreeCamera, _super);
  56877. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56878. _super.call(this, name, position, scene);
  56879. this.interaxialDistance = interaxialDistance;
  56880. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56881. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56882. }
  56883. StereoscopicFreeCamera.prototype.getTypeName = function () {
  56884. return "StereoscopicFreeCamera";
  56885. };
  56886. return StereoscopicFreeCamera;
  56887. }(BABYLON.FreeCamera));
  56888. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  56889. var StereoscopicArcRotateCamera = (function (_super) {
  56890. __extends(StereoscopicArcRotateCamera, _super);
  56891. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56892. _super.call(this, name, alpha, beta, radius, target, scene);
  56893. this.interaxialDistance = interaxialDistance;
  56894. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56895. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56896. }
  56897. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56898. return "StereoscopicArcRotateCamera";
  56899. };
  56900. return StereoscopicArcRotateCamera;
  56901. }(BABYLON.ArcRotateCamera));
  56902. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56903. var StereoscopicGamepadCamera = (function (_super) {
  56904. __extends(StereoscopicGamepadCamera, _super);
  56905. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56906. _super.call(this, name, position, scene);
  56907. this.interaxialDistance = interaxialDistance;
  56908. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56909. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56910. }
  56911. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56912. return "StereoscopicGamepadCamera";
  56913. };
  56914. return StereoscopicGamepadCamera;
  56915. }(BABYLON.GamepadCamera));
  56916. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56917. var StereoscopicUniversalCamera = (function (_super) {
  56918. __extends(StereoscopicUniversalCamera, _super);
  56919. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56920. _super.call(this, name, position, scene);
  56921. this.interaxialDistance = interaxialDistance;
  56922. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56923. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56924. }
  56925. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56926. return "StereoscopicUniversalCamera";
  56927. };
  56928. return StereoscopicUniversalCamera;
  56929. }(BABYLON.UniversalCamera));
  56930. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56931. })(BABYLON || (BABYLON = {}));
  56932. var BABYLON;
  56933. (function (BABYLON) {
  56934. var HDRRenderingPipeline = (function (_super) {
  56935. __extends(HDRRenderingPipeline, _super);
  56936. /**
  56937. * @constructor
  56938. * @param {string} name - The rendering pipeline name
  56939. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56940. * @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)
  56941. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56942. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56943. */
  56944. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56945. var _this = this;
  56946. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56947. _super.call(this, scene.getEngine(), name);
  56948. /**
  56949. * Public members
  56950. */
  56951. // Gaussian Blur
  56952. /**
  56953. * Gaussian blur coefficient
  56954. * @type {number}
  56955. */
  56956. this.gaussCoeff = 0.3;
  56957. /**
  56958. * Gaussian blur mean
  56959. * @type {number}
  56960. */
  56961. this.gaussMean = 1.0;
  56962. /**
  56963. * Gaussian blur standard deviation
  56964. * @type {number}
  56965. */
  56966. this.gaussStandDev = 0.8;
  56967. /**
  56968. * Gaussian blur multiplier. Multiplies the blur effect
  56969. * @type {number}
  56970. */
  56971. this.gaussMultiplier = 4.0;
  56972. // HDR
  56973. /**
  56974. * Exposure, controls the overall intensity of the pipeline
  56975. * @type {number}
  56976. */
  56977. this.exposure = 1.0;
  56978. /**
  56979. * Minimum luminance that the post-process can output. Luminance is >= 0
  56980. * @type {number}
  56981. */
  56982. this.minimumLuminance = 1.0;
  56983. /**
  56984. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56985. * @type {number}
  56986. */
  56987. this.maximumLuminance = 1e20;
  56988. /**
  56989. * Increase rate for luminance: eye adaptation speed to dark
  56990. * @type {number}
  56991. */
  56992. this.luminanceIncreaserate = 0.5;
  56993. /**
  56994. * Decrease rate for luminance: eye adaptation speed to bright
  56995. * @type {number}
  56996. */
  56997. this.luminanceDecreaseRate = 0.5;
  56998. // Bright pass
  56999. /**
  57000. * Minimum luminance needed to compute HDR
  57001. * @type {number}
  57002. */
  57003. this.brightThreshold = 0.8;
  57004. this._needUpdate = true;
  57005. this._scene = scene;
  57006. // Bright pass
  57007. this._createBrightPassPostProcess(scene, ratio);
  57008. // Down sample X4
  57009. this._createDownSampleX4PostProcess(scene, ratio);
  57010. // Create gaussian blur post-processes
  57011. this._createGaussianBlurPostProcess(scene, ratio);
  57012. // Texture adder
  57013. this._createTextureAdderPostProcess(scene, ratio);
  57014. // Luminance generator
  57015. this._createLuminanceGeneratorPostProcess(scene);
  57016. // HDR
  57017. this._createHDRPostProcess(scene, ratio);
  57018. // Pass postprocess
  57019. if (originalPostProcess === null) {
  57020. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57021. }
  57022. else {
  57023. this._originalPostProcess = originalPostProcess;
  57024. }
  57025. // Configure pipeline
  57026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  57027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  57028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  57029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  57030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  57031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  57032. var addDownSamplerPostProcess = function (id) {
  57033. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  57034. };
  57035. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  57036. addDownSamplerPostProcess(i);
  57037. }
  57038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  57039. // Finish
  57040. scene.postProcessRenderPipelineManager.addPipeline(this);
  57041. if (cameras !== null) {
  57042. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57043. }
  57044. this.update();
  57045. }
  57046. /**
  57047. * Tells the pipeline to update its post-processes
  57048. */
  57049. HDRRenderingPipeline.prototype.update = function () {
  57050. this._needUpdate = true;
  57051. };
  57052. /**
  57053. * Returns the current calculated luminance
  57054. */
  57055. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  57056. return this._hdrCurrentLuminance;
  57057. };
  57058. /**
  57059. * Returns the currently drawn luminance
  57060. */
  57061. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  57062. return this._hdrOutputLuminance;
  57063. };
  57064. /**
  57065. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  57066. */
  57067. HDRRenderingPipeline.prototype.dispose = function () {
  57068. this._originalPostProcess = undefined;
  57069. this._brightPassPostProcess = undefined;
  57070. this._downSampleX4PostProcess = undefined;
  57071. this._guassianBlurHPostProcess = undefined;
  57072. this._guassianBlurVPostProcess = undefined;
  57073. this._textureAdderPostProcess = undefined;
  57074. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  57075. this._downSamplePostProcesses[i] = undefined;
  57076. }
  57077. this._hdrPostProcess = undefined;
  57078. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57079. };
  57080. /**
  57081. * Creates the HDR post-process and computes the luminance adaptation
  57082. */
  57083. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  57084. var _this = this;
  57085. var hdrLastLuminance = 0.0;
  57086. this._hdrOutputLuminance = -1.0;
  57087. this._hdrCurrentLuminance = 1.0;
  57088. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  57089. this._hdrPostProcess.onApply = function (effect) {
  57090. if (_this._hdrOutputLuminance < 0.0) {
  57091. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  57092. }
  57093. else {
  57094. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  57095. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  57096. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  57097. }
  57098. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  57099. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  57100. }
  57101. else {
  57102. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  57103. }
  57104. }
  57105. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  57106. hdrLastLuminance += scene.getEngine().getDeltaTime();
  57107. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  57108. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  57109. effect.setFloat("exposure", _this.exposure);
  57110. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  57111. _this._needUpdate = false;
  57112. };
  57113. };
  57114. /**
  57115. * Texture Adder post-process
  57116. */
  57117. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57118. var _this = this;
  57119. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  57120. this._textureAdderPostProcess.onApply = function (effect) {
  57121. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  57122. };
  57123. };
  57124. /**
  57125. * Down sample X4 post-process
  57126. */
  57127. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57128. var _this = this;
  57129. var downSampleX4Offsets = new Array(32);
  57130. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  57131. this._downSampleX4PostProcess.onApply = function (effect) {
  57132. if (_this._needUpdate) {
  57133. var id = 0;
  57134. for (var i = -2; i < 2; i++) {
  57135. for (var j = -2; j < 2; j++) {
  57136. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  57137. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  57138. id += 2;
  57139. }
  57140. }
  57141. }
  57142. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57143. };
  57144. };
  57145. /**
  57146. * Bright pass post-process
  57147. */
  57148. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57149. var _this = this;
  57150. var brightOffsets = new Array(8);
  57151. var brightPassCallback = function (effect) {
  57152. if (_this._needUpdate) {
  57153. var sU = (1.0 / _this._brightPassPostProcess.width);
  57154. var sV = (1.0 / _this._brightPassPostProcess.height);
  57155. brightOffsets[0] = -0.5 * sU;
  57156. brightOffsets[1] = 0.5 * sV;
  57157. brightOffsets[2] = 0.5 * sU;
  57158. brightOffsets[3] = 0.5 * sV;
  57159. brightOffsets[4] = -0.5 * sU;
  57160. brightOffsets[5] = -0.5 * sV;
  57161. brightOffsets[6] = 0.5 * sU;
  57162. brightOffsets[7] = -0.5 * sV;
  57163. }
  57164. effect.setArray2("dsOffsets", brightOffsets);
  57165. effect.setFloat("brightThreshold", _this.brightThreshold);
  57166. };
  57167. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  57168. this._brightPassPostProcess.onApply = brightPassCallback;
  57169. };
  57170. /**
  57171. * Luminance generator. Creates the luminance post-process and down sample post-processes
  57172. */
  57173. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  57174. var _this = this;
  57175. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  57176. var luminanceOffsets = new Array(8);
  57177. var downSampleOffsets = new Array(18);
  57178. var halfDestPixelSize;
  57179. this._downSamplePostProcesses = new Array(lumSteps);
  57180. // Utils for luminance
  57181. var luminanceUpdateSourceOffsets = function (width, height) {
  57182. var sU = (1.0 / width);
  57183. var sV = (1.0 / height);
  57184. luminanceOffsets[0] = -0.5 * sU;
  57185. luminanceOffsets[1] = 0.5 * sV;
  57186. luminanceOffsets[2] = 0.5 * sU;
  57187. luminanceOffsets[3] = 0.5 * sV;
  57188. luminanceOffsets[4] = -0.5 * sU;
  57189. luminanceOffsets[5] = -0.5 * sV;
  57190. luminanceOffsets[6] = 0.5 * sU;
  57191. luminanceOffsets[7] = -0.5 * sV;
  57192. };
  57193. var luminanceUpdateDestOffsets = function (width, height) {
  57194. var id = 0;
  57195. for (var x = -1; x < 2; x++) {
  57196. for (var y = -1; y < 2; y++) {
  57197. downSampleOffsets[id] = (x) / width;
  57198. downSampleOffsets[id + 1] = (y) / height;
  57199. id += 2;
  57200. }
  57201. }
  57202. };
  57203. // Luminance callback
  57204. var luminanceCallback = function (effect) {
  57205. if (_this._needUpdate) {
  57206. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  57207. }
  57208. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  57209. effect.setArray2("lumOffsets", luminanceOffsets);
  57210. };
  57211. // Down sample callbacks
  57212. var downSampleCallback = function (indice) {
  57213. var i = indice;
  57214. return function (effect) {
  57215. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57216. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  57217. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  57218. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  57219. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  57220. effect.setArray2("dsOffsets", downSampleOffsets);
  57221. };
  57222. };
  57223. var downSampleAfterRenderCallback = function (effect) {
  57224. // Unpack result
  57225. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  57226. 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);
  57227. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  57228. };
  57229. // Create luminance post-process
  57230. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  57231. 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);
  57232. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  57233. // Create down sample post-processes
  57234. for (var i = lumSteps - 2; i >= 0; i--) {
  57235. var length = Math.pow(3, i);
  57236. ratio = { width: length, height: length };
  57237. var defines = "#define DOWN_SAMPLE\n";
  57238. if (i === 0) {
  57239. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  57240. }
  57241. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57242. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  57243. if (i === 0) {
  57244. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  57245. }
  57246. }
  57247. };
  57248. /**
  57249. * Gaussian blur post-processes. Horizontal and Vertical
  57250. */
  57251. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  57252. var _this = this;
  57253. var blurOffsetsW = new Array(9);
  57254. var blurOffsetsH = new Array(9);
  57255. var blurWeights = new Array(9);
  57256. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  57257. // Utils for gaussian blur
  57258. var calculateBlurOffsets = function (height) {
  57259. var lastOutputDimensions = {
  57260. width: scene.getEngine().getRenderWidth(),
  57261. height: scene.getEngine().getRenderHeight()
  57262. };
  57263. for (var i = 0; i < 9; i++) {
  57264. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57265. if (height) {
  57266. blurOffsetsH[i] = value;
  57267. }
  57268. else {
  57269. blurOffsetsW[i] = value;
  57270. }
  57271. }
  57272. };
  57273. var calculateWeights = function () {
  57274. var x = 0.0;
  57275. for (var i = 0; i < 9; i++) {
  57276. x = (i - 4.0) / 4.0;
  57277. 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));
  57278. }
  57279. };
  57280. // Callback
  57281. var gaussianBlurCallback = function (height) {
  57282. return function (effect) {
  57283. if (_this._needUpdate) {
  57284. calculateWeights();
  57285. calculateBlurOffsets(height);
  57286. }
  57287. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  57288. effect.setArray("blurWeights", blurWeights);
  57289. effect.setFloat("multiplier", _this.gaussMultiplier);
  57290. };
  57291. };
  57292. // Create horizontal gaussian blur post-processes
  57293. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  57294. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  57295. // Create vertical gaussian blur post-process
  57296. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  57297. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  57298. };
  57299. // Luminance generator
  57300. HDRRenderingPipeline.LUM_STEPS = 6;
  57301. return HDRRenderingPipeline;
  57302. }(BABYLON.PostProcessRenderPipeline));
  57303. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  57304. })(BABYLON || (BABYLON = {}));
  57305. var BABYLON;
  57306. (function (BABYLON) {
  57307. var FaceAdjacencies = (function () {
  57308. function FaceAdjacencies() {
  57309. this.edges = new Array();
  57310. this.edgesConnectedCount = 0;
  57311. }
  57312. return FaceAdjacencies;
  57313. }());
  57314. var EdgesRenderer = (function () {
  57315. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  57316. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  57317. if (epsilon === void 0) { epsilon = 0.95; }
  57318. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  57319. this.edgesWidthScalerForOrthographic = 1000.0;
  57320. this.edgesWidthScalerForPerspective = 50.0;
  57321. this._linesPositions = new Array();
  57322. this._linesNormals = new Array();
  57323. this._linesIndices = new Array();
  57324. this._buffers = {};
  57325. this._checkVerticesInsteadOfIndices = false;
  57326. this._source = source;
  57327. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  57328. this._epsilon = epsilon;
  57329. this._prepareRessources();
  57330. this._generateEdgesLines();
  57331. }
  57332. EdgesRenderer.prototype._prepareRessources = function () {
  57333. if (this._lineShader) {
  57334. return;
  57335. }
  57336. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  57337. attributes: ["position", "normal"],
  57338. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  57339. });
  57340. this._lineShader.disableDepthWrite = true;
  57341. this._lineShader.backFaceCulling = false;
  57342. };
  57343. EdgesRenderer.prototype.dispose = function () {
  57344. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  57345. if (buffer) {
  57346. buffer.dispose();
  57347. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  57348. }
  57349. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  57350. if (buffer) {
  57351. buffer.dispose();
  57352. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  57353. }
  57354. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  57355. this._lineShader.dispose();
  57356. };
  57357. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  57358. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  57359. return 0;
  57360. }
  57361. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  57362. return 1;
  57363. }
  57364. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  57365. return 2;
  57366. }
  57367. return -1;
  57368. };
  57369. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  57370. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  57371. return 0;
  57372. }
  57373. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  57374. return 1;
  57375. }
  57376. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  57377. return 2;
  57378. }
  57379. return -1;
  57380. };
  57381. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  57382. var needToCreateLine;
  57383. if (edge === undefined) {
  57384. needToCreateLine = true;
  57385. }
  57386. else {
  57387. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  57388. needToCreateLine = dotProduct < this._epsilon;
  57389. }
  57390. if (needToCreateLine) {
  57391. var offset = this._linesPositions.length / 3;
  57392. var normal = p0.subtract(p1);
  57393. normal.normalize();
  57394. // Positions
  57395. this._linesPositions.push(p0.x);
  57396. this._linesPositions.push(p0.y);
  57397. this._linesPositions.push(p0.z);
  57398. this._linesPositions.push(p0.x);
  57399. this._linesPositions.push(p0.y);
  57400. this._linesPositions.push(p0.z);
  57401. this._linesPositions.push(p1.x);
  57402. this._linesPositions.push(p1.y);
  57403. this._linesPositions.push(p1.z);
  57404. this._linesPositions.push(p1.x);
  57405. this._linesPositions.push(p1.y);
  57406. this._linesPositions.push(p1.z);
  57407. // Normals
  57408. this._linesNormals.push(p1.x);
  57409. this._linesNormals.push(p1.y);
  57410. this._linesNormals.push(p1.z);
  57411. this._linesNormals.push(-1);
  57412. this._linesNormals.push(p1.x);
  57413. this._linesNormals.push(p1.y);
  57414. this._linesNormals.push(p1.z);
  57415. this._linesNormals.push(1);
  57416. this._linesNormals.push(p0.x);
  57417. this._linesNormals.push(p0.y);
  57418. this._linesNormals.push(p0.z);
  57419. this._linesNormals.push(-1);
  57420. this._linesNormals.push(p0.x);
  57421. this._linesNormals.push(p0.y);
  57422. this._linesNormals.push(p0.z);
  57423. this._linesNormals.push(1);
  57424. // Indices
  57425. this._linesIndices.push(offset);
  57426. this._linesIndices.push(offset + 1);
  57427. this._linesIndices.push(offset + 2);
  57428. this._linesIndices.push(offset);
  57429. this._linesIndices.push(offset + 2);
  57430. this._linesIndices.push(offset + 3);
  57431. }
  57432. };
  57433. EdgesRenderer.prototype._generateEdgesLines = function () {
  57434. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57435. var indices = this._source.getIndices();
  57436. // First let's find adjacencies
  57437. var adjacencies = new Array();
  57438. var faceNormals = new Array();
  57439. var index;
  57440. var faceAdjacencies;
  57441. // Prepare faces
  57442. for (index = 0; index < indices.length; index += 3) {
  57443. faceAdjacencies = new FaceAdjacencies();
  57444. var p0Index = indices[index];
  57445. var p1Index = indices[index + 1];
  57446. var p2Index = indices[index + 2];
  57447. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  57448. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  57449. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  57450. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  57451. faceNormal.normalize();
  57452. faceNormals.push(faceNormal);
  57453. adjacencies.push(faceAdjacencies);
  57454. }
  57455. // Scan
  57456. for (index = 0; index < adjacencies.length; index++) {
  57457. faceAdjacencies = adjacencies[index];
  57458. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  57459. var otherFaceAdjacencies = adjacencies[otherIndex];
  57460. if (faceAdjacencies.edgesConnectedCount === 3) {
  57461. break;
  57462. }
  57463. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  57464. continue;
  57465. }
  57466. var otherP0 = indices[otherIndex * 3];
  57467. var otherP1 = indices[otherIndex * 3 + 1];
  57468. var otherP2 = indices[otherIndex * 3 + 2];
  57469. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  57470. var otherEdgeIndex;
  57471. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  57472. continue;
  57473. }
  57474. switch (edgeIndex) {
  57475. case 0:
  57476. if (this._checkVerticesInsteadOfIndices) {
  57477. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57478. }
  57479. else {
  57480. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  57481. }
  57482. break;
  57483. case 1:
  57484. if (this._checkVerticesInsteadOfIndices) {
  57485. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57486. }
  57487. else {
  57488. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  57489. }
  57490. break;
  57491. case 2:
  57492. if (this._checkVerticesInsteadOfIndices) {
  57493. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57494. }
  57495. else {
  57496. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  57497. }
  57498. break;
  57499. }
  57500. if (otherEdgeIndex === -1) {
  57501. continue;
  57502. }
  57503. faceAdjacencies.edges[edgeIndex] = otherIndex;
  57504. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  57505. faceAdjacencies.edgesConnectedCount++;
  57506. otherFaceAdjacencies.edgesConnectedCount++;
  57507. if (faceAdjacencies.edgesConnectedCount === 3) {
  57508. break;
  57509. }
  57510. }
  57511. }
  57512. }
  57513. // Create lines
  57514. for (index = 0; index < adjacencies.length; index++) {
  57515. // 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
  57516. var current = adjacencies[index];
  57517. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  57518. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  57519. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  57520. }
  57521. // Merge into a single mesh
  57522. var engine = this._source.getScene().getEngine();
  57523. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  57524. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  57525. this._ib = engine.createIndexBuffer(this._linesIndices);
  57526. this._indicesCount = this._linesIndices.length;
  57527. };
  57528. EdgesRenderer.prototype.render = function () {
  57529. if (!this._lineShader.isReady()) {
  57530. return;
  57531. }
  57532. var scene = this._source.getScene();
  57533. var engine = scene.getEngine();
  57534. this._lineShader._preBind();
  57535. // VBOs
  57536. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  57537. scene.resetCachedMaterial();
  57538. this._lineShader.setColor4("color", this._source.edgesColor);
  57539. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  57540. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  57541. }
  57542. else {
  57543. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  57544. }
  57545. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  57546. this._lineShader.bind(this._source.getWorldMatrix());
  57547. // Draw order
  57548. engine.draw(true, 0, this._indicesCount);
  57549. this._lineShader.unbind();
  57550. engine.setDepthWrite(true);
  57551. };
  57552. return EdgesRenderer;
  57553. }());
  57554. BABYLON.EdgesRenderer = EdgesRenderer;
  57555. })(BABYLON || (BABYLON = {}));
  57556. var BABYLON;
  57557. (function (BABYLON) {
  57558. (function (TonemappingOperator) {
  57559. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57560. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57561. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57562. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57563. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57564. var TonemappingOperator = BABYLON.TonemappingOperator;
  57565. ;
  57566. var TonemapPostProcess = (function (_super) {
  57567. __extends(TonemapPostProcess, _super);
  57568. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57569. var _this = this;
  57570. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57571. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57572. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  57573. this._operator = _operator;
  57574. this.exposureAdjustment = exposureAdjustment;
  57575. var defines = "#define ";
  57576. if (this._operator === TonemappingOperator.Hable)
  57577. defines += "HABLE_TONEMAPPING";
  57578. else if (this._operator === TonemappingOperator.Reinhard)
  57579. defines += "REINHARD_TONEMAPPING";
  57580. else if (this._operator === TonemappingOperator.HejiDawson)
  57581. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57582. else if (this._operator === TonemappingOperator.Photographic)
  57583. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57584. //sadly a second call to create the effect.
  57585. this.updateEffect(defines);
  57586. this.onApply = function (effect) {
  57587. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57588. };
  57589. }
  57590. return TonemapPostProcess;
  57591. }(BABYLON.PostProcess));
  57592. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57593. })(BABYLON || (BABYLON = {}));
  57594. var BABYLON;
  57595. (function (BABYLON) {
  57596. var ReflectionProbe = (function () {
  57597. function ReflectionProbe(name, size, scene, generateMipMaps) {
  57598. var _this = this;
  57599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57600. this.name = name;
  57601. this._viewMatrix = BABYLON.Matrix.Identity();
  57602. this._target = BABYLON.Vector3.Zero();
  57603. this._add = BABYLON.Vector3.Zero();
  57604. this.invertYAxis = false;
  57605. this.position = BABYLON.Vector3.Zero();
  57606. this._scene = scene;
  57607. this._scene.reflectionProbes.push(this);
  57608. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  57609. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  57610. switch (faceIndex) {
  57611. case 0:
  57612. _this._add.copyFromFloats(1, 0, 0);
  57613. break;
  57614. case 1:
  57615. _this._add.copyFromFloats(-1, 0, 0);
  57616. break;
  57617. case 2:
  57618. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  57619. break;
  57620. case 3:
  57621. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  57622. break;
  57623. case 4:
  57624. _this._add.copyFromFloats(0, 0, 1);
  57625. break;
  57626. case 5:
  57627. _this._add.copyFromFloats(0, 0, -1);
  57628. break;
  57629. }
  57630. if (_this._attachedMesh) {
  57631. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  57632. }
  57633. _this.position.addToRef(_this._add, _this._target);
  57634. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  57635. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  57636. });
  57637. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  57638. scene.updateTransformMatrix(true);
  57639. });
  57640. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  57641. }
  57642. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  57643. get: function () {
  57644. return this._renderTargetTexture.refreshRate;
  57645. },
  57646. set: function (value) {
  57647. this._renderTargetTexture.refreshRate = value;
  57648. },
  57649. enumerable: true,
  57650. configurable: true
  57651. });
  57652. ReflectionProbe.prototype.getScene = function () {
  57653. return this._scene;
  57654. };
  57655. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  57656. get: function () {
  57657. return this._renderTargetTexture;
  57658. },
  57659. enumerable: true,
  57660. configurable: true
  57661. });
  57662. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  57663. get: function () {
  57664. return this._renderTargetTexture.renderList;
  57665. },
  57666. enumerable: true,
  57667. configurable: true
  57668. });
  57669. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  57670. this._attachedMesh = mesh;
  57671. };
  57672. ReflectionProbe.prototype.dispose = function () {
  57673. var index = this._scene.reflectionProbes.indexOf(this);
  57674. if (index !== -1) {
  57675. // Remove from the scene if found
  57676. this._scene.reflectionProbes.splice(index, 1);
  57677. }
  57678. if (this._renderTargetTexture) {
  57679. this._renderTargetTexture.dispose();
  57680. this._renderTargetTexture = null;
  57681. }
  57682. };
  57683. return ReflectionProbe;
  57684. }());
  57685. BABYLON.ReflectionProbe = ReflectionProbe;
  57686. })(BABYLON || (BABYLON = {}));
  57687. var BABYLON;
  57688. (function (BABYLON) {
  57689. var SolidParticle = (function () {
  57690. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  57691. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  57692. this.position = BABYLON.Vector3.Zero(); // position
  57693. this.rotation = BABYLON.Vector3.Zero(); // rotation
  57694. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  57695. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  57696. this.velocity = BABYLON.Vector3.Zero(); // velocity
  57697. this.alive = true; // alive
  57698. this.isVisible = true; // visibility
  57699. this.idx = particleIndex;
  57700. this._pos = positionIndex;
  57701. this._model = model;
  57702. this.shapeId = shapeId;
  57703. this.idxInShape = idxInShape;
  57704. }
  57705. Object.defineProperty(SolidParticle.prototype, "scale", {
  57706. //legacy support, changed scale to scaling
  57707. get: function () {
  57708. return this.scaling;
  57709. },
  57710. set: function (scale) {
  57711. this.scaling = scale;
  57712. },
  57713. enumerable: true,
  57714. configurable: true
  57715. });
  57716. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57717. //legacy support, changed quaternion to rotationQuaternion
  57718. get: function () {
  57719. return this.rotationQuaternion;
  57720. },
  57721. set: function (q) {
  57722. this.rotationQuaternion = q;
  57723. },
  57724. enumerable: true,
  57725. configurable: true
  57726. });
  57727. return SolidParticle;
  57728. }());
  57729. BABYLON.SolidParticle = SolidParticle;
  57730. var ModelShape = (function () {
  57731. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  57732. this.shapeID = id;
  57733. this._shape = shape;
  57734. this._shapeUV = shapeUV;
  57735. this._positionFunction = posFunction;
  57736. this._vertexFunction = vtxFunction;
  57737. }
  57738. return ModelShape;
  57739. }());
  57740. BABYLON.ModelShape = ModelShape;
  57741. })(BABYLON || (BABYLON = {}));
  57742. var BABYLON;
  57743. (function (BABYLON) {
  57744. /**
  57745. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57746. */
  57747. var SolidParticleSystem = (function () {
  57748. /**
  57749. * Creates a SPS (Solid Particle System) object.
  57750. * `name` (String) is the SPS name, this will be the underlying mesh name.
  57751. * `scene` (Scene) is the scene in which the SPS is added.
  57752. * `updatable` (default true) : if the SPS must be updatable or immutable.
  57753. * `isPickable` (default false) : if the solid particles must be pickable.
  57754. */
  57755. function SolidParticleSystem(name, scene, options) {
  57756. // public members
  57757. /**
  57758. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57759. * Example : var p = SPS.particles[i];
  57760. */
  57761. this.particles = new Array();
  57762. /**
  57763. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57764. */
  57765. this.nbParticles = 0;
  57766. /**
  57767. * If the particles must ever face the camera (default false). Useful for planar particles.
  57768. */
  57769. this.billboard = false;
  57770. /**
  57771. * Recompute normals when adding a shape
  57772. */
  57773. this.recomputeNormals = true;
  57774. /**
  57775. * This a counter ofr your own usage. It's not set by any SPS functions.
  57776. */
  57777. this.counter = 0;
  57778. /**
  57779. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57780. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57781. */
  57782. this.vars = {};
  57783. this._positions = new Array();
  57784. this._indices = new Array();
  57785. this._normals = new Array();
  57786. this._colors = new Array();
  57787. this._uvs = new Array();
  57788. this._index = 0; // indices index
  57789. this._updatable = true;
  57790. this._pickable = false;
  57791. this._isVisibilityBoxLocked = false;
  57792. this._alwaysVisible = false;
  57793. this._shapeCounter = 0;
  57794. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  57795. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57796. this._computeParticleColor = true;
  57797. this._computeParticleTexture = true;
  57798. this._computeParticleRotation = true;
  57799. this._computeParticleVertex = false;
  57800. this._computeBoundingBox = false;
  57801. this._cam_axisZ = BABYLON.Vector3.Zero();
  57802. this._cam_axisY = BABYLON.Vector3.Zero();
  57803. this._cam_axisX = BABYLON.Vector3.Zero();
  57804. this._axisX = BABYLON.Axis.X;
  57805. this._axisY = BABYLON.Axis.Y;
  57806. this._axisZ = BABYLON.Axis.Z;
  57807. this._camDir = BABYLON.Vector3.Zero();
  57808. this._rotMatrix = new BABYLON.Matrix();
  57809. this._invertMatrix = new BABYLON.Matrix();
  57810. this._rotated = BABYLON.Vector3.Zero();
  57811. this._quaternion = new BABYLON.Quaternion();
  57812. this._vertex = BABYLON.Vector3.Zero();
  57813. this._normal = BABYLON.Vector3.Zero();
  57814. this._yaw = 0.0;
  57815. this._pitch = 0.0;
  57816. this._roll = 0.0;
  57817. this._halfroll = 0.0;
  57818. this._halfpitch = 0.0;
  57819. this._halfyaw = 0.0;
  57820. this._sinRoll = 0.0;
  57821. this._cosRoll = 0.0;
  57822. this._sinPitch = 0.0;
  57823. this._cosPitch = 0.0;
  57824. this._sinYaw = 0.0;
  57825. this._cosYaw = 0.0;
  57826. this._w = 0.0;
  57827. this._minimum = BABYLON.Tmp.Vector3[0];
  57828. this._maximum = BABYLON.Tmp.Vector3[1];
  57829. this.name = name;
  57830. this._scene = scene;
  57831. this._camera = scene.activeCamera;
  57832. this._pickable = options ? options.isPickable : false;
  57833. if (options && options.updatable) {
  57834. this._updatable = options.updatable;
  57835. }
  57836. else {
  57837. this._updatable = true;
  57838. }
  57839. if (this._pickable) {
  57840. this.pickedParticles = [];
  57841. }
  57842. }
  57843. /**
  57844. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57845. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57846. */
  57847. SolidParticleSystem.prototype.buildMesh = function () {
  57848. if (this.nbParticles === 0) {
  57849. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57850. this.addShape(triangle, 1);
  57851. triangle.dispose();
  57852. }
  57853. this._positions32 = new Float32Array(this._positions);
  57854. this._uvs32 = new Float32Array(this._uvs);
  57855. this._colors32 = new Float32Array(this._colors);
  57856. if (this.recomputeNormals) {
  57857. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  57858. }
  57859. this._normals32 = new Float32Array(this._normals);
  57860. this._fixedNormal32 = new Float32Array(this._normals);
  57861. var vertexData = new BABYLON.VertexData();
  57862. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57863. vertexData.indices = this._indices;
  57864. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57865. if (this._uvs32) {
  57866. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57867. ;
  57868. }
  57869. if (this._colors32) {
  57870. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57871. }
  57872. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57873. vertexData.applyToMesh(mesh, this._updatable);
  57874. this.mesh = mesh;
  57875. this.mesh.isPickable = this._pickable;
  57876. // free memory
  57877. this._positions = null;
  57878. this._normals = null;
  57879. this._uvs = null;
  57880. this._colors = null;
  57881. if (!this._updatable) {
  57882. this.particles.length = 0;
  57883. }
  57884. return mesh;
  57885. };
  57886. /**
  57887. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57888. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57889. * Thus the particles generated from `digest()` have their property `position` set yet.
  57890. * `mesh` ( Mesh ) is the mesh to be digested
  57891. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  57892. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57893. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57894. */
  57895. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57896. var size = (options && options.facetNb) || 1;
  57897. var number = (options && options.number);
  57898. var delta = (options && options.delta) || 0;
  57899. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57900. var meshInd = mesh.getIndices();
  57901. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57902. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57903. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57904. var f = 0; // facet counter
  57905. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57906. // compute size from number
  57907. if (number) {
  57908. number = (number > totalFacets) ? totalFacets : number;
  57909. size = Math.round(totalFacets / number);
  57910. delta = 0;
  57911. }
  57912. else {
  57913. size = (size > totalFacets) ? totalFacets : size;
  57914. }
  57915. var facetPos = []; // submesh positions
  57916. var facetInd = []; // submesh indices
  57917. var facetUV = []; // submesh UV
  57918. var facetCol = []; // submesh colors
  57919. var barycenter = BABYLON.Tmp.Vector3[0];
  57920. var rand;
  57921. var sizeO = size;
  57922. while (f < totalFacets) {
  57923. size = sizeO + Math.floor((1 + delta) * Math.random());
  57924. if (f > totalFacets - size) {
  57925. size = totalFacets - f;
  57926. }
  57927. // reset temp arrays
  57928. facetPos.length = 0;
  57929. facetInd.length = 0;
  57930. facetUV.length = 0;
  57931. facetCol.length = 0;
  57932. // iterate over "size" facets
  57933. var fi = 0;
  57934. for (var j = f * 3; j < (f + size) * 3; j++) {
  57935. facetInd.push(fi);
  57936. var i = meshInd[j];
  57937. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57938. if (meshUV) {
  57939. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57940. }
  57941. if (meshCol) {
  57942. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57943. }
  57944. fi++;
  57945. }
  57946. // create a model shape for each single particle
  57947. var idx = this.nbParticles;
  57948. var shape = this._posToShape(facetPos);
  57949. var shapeUV = this._uvsToShapeUV(facetUV);
  57950. // compute the barycenter of the shape
  57951. var v;
  57952. for (v = 0; v < shape.length; v++) {
  57953. barycenter.addInPlace(shape[v]);
  57954. }
  57955. barycenter.scaleInPlace(1 / shape.length);
  57956. // shift the shape from its barycenter to the origin
  57957. for (v = 0; v < shape.length; v++) {
  57958. shape[v].subtractInPlace(barycenter);
  57959. }
  57960. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57961. // add the particle in the SPS
  57962. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57963. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57964. // initialize the particle position
  57965. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57966. this._index += shape.length;
  57967. idx++;
  57968. this.nbParticles++;
  57969. this._shapeCounter++;
  57970. f += size;
  57971. }
  57972. return this;
  57973. };
  57974. //reset copy
  57975. SolidParticleSystem.prototype._resetCopy = function () {
  57976. this._copy.position.x = 0;
  57977. this._copy.position.y = 0;
  57978. this._copy.position.z = 0;
  57979. this._copy.rotation.x = 0;
  57980. this._copy.rotation.y = 0;
  57981. this._copy.rotation.z = 0;
  57982. this._copy.rotationQuaternion = null;
  57983. this._copy.scaling.x = 1;
  57984. this._copy.scaling.y = 1;
  57985. this._copy.scaling.z = 1;
  57986. this._copy.uvs.x = 0;
  57987. this._copy.uvs.y = 0;
  57988. this._copy.uvs.z = 1;
  57989. this._copy.uvs.w = 1;
  57990. this._copy.color = null;
  57991. };
  57992. // _meshBuilder : inserts the shape model in the global SPS mesh
  57993. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57994. var i;
  57995. var u = 0;
  57996. var c = 0;
  57997. var n = 0;
  57998. this._resetCopy();
  57999. if (options && options.positionFunction) {
  58000. options.positionFunction(this._copy, idx, idxInShape);
  58001. }
  58002. if (this._copy.rotationQuaternion) {
  58003. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58004. }
  58005. else {
  58006. this._yaw = this._copy.rotation.y;
  58007. this._pitch = this._copy.rotation.x;
  58008. this._roll = this._copy.rotation.z;
  58009. this._quaternionRotationYPR();
  58010. }
  58011. this._quaternionToRotationMatrix();
  58012. for (i = 0; i < shape.length; i++) {
  58013. this._vertex.x = shape[i].x;
  58014. this._vertex.y = shape[i].y;
  58015. this._vertex.z = shape[i].z;
  58016. if (options && options.vertexFunction) {
  58017. options.vertexFunction(this._copy, this._vertex, i);
  58018. }
  58019. this._vertex.x *= this._copy.scaling.x;
  58020. this._vertex.y *= this._copy.scaling.y;
  58021. this._vertex.z *= this._copy.scaling.z;
  58022. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58023. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58024. if (meshUV) {
  58025. 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);
  58026. u += 2;
  58027. }
  58028. if (this._copy.color) {
  58029. this._color = this._copy.color;
  58030. }
  58031. else if (meshCol && meshCol[c] !== undefined) {
  58032. this._color.r = meshCol[c];
  58033. this._color.g = meshCol[c + 1];
  58034. this._color.b = meshCol[c + 2];
  58035. this._color.a = meshCol[c + 3];
  58036. }
  58037. else {
  58038. this._color.r = 1;
  58039. this._color.g = 1;
  58040. this._color.b = 1;
  58041. this._color.a = 1;
  58042. }
  58043. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58044. c += 4;
  58045. if (!this.recomputeNormals && meshNor) {
  58046. this._normal.x = meshNor[n];
  58047. this._normal.y = meshNor[n + 1];
  58048. this._normal.z = meshNor[n + 2];
  58049. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  58050. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58051. n += 3;
  58052. }
  58053. }
  58054. for (i = 0; i < meshInd.length; i++) {
  58055. indices.push(p + meshInd[i]);
  58056. }
  58057. if (this._pickable) {
  58058. var nbfaces = meshInd.length / 3;
  58059. for (i = 0; i < nbfaces; i++) {
  58060. this.pickedParticles.push({ idx: idx, faceId: i });
  58061. }
  58062. }
  58063. };
  58064. // returns a shape array from positions array
  58065. SolidParticleSystem.prototype._posToShape = function (positions) {
  58066. var shape = [];
  58067. for (var i = 0; i < positions.length; i += 3) {
  58068. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58069. }
  58070. return shape;
  58071. };
  58072. // returns a shapeUV array from a Vector4 uvs
  58073. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58074. var shapeUV = [];
  58075. if (uvs) {
  58076. for (var i = 0; i < uvs.length; i++)
  58077. shapeUV.push(uvs[i]);
  58078. }
  58079. return shapeUV;
  58080. };
  58081. // adds a new particle object in the particles array
  58082. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  58083. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  58084. };
  58085. /**
  58086. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58087. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58088. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  58089. * `nb` (positive integer) the number of particles to be created from this model
  58090. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  58091. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  58092. */
  58093. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58094. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58095. var meshInd = mesh.getIndices();
  58096. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58097. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58098. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58099. var shape = this._posToShape(meshPos);
  58100. var shapeUV = this._uvsToShapeUV(meshUV);
  58101. var posfunc = options ? options.positionFunction : null;
  58102. var vtxfunc = options ? options.vertexFunction : null;
  58103. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  58104. // particles
  58105. var idx = this.nbParticles;
  58106. for (var i = 0; i < nb; i++) {
  58107. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58108. if (this._updatable) {
  58109. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  58110. }
  58111. this._index += shape.length;
  58112. idx++;
  58113. }
  58114. this.nbParticles += nb;
  58115. this._shapeCounter++;
  58116. return this._shapeCounter - 1;
  58117. };
  58118. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58119. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58120. this._resetCopy();
  58121. if (particle._model._positionFunction) {
  58122. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58123. }
  58124. if (this._copy.rotationQuaternion) {
  58125. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58126. }
  58127. else {
  58128. this._yaw = this._copy.rotation.y;
  58129. this._pitch = this._copy.rotation.x;
  58130. this._roll = this._copy.rotation.z;
  58131. this._quaternionRotationYPR();
  58132. }
  58133. this._quaternionToRotationMatrix();
  58134. this._shape = particle._model._shape;
  58135. for (var pt = 0; pt < this._shape.length; pt++) {
  58136. this._vertex.x = this._shape[pt].x;
  58137. this._vertex.y = this._shape[pt].y;
  58138. this._vertex.z = this._shape[pt].z;
  58139. if (particle._model._vertexFunction) {
  58140. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58141. }
  58142. this._vertex.x *= this._copy.scaling.x;
  58143. this._vertex.y *= this._copy.scaling.y;
  58144. this._vertex.z *= this._copy.scaling.z;
  58145. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58146. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58147. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58148. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58149. }
  58150. particle.position.x = 0;
  58151. particle.position.y = 0;
  58152. particle.position.z = 0;
  58153. particle.rotation.x = 0;
  58154. particle.rotation.y = 0;
  58155. particle.rotation.z = 0;
  58156. particle.rotationQuaternion = null;
  58157. particle.scaling.x = 1;
  58158. particle.scaling.y = 1;
  58159. particle.scaling.z = 1;
  58160. };
  58161. /**
  58162. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58163. */
  58164. SolidParticleSystem.prototype.rebuildMesh = function () {
  58165. for (var p = 0; p < this.particles.length; p++) {
  58166. this._rebuildParticle(this.particles[p]);
  58167. }
  58168. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58169. };
  58170. /**
  58171. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58172. * This method calls `updateParticle()` for each particle of the SPS.
  58173. * For an animated SPS, it is usually called within the render loop.
  58174. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58175. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58176. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58177. */
  58178. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58179. if (start === void 0) { start = 0; }
  58180. if (end === void 0) { end = this.nbParticles - 1; }
  58181. if (update === void 0) { update = true; }
  58182. if (!this._updatable) {
  58183. return;
  58184. }
  58185. // custom beforeUpdate
  58186. this.beforeUpdateParticles(start, end, update);
  58187. this._cam_axisX.x = 1.0;
  58188. this._cam_axisX.y = 0.0;
  58189. this._cam_axisX.z = 0.0;
  58190. this._cam_axisY.x = 0.0;
  58191. this._cam_axisY.y = 1.0;
  58192. this._cam_axisY.z = 0.0;
  58193. this._cam_axisZ.x = 0.0;
  58194. this._cam_axisZ.y = 0.0;
  58195. this._cam_axisZ.z = 1.0;
  58196. // if the particles will always face the camera
  58197. if (this.billboard) {
  58198. // compute the camera position and un-rotate it by the current mesh rotation
  58199. this._yaw = this.mesh.rotation.y;
  58200. this._pitch = this.mesh.rotation.x;
  58201. this._roll = this.mesh.rotation.z;
  58202. this._quaternionRotationYPR();
  58203. this._quaternionToRotationMatrix();
  58204. this._rotMatrix.invertToRef(this._invertMatrix);
  58205. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  58206. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58207. this._cam_axisZ.normalize();
  58208. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  58209. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  58210. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58211. this._cam_axisY.normalize();
  58212. this._cam_axisX.normalize();
  58213. }
  58214. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58215. var idx = 0;
  58216. var index = 0;
  58217. var colidx = 0;
  58218. var colorIndex = 0;
  58219. var uvidx = 0;
  58220. var uvIndex = 0;
  58221. var pt = 0;
  58222. if (this._computeBoundingBox) {
  58223. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58224. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58225. }
  58226. // particle loop
  58227. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  58228. for (var p = start; p <= end; p++) {
  58229. this._particle = this.particles[p];
  58230. this._shape = this._particle._model._shape;
  58231. this._shapeUV = this._particle._model._shapeUV;
  58232. // call to custom user function to update the particle properties
  58233. this.updateParticle(this._particle);
  58234. if (this._particle.isVisible) {
  58235. // particle rotation matrix
  58236. if (this.billboard) {
  58237. this._particle.rotation.x = 0.0;
  58238. this._particle.rotation.y = 0.0;
  58239. }
  58240. if (this._computeParticleRotation || this.billboard) {
  58241. if (this._particle.rotationQuaternion) {
  58242. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58243. }
  58244. else {
  58245. this._yaw = this._particle.rotation.y;
  58246. this._pitch = this._particle.rotation.x;
  58247. this._roll = this._particle.rotation.z;
  58248. this._quaternionRotationYPR();
  58249. }
  58250. this._quaternionToRotationMatrix();
  58251. }
  58252. // particle vertex loop
  58253. for (pt = 0; pt < this._shape.length; pt++) {
  58254. idx = index + pt * 3;
  58255. colidx = colorIndex + pt * 4;
  58256. uvidx = uvIndex + pt * 2;
  58257. this._vertex.x = this._shape[pt].x;
  58258. this._vertex.y = this._shape[pt].y;
  58259. this._vertex.z = this._shape[pt].z;
  58260. if (this._computeParticleVertex) {
  58261. this.updateParticleVertex(this._particle, this._vertex, pt);
  58262. }
  58263. // positions
  58264. this._vertex.x *= this._particle.scaling.x;
  58265. this._vertex.y *= this._particle.scaling.y;
  58266. this._vertex.z *= this._particle.scaling.z;
  58267. 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];
  58268. 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;
  58269. 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;
  58270. 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;
  58271. 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;
  58272. 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;
  58273. 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;
  58274. if (this._computeBoundingBox) {
  58275. if (this._positions32[idx] < this._minimum.x) {
  58276. this._minimum.x = this._positions32[idx];
  58277. }
  58278. if (this._positions32[idx] > this._maximum.x) {
  58279. this._maximum.x = this._positions32[idx];
  58280. }
  58281. if (this._positions32[idx + 1] < this._minimum.y) {
  58282. this._minimum.y = this._positions32[idx + 1];
  58283. }
  58284. if (this._positions32[idx + 1] > this._maximum.y) {
  58285. this._maximum.y = this._positions32[idx + 1];
  58286. }
  58287. if (this._positions32[idx + 2] < this._minimum.z) {
  58288. this._minimum.z = this._positions32[idx + 2];
  58289. }
  58290. if (this._positions32[idx + 2] > this._maximum.z) {
  58291. this._maximum.z = this._positions32[idx + 2];
  58292. }
  58293. }
  58294. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  58295. if (!this._computeParticleVertex) {
  58296. this._normal.x = this._fixedNormal32[idx];
  58297. this._normal.y = this._fixedNormal32[idx + 1];
  58298. this._normal.z = this._fixedNormal32[idx + 2];
  58299. 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];
  58300. 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;
  58301. 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;
  58302. 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;
  58303. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58304. 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;
  58305. 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;
  58306. }
  58307. if (this._computeParticleColor) {
  58308. this._colors32[colidx] = this._particle.color.r;
  58309. this._colors32[colidx + 1] = this._particle.color.g;
  58310. this._colors32[colidx + 2] = this._particle.color.b;
  58311. this._colors32[colidx + 3] = this._particle.color.a;
  58312. }
  58313. if (this._computeParticleTexture) {
  58314. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58315. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58316. }
  58317. }
  58318. }
  58319. else {
  58320. for (pt = 0; pt < this._shape.length; pt++) {
  58321. idx = index + pt * 3;
  58322. colidx = colorIndex + pt * 4;
  58323. uvidx = uvIndex + pt * 2;
  58324. this._positions32[idx] = this._camera.position.x;
  58325. this._positions32[idx + 1] = this._camera.position.y;
  58326. this._positions32[idx + 2] = this._camera.position.z;
  58327. this._normals32[idx] = 0.0;
  58328. this._normals32[idx + 1] = 0.0;
  58329. this._normals32[idx + 2] = 0.0;
  58330. if (this._computeParticleColor) {
  58331. this._colors32[colidx] = this._particle.color.r;
  58332. this._colors32[colidx + 1] = this._particle.color.g;
  58333. this._colors32[colidx + 2] = this._particle.color.b;
  58334. this._colors32[colidx + 3] = this._particle.color.a;
  58335. }
  58336. if (this._computeParticleTexture) {
  58337. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58338. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58339. }
  58340. }
  58341. }
  58342. // increment indexes for the next particle
  58343. index = idx + 3;
  58344. colorIndex = colidx + 4;
  58345. uvIndex = uvidx + 2;
  58346. }
  58347. // if the VBO must be updated
  58348. if (update) {
  58349. if (this._computeParticleColor) {
  58350. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58351. }
  58352. if (this._computeParticleTexture) {
  58353. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58354. }
  58355. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58356. if (!this.mesh.areNormalsFrozen) {
  58357. if (this._computeParticleVertex) {
  58358. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58359. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  58360. for (var i = 0; i < this._normals32.length; i++) {
  58361. this._fixedNormal32[i] = this._normals32[i];
  58362. }
  58363. }
  58364. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58365. }
  58366. }
  58367. if (this._computeBoundingBox) {
  58368. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58369. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58370. }
  58371. this.afterUpdateParticles(start, end, update);
  58372. };
  58373. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58374. this._halfroll = this._roll * 0.5;
  58375. this._halfpitch = this._pitch * 0.5;
  58376. this._halfyaw = this._yaw * 0.5;
  58377. this._sinRoll = Math.sin(this._halfroll);
  58378. this._cosRoll = Math.cos(this._halfroll);
  58379. this._sinPitch = Math.sin(this._halfpitch);
  58380. this._cosPitch = Math.cos(this._halfpitch);
  58381. this._sinYaw = Math.sin(this._halfyaw);
  58382. this._cosYaw = Math.cos(this._halfyaw);
  58383. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  58384. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  58385. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  58386. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  58387. };
  58388. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58389. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58390. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58391. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58392. this._rotMatrix.m[3] = 0;
  58393. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58394. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58395. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58396. this._rotMatrix.m[7] = 0;
  58397. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58398. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58399. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58400. this._rotMatrix.m[11] = 0;
  58401. this._rotMatrix.m[12] = 0;
  58402. this._rotMatrix.m[13] = 0;
  58403. this._rotMatrix.m[14] = 0;
  58404. this._rotMatrix.m[15] = 1.0;
  58405. };
  58406. /**
  58407. * Disposes the SPS
  58408. */
  58409. SolidParticleSystem.prototype.dispose = function () {
  58410. this.mesh.dispose();
  58411. this.vars = null;
  58412. // drop references to internal big arrays for the GC
  58413. this._positions = null;
  58414. this._indices = null;
  58415. this._normals = null;
  58416. this._uvs = null;
  58417. this._colors = null;
  58418. this._positions32 = null;
  58419. this._normals32 = null;
  58420. this._fixedNormal32 = null;
  58421. this._uvs32 = null;
  58422. this._colors32 = null;
  58423. this.pickedParticles = null;
  58424. };
  58425. /**
  58426. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58427. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58428. */
  58429. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58430. if (!this._isVisibilityBoxLocked) {
  58431. this.mesh.refreshBoundingInfo();
  58432. }
  58433. };
  58434. /**
  58435. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58436. * @param size the size (float) of the visibility box
  58437. * note : this doesn't lock the SPS mesh bounding box.
  58438. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58439. */
  58440. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58441. var vis = size / 2;
  58442. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58443. };
  58444. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58445. // getter and setter
  58446. get: function () {
  58447. return this._alwaysVisible;
  58448. },
  58449. /**
  58450. * Sets the SPS as always visible or not
  58451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58452. */
  58453. set: function (val) {
  58454. this._alwaysVisible = val;
  58455. this.mesh.alwaysSelectAsActiveMesh = val;
  58456. },
  58457. enumerable: true,
  58458. configurable: true
  58459. });
  58460. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58461. get: function () {
  58462. return this._isVisibilityBoxLocked;
  58463. },
  58464. /**
  58465. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58467. */
  58468. set: function (val) {
  58469. this._isVisibilityBoxLocked = val;
  58470. this.mesh.getBoundingInfo().isLocked = val;
  58471. },
  58472. enumerable: true,
  58473. configurable: true
  58474. });
  58475. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58476. // getters
  58477. get: function () {
  58478. return this._computeParticleRotation;
  58479. },
  58480. // Optimizer setters
  58481. /**
  58482. * Tells to `setParticles()` to compute the particle rotations or not.
  58483. * Default value : true. The SPS is faster when it's set to false.
  58484. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58485. */
  58486. set: function (val) {
  58487. this._computeParticleRotation = val;
  58488. },
  58489. enumerable: true,
  58490. configurable: true
  58491. });
  58492. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58493. get: function () {
  58494. return this._computeParticleColor;
  58495. },
  58496. /**
  58497. * Tells to `setParticles()` to compute the particle colors or not.
  58498. * Default value : true. The SPS is faster when it's set to false.
  58499. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58500. */
  58501. set: function (val) {
  58502. this._computeParticleColor = val;
  58503. },
  58504. enumerable: true,
  58505. configurable: true
  58506. });
  58507. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58508. get: function () {
  58509. return this._computeParticleTexture;
  58510. },
  58511. /**
  58512. * Tells to `setParticles()` to compute the particle textures or not.
  58513. * Default value : true. The SPS is faster when it's set to false.
  58514. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58515. */
  58516. set: function (val) {
  58517. this._computeParticleTexture = val;
  58518. },
  58519. enumerable: true,
  58520. configurable: true
  58521. });
  58522. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58523. get: function () {
  58524. return this._computeParticleVertex;
  58525. },
  58526. /**
  58527. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58528. * Default value : false. The SPS is faster when it's set to false.
  58529. * Note : the particle custom vertex positions aren't stored values.
  58530. */
  58531. set: function (val) {
  58532. this._computeParticleVertex = val;
  58533. },
  58534. enumerable: true,
  58535. configurable: true
  58536. });
  58537. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58538. get: function () {
  58539. return this._computeBoundingBox;
  58540. },
  58541. /**
  58542. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58543. */
  58544. set: function (val) {
  58545. this._computeBoundingBox = val;
  58546. },
  58547. enumerable: true,
  58548. configurable: true
  58549. });
  58550. // =======================================================================
  58551. // Particle behavior logic
  58552. // these following methods may be overwritten by the user to fit his needs
  58553. /**
  58554. * This function does nothing. It may be overwritten to set all the particle first values.
  58555. * The SPS doesn't call this function, you may have to call it by your own.
  58556. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58557. */
  58558. SolidParticleSystem.prototype.initParticles = function () {
  58559. };
  58560. /**
  58561. * This function does nothing. It may be overwritten to recycle a particle.
  58562. * The SPS doesn't call this function, you may have to call it by your own.
  58563. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58564. */
  58565. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58566. return particle;
  58567. };
  58568. /**
  58569. * Updates a particle : this function should be overwritten by the user.
  58570. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58571. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58572. * ex : just set a particle position or velocity and recycle conditions
  58573. */
  58574. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58575. return particle;
  58576. };
  58577. /**
  58578. * Updates a vertex of a particle : it can be overwritten by the user.
  58579. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58580. * @param particle the current particle
  58581. * @param vertex the current index of the current particle
  58582. * @param pt the index of the current vertex in the particle shape
  58583. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58584. * ex : just set a vertex particle position
  58585. */
  58586. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58587. return vertex;
  58588. };
  58589. /**
  58590. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58591. * This does nothing and may be overwritten by the user.
  58592. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58593. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58594. * @param update the boolean update value actually passed to setParticles()
  58595. */
  58596. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58597. };
  58598. /**
  58599. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58600. * This will be passed three parameters.
  58601. * This does nothing and may be overwritten by the user.
  58602. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58603. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58604. * @param update the boolean update value actually passed to setParticles()
  58605. */
  58606. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58607. };
  58608. return SolidParticleSystem;
  58609. }());
  58610. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58611. })(BABYLON || (BABYLON = {}));
  58612. var BABYLON;
  58613. (function (BABYLON) {
  58614. var Internals;
  58615. (function (Internals) {
  58616. var FileFaceOrientation = (function () {
  58617. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58618. this.name = name;
  58619. this.worldAxisForNormal = worldAxisForNormal;
  58620. this.worldAxisForFileX = worldAxisForFileX;
  58621. this.worldAxisForFileY = worldAxisForFileY;
  58622. }
  58623. return FileFaceOrientation;
  58624. }());
  58625. ;
  58626. /**
  58627. * Helper class dealing with the extraction of spherical polynomial dataArray
  58628. * from a cube map.
  58629. */
  58630. var CubeMapToSphericalPolynomialTools = (function () {
  58631. function CubeMapToSphericalPolynomialTools() {
  58632. }
  58633. /**
  58634. * Converts a cubemap to the according Spherical Polynomial data.
  58635. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58636. *
  58637. * @param cubeInfo The Cube map to extract the information from.
  58638. * @return The Spherical Polynomial data.
  58639. */
  58640. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58641. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58642. var totalSolidAngle = 0.0;
  58643. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58644. var du = 2.0 / cubeInfo.size;
  58645. var dv = du;
  58646. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58647. var minUV = du * 0.5 - 1.0;
  58648. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58649. var fileFace = this.FileFaces[faceIndex];
  58650. var dataArray = cubeInfo[fileFace.name];
  58651. var v = minUV;
  58652. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58653. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58654. // Because SP is still linear, so summation is fine in that basis.
  58655. for (var y = 0; y < cubeInfo.size; y++) {
  58656. var u = minUV;
  58657. for (var x = 0; x < cubeInfo.size; x++) {
  58658. // World direction (not normalised)
  58659. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58660. worldDirection.normalize();
  58661. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58662. if (1) {
  58663. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  58664. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  58665. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  58666. var color = new BABYLON.Color3(r, g, b);
  58667. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58668. }
  58669. else {
  58670. if (faceIndex == 0) {
  58671. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58672. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58673. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58674. }
  58675. else if (faceIndex == 1) {
  58676. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58677. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58678. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58679. }
  58680. else if (faceIndex == 2) {
  58681. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58682. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58683. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58684. }
  58685. else if (faceIndex == 3) {
  58686. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58687. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58688. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58689. }
  58690. else if (faceIndex == 4) {
  58691. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58692. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58693. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58694. }
  58695. else if (faceIndex == 5) {
  58696. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58697. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58698. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58699. }
  58700. 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]);
  58701. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58702. }
  58703. totalSolidAngle += deltaSolidAngle;
  58704. u += du;
  58705. }
  58706. v += dv;
  58707. }
  58708. }
  58709. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  58710. var correction = correctSolidAngle / totalSolidAngle;
  58711. sphericalHarmonics.scale(correction);
  58712. // Additionally scale by pi -- audit needed
  58713. sphericalHarmonics.scale(1.0 / Math.PI);
  58714. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58715. };
  58716. CubeMapToSphericalPolynomialTools.FileFaces = [
  58717. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58718. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58719. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58720. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58721. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58722. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58723. ];
  58724. return CubeMapToSphericalPolynomialTools;
  58725. }());
  58726. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58727. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58728. })(BABYLON || (BABYLON = {}));
  58729. var BABYLON;
  58730. (function (BABYLON) {
  58731. var Internals;
  58732. (function (Internals) {
  58733. /**
  58734. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58735. */
  58736. var PanoramaToCubeMapTools = (function () {
  58737. function PanoramaToCubeMapTools() {
  58738. }
  58739. /**
  58740. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58741. *
  58742. * @param float32Array The source data.
  58743. * @param inputWidth The width of the input panorama.
  58744. * @param inputhHeight The height of the input panorama.
  58745. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58746. * @return The cubemap data
  58747. */
  58748. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58749. if (!float32Array) {
  58750. throw "ConvertPanoramaToCubemap: input cannot be null";
  58751. }
  58752. if (float32Array.length != inputWidth * inputHeight * 3) {
  58753. throw "ConvertPanoramaToCubemap: input size is wrong";
  58754. }
  58755. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58756. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58757. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58758. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58759. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58760. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58761. return {
  58762. front: textureFront,
  58763. back: textureBack,
  58764. left: textureLeft,
  58765. right: textureRight,
  58766. up: textureUp,
  58767. down: textureDown,
  58768. size: size
  58769. };
  58770. };
  58771. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58772. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58773. var textureArray = new Float32Array(buffer);
  58774. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58775. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58776. var dy = 1 / texSize;
  58777. var fy = 0;
  58778. for (var y = 0; y < texSize; y++) {
  58779. var xv1 = faceData[0];
  58780. var xv2 = faceData[2];
  58781. for (var x = 0; x < texSize; x++) {
  58782. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58783. v.normalize();
  58784. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58785. // 3 channels per pixels
  58786. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58787. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58788. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58789. xv1 = xv1.add(rotDX1);
  58790. xv2 = xv2.add(rotDX2);
  58791. }
  58792. fy += dy;
  58793. }
  58794. return textureArray;
  58795. };
  58796. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58797. var theta = Math.atan2(vDir.z, vDir.x);
  58798. var phi = Math.acos(vDir.y);
  58799. while (theta < -Math.PI)
  58800. theta += 2 * Math.PI;
  58801. while (theta > Math.PI)
  58802. theta -= 2 * Math.PI;
  58803. var dx = theta / Math.PI;
  58804. var dy = phi / Math.PI;
  58805. // recenter.
  58806. dx = dx * 0.5 + 0.5;
  58807. var px = Math.round(dx * inputWidth);
  58808. if (px < 0)
  58809. px = 0;
  58810. else if (px >= inputWidth)
  58811. px = inputWidth - 1;
  58812. var py = Math.round(dy * inputHeight);
  58813. if (py < 0)
  58814. py = 0;
  58815. else if (py >= inputHeight)
  58816. py = inputHeight - 1;
  58817. var inputY = (inputHeight - py - 1);
  58818. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58819. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58820. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58821. return {
  58822. r: r,
  58823. g: g,
  58824. b: b
  58825. };
  58826. };
  58827. PanoramaToCubeMapTools.FACE_FRONT = [
  58828. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58829. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58830. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58831. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58832. ];
  58833. PanoramaToCubeMapTools.FACE_BACK = [
  58834. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58835. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58836. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58837. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58838. ];
  58839. PanoramaToCubeMapTools.FACE_RIGHT = [
  58840. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58841. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58842. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58843. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58844. ];
  58845. PanoramaToCubeMapTools.FACE_LEFT = [
  58846. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58847. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58848. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58849. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58850. ];
  58851. PanoramaToCubeMapTools.FACE_DOWN = [
  58852. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58853. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58854. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58855. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58856. ];
  58857. PanoramaToCubeMapTools.FACE_UP = [
  58858. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58859. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58860. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58861. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58862. ];
  58863. return PanoramaToCubeMapTools;
  58864. }());
  58865. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58866. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58867. })(BABYLON || (BABYLON = {}));
  58868. var BABYLON;
  58869. (function (BABYLON) {
  58870. var Internals;
  58871. (function (Internals) {
  58872. ;
  58873. /**
  58874. * This groups tools to convert HDR texture to native colors array.
  58875. */
  58876. var HDRTools = (function () {
  58877. function HDRTools() {
  58878. }
  58879. HDRTools.Ldexp = function (mantissa, exponent) {
  58880. if (exponent > 1023) {
  58881. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58882. }
  58883. if (exponent < -1074) {
  58884. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58885. }
  58886. return mantissa * Math.pow(2, exponent);
  58887. };
  58888. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58889. if (exponent > 0) {
  58890. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58891. float32array[index + 0] = red * exponent;
  58892. float32array[index + 1] = green * exponent;
  58893. float32array[index + 2] = blue * exponent;
  58894. }
  58895. else {
  58896. float32array[index + 0] = 0;
  58897. float32array[index + 1] = 0;
  58898. float32array[index + 2] = 0;
  58899. }
  58900. };
  58901. HDRTools.readStringLine = function (uint8array, startIndex) {
  58902. var line = "";
  58903. var character = "";
  58904. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58905. character = String.fromCharCode(uint8array[i]);
  58906. if (character == "\n") {
  58907. break;
  58908. }
  58909. line += character;
  58910. }
  58911. return line;
  58912. };
  58913. /**
  58914. * Reads header information from an RGBE texture stored in a native array.
  58915. * More information on this format are available here:
  58916. * https://en.wikipedia.org/wiki/RGBE_image_format
  58917. *
  58918. * @param uint8array The binary file stored in native array.
  58919. * @return The header information.
  58920. */
  58921. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58922. var height = 0;
  58923. var width = 0;
  58924. var line = this.readStringLine(uint8array, 0);
  58925. if (line[0] != '#' || line[1] != '?') {
  58926. throw "Bad HDR Format.";
  58927. }
  58928. var endOfHeader = false;
  58929. var findFormat = false;
  58930. var lineIndex = 0;
  58931. do {
  58932. lineIndex += (line.length + 1);
  58933. line = this.readStringLine(uint8array, lineIndex);
  58934. if (line == "FORMAT=32-bit_rle_rgbe") {
  58935. findFormat = true;
  58936. }
  58937. else if (line.length == 0) {
  58938. endOfHeader = true;
  58939. }
  58940. } while (!endOfHeader);
  58941. if (!findFormat) {
  58942. throw "HDR Bad header format, unsupported FORMAT";
  58943. }
  58944. lineIndex += (line.length + 1);
  58945. line = this.readStringLine(uint8array, lineIndex);
  58946. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58947. var match = sizeRegexp.exec(line);
  58948. // TODO. Support +Y and -X if needed.
  58949. if (match.length < 3) {
  58950. throw "HDR Bad header format, no size";
  58951. }
  58952. width = parseInt(match[2]);
  58953. height = parseInt(match[1]);
  58954. if (width < 8 || width > 0x7fff) {
  58955. throw "HDR Bad header format, unsupported size";
  58956. }
  58957. lineIndex += (line.length + 1);
  58958. return {
  58959. height: height,
  58960. width: width,
  58961. dataPosition: lineIndex
  58962. };
  58963. };
  58964. /**
  58965. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58966. * This RGBE texture needs to store the information as a panorama.
  58967. *
  58968. * More information on this format are available here:
  58969. * https://en.wikipedia.org/wiki/RGBE_image_format
  58970. *
  58971. * @param buffer The binary file stored in an array buffer.
  58972. * @param size The expected size of the extracted cubemap.
  58973. * @return The Cube Map information.
  58974. */
  58975. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58976. var uint8array = new Uint8Array(buffer);
  58977. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58978. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58979. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58980. return cubeMapData;
  58981. };
  58982. /**
  58983. * Returns the pixels data extracted from an RGBE texture.
  58984. * This pixels will be stored left to right up to down in the R G B order in one array.
  58985. *
  58986. * More information on this format are available here:
  58987. * https://en.wikipedia.org/wiki/RGBE_image_format
  58988. *
  58989. * @param uint8array The binary file stored in an array buffer.
  58990. * @param hdrInfo The header information of the file.
  58991. * @return The pixels data in RGB right to left up to down order.
  58992. */
  58993. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58994. // Keep for multi format supports.
  58995. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58996. };
  58997. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58998. var num_scanlines = hdrInfo.height;
  58999. var scanline_width = hdrInfo.width;
  59000. var a, b, c, d, count;
  59001. var dataIndex = hdrInfo.dataPosition;
  59002. var index = 0, endIndex = 0, i = 0;
  59003. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  59004. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  59005. // 3 channels of 4 bytes per pixel in float.
  59006. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  59007. var resultArray = new Float32Array(resultBuffer);
  59008. // read in each successive scanline
  59009. while (num_scanlines > 0) {
  59010. a = uint8array[dataIndex++];
  59011. b = uint8array[dataIndex++];
  59012. c = uint8array[dataIndex++];
  59013. d = uint8array[dataIndex++];
  59014. if (a != 2 || b != 2 || (c & 0x80)) {
  59015. // this file is not run length encoded
  59016. throw "HDR Bad header format, not RLE";
  59017. }
  59018. if (((c << 8) | d) != scanline_width) {
  59019. throw "HDR Bad header format, wrong scan line width";
  59020. }
  59021. index = 0;
  59022. // read each of the four channels for the scanline into the buffer
  59023. for (i = 0; i < 4; i++) {
  59024. endIndex = (i + 1) * scanline_width;
  59025. while (index < endIndex) {
  59026. a = uint8array[dataIndex++];
  59027. b = uint8array[dataIndex++];
  59028. if (a > 128) {
  59029. // a run of the same value
  59030. count = a - 128;
  59031. if ((count == 0) || (count > endIndex - index)) {
  59032. throw "HDR Bad Format, bad scanline data (run)";
  59033. }
  59034. while (count-- > 0) {
  59035. scanLineArray[index++] = b;
  59036. }
  59037. }
  59038. else {
  59039. // a non-run
  59040. count = a;
  59041. if ((count == 0) || (count > endIndex - index)) {
  59042. throw "HDR Bad Format, bad scanline data (non-run)";
  59043. }
  59044. scanLineArray[index++] = b;
  59045. if (--count > 0) {
  59046. for (var j = 0; j < count; j++) {
  59047. scanLineArray[index++] = uint8array[dataIndex++];
  59048. }
  59049. }
  59050. }
  59051. }
  59052. }
  59053. // now convert data from buffer into floats
  59054. for (i = 0; i < scanline_width; i++) {
  59055. a = scanLineArray[i];
  59056. b = scanLineArray[i + scanline_width];
  59057. c = scanLineArray[i + 2 * scanline_width];
  59058. d = scanLineArray[i + 3 * scanline_width];
  59059. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  59060. }
  59061. num_scanlines--;
  59062. }
  59063. return resultArray;
  59064. };
  59065. return HDRTools;
  59066. }());
  59067. Internals.HDRTools = HDRTools;
  59068. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59069. })(BABYLON || (BABYLON = {}));
  59070. //_______________________________________________________________
  59071. // Extracted from CubeMapGen:
  59072. // https://code.google.com/archive/p/cubemapgen/
  59073. //
  59074. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  59075. //_______________________________________________________________
  59076. var BABYLON;
  59077. (function (BABYLON) {
  59078. var Internals;
  59079. (function (Internals) {
  59080. /**
  59081. * The bounding box information used during the conversion process.
  59082. */
  59083. var CMGBoundinBox = (function () {
  59084. function CMGBoundinBox() {
  59085. this.min = new BABYLON.Vector3(0, 0, 0);
  59086. this.max = new BABYLON.Vector3(0, 0, 0);
  59087. this.clear();
  59088. }
  59089. CMGBoundinBox.prototype.clear = function () {
  59090. this.min.x = CMGBoundinBox.MAX;
  59091. this.min.y = CMGBoundinBox.MAX;
  59092. this.min.z = CMGBoundinBox.MAX;
  59093. this.max.x = CMGBoundinBox.MIN;
  59094. this.max.y = CMGBoundinBox.MIN;
  59095. this.max.z = CMGBoundinBox.MIN;
  59096. };
  59097. CMGBoundinBox.prototype.augment = function (x, y, z) {
  59098. this.min.x = Math.min(this.min.x, x);
  59099. this.min.y = Math.min(this.min.y, y);
  59100. this.min.z = Math.min(this.min.z, z);
  59101. this.max.x = Math.max(this.max.x, x);
  59102. this.max.y = Math.max(this.max.y, y);
  59103. this.max.z = Math.max(this.max.z, z);
  59104. };
  59105. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  59106. this.min.x = Math.max(this.min.x, x);
  59107. this.min.y = Math.max(this.min.y, y);
  59108. this.min.z = Math.max(this.min.z, z);
  59109. };
  59110. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  59111. this.max.x = Math.min(this.max.x, x);
  59112. this.max.y = Math.min(this.max.y, y);
  59113. this.max.z = Math.min(this.max.z, z);
  59114. };
  59115. CMGBoundinBox.prototype.empty = function () {
  59116. if ((this.min.x > this.max.y) ||
  59117. (this.min.y > this.max.y) ||
  59118. (this.min.z > this.max.y)) {
  59119. return true;
  59120. }
  59121. else {
  59122. return false;
  59123. }
  59124. };
  59125. CMGBoundinBox.MAX = Number.MAX_VALUE;
  59126. CMGBoundinBox.MIN = Number.MIN_VALUE;
  59127. return CMGBoundinBox;
  59128. }());
  59129. /**
  59130. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  59131. * required by the glossinees of a material.
  59132. *
  59133. * This only supports the cosine drop power as well as Warp fixup generation method.
  59134. *
  59135. * This is using the process from CubeMapGen described here:
  59136. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  59137. */
  59138. var PMREMGenerator = (function () {
  59139. /**
  59140. * Constructor of the generator.
  59141. *
  59142. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  59143. * @param inputSize The size of the cubemap faces
  59144. * @param outputSize The size of the output cubemap faces
  59145. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  59146. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  59147. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  59148. * @param specularPower The max specular level of the desired cubemap
  59149. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  59150. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  59151. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  59152. */
  59153. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  59154. this.input = input;
  59155. this.inputSize = inputSize;
  59156. this.outputSize = outputSize;
  59157. this.maxNumMipLevels = maxNumMipLevels;
  59158. this.numChannels = numChannels;
  59159. this.isFloat = isFloat;
  59160. this.specularPower = specularPower;
  59161. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  59162. this.excludeBase = excludeBase;
  59163. this.fixup = fixup;
  59164. this._outputSurface = [];
  59165. this._numMipLevels = 0;
  59166. }
  59167. /**
  59168. * Launches the filter process and return the result.
  59169. *
  59170. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  59171. */
  59172. PMREMGenerator.prototype.filterCubeMap = function () {
  59173. // Init cubemap processor
  59174. this.init();
  59175. // Filters the cubemap
  59176. this.filterCubeMapMipChain();
  59177. // Returns the filtered mips.
  59178. return this._outputSurface;
  59179. };
  59180. PMREMGenerator.prototype.init = function () {
  59181. var i;
  59182. var j;
  59183. var mipLevelSize;
  59184. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  59185. if (this.maxNumMipLevels == 0) {
  59186. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  59187. }
  59188. //first miplevel size
  59189. mipLevelSize = this.outputSize;
  59190. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  59191. for (j = 0; j < this.maxNumMipLevels; j++) {
  59192. this._outputSurface.length++;
  59193. this._outputSurface[j] = [];
  59194. //Iterate over faces for output images
  59195. for (i = 0; i < 6; i++) {
  59196. this._outputSurface[j].length++;
  59197. // Initializes a new array for the output.
  59198. if (this.isFloat) {
  59199. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59200. }
  59201. else {
  59202. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  59203. }
  59204. }
  59205. //next mip level is half size
  59206. mipLevelSize >>= 1;
  59207. this._numMipLevels++;
  59208. //terminate if mip chain becomes too small
  59209. if (mipLevelSize == 0) {
  59210. this.maxNumMipLevels = j;
  59211. return;
  59212. }
  59213. }
  59214. };
  59215. //--------------------------------------------------------------------------------------
  59216. //Cube map filtering and mip chain generation.
  59217. // the cube map filtereing is specified using a number of parameters:
  59218. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  59219. // indicates the region of the hemisphere to filter over for each tap.
  59220. //
  59221. // Note that the top mip level is also a filtered version of the original input images
  59222. // as well in order to create mip chains for diffuse environment illumination.
  59223. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  59224. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  59225. //
  59226. // Then the mip angle used to genreate the next level of the mip chain from the first level
  59227. // is a_InitialMipAngle
  59228. //
  59229. // The angle for the subsequent levels of the mip chain are specified by their parents
  59230. // filtering angle and a per-level scale and bias
  59231. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  59232. //
  59233. //--------------------------------------------------------------------------------------
  59234. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  59235. // First, take count of the lighting model to modify SpecularPower
  59236. // 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;
  59237. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  59238. //Cone angle start (for generating subsequent mip levels)
  59239. var currentSpecularPower = this.specularPower;
  59240. //Build filter lookup tables based on the source miplevel size
  59241. this.precomputeFilterLookupTables(this.inputSize);
  59242. // Note that we need to filter the first level before generating mipmap
  59243. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  59244. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  59245. // TODO : Write a function to copy and scale the base mipmap in output
  59246. // I am just lazy here and just put a high specular power value, and do some if.
  59247. if (this.excludeBase && (levelIndex == 0)) {
  59248. // 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).
  59249. currentSpecularPower = 100000.0;
  59250. }
  59251. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  59252. var srcCubeImage = this.input;
  59253. var dstCubeImage = this._outputSurface[levelIndex];
  59254. var dstSize = this.outputSize >> levelIndex;
  59255. // Compute required angle.
  59256. var angle = this.getBaseFilterAngle(currentSpecularPower);
  59257. // filter cube surfaces
  59258. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  59259. // fix seams
  59260. if (this.fixup) {
  59261. this.fixupCubeEdges(dstCubeImage, dstSize);
  59262. }
  59263. // Decrease the specular power to generate the mipmap chain
  59264. // TODO : Use another method for Exclude (see first comment at start of the function
  59265. if (this.excludeBase && (levelIndex == 0)) {
  59266. currentSpecularPower = this.specularPower;
  59267. }
  59268. currentSpecularPower *= this.cosinePowerDropPerMip;
  59269. }
  59270. };
  59271. //--------------------------------------------------------------------------------------
  59272. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  59273. // It allow to optimize the texel to access base on the specular power.
  59274. //--------------------------------------------------------------------------------------
  59275. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  59276. // We want to find the alpha such that:
  59277. // cos(alpha)^cosinePower = epsilon
  59278. // That's: acos(epsilon^(1/cosinePower))
  59279. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  59280. var angle = 180.0;
  59281. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  59282. angle *= 180.0 / Math.PI; // Convert to degree
  59283. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  59284. return angle;
  59285. };
  59286. //--------------------------------------------------------------------------------------
  59287. //Builds the following lookup tables prior to filtering:
  59288. // -normalizer cube map
  59289. // -tap weight lookup table
  59290. //
  59291. //--------------------------------------------------------------------------------------
  59292. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  59293. var srcTexelAngle;
  59294. var iCubeFace;
  59295. //clear pre-existing normalizer cube map
  59296. this._normCubeMap = [];
  59297. //Normalized vectors per cubeface and per-texel solid angle
  59298. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  59299. };
  59300. //--------------------------------------------------------------------------------------
  59301. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  59302. //
  59303. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  59304. //
  59305. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  59306. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  59307. // below
  59308. //--------------------------------------------------------------------------------------
  59309. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  59310. var iCubeFace;
  59311. var u;
  59312. var v;
  59313. //iterate over cube faces
  59314. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59315. //First three channels for norm cube, and last channel for solid angle
  59316. this._normCubeMap.push(new Float32Array(size * size * 4));
  59317. //fast texture walk, build normalizer cube map
  59318. var facesData = this.input[iCubeFace];
  59319. for (v = 0; v < size; v++) {
  59320. for (u = 0; u < size; u++) {
  59321. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  59322. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  59323. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  59324. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  59325. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  59326. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  59327. }
  59328. }
  59329. }
  59330. };
  59331. //--------------------------------------------------------------------------------------
  59332. // Convert cubemap face texel coordinates and face idx to 3D vector
  59333. // note the U and V coords are integer coords and range from 0 to size-1
  59334. // this routine can be used to generate a normalizer cube map
  59335. //--------------------------------------------------------------------------------------
  59336. // SL BEGIN
  59337. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  59338. var nvcU;
  59339. var nvcV;
  59340. var tempVec;
  59341. // Change from original AMD code
  59342. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59343. // + 0.5f is for texel center addressing
  59344. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  59345. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  59346. // warp fixup
  59347. if (fixup && size > 1) {
  59348. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  59349. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  59350. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  59351. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  59352. }
  59353. // Get current vector
  59354. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  59355. // U contribution
  59356. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59357. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  59358. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  59359. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  59360. // V contribution and Sum
  59361. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59362. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  59363. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  59364. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  59365. //add face axis
  59366. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  59367. PMREMGenerator._vectorTemp.x += faceAxis[0];
  59368. PMREMGenerator._vectorTemp.y += faceAxis[1];
  59369. PMREMGenerator._vectorTemp.z += faceAxis[2];
  59370. //normalize vector
  59371. PMREMGenerator._vectorTemp.normalize();
  59372. return PMREMGenerator._vectorTemp;
  59373. };
  59374. //--------------------------------------------------------------------------------------
  59375. // Convert 3D vector to cubemap face texel coordinates and face idx
  59376. // note the U and V coords are integer coords and range from 0 to size-1
  59377. // this routine can be used to generate a normalizer cube map
  59378. //
  59379. // returns face IDX and texel coords
  59380. //--------------------------------------------------------------------------------------
  59381. // SL BEGIN
  59382. /*
  59383. Mapping Texture Coordinates to Cube Map Faces
  59384. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  59385. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  59386. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  59387. map arrangement in Pixar's RenderMan package.
  59388. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  59389. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  59390. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  59391. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  59392. the major axis direction). The target column in the table below explains how the major axis direction
  59393. maps to the 2D image of a particular cube map target.
  59394. major axis
  59395. direction target sc tc ma
  59396. ---------- --------------------------------- --- --- ---
  59397. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  59398. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  59399. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  59400. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  59401. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  59402. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  59403. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  59404. an updated (s,t) is calculated as follows
  59405. s = ( sc/|ma| + 1 ) / 2
  59406. t = ( tc/|ma| + 1 ) / 2
  59407. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  59408. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  59409. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  59410. */
  59411. // Note this method return U and V in range from 0 to size-1
  59412. // SL END
  59413. // Store the information in vector3 for convenience (faceindex, u, v)
  59414. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  59415. var maxCoord;
  59416. var faceIdx;
  59417. //absolute value 3
  59418. var absX = Math.abs(x);
  59419. var absY = Math.abs(y);
  59420. var absZ = Math.abs(z);
  59421. if (absX >= absY && absX >= absZ) {
  59422. maxCoord = absX;
  59423. if (x >= 0) {
  59424. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  59425. }
  59426. else {
  59427. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59428. }
  59429. }
  59430. else if (absY >= absX && absY >= absZ) {
  59431. maxCoord = absY;
  59432. if (y >= 0) {
  59433. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59434. }
  59435. else {
  59436. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59437. }
  59438. }
  59439. else {
  59440. maxCoord = absZ;
  59441. if (z >= 0) {
  59442. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59443. }
  59444. else {
  59445. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59446. }
  59447. }
  59448. //divide through by max coord so face vector lies on cube face
  59449. var scale = 1 / maxCoord;
  59450. x *= scale;
  59451. y *= scale;
  59452. z *= scale;
  59453. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59454. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  59455. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59456. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  59457. // Modify original AMD code to return value from 0 to Size - 1
  59458. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  59459. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  59460. PMREMGenerator._vectorTemp.x = faceIdx;
  59461. PMREMGenerator._vectorTemp.y = u;
  59462. PMREMGenerator._vectorTemp.z = v;
  59463. return PMREMGenerator._vectorTemp;
  59464. };
  59465. //--------------------------------------------------------------------------------------
  59466. //Original code from Ignacio CastaÒo
  59467. // This formula is from Manne ÷hrstrˆm's thesis.
  59468. // Take two coordiantes in the range [-1, 1] that define a portion of a
  59469. // cube face and return the area of the projection of that portion on the
  59470. // surface of the sphere.
  59471. //--------------------------------------------------------------------------------------
  59472. PMREMGenerator.prototype.areaElement = function (x, y) {
  59473. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  59474. };
  59475. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  59476. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59477. // (+ 0.5f is for texel center addressing)
  59478. u = (2.0 * (u + 0.5) / size) - 1.0;
  59479. v = (2.0 * (v + 0.5) / size) - 1.0;
  59480. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  59481. var invResolution = 1.0 / size;
  59482. // U and V are the -1..1 texture coordinate on the current face.
  59483. // Get projected area for this texel
  59484. var x0 = u - invResolution;
  59485. var y0 = v - invResolution;
  59486. var x1 = u + invResolution;
  59487. var y1 = v + invResolution;
  59488. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  59489. return solidAngle;
  59490. };
  59491. //--------------------------------------------------------------------------------------
  59492. //The key to the speed of these filtering routines is to quickly define a per-face
  59493. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  59494. // Later these pixels are selectively processed based on their dot products to see if
  59495. // they reside within the filtering cone.
  59496. //
  59497. //This is done by computing the smallest per-texel angle to get a conservative estimate
  59498. // of the number of texels needed to be covered in width and height order to filter the
  59499. // region. the bounding box for the center taps face is defined first, and if the
  59500. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  59501. // defined next
  59502. //--------------------------------------------------------------------------------------
  59503. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  59504. // note that pixels within these regions may be rejected
  59505. // based on the anlge
  59506. var iCubeFace;
  59507. var u;
  59508. var v;
  59509. // bounding box per face to specify region to process
  59510. var filterExtents = [];
  59511. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59512. filterExtents.push(new CMGBoundinBox());
  59513. }
  59514. // min angle a src texel can cover (in degrees)
  59515. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  59516. // angle about center tap to define filter cone
  59517. // filter angle is 1/2 the cone angle
  59518. var filterAngle = filterConeAngle / 2.0;
  59519. //ensure filter angle is larger than a texel
  59520. if (filterAngle < srcTexelAngle) {
  59521. filterAngle = srcTexelAngle;
  59522. }
  59523. //ensure filter cone is always smaller than the hemisphere
  59524. if (filterAngle > 90.0) {
  59525. filterAngle = 90.0;
  59526. }
  59527. // the maximum number of texels in 1D the filter cone angle will cover
  59528. // used to determine bounding box size for filter extents
  59529. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  59530. // ensure conservative region always covers at least one texel
  59531. if (filterSize < 1) {
  59532. filterSize = 1;
  59533. }
  59534. // dotProdThresh threshold based on cone angle to determine whether or not taps
  59535. // reside within the cone angle
  59536. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  59537. // process required faces
  59538. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59539. //iterate over dst cube map face texel
  59540. for (v = 0; v < dstSize; v++) {
  59541. for (u = 0; u < dstSize; u++) {
  59542. //get center tap direction
  59543. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  59544. //clear old per-face filter extents
  59545. this.clearFilterExtents(filterExtents);
  59546. //define per-face filter extents
  59547. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  59548. //perform filtering of src faces using filter extents
  59549. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  59550. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  59551. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  59552. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  59553. }
  59554. }
  59555. }
  59556. };
  59557. //--------------------------------------------------------------------------------------
  59558. //Clear filter extents for the 6 cube map faces
  59559. //--------------------------------------------------------------------------------------
  59560. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  59561. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  59562. filterExtents[iCubeFaces].clear();
  59563. }
  59564. };
  59565. //--------------------------------------------------------------------------------------
  59566. //Define per-face bounding box filter extents
  59567. //
  59568. // These define conservative texel regions in each of the faces the filter can possibly
  59569. // process. When the pixels in the regions are actually processed, the dot product
  59570. // between the tap vector and the center tap vector is used to determine the weight of
  59571. // the tap and whether or not the tap is within the cone.
  59572. //
  59573. //--------------------------------------------------------------------------------------
  59574. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  59575. //neighboring face and bleed over amount, and width of BBOX for
  59576. // left, right, top, and bottom edges of this face
  59577. var bleedOverAmount = [0, 0, 0, 0];
  59578. var bleedOverBBoxMin = [0, 0, 0, 0];
  59579. var bleedOverBBoxMax = [0, 0, 0, 0];
  59580. var neighborFace;
  59581. var neighborEdge;
  59582. var oppositeFaceIdx;
  59583. //get face idx, and u, v info from center tap dir
  59584. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  59585. var faceIdx = result.x;
  59586. var u = result.y;
  59587. var v = result.z;
  59588. //define bbox size within face
  59589. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  59590. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  59591. filterExtents[faceIdx].clampMin(0, 0, 0);
  59592. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  59593. //u and v extent in face corresponding to center tap
  59594. var minU = filterExtents[faceIdx].min.x;
  59595. var minV = filterExtents[faceIdx].min.y;
  59596. var maxU = filterExtents[faceIdx].max.x;
  59597. var maxV = filterExtents[faceIdx].max.y;
  59598. //bleed over amounts for face across u=0 edge (left)
  59599. bleedOverAmount[0] = (bboxSize - u);
  59600. bleedOverBBoxMin[0] = minV;
  59601. bleedOverBBoxMax[0] = maxV;
  59602. //bleed over amounts for face across u=1 edge (right)
  59603. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  59604. bleedOverBBoxMin[1] = minV;
  59605. bleedOverBBoxMax[1] = maxV;
  59606. //bleed over to face across v=0 edge (up)
  59607. bleedOverAmount[2] = (bboxSize - v);
  59608. bleedOverBBoxMin[2] = minU;
  59609. bleedOverBBoxMax[2] = maxU;
  59610. //bleed over to face across v=1 edge (down)
  59611. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  59612. bleedOverBBoxMin[3] = minU;
  59613. bleedOverBBoxMax[3] = maxU;
  59614. //compute bleed over regions in neighboring faces
  59615. for (var i = 0; i < 4; i++) {
  59616. if (bleedOverAmount[i] > 0) {
  59617. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  59618. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  59619. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  59620. // be flipped: the cases are
  59621. // if a left edge mates with a left or bottom edge on the neighbor
  59622. // if a top edge mates with a top or right edge on the neighbor
  59623. // if a right edge mates with a right or top edge on the neighbor
  59624. // if a bottom edge mates with a bottom or left edge on the neighbor
  59625. //Seeing as the edges are enumerated as follows
  59626. // left =0
  59627. // right =1
  59628. // top =2
  59629. // bottom =3
  59630. //
  59631. // so if the edge enums are the same, or the sum of the enums == 3,
  59632. // the bbox needs to be flipped
  59633. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  59634. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  59635. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  59636. }
  59637. //The way the bounding box is extended onto the neighboring face
  59638. // depends on which edge of neighboring face abuts with this one
  59639. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  59640. case PMREMGenerator.CP_EDGE_LEFT:
  59641. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  59642. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59643. break;
  59644. case PMREMGenerator.CP_EDGE_RIGHT:
  59645. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  59646. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59647. break;
  59648. case PMREMGenerator.CP_EDGE_TOP:
  59649. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  59650. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  59651. break;
  59652. case PMREMGenerator.CP_EDGE_BOTTOM:
  59653. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  59654. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  59655. break;
  59656. }
  59657. //clamp filter extents in non-center tap faces to remain within surface
  59658. filterExtents[neighborFace].clampMin(0, 0, 0);
  59659. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  59660. }
  59661. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  59662. // from the center tap face, then process the opposite face entirely for now.
  59663. //Note that the cases in which this happens, what usually happens is that
  59664. // more than one edge bleeds onto the opposite face, and the bounding box
  59665. // encompasses the entire cube map face.
  59666. if (bleedOverAmount[i] > srcSize) {
  59667. //determine opposite face
  59668. switch (faceIdx) {
  59669. case PMREMGenerator.CP_FACE_X_POS:
  59670. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59671. break;
  59672. case PMREMGenerator.CP_FACE_X_NEG:
  59673. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  59674. break;
  59675. case PMREMGenerator.CP_FACE_Y_POS:
  59676. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59677. break;
  59678. case PMREMGenerator.CP_FACE_Y_NEG:
  59679. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59680. break;
  59681. case PMREMGenerator.CP_FACE_Z_POS:
  59682. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59683. break;
  59684. case PMREMGenerator.CP_FACE_Z_NEG:
  59685. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59686. break;
  59687. default:
  59688. break;
  59689. }
  59690. //just encompass entire face for now
  59691. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  59692. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  59693. }
  59694. }
  59695. };
  59696. //--------------------------------------------------------------------------------------
  59697. //ProcessFilterExtents
  59698. // Process bounding box in each cube face
  59699. //
  59700. //--------------------------------------------------------------------------------------
  59701. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  59702. //accumulators are 64-bit floats in order to have the precision needed
  59703. // over a summation of a large number of pixels
  59704. var dstAccum = [0, 0, 0, 0];
  59705. var weightAccum = 0;
  59706. var k = 0;
  59707. var nSrcChannels = this.numChannels;
  59708. // norm cube map and srcCubeMap have same face width
  59709. var faceWidth = srcSize;
  59710. //amount to add to pointer to move to next scanline in images
  59711. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  59712. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  59713. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  59714. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  59715. // iterate over cubefaces
  59716. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  59717. //if bbox is non empty
  59718. if (!filterExtents[iFaceIdx].empty()) {
  59719. var uStart = filterExtents[iFaceIdx].min.x;
  59720. var vStart = filterExtents[iFaceIdx].min.y;
  59721. var uEnd = filterExtents[iFaceIdx].max.x;
  59722. var vEnd = filterExtents[iFaceIdx].max.y;
  59723. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  59724. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  59725. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  59726. for (var v = vStart; v <= vEnd; v++) {
  59727. var normCubeRowWalk = 0;
  59728. var srcCubeRowWalk = 0;
  59729. for (var u = uStart; u <= uEnd; u++) {
  59730. //pointer to direction in cube map associated with texel
  59731. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  59732. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  59733. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  59734. //check dot product to see if texel is within cone
  59735. var tapDotProd = texelVectX * centerTapDir.x +
  59736. texelVectY * centerTapDir.y +
  59737. texelVectZ * centerTapDir.z;
  59738. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  59739. //solid angle stored in 4th channel of normalizer/solid angle cube map
  59740. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  59741. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  59742. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  59743. // so just adding one to specularpower do the trick.
  59744. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  59745. //iterate over channels
  59746. for (k = 0; k < nSrcChannels; k++) {
  59747. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  59748. srcCubeRowWalk++;
  59749. }
  59750. weightAccum += weight; //accumulate weight
  59751. }
  59752. else {
  59753. //step across source pixel
  59754. srcCubeRowWalk += nSrcChannels;
  59755. }
  59756. normCubeRowWalk += 4; // 4 channels per norm cube map.
  59757. }
  59758. startIndexNormCubeMap += normCubePitch;
  59759. startIndexSrcCubeMap += srcCubePitch;
  59760. }
  59761. }
  59762. }
  59763. //divide through by weights if weight is non zero
  59764. if (weightAccum != 0.0) {
  59765. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  59766. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  59767. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  59768. if (this.numChannels > 3) {
  59769. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  59770. }
  59771. }
  59772. else {
  59773. // otherwise sample nearest
  59774. // get face idx and u, v texel coordinate in face
  59775. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  59776. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  59777. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  59778. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  59779. if (this.numChannels > 3) {
  59780. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  59781. }
  59782. }
  59783. return PMREMGenerator._vectorTemp;
  59784. };
  59785. //--------------------------------------------------------------------------------------
  59786. // Fixup cube edges
  59787. //
  59788. // average texels on cube map faces across the edges
  59789. // WARP/BENT Method Only.
  59790. //--------------------------------------------------------------------------------------
  59791. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  59792. var k;
  59793. var j;
  59794. var i;
  59795. var iFace;
  59796. var iCorner = 0;
  59797. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  59798. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  59799. // note that if functionality to filter across the three texels for each corner, then
  59800. //indexed by corner and face idx. the array contains the face the start points belongs to.
  59801. var cornerPtr = [
  59802. [[], [], []],
  59803. [[], [], []],
  59804. [[], [], []],
  59805. [[], [], []],
  59806. [[], [], []],
  59807. [[], [], []],
  59808. [[], [], []],
  59809. [[], [], []]
  59810. ];
  59811. //if there is no fixup, or fixup width = 0, do nothing
  59812. if (cubeMapSize < 1) {
  59813. return;
  59814. }
  59815. //special case 1x1 cubemap, average face colors
  59816. if (cubeMapSize == 1) {
  59817. //iterate over channels
  59818. for (k = 0; k < this.numChannels; k++) {
  59819. var accum = 0.0;
  59820. //iterate over faces to accumulate face colors
  59821. for (iFace = 0; iFace < 6; iFace++) {
  59822. accum += cubeMap[iFace][k];
  59823. }
  59824. //compute average over 6 face colors
  59825. accum /= 6.0;
  59826. //iterate over faces to distribute face colors
  59827. for (iFace = 0; iFace < 6; iFace++) {
  59828. cubeMap[iFace][k] = accum;
  59829. }
  59830. }
  59831. return;
  59832. }
  59833. //iterate over faces to collect list of corner texel pointers
  59834. for (iFace = 0; iFace < 6; iFace++) {
  59835. //the 4 corner pointers for this face
  59836. faceCornerStartIndicies[0] = [iFace, 0];
  59837. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  59838. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  59839. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  59840. //iterate over face corners to collect cube corner pointers
  59841. for (iCorner = 0; iCorner < 4; iCorner++) {
  59842. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  59843. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  59844. cornerNumPtrs[corner]++;
  59845. }
  59846. }
  59847. //iterate over corners to average across corner tap values
  59848. for (iCorner = 0; iCorner < 8; iCorner++) {
  59849. for (k = 0; k < this.numChannels; k++) {
  59850. var cornerTapAccum = 0.0;
  59851. //iterate over corner texels and average results
  59852. for (i = 0; i < 3; i++) {
  59853. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  59854. }
  59855. //divide by 3 to compute average of corner tap values
  59856. cornerTapAccum *= (1.0 / 3.0);
  59857. //iterate over corner texels and average results
  59858. for (i = 0; i < 3; i++) {
  59859. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  59860. }
  59861. }
  59862. }
  59863. //iterate over the twelve edges of the cube to average across edges
  59864. for (i = 0; i < 12; i++) {
  59865. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  59866. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  59867. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  59868. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  59869. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  59870. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  59871. var edgeWalk = 0;
  59872. var neighborEdgeWalk = 0;
  59873. //Determine walking pointers based on edge type
  59874. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  59875. switch (edge) {
  59876. case PMREMGenerator.CP_EDGE_LEFT:
  59877. // no change to faceEdgeStartPtr
  59878. edgeWalk = this.numChannels * cubeMapSize;
  59879. break;
  59880. case PMREMGenerator.CP_EDGE_RIGHT:
  59881. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59882. edgeWalk = this.numChannels * cubeMapSize;
  59883. break;
  59884. case PMREMGenerator.CP_EDGE_TOP:
  59885. // no change to faceEdgeStartPtr
  59886. edgeWalk = this.numChannels;
  59887. break;
  59888. case PMREMGenerator.CP_EDGE_BOTTOM:
  59889. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59890. edgeWalk = this.numChannels;
  59891. break;
  59892. }
  59893. //For certain types of edge abutments, the neighbor edge walk needs to
  59894. // be flipped: the cases are
  59895. // if a left edge mates with a left or bottom edge on the neighbor
  59896. // if a top edge mates with a top or right edge on the neighbor
  59897. // if a right edge mates with a right or top edge on the neighbor
  59898. // if a bottom edge mates with a bottom or left edge on the neighbor
  59899. //Seeing as the edges are enumerated as follows
  59900. // left =0
  59901. // right =1
  59902. // top =2
  59903. // bottom =3
  59904. //
  59905. //If the edge enums are the same, or the sum of the enums == 3,
  59906. // the neighbor edge walk needs to be flipped
  59907. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59908. switch (neighborEdge) {
  59909. case PMREMGenerator.CP_EDGE_LEFT:
  59910. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59911. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59912. break;
  59913. case PMREMGenerator.CP_EDGE_RIGHT:
  59914. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59915. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59916. break;
  59917. case PMREMGenerator.CP_EDGE_TOP:
  59918. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59919. neighborEdgeWalk = -this.numChannels;
  59920. break;
  59921. case PMREMGenerator.CP_EDGE_BOTTOM:
  59922. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59923. neighborEdgeWalk = -this.numChannels;
  59924. break;
  59925. }
  59926. }
  59927. else {
  59928. //swapped direction neighbor edge walk
  59929. switch (neighborEdge) {
  59930. case PMREMGenerator.CP_EDGE_LEFT:
  59931. //no change to neighborEdgeStartPtr for this case since it points
  59932. // to the upper left corner already
  59933. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59934. break;
  59935. case PMREMGenerator.CP_EDGE_RIGHT:
  59936. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59937. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59938. break;
  59939. case PMREMGenerator.CP_EDGE_TOP:
  59940. //no change to neighborEdgeStartPtr for this case since it points
  59941. // to the upper left corner already
  59942. neighborEdgeWalk = this.numChannels;
  59943. break;
  59944. case PMREMGenerator.CP_EDGE_BOTTOM:
  59945. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59946. neighborEdgeWalk = this.numChannels;
  59947. break;
  59948. }
  59949. }
  59950. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59951. //nearby neighborhood
  59952. //step ahead one texel on edge
  59953. edgeStartIndex += edgeWalk;
  59954. neighborEdgeStartIndex += neighborEdgeWalk;
  59955. // note that this loop does not process the corner texels, since they have already been
  59956. // averaged across faces across earlier
  59957. for (j = 1; j < (cubeMapSize - 1); j++) {
  59958. //for each set of taps along edge, average them
  59959. // and rewrite the results into the edges
  59960. for (k = 0; k < this.numChannels; k++) {
  59961. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59962. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59963. //compute average of tap intensity values
  59964. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59965. //propagate average of taps to edge taps
  59966. cubeMap[face][edgeStartIndex + k] = avgTap;
  59967. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59968. }
  59969. edgeStartIndex += edgeWalk;
  59970. neighborEdgeStartIndex += neighborEdgeWalk;
  59971. }
  59972. }
  59973. };
  59974. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59975. PMREMGenerator.CP_UDIR = 0;
  59976. PMREMGenerator.CP_VDIR = 1;
  59977. PMREMGenerator.CP_FACEAXIS = 2;
  59978. //used to index cube faces
  59979. PMREMGenerator.CP_FACE_X_POS = 0;
  59980. PMREMGenerator.CP_FACE_X_NEG = 1;
  59981. PMREMGenerator.CP_FACE_Y_POS = 2;
  59982. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59983. PMREMGenerator.CP_FACE_Z_POS = 4;
  59984. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59985. //used to index image edges
  59986. // NOTE.. the actual number corresponding to the edge is important
  59987. // do not change these, or the code will break
  59988. //
  59989. // CP_EDGE_LEFT is u = 0
  59990. // CP_EDGE_RIGHT is u = width-1
  59991. // CP_EDGE_TOP is v = 0
  59992. // CP_EDGE_BOTTOM is v = height-1
  59993. PMREMGenerator.CP_EDGE_LEFT = 0;
  59994. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59995. PMREMGenerator.CP_EDGE_TOP = 2;
  59996. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59997. //corners of CUBE map (P or N specifys if it corresponds to the
  59998. // positive or negative direction each of X, Y, and Z
  59999. PMREMGenerator.CP_CORNER_NNN = 0;
  60000. PMREMGenerator.CP_CORNER_NNP = 1;
  60001. PMREMGenerator.CP_CORNER_NPN = 2;
  60002. PMREMGenerator.CP_CORNER_NPP = 3;
  60003. PMREMGenerator.CP_CORNER_PNN = 4;
  60004. PMREMGenerator.CP_CORNER_PNP = 5;
  60005. PMREMGenerator.CP_CORNER_PPN = 6;
  60006. PMREMGenerator.CP_CORNER_PPP = 7;
  60007. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  60008. //3x2 matrices that map cube map indexing vectors in 3d
  60009. // (after face selection and divide through by the
  60010. // _ABSOLUTE VALUE_ of the max coord)
  60011. // into NVC space
  60012. //Note this currently assumes the D3D cube face ordering and orientation
  60013. PMREMGenerator._sgFace2DMapping = [
  60014. //XPOS face
  60015. [[0, 0, -1],
  60016. [0, -1, 0],
  60017. [1, 0, 0]],
  60018. //XNEG face
  60019. [[0, 0, 1],
  60020. [0, -1, 0],
  60021. [-1, 0, 0]],
  60022. //YPOS face
  60023. [[1, 0, 0],
  60024. [0, 0, 1],
  60025. [0, 1, 0]],
  60026. //YNEG face
  60027. [[1, 0, 0],
  60028. [0, 0, -1],
  60029. [0, -1, 0]],
  60030. //ZPOS face
  60031. [[1, 0, 0],
  60032. [0, -1, 0],
  60033. [0, 0, 1]],
  60034. //ZNEG face
  60035. [[-1, 0, 0],
  60036. [0, -1, 0],
  60037. [0, 0, -1]],
  60038. ];
  60039. //------------------------------------------------------------------------------
  60040. // D3D cube map face specification
  60041. // mapping from 3D x,y,z cube map lookup coordinates
  60042. // to 2D within face u,v coordinates
  60043. //
  60044. // --------------------> U direction
  60045. // | (within-face texture space)
  60046. // | _____
  60047. // | | |
  60048. // | | +Y |
  60049. // | _____|_____|_____ _____
  60050. // | | | | | |
  60051. // | | -X | +Z | +X | -Z |
  60052. // | |_____|_____|_____|_____|
  60053. // | | |
  60054. // | | -Y |
  60055. // | |_____|
  60056. // |
  60057. // v V direction
  60058. // (within-face texture space)
  60059. //------------------------------------------------------------------------------
  60060. //Information about neighbors and how texture coorrdinates change across faces
  60061. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  60062. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  60063. //Note this currently assumes the D3D cube face ordering and orientation
  60064. PMREMGenerator._sgCubeNgh = [
  60065. //XPOS face
  60066. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  60067. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  60068. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  60069. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  60070. //XNEG face
  60071. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  60072. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  60073. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  60074. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  60075. //YPOS face
  60076. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  60077. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  60078. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  60079. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  60080. //YNEG face
  60081. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  60082. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  60083. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  60084. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  60085. //ZPOS face
  60086. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  60087. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  60088. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  60089. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  60090. //ZNEG face
  60091. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  60092. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  60093. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  60094. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  60095. ];
  60096. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  60097. // this table is used to average over the edges.
  60098. PMREMGenerator._sgCubeEdgeList = [
  60099. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  60100. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  60101. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  60102. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  60103. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  60104. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  60105. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  60106. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  60107. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  60108. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  60109. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  60110. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  60111. ];
  60112. //Information about which of the 8 cube corners are correspond to the
  60113. // the 4 corners in each cube face
  60114. // the order is upper left, upper right, lower left, lower right
  60115. PMREMGenerator._sgCubeCornerList = [
  60116. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  60117. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  60118. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  60119. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  60120. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  60121. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  60122. ];
  60123. return PMREMGenerator;
  60124. }());
  60125. Internals.PMREMGenerator = PMREMGenerator;
  60126. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60127. })(BABYLON || (BABYLON = {}));
  60128. var BABYLON;
  60129. (function (BABYLON) {
  60130. /**
  60131. * This represents a texture coming from an HDR input.
  60132. *
  60133. * The only supported format is currently panorama picture stored in RGBE format.
  60134. * Example of such files can be found on HDRLib: http://hdrlib.com/
  60135. */
  60136. var HDRCubeTexture = (function (_super) {
  60137. __extends(HDRCubeTexture, _super);
  60138. /**
  60139. * Instantiates an HDRTexture from the following parameters.
  60140. *
  60141. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  60142. * @param scene The scene the texture will be used in
  60143. * @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.
  60144. * @param noMipmap Forces to not generate the mipmap if true
  60145. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  60146. * @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)
  60147. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  60148. */
  60149. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  60150. if (noMipmap === void 0) { noMipmap = false; }
  60151. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60152. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60153. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60154. _super.call(this, scene);
  60155. this._useInGammaSpace = false;
  60156. this._generateHarmonics = true;
  60157. this._isBABYLONPreprocessed = false;
  60158. /**
  60159. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  60160. */
  60161. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  60162. /**
  60163. * The spherical polynomial data extracted from the texture.
  60164. */
  60165. this.sphericalPolynomial = null;
  60166. /**
  60167. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  60168. * This is usefull at run time to apply the good shader.
  60169. */
  60170. this.isPMREM = false;
  60171. if (!url) {
  60172. return;
  60173. }
  60174. this.name = url;
  60175. this.url = url;
  60176. this.hasAlpha = false;
  60177. this.isCube = true;
  60178. this._textureMatrix = BABYLON.Matrix.Identity();
  60179. if (size) {
  60180. this._isBABYLONPreprocessed = false;
  60181. this._noMipmap = noMipmap;
  60182. this._size = size;
  60183. this._useInGammaSpace = useInGammaSpace;
  60184. this._usePMREMGenerator = usePMREMGenerator &&
  60185. scene.getEngine().getCaps().textureLOD &&
  60186. this.getScene().getEngine().getCaps().textureFloat &&
  60187. !this._useInGammaSpace;
  60188. }
  60189. else {
  60190. this._isBABYLONPreprocessed = true;
  60191. this._noMipmap = false;
  60192. this._useInGammaSpace = false;
  60193. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  60194. this.getScene().getEngine().getCaps().textureFloat &&
  60195. !this._useInGammaSpace;
  60196. }
  60197. this.isPMREM = this._usePMREMGenerator;
  60198. this._texture = this._getFromCache(url, this._noMipmap);
  60199. if (!this._texture) {
  60200. if (!scene.useDelayedTextureLoading) {
  60201. this.loadTexture();
  60202. }
  60203. else {
  60204. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60205. }
  60206. }
  60207. }
  60208. /**
  60209. * Occurs when the file is a preprocessed .babylon.hdr file.
  60210. */
  60211. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  60212. var _this = this;
  60213. var mipLevels = 0;
  60214. var floatArrayView = null;
  60215. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  60216. var mips = [];
  60217. var startIndex = 30;
  60218. for (var level = 0; level < mipLevels; level++) {
  60219. mips.push([]);
  60220. // Fill each pixel of the mip level.
  60221. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  60222. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60223. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  60224. mips[level].push(faceData);
  60225. startIndex += faceSize;
  60226. }
  60227. }
  60228. return mips;
  60229. } : null;
  60230. var callback = function (buffer) {
  60231. // Create Native Array Views
  60232. var intArrayView = new Int32Array(buffer);
  60233. floatArrayView = new Float32Array(buffer);
  60234. // Fill header.
  60235. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  60236. _this._size = intArrayView[1]; // CubeMap max mip face size.
  60237. // Update Texture Information.
  60238. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  60239. // Fill polynomial information.
  60240. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  60241. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  60242. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  60243. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  60244. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  60245. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  60246. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  60247. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  60248. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  60249. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  60250. // Fill pixel data.
  60251. mipLevels = intArrayView[29]; // Number of mip levels.
  60252. var startIndex = 30;
  60253. var data = [];
  60254. var faceSize = Math.pow(_this._size, 2) * 3;
  60255. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60256. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  60257. startIndex += faceSize;
  60258. }
  60259. var results = [];
  60260. var byteArray = null;
  60261. // Push each faces.
  60262. for (var k = 0; k < 6; k++) {
  60263. var dataFace = null;
  60264. // If special cases.
  60265. if (!mipmapGenerator) {
  60266. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  60267. dataFace = data[j];
  60268. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60269. // 3 channels of 1 bytes per pixel in bytes.
  60270. var byteBuffer = new ArrayBuffer(faceSize);
  60271. byteArray = new Uint8Array(byteBuffer);
  60272. }
  60273. for (var i = 0; i < _this._size * _this._size; i++) {
  60274. // Put in gamma space if requested.
  60275. if (_this._useInGammaSpace) {
  60276. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60277. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60278. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60279. }
  60280. // Convert to int texture for fallback.
  60281. if (byteArray) {
  60282. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60283. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60284. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60285. // May use luminance instead if the result is not accurate.
  60286. var max = Math.max(Math.max(r, g), b);
  60287. if (max > 255) {
  60288. var scale = 255 / max;
  60289. r *= scale;
  60290. g *= scale;
  60291. b *= scale;
  60292. }
  60293. byteArray[(i * 3) + 0] = r;
  60294. byteArray[(i * 3) + 1] = g;
  60295. byteArray[(i * 3) + 2] = b;
  60296. }
  60297. }
  60298. }
  60299. else {
  60300. dataFace = data[k];
  60301. }
  60302. // Fill the array accordingly.
  60303. if (byteArray) {
  60304. results.push(byteArray);
  60305. }
  60306. else {
  60307. results.push(dataFace);
  60308. }
  60309. }
  60310. return results;
  60311. };
  60312. 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);
  60313. };
  60314. /**
  60315. * Occurs when the file is raw .hdr file.
  60316. */
  60317. HDRCubeTexture.prototype.loadHDRTexture = function () {
  60318. var _this = this;
  60319. var callback = function (buffer) {
  60320. // Extract the raw linear data.
  60321. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  60322. // Generate harmonics if needed.
  60323. if (_this._generateHarmonics) {
  60324. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  60325. }
  60326. var results = [];
  60327. var byteArray = null;
  60328. // Push each faces.
  60329. for (var j = 0; j < 6; j++) {
  60330. // Create uintarray fallback.
  60331. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  60332. // 3 channels of 1 bytes per pixel in bytes.
  60333. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  60334. byteArray = new Uint8Array(byteBuffer);
  60335. }
  60336. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  60337. // If special cases.
  60338. if (_this._useInGammaSpace || byteArray) {
  60339. for (var i = 0; i < _this._size * _this._size; i++) {
  60340. // Put in gamma space if requested.
  60341. if (_this._useInGammaSpace) {
  60342. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  60343. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  60344. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  60345. }
  60346. // Convert to int texture for fallback.
  60347. if (byteArray) {
  60348. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  60349. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  60350. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  60351. // May use luminance instead if the result is not accurate.
  60352. var max = Math.max(Math.max(r, g), b);
  60353. if (max > 255) {
  60354. var scale = 255 / max;
  60355. r *= scale;
  60356. g *= scale;
  60357. b *= scale;
  60358. }
  60359. byteArray[(i * 3) + 0] = r;
  60360. byteArray[(i * 3) + 1] = g;
  60361. byteArray[(i * 3) + 2] = b;
  60362. }
  60363. }
  60364. }
  60365. if (byteArray) {
  60366. results.push(byteArray);
  60367. }
  60368. else {
  60369. results.push(dataFace);
  60370. }
  60371. }
  60372. return results;
  60373. };
  60374. var mipmapGenerator = null;
  60375. if (!this._noMipmap &&
  60376. this._usePMREMGenerator) {
  60377. mipmapGenerator = function (data) {
  60378. // Custom setup of the generator matching with the PBR shader values.
  60379. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  60380. return generator.filterCubeMap();
  60381. };
  60382. }
  60383. 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);
  60384. };
  60385. /**
  60386. * Starts the loading process of the texture.
  60387. */
  60388. HDRCubeTexture.prototype.loadTexture = function () {
  60389. if (this._isBABYLONPreprocessed) {
  60390. this.loadBabylonTexture();
  60391. }
  60392. else {
  60393. this.loadHDRTexture();
  60394. }
  60395. };
  60396. HDRCubeTexture.prototype.clone = function () {
  60397. var size = this._isBABYLONPreprocessed ? null : this._size;
  60398. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  60399. // Base texture
  60400. newTexture.level = this.level;
  60401. newTexture.wrapU = this.wrapU;
  60402. newTexture.wrapV = this.wrapV;
  60403. newTexture.coordinatesIndex = this.coordinatesIndex;
  60404. newTexture.coordinatesMode = this.coordinatesMode;
  60405. return newTexture;
  60406. };
  60407. // Methods
  60408. HDRCubeTexture.prototype.delayLoad = function () {
  60409. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60410. return;
  60411. }
  60412. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60413. this._texture = this._getFromCache(this.url, this._noMipmap);
  60414. if (!this._texture) {
  60415. this.loadTexture();
  60416. }
  60417. };
  60418. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  60419. return this._textureMatrix;
  60420. };
  60421. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60422. var texture = null;
  60423. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60424. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  60425. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  60426. texture.name = parsedTexture.name;
  60427. texture.hasAlpha = parsedTexture.hasAlpha;
  60428. texture.level = parsedTexture.level;
  60429. texture.coordinatesMode = parsedTexture.coordinatesMode;
  60430. }
  60431. return texture;
  60432. };
  60433. HDRCubeTexture.prototype.serialize = function () {
  60434. if (!this.name) {
  60435. return null;
  60436. }
  60437. var serializationObject = {};
  60438. serializationObject.name = this.name;
  60439. serializationObject.hasAlpha = this.hasAlpha;
  60440. serializationObject.isCube = true;
  60441. serializationObject.level = this.level;
  60442. serializationObject.size = this._size;
  60443. serializationObject.coordinatesMode = this.coordinatesMode;
  60444. serializationObject.useInGammaSpace = this._useInGammaSpace;
  60445. serializationObject.generateHarmonics = this._generateHarmonics;
  60446. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  60447. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  60448. serializationObject.customType = "BABYLON.HDRCubeTexture";
  60449. return serializationObject;
  60450. };
  60451. /**
  60452. * Saves as a file the data contained in the texture in a binary format.
  60453. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60454. * as the spherical used in the lighting.
  60455. * @param url The HDR file url.
  60456. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60457. * @param onError Method called if any error happens during download.
  60458. * @return The packed binary data.
  60459. */
  60460. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  60461. if (onError === void 0) { onError = null; }
  60462. var callback = function (buffer) {
  60463. var data = new Blob([buffer], { type: 'application/octet-stream' });
  60464. // Returns a URL you can use as a href.
  60465. var objUrl = window.URL.createObjectURL(data);
  60466. // Simulates a link to it and click to dowload.
  60467. var a = document.createElement("a");
  60468. document.body.appendChild(a);
  60469. a.style.display = "none";
  60470. a.href = objUrl;
  60471. a.download = "envmap.babylon.hdr";
  60472. a.click();
  60473. };
  60474. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  60475. };
  60476. /**
  60477. * Serializes the data contained in the texture in a binary format.
  60478. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60479. * as the spherical used in the lighting.
  60480. * @param url The HDR file url.
  60481. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60482. * @param onError Method called if any error happens during download.
  60483. * @return The packed binary data.
  60484. */
  60485. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  60486. if (onError === void 0) { onError = null; }
  60487. // Needs the url tho create the texture.
  60488. if (!url) {
  60489. return null;
  60490. }
  60491. // Check Power of two size.
  60492. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  60493. return null;
  60494. }
  60495. var getDataCallback = function (dataBuffer) {
  60496. // Extract the raw linear data.
  60497. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  60498. // Generate harmonics if needed.
  60499. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  60500. // Generate seamless faces
  60501. var mipGeneratorArray = [];
  60502. // Data are known to be in +X +Y +Z -X -Y -Z
  60503. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  60504. mipGeneratorArray.push(cubeData.right); // +X
  60505. mipGeneratorArray.push(cubeData.left); // -X
  60506. mipGeneratorArray.push(cubeData.up); // +Y
  60507. mipGeneratorArray.push(cubeData.down); // -Y
  60508. mipGeneratorArray.push(cubeData.front); // +Z
  60509. mipGeneratorArray.push(cubeData.back); // -Z
  60510. // Custom setup of the generator matching with the PBR shader values.
  60511. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  60512. var mippedData = generator.filterCubeMap();
  60513. // Compute required byte length.
  60514. var byteLength = 1 * 4; // Raw Data Version int32.
  60515. byteLength += 4; // CubeMap max mip face size int32.
  60516. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  60517. // Add data size.
  60518. byteLength += 4; // Number of mip levels int32.
  60519. for (var level = 0; level < mippedData.length; level++) {
  60520. var mipSize = size >> level;
  60521. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  60522. }
  60523. // Prepare binary structure.
  60524. var buffer = new ArrayBuffer(byteLength);
  60525. var intArrayView = new Int32Array(buffer);
  60526. var floatArrayView = new Float32Array(buffer);
  60527. // Fill header.
  60528. intArrayView[0] = 1; // Version 1.
  60529. intArrayView[1] = size; // CubeMap max mip face size.
  60530. // Fill polynomial information.
  60531. sphericalPolynomial.x.toArray(floatArrayView, 2);
  60532. sphericalPolynomial.y.toArray(floatArrayView, 5);
  60533. sphericalPolynomial.z.toArray(floatArrayView, 8);
  60534. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  60535. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  60536. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  60537. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  60538. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  60539. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  60540. // Fill pixel data.
  60541. intArrayView[29] = mippedData.length; // Number of mip levels.
  60542. var startIndex = 30;
  60543. for (var level = 0; level < mippedData.length; level++) {
  60544. // Fill each pixel of the mip level.
  60545. var faceSize = Math.pow(size >> level, 2) * 3;
  60546. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60547. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  60548. startIndex += faceSize;
  60549. }
  60550. }
  60551. // Callback.
  60552. callback(buffer);
  60553. };
  60554. // Download and process.
  60555. BABYLON.Tools.LoadFile(url, function (data) {
  60556. getDataCallback(data);
  60557. }, null, null, true, onError);
  60558. };
  60559. HDRCubeTexture._facesMapping = [
  60560. "right",
  60561. "up",
  60562. "front",
  60563. "left",
  60564. "down",
  60565. "back"
  60566. ];
  60567. return HDRCubeTexture;
  60568. }(BABYLON.BaseTexture));
  60569. BABYLON.HDRCubeTexture = HDRCubeTexture;
  60570. })(BABYLON || (BABYLON = {}));
  60571. var BABYLON;
  60572. (function (BABYLON) {
  60573. var Debug;
  60574. (function (Debug) {
  60575. /**
  60576. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  60577. */
  60578. var SkeletonViewer = (function () {
  60579. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  60580. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60581. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60582. this.skeleton = skeleton;
  60583. this.mesh = mesh;
  60584. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60585. this.renderingGroupId = renderingGroupId;
  60586. this.color = BABYLON.Color3.White();
  60587. this._debugLines = [];
  60588. this._isEnabled = false;
  60589. this._scene = scene;
  60590. this.update();
  60591. this._renderFunction = this.update.bind(this);
  60592. }
  60593. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60594. get: function () {
  60595. return this._isEnabled;
  60596. },
  60597. set: function (value) {
  60598. if (this._isEnabled === value) {
  60599. return;
  60600. }
  60601. this._isEnabled = value;
  60602. if (value) {
  60603. this._scene.registerBeforeRender(this._renderFunction);
  60604. }
  60605. else {
  60606. this._scene.unregisterBeforeRender(this._renderFunction);
  60607. }
  60608. },
  60609. enumerable: true,
  60610. configurable: true
  60611. });
  60612. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60613. if (x === void 0) { x = 0; }
  60614. if (y === void 0) { y = 0; }
  60615. if (z === void 0) { z = 0; }
  60616. var tmat = BABYLON.Tmp.Matrix[0];
  60617. var parentBone = bone.getParent();
  60618. tmat.copyFrom(bone.getLocalMatrix());
  60619. if (x !== 0 || y !== 0 || z !== 0) {
  60620. var tmat2 = BABYLON.Tmp.Matrix[1];
  60621. BABYLON.Matrix.IdentityToRef(tmat2);
  60622. tmat2.m[12] = x;
  60623. tmat2.m[13] = y;
  60624. tmat2.m[14] = z;
  60625. tmat2.multiplyToRef(tmat, tmat);
  60626. }
  60627. if (parentBone) {
  60628. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60629. }
  60630. tmat.multiplyToRef(meshMat, tmat);
  60631. position.x = tmat.m[12];
  60632. position.y = tmat.m[13];
  60633. position.z = tmat.m[14];
  60634. };
  60635. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60636. var len = bones.length;
  60637. for (var i = 0; i < len; i++) {
  60638. var bone = bones[i];
  60639. var points = this._debugLines[i];
  60640. if (!points) {
  60641. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60642. this._debugLines[i] = points;
  60643. }
  60644. this._getBonePosition(points[0], bone, meshMat);
  60645. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60646. }
  60647. };
  60648. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60649. var len = bones.length;
  60650. var boneNum = 0;
  60651. for (var i = len - 1; i >= 0; i--) {
  60652. var childBone = bones[i];
  60653. var parentBone = childBone.getParent();
  60654. if (!parentBone) {
  60655. continue;
  60656. }
  60657. var points = this._debugLines[boneNum];
  60658. if (!points) {
  60659. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60660. this._debugLines[boneNum] = points;
  60661. }
  60662. this._getBonePosition(points[0], childBone, meshMat);
  60663. this._getBonePosition(points[1], parentBone, meshMat);
  60664. boneNum++;
  60665. }
  60666. };
  60667. SkeletonViewer.prototype.update = function () {
  60668. if (this.autoUpdateBonesMatrices) {
  60669. this._updateBoneMatrix(this.skeleton.bones[0]);
  60670. }
  60671. if (this.skeleton.bones[0].length === undefined) {
  60672. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60673. }
  60674. else {
  60675. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60676. }
  60677. if (!this._debugMesh) {
  60678. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  60679. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60680. }
  60681. else {
  60682. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60683. }
  60684. this._debugMesh.color = this.color;
  60685. };
  60686. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  60687. if (bone.getParent()) {
  60688. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  60689. }
  60690. var children = bone.children;
  60691. var len = children.length;
  60692. for (var i = 0; i < len; i++) {
  60693. this._updateBoneMatrix(children[i]);
  60694. }
  60695. };
  60696. SkeletonViewer.prototype.dispose = function () {
  60697. if (this._debugMesh) {
  60698. this.isEnabled = false;
  60699. this._debugMesh.dispose();
  60700. this._debugMesh = null;
  60701. }
  60702. };
  60703. return SkeletonViewer;
  60704. }());
  60705. Debug.SkeletonViewer = SkeletonViewer;
  60706. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60707. })(BABYLON || (BABYLON = {}));
  60708. var BABYLON;
  60709. (function (BABYLON) {
  60710. /**
  60711. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60712. * It can help converting any input color in a desired output one. This can then be used to create effects
  60713. * from sepia, black and white to sixties or futuristic rendering...
  60714. *
  60715. * The only supported format is currently 3dl.
  60716. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60717. */
  60718. var ColorGradingTexture = (function (_super) {
  60719. __extends(ColorGradingTexture, _super);
  60720. /**
  60721. * Instantiates a ColorGradingTexture from the following parameters.
  60722. *
  60723. * @param url The location of the color gradind data (currently only supporting 3dl)
  60724. * @param scene The scene the texture will be used in
  60725. */
  60726. function ColorGradingTexture(url, scene) {
  60727. _super.call(this, scene);
  60728. if (!url) {
  60729. return;
  60730. }
  60731. this._textureMatrix = BABYLON.Matrix.Identity();
  60732. this.name = url;
  60733. this.url = url;
  60734. this.hasAlpha = false;
  60735. this.isCube = false;
  60736. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60737. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60738. this.anisotropicFilteringLevel = 1;
  60739. this._texture = this._getFromCache(url, true);
  60740. if (!this._texture) {
  60741. if (!scene.useDelayedTextureLoading) {
  60742. this.loadTexture();
  60743. }
  60744. else {
  60745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60746. }
  60747. }
  60748. }
  60749. /**
  60750. * Returns the texture matrix used in most of the material.
  60751. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60752. */
  60753. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60754. return this._textureMatrix;
  60755. };
  60756. /**
  60757. * Occurs when the file being loaded is a .3dl LUT file.
  60758. */
  60759. ColorGradingTexture.prototype.load3dlTexture = function () {
  60760. var _this = this;
  60761. var mipLevels = 0;
  60762. var floatArrayView = null;
  60763. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60764. this._texture = texture;
  60765. var callback = function (text) {
  60766. var data;
  60767. var tempData;
  60768. var line;
  60769. var lines = text.split('\n');
  60770. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60771. var maxColor = 0;
  60772. for (var i = 0; i < lines.length; i++) {
  60773. line = lines[i];
  60774. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60775. continue;
  60776. if (line.indexOf('#') === 0)
  60777. continue;
  60778. var words = line.split(" ");
  60779. if (size === 0) {
  60780. // Number of space + one
  60781. size = words.length;
  60782. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60783. tempData = new Float32Array(size * size * size * 4);
  60784. continue;
  60785. }
  60786. if (size != 0) {
  60787. var r = Math.max(parseInt(words[0]), 0);
  60788. var g = Math.max(parseInt(words[1]), 0);
  60789. var b = Math.max(parseInt(words[2]), 0);
  60790. maxColor = Math.max(r, maxColor);
  60791. maxColor = Math.max(g, maxColor);
  60792. maxColor = Math.max(b, maxColor);
  60793. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60794. tempData[pixelStorageIndex + 0] = r;
  60795. tempData[pixelStorageIndex + 1] = g;
  60796. tempData[pixelStorageIndex + 2] = b;
  60797. tempData[pixelStorageIndex + 3] = 0;
  60798. pixelIndexSlice++;
  60799. if (pixelIndexSlice % size == 0) {
  60800. pixelIndexH++;
  60801. pixelIndexSlice = 0;
  60802. if (pixelIndexH % size == 0) {
  60803. pixelIndexW++;
  60804. pixelIndexH = 0;
  60805. }
  60806. }
  60807. }
  60808. }
  60809. for (var i = 0; i < tempData.length; i++) {
  60810. var value = tempData[i];
  60811. data[i] = (value / maxColor * 255);
  60812. }
  60813. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60814. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60815. };
  60816. BABYLON.Tools.LoadFile(this.url, callback);
  60817. return this._texture;
  60818. };
  60819. /**
  60820. * Starts the loading process of the texture.
  60821. */
  60822. ColorGradingTexture.prototype.loadTexture = function () {
  60823. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60824. this.load3dlTexture();
  60825. }
  60826. };
  60827. /**
  60828. * Clones the color gradind texture.
  60829. */
  60830. ColorGradingTexture.prototype.clone = function () {
  60831. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60832. // Base texture
  60833. newTexture.level = this.level;
  60834. return newTexture;
  60835. };
  60836. /**
  60837. * Called during delayed load for textures.
  60838. */
  60839. ColorGradingTexture.prototype.delayLoad = function () {
  60840. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60841. return;
  60842. }
  60843. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60844. this._texture = this._getFromCache(this.url, true);
  60845. if (!this._texture) {
  60846. this.loadTexture();
  60847. }
  60848. };
  60849. /**
  60850. * Binds the color grading to the shader.
  60851. * @param colorGrading The texture to bind
  60852. * @param effect The effect to bind to
  60853. */
  60854. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60855. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60856. var x = colorGrading.level; // Texture Level
  60857. var y = colorGrading.getSize().height; // Texture Size example with 8
  60858. var z = y - 1.0; // SizeMinusOne 8 - 1
  60859. var w = 1 / y; // Space of 1 slice 1 / 8
  60860. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60861. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60862. 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
  60863. 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
  60864. 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
  60865. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60866. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60867. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60868. };
  60869. /**
  60870. * Prepare the list of uniforms associated with the ColorGrading effects.
  60871. * @param uniformsList The list of uniforms used in the effect
  60872. * @param samplersList The list of samplers used in the effect
  60873. */
  60874. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60875. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60876. samplersList.push("cameraColorGrading2DSampler");
  60877. };
  60878. /**
  60879. * Parses a color grading texture serialized by Babylon.
  60880. * @param parsedTexture The texture information being parsedTexture
  60881. * @param scene The scene to load the texture in
  60882. * @param rootUrl The root url of the data assets to load
  60883. * @return A color gradind texture
  60884. */
  60885. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60886. var texture = null;
  60887. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60888. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60889. texture.name = parsedTexture.name;
  60890. texture.level = parsedTexture.level;
  60891. }
  60892. return texture;
  60893. };
  60894. /**
  60895. * Serializes the LUT texture to json format.
  60896. */
  60897. ColorGradingTexture.prototype.serialize = function () {
  60898. if (!this.name) {
  60899. return null;
  60900. }
  60901. var serializationObject = {};
  60902. serializationObject.name = this.name;
  60903. serializationObject.level = this.level;
  60904. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60905. return serializationObject;
  60906. };
  60907. /**
  60908. * Empty line regex stored for GC.
  60909. */
  60910. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60911. return ColorGradingTexture;
  60912. }(BABYLON.BaseTexture));
  60913. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60914. })(BABYLON || (BABYLON = {}));
  60915. var BABYLON;
  60916. (function (BABYLON) {
  60917. /**
  60918. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60919. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60920. * 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;
  60921. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60922. */
  60923. var ColorCurves = (function () {
  60924. function ColorCurves() {
  60925. this._dirty = true;
  60926. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60927. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60928. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60929. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60930. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60931. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60932. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60933. this._globalHue = 30;
  60934. this._globalDensity = 0;
  60935. this._globalSaturation = 0;
  60936. this._globalExposure = 0;
  60937. this._highlightsHue = 30;
  60938. this._highlightsDensity = 0;
  60939. this._highlightsSaturation = 0;
  60940. this._highlightsExposure = 0;
  60941. this._midtonesHue = 30;
  60942. this._midtonesDensity = 0;
  60943. this._midtonesSaturation = 0;
  60944. this._midtonesExposure = 0;
  60945. this._shadowsHue = 30;
  60946. this._shadowsDensity = 0;
  60947. this._shadowsSaturation = 0;
  60948. this._shadowsExposure = 0;
  60949. }
  60950. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  60951. /**
  60952. * Gets the global Hue value.
  60953. * 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).
  60954. */
  60955. get: function () {
  60956. return this._globalHue;
  60957. },
  60958. /**
  60959. * Sets the global Hue value.
  60960. * 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).
  60961. */
  60962. set: function (value) {
  60963. this._globalHue = value;
  60964. this._dirty = true;
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  60970. /**
  60971. * Gets the global Density value.
  60972. * 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.
  60973. * Values less than zero provide a filter of opposite hue.
  60974. */
  60975. get: function () {
  60976. return this._globalDensity;
  60977. },
  60978. /**
  60979. * Sets the global Density value.
  60980. * 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.
  60981. * Values less than zero provide a filter of opposite hue.
  60982. */
  60983. set: function (value) {
  60984. this._globalDensity = value;
  60985. this._dirty = true;
  60986. },
  60987. enumerable: true,
  60988. configurable: true
  60989. });
  60990. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  60991. /**
  60992. * Gets the global Saturation value.
  60993. * 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.
  60994. */
  60995. get: function () {
  60996. return this._globalSaturation;
  60997. },
  60998. /**
  60999. * Sets the global Saturation value.
  61000. * 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.
  61001. */
  61002. set: function (value) {
  61003. this._globalSaturation = value;
  61004. this._dirty = true;
  61005. },
  61006. enumerable: true,
  61007. configurable: true
  61008. });
  61009. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  61010. /**
  61011. * Gets the highlights Hue value.
  61012. * 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).
  61013. */
  61014. get: function () {
  61015. return this._highlightsHue;
  61016. },
  61017. /**
  61018. * Sets the highlights Hue value.
  61019. * 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).
  61020. */
  61021. set: function (value) {
  61022. this._highlightsHue = value;
  61023. this._dirty = true;
  61024. },
  61025. enumerable: true,
  61026. configurable: true
  61027. });
  61028. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  61029. /**
  61030. * Gets the highlights Density value.
  61031. * 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.
  61032. * Values less than zero provide a filter of opposite hue.
  61033. */
  61034. get: function () {
  61035. return this._highlightsDensity;
  61036. },
  61037. /**
  61038. * Sets the highlights Density value.
  61039. * 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.
  61040. * Values less than zero provide a filter of opposite hue.
  61041. */
  61042. set: function (value) {
  61043. this._highlightsDensity = value;
  61044. this._dirty = true;
  61045. },
  61046. enumerable: true,
  61047. configurable: true
  61048. });
  61049. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  61050. /**
  61051. * Gets the highlights Saturation value.
  61052. * 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.
  61053. */
  61054. get: function () {
  61055. return this._highlightsSaturation;
  61056. },
  61057. /**
  61058. * Sets the highlights Saturation value.
  61059. * 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.
  61060. */
  61061. set: function (value) {
  61062. this._highlightsSaturation = value;
  61063. this._dirty = true;
  61064. },
  61065. enumerable: true,
  61066. configurable: true
  61067. });
  61068. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  61069. /**
  61070. * Gets the highlights Exposure value.
  61071. * 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.
  61072. */
  61073. get: function () {
  61074. return this._highlightsExposure;
  61075. },
  61076. /**
  61077. * Sets the highlights Exposure value.
  61078. * 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.
  61079. */
  61080. set: function (value) {
  61081. this._highlightsExposure = value;
  61082. this._dirty = true;
  61083. },
  61084. enumerable: true,
  61085. configurable: true
  61086. });
  61087. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  61088. /**
  61089. * Gets the midtones Hue value.
  61090. * 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).
  61091. */
  61092. get: function () {
  61093. return this._midtonesHue;
  61094. },
  61095. /**
  61096. * Sets the midtones Hue value.
  61097. * 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).
  61098. */
  61099. set: function (value) {
  61100. this._midtonesHue = value;
  61101. this._dirty = true;
  61102. },
  61103. enumerable: true,
  61104. configurable: true
  61105. });
  61106. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  61107. /**
  61108. * Gets the midtones Density value.
  61109. * 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.
  61110. * Values less than zero provide a filter of opposite hue.
  61111. */
  61112. get: function () {
  61113. return this._midtonesDensity;
  61114. },
  61115. /**
  61116. * Sets the midtones Density value.
  61117. * 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.
  61118. * Values less than zero provide a filter of opposite hue.
  61119. */
  61120. set: function (value) {
  61121. this._midtonesDensity = value;
  61122. this._dirty = true;
  61123. },
  61124. enumerable: true,
  61125. configurable: true
  61126. });
  61127. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  61128. /**
  61129. * Gets the midtones Saturation value.
  61130. * 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.
  61131. */
  61132. get: function () {
  61133. return this._midtonesSaturation;
  61134. },
  61135. /**
  61136. * Sets the midtones Saturation value.
  61137. * 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.
  61138. */
  61139. set: function (value) {
  61140. this._midtonesSaturation = value;
  61141. this._dirty = true;
  61142. },
  61143. enumerable: true,
  61144. configurable: true
  61145. });
  61146. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  61147. /**
  61148. * Gets the midtones Exposure value.
  61149. * 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.
  61150. */
  61151. get: function () {
  61152. return this._midtonesExposure;
  61153. },
  61154. /**
  61155. * Sets the midtones Exposure value.
  61156. * 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.
  61157. */
  61158. set: function (value) {
  61159. this._midtonesExposure = value;
  61160. this._dirty = true;
  61161. },
  61162. enumerable: true,
  61163. configurable: true
  61164. });
  61165. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  61166. /**
  61167. * Gets the shadows Hue value.
  61168. * 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).
  61169. */
  61170. get: function () {
  61171. return this._shadowsHue;
  61172. },
  61173. /**
  61174. * Sets the shadows Hue value.
  61175. * 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).
  61176. */
  61177. set: function (value) {
  61178. this._shadowsHue = value;
  61179. this._dirty = true;
  61180. },
  61181. enumerable: true,
  61182. configurable: true
  61183. });
  61184. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  61185. /**
  61186. * Gets the shadows Density value.
  61187. * 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.
  61188. * Values less than zero provide a filter of opposite hue.
  61189. */
  61190. get: function () {
  61191. return this._shadowsDensity;
  61192. },
  61193. /**
  61194. * Sets the shadows Density value.
  61195. * 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.
  61196. * Values less than zero provide a filter of opposite hue.
  61197. */
  61198. set: function (value) {
  61199. this._shadowsDensity = value;
  61200. this._dirty = true;
  61201. },
  61202. enumerable: true,
  61203. configurable: true
  61204. });
  61205. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  61206. /**
  61207. * Gets the shadows Saturation value.
  61208. * 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.
  61209. */
  61210. get: function () {
  61211. return this._shadowsSaturation;
  61212. },
  61213. /**
  61214. * Sets the shadows Saturation value.
  61215. * 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.
  61216. */
  61217. set: function (value) {
  61218. this._shadowsSaturation = value;
  61219. this._dirty = true;
  61220. },
  61221. enumerable: true,
  61222. configurable: true
  61223. });
  61224. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  61225. /**
  61226. * Gets the shadows Exposure value.
  61227. * 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.
  61228. */
  61229. get: function () {
  61230. return this._shadowsExposure;
  61231. },
  61232. /**
  61233. * Sets the shadows Exposure value.
  61234. * 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.
  61235. */
  61236. set: function (value) {
  61237. this._shadowsExposure = value;
  61238. this._dirty = true;
  61239. },
  61240. enumerable: true,
  61241. configurable: true
  61242. });
  61243. /**
  61244. * Binds the color curves to the shader.
  61245. * @param colorCurves The color curve to bind
  61246. * @param effect The effect to bind to
  61247. */
  61248. ColorCurves.Bind = function (colorCurves, effect) {
  61249. if (colorCurves._dirty) {
  61250. colorCurves._dirty = false;
  61251. // Fill in global info.
  61252. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  61253. // Compute highlights info.
  61254. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  61255. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  61256. // Compute midtones info.
  61257. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  61258. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  61259. // Compute shadows info.
  61260. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  61261. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  61262. // Compute deltas (neutral is midtones).
  61263. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  61264. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  61265. }
  61266. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  61267. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  61268. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  61269. };
  61270. /**
  61271. * Prepare the list of uniforms associated with the ColorCurves effects.
  61272. * @param uniformsList The list of uniforms used in the effect
  61273. */
  61274. ColorCurves.PrepareUniforms = function (uniformsList) {
  61275. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  61276. };
  61277. /**
  61278. * Returns color grading data based on a hue, density, saturation and exposure value.
  61279. * @param filterHue The hue of the color filter.
  61280. * @param filterDensity The density of the color filter.
  61281. * @param saturation The saturation.
  61282. * @param exposure The exposure.
  61283. * @param result The result data container.
  61284. */
  61285. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  61286. if (hue == null) {
  61287. return;
  61288. }
  61289. hue = ColorCurves.clamp(hue, 0, 360);
  61290. density = ColorCurves.clamp(density, -100, 100);
  61291. saturation = ColorCurves.clamp(saturation, -100, 100);
  61292. exposure = ColorCurves.clamp(exposure, -100, 100);
  61293. // Remap the slider/config filter density with non-linear mapping and also scale by half
  61294. // so that the maximum filter density is only 50% control. This provides fine control
  61295. // for small values and reasonable range.
  61296. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  61297. density *= 0.5;
  61298. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  61299. if (density < 0) {
  61300. density *= -1;
  61301. hue = (hue + 180) % 360;
  61302. }
  61303. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  61304. result.scaleToRef(2, result);
  61305. result.a = 1 + 0.01 * saturation;
  61306. };
  61307. /**
  61308. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  61309. * @param value The input slider value in range [-100,100].
  61310. * @returns Adjusted value.
  61311. */
  61312. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  61313. value /= 100;
  61314. var x = Math.abs(value);
  61315. x = Math.pow(x, 2);
  61316. if (value < 0) {
  61317. x *= -1;
  61318. }
  61319. x *= 100;
  61320. return x;
  61321. };
  61322. /**
  61323. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  61324. * @param hue The hue (H) input.
  61325. * @param saturation The saturation (S) input.
  61326. * @param brightness The brightness (B) input.
  61327. * @result An RGBA color represented as Vector4.
  61328. */
  61329. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  61330. var h = ColorCurves.clamp(hue, 0, 360);
  61331. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  61332. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  61333. if (s === 0) {
  61334. result.r = v;
  61335. result.g = v;
  61336. result.b = v;
  61337. }
  61338. else {
  61339. // sector 0 to 5
  61340. h /= 60;
  61341. var i = Math.floor(h);
  61342. // fractional part of h
  61343. var f = h - i;
  61344. var p = v * (1 - s);
  61345. var q = v * (1 - s * f);
  61346. var t = v * (1 - s * (1 - f));
  61347. switch (i) {
  61348. case 0:
  61349. result.r = v;
  61350. result.g = t;
  61351. result.b = p;
  61352. break;
  61353. case 1:
  61354. result.r = q;
  61355. result.g = v;
  61356. result.b = p;
  61357. break;
  61358. case 2:
  61359. result.r = p;
  61360. result.g = v;
  61361. result.b = t;
  61362. break;
  61363. case 3:
  61364. result.r = p;
  61365. result.g = q;
  61366. result.b = v;
  61367. break;
  61368. case 4:
  61369. result.r = t;
  61370. result.g = p;
  61371. result.b = v;
  61372. break;
  61373. default:
  61374. result.r = v;
  61375. result.g = p;
  61376. result.b = q;
  61377. break;
  61378. }
  61379. }
  61380. result.a = 1;
  61381. };
  61382. /**
  61383. * Returns a value clamped between min and max
  61384. * @param value The value to clamp
  61385. * @param min The minimum of value
  61386. * @param max The maximum of value
  61387. * @returns The clamped value.
  61388. */
  61389. ColorCurves.clamp = function (value, min, max) {
  61390. return Math.min(Math.max(value, min), max);
  61391. };
  61392. /**
  61393. * Clones the current color curve instance.
  61394. * @return The cloned curves
  61395. */
  61396. ColorCurves.prototype.clone = function () {
  61397. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  61398. };
  61399. /**
  61400. * Serializes the current color curve instance to a json representation.
  61401. * @return a JSON representation
  61402. */
  61403. ColorCurves.prototype.serialize = function () {
  61404. return BABYLON.SerializationHelper.Serialize(this);
  61405. };
  61406. /**
  61407. * Parses the color curve from a json representation.
  61408. * @param source the JSON source to parse
  61409. * @return The parsed curves
  61410. */
  61411. ColorCurves.Parse = function (source) {
  61412. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  61413. };
  61414. __decorate([
  61415. BABYLON.serialize()
  61416. ], ColorCurves.prototype, "_globalHue", void 0);
  61417. __decorate([
  61418. BABYLON.serialize()
  61419. ], ColorCurves.prototype, "_globalDensity", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], ColorCurves.prototype, "_globalSaturation", void 0);
  61423. __decorate([
  61424. BABYLON.serialize()
  61425. ], ColorCurves.prototype, "_globalExposure", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], ColorCurves.prototype, "_highlightsHue", void 0);
  61429. __decorate([
  61430. BABYLON.serialize()
  61431. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  61435. __decorate([
  61436. BABYLON.serialize()
  61437. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  61438. __decorate([
  61439. BABYLON.serialize()
  61440. ], ColorCurves.prototype, "_midtonesHue", void 0);
  61441. __decorate([
  61442. BABYLON.serialize()
  61443. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  61447. __decorate([
  61448. BABYLON.serialize()
  61449. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  61450. return ColorCurves;
  61451. }());
  61452. BABYLON.ColorCurves = ColorCurves;
  61453. })(BABYLON || (BABYLON = {}));
  61454. var BABYLON;
  61455. (function (BABYLON) {
  61456. var PBRMaterialDefines = (function (_super) {
  61457. __extends(PBRMaterialDefines, _super);
  61458. function PBRMaterialDefines() {
  61459. _super.call(this);
  61460. this.ALBEDO = false;
  61461. this.AMBIENT = false;
  61462. this.OPACITY = false;
  61463. this.OPACITYRGB = false;
  61464. this.REFLECTION = false;
  61465. this.EMISSIVE = false;
  61466. this.REFLECTIVITY = false;
  61467. this.BUMP = false;
  61468. this.PARALLAX = false;
  61469. this.PARALLAXOCCLUSION = false;
  61470. this.SPECULAROVERALPHA = false;
  61471. this.CLIPPLANE = false;
  61472. this.ALPHATEST = false;
  61473. this.ALPHAFROMALBEDO = false;
  61474. this.POINTSIZE = false;
  61475. this.FOG = false;
  61476. this.SPECULARTERM = false;
  61477. this.OPACITYFRESNEL = false;
  61478. this.EMISSIVEFRESNEL = false;
  61479. this.FRESNEL = false;
  61480. this.NORMAL = false;
  61481. this.UV1 = false;
  61482. this.UV2 = false;
  61483. this.VERTEXCOLOR = false;
  61484. this.VERTEXALPHA = false;
  61485. this.NUM_BONE_INFLUENCERS = 0;
  61486. this.BonesPerMesh = 0;
  61487. this.INSTANCES = false;
  61488. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  61489. this.MICROSURFACEAUTOMATIC = false;
  61490. this.EMISSIVEASILLUMINATION = false;
  61491. this.LINKEMISSIVEWITHALBEDO = false;
  61492. this.LIGHTMAP = false;
  61493. this.USELIGHTMAPASSHADOWMAP = false;
  61494. this.REFLECTIONMAP_3D = false;
  61495. this.REFLECTIONMAP_SPHERICAL = false;
  61496. this.REFLECTIONMAP_PLANAR = false;
  61497. this.REFLECTIONMAP_CUBIC = false;
  61498. this.REFLECTIONMAP_PROJECTION = false;
  61499. this.REFLECTIONMAP_SKYBOX = false;
  61500. this.REFLECTIONMAP_EXPLICIT = false;
  61501. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  61502. this.INVERTCUBICMAP = false;
  61503. this.LOGARITHMICDEPTH = false;
  61504. this.CAMERATONEMAP = false;
  61505. this.CAMERACONTRAST = false;
  61506. this.CAMERACOLORGRADING = false;
  61507. this.CAMERACOLORCURVES = false;
  61508. this.OVERLOADEDVALUES = false;
  61509. this.OVERLOADEDSHADOWVALUES = false;
  61510. this.USESPHERICALFROMREFLECTIONMAP = false;
  61511. this.REFRACTION = false;
  61512. this.REFRACTIONMAP_3D = false;
  61513. this.LINKREFRACTIONTOTRANSPARENCY = false;
  61514. this.REFRACTIONMAPINLINEARSPACE = false;
  61515. this.LODBASEDMICROSFURACE = false;
  61516. this.USEPHYSICALLIGHTFALLOFF = false;
  61517. this.RADIANCEOVERALPHA = false;
  61518. this.USEPMREMREFLECTION = false;
  61519. this.USEPMREMREFRACTION = false;
  61520. this.OPENGLNORMALMAP = false;
  61521. this.INVERTNORMALMAPX = false;
  61522. this.INVERTNORMALMAPY = false;
  61523. this.SHADOWFULLFLOAT = false;
  61524. this.rebuild();
  61525. }
  61526. return PBRMaterialDefines;
  61527. }(BABYLON.MaterialDefines));
  61528. /**
  61529. * The Physically based material of BJS.
  61530. *
  61531. * This offers the main features of a standard PBR material.
  61532. * For more information, please refer to the documentation :
  61533. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  61534. */
  61535. var PBRMaterial = (function (_super) {
  61536. __extends(PBRMaterial, _super);
  61537. /**
  61538. * Instantiates a new PBRMaterial instance.
  61539. *
  61540. * @param name The material name
  61541. * @param scene The scene the material will be use in.
  61542. */
  61543. function PBRMaterial(name, scene) {
  61544. var _this = this;
  61545. _super.call(this, name, scene);
  61546. /**
  61547. * Intensity of the direct lights e.g. the four lights available in your scene.
  61548. * This impacts both the direct diffuse and specular highlights.
  61549. */
  61550. this.directIntensity = 1.0;
  61551. /**
  61552. * Intensity of the emissive part of the material.
  61553. * This helps controlling the emissive effect without modifying the emissive color.
  61554. */
  61555. this.emissiveIntensity = 1.0;
  61556. /**
  61557. * Intensity of the environment e.g. how much the environment will light the object
  61558. * either through harmonics for rough material or through the refelction for shiny ones.
  61559. */
  61560. this.environmentIntensity = 1.0;
  61561. /**
  61562. * This is a special control allowing the reduction of the specular highlights coming from the
  61563. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  61564. */
  61565. this.specularIntensity = 1.0;
  61566. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  61567. /**
  61568. * Debug Control allowing disabling the bump map on this material.
  61569. */
  61570. this.disableBumpMap = false;
  61571. /**
  61572. * Debug Control helping enforcing or dropping the darkness of shadows.
  61573. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  61574. */
  61575. this.overloadedShadowIntensity = 1.0;
  61576. /**
  61577. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  61578. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  61579. */
  61580. this.overloadedShadeIntensity = 1.0;
  61581. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  61582. /**
  61583. * The camera exposure used on this material.
  61584. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  61585. * This corresponds to a photographic exposure.
  61586. */
  61587. this.cameraExposure = 1.0;
  61588. /**
  61589. * The camera contrast used on this material.
  61590. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  61591. */
  61592. this.cameraContrast = 1.0;
  61593. /**
  61594. * Color Grading 2D Lookup Texture.
  61595. * This allows special effects like sepia, black and white to sixties rendering style.
  61596. */
  61597. this.cameraColorGradingTexture = null;
  61598. /**
  61599. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  61600. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  61601. * 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;
  61602. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  61603. */
  61604. this.cameraColorCurves = null;
  61605. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  61606. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  61607. /**
  61608. * Debug Control allowing to overload the ambient color.
  61609. * This as to be use with the overloadedAmbientIntensity parameter.
  61610. */
  61611. this.overloadedAmbient = BABYLON.Color3.White();
  61612. /**
  61613. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  61614. */
  61615. this.overloadedAmbientIntensity = 0.0;
  61616. /**
  61617. * Debug Control allowing to overload the albedo color.
  61618. * This as to be use with the overloadedAlbedoIntensity parameter.
  61619. */
  61620. this.overloadedAlbedo = BABYLON.Color3.White();
  61621. /**
  61622. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  61623. */
  61624. this.overloadedAlbedoIntensity = 0.0;
  61625. /**
  61626. * Debug Control allowing to overload the reflectivity color.
  61627. * This as to be use with the overloadedReflectivityIntensity parameter.
  61628. */
  61629. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  61630. /**
  61631. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  61632. */
  61633. this.overloadedReflectivityIntensity = 0.0;
  61634. /**
  61635. * Debug Control allowing to overload the emissive color.
  61636. * This as to be use with the overloadedEmissiveIntensity parameter.
  61637. */
  61638. this.overloadedEmissive = BABYLON.Color3.White();
  61639. /**
  61640. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  61641. */
  61642. this.overloadedEmissiveIntensity = 0.0;
  61643. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  61644. /**
  61645. * Debug Control allowing to overload the reflection color.
  61646. * This as to be use with the overloadedReflectionIntensity parameter.
  61647. */
  61648. this.overloadedReflection = BABYLON.Color3.White();
  61649. /**
  61650. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  61651. */
  61652. this.overloadedReflectionIntensity = 0.0;
  61653. /**
  61654. * Debug Control allowing to overload the microsurface.
  61655. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  61656. */
  61657. this.overloadedMicroSurface = 0.0;
  61658. /**
  61659. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  61660. */
  61661. this.overloadedMicroSurfaceIntensity = 0.0;
  61662. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  61663. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  61664. /**
  61665. * AKA Diffuse Color in other nomenclature.
  61666. */
  61667. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  61668. /**
  61669. * AKA Specular Color in other nomenclature.
  61670. */
  61671. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  61672. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  61673. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  61674. /**
  61675. * AKA Glossiness in other nomenclature.
  61676. */
  61677. this.microSurface = 0.9;
  61678. /**
  61679. * source material index of refraction (IOR)' / 'destination material IOR.
  61680. */
  61681. this.indexOfRefraction = 0.66;
  61682. /**
  61683. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  61684. */
  61685. this.invertRefractionY = false;
  61686. /**
  61687. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  61688. * Materials half opaque for instance using refraction could benefit from this control.
  61689. */
  61690. this.linkRefractionWithTransparency = false;
  61691. /**
  61692. * The emissive and albedo are linked to never be more than one (Energy conservation).
  61693. */
  61694. this.linkEmissiveWithAlbedo = false;
  61695. this.useLightmapAsShadowmap = false;
  61696. /**
  61697. * In this mode, the emissive informtaion will always be added to the lighting once.
  61698. * A light for instance can be thought as emissive.
  61699. */
  61700. this.useEmissiveAsIllumination = false;
  61701. /**
  61702. * Secifies that the alpha is coming form the albedo channel alpha channel.
  61703. */
  61704. this.useAlphaFromAlbedoTexture = false;
  61705. /**
  61706. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  61707. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  61708. */
  61709. this.useSpecularOverAlpha = true;
  61710. /**
  61711. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  61712. */
  61713. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  61714. /**
  61715. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  61716. * The material will try to infer what glossiness each pixel should be.
  61717. */
  61718. this.useAutoMicroSurfaceFromReflectivityMap = false;
  61719. /**
  61720. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  61721. * the creation of the material.
  61722. */
  61723. this.useScalarInLinearSpace = false;
  61724. /**
  61725. * BJS is using an harcoded light falloff based on a manually sets up range.
  61726. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  61727. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  61728. */
  61729. this.usePhysicalLightFalloff = true;
  61730. /**
  61731. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  61732. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  61733. */
  61734. this.useRadianceOverAlpha = true;
  61735. /**
  61736. * Allows using the bump map in parallax mode.
  61737. */
  61738. this.useParallax = false;
  61739. /**
  61740. * Allows using the bump map in parallax occlusion mode.
  61741. */
  61742. this.useParallaxOcclusion = false;
  61743. /**
  61744. * Controls the scale bias of the parallax mode.
  61745. */
  61746. this.parallaxScaleBias = 0.05;
  61747. /**
  61748. * If sets to true, disables all the lights affecting the material.
  61749. */
  61750. this.disableLighting = false;
  61751. /**
  61752. * Number of Simultaneous lights allowed on the material.
  61753. */
  61754. this.maxSimultaneousLights = 4;
  61755. /**
  61756. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  61757. */
  61758. this.invertNormalMapX = false;
  61759. /**
  61760. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  61761. */
  61762. this.invertNormalMapY = false;
  61763. this._renderTargets = new BABYLON.SmartArray(16);
  61764. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  61765. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  61766. this._tempColor = new BABYLON.Color3();
  61767. this._defines = new PBRMaterialDefines();
  61768. this._cachedDefines = new PBRMaterialDefines();
  61769. this._myScene = null;
  61770. this._myShadowGenerator = null;
  61771. this._cachedDefines.BonesPerMesh = -1;
  61772. this.getRenderTargetTextures = function () {
  61773. _this._renderTargets.reset();
  61774. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  61775. _this._renderTargets.push(_this.reflectionTexture);
  61776. }
  61777. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  61778. _this._renderTargets.push(_this.refractionTexture);
  61779. }
  61780. return _this._renderTargets;
  61781. };
  61782. }
  61783. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  61784. get: function () {
  61785. return this._useLogarithmicDepth;
  61786. },
  61787. set: function (value) {
  61788. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  61789. },
  61790. enumerable: true,
  61791. configurable: true
  61792. });
  61793. PBRMaterial.prototype.needAlphaBlending = function () {
  61794. if (this.linkRefractionWithTransparency) {
  61795. return false;
  61796. }
  61797. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  61798. };
  61799. PBRMaterial.prototype.needAlphaTesting = function () {
  61800. if (this.linkRefractionWithTransparency) {
  61801. return false;
  61802. }
  61803. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  61804. };
  61805. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  61806. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  61807. };
  61808. PBRMaterial.prototype.getAlphaTestTexture = function () {
  61809. return this.albedoTexture;
  61810. };
  61811. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61812. if (!mesh) {
  61813. return true;
  61814. }
  61815. if (this._defines.INSTANCES !== useInstances) {
  61816. return false;
  61817. }
  61818. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  61819. return true;
  61820. }
  61821. return false;
  61822. };
  61823. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  61824. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  61825. };
  61826. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  61827. if (!useScalarInLinear) {
  61828. color.toLinearSpaceToRef(ref);
  61829. }
  61830. else {
  61831. ref.r = color.r;
  61832. ref.g = color.g;
  61833. ref.b = color.b;
  61834. }
  61835. };
  61836. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  61837. var lightIndex = 0;
  61838. var depthValuesAlreadySet = false;
  61839. for (var index = 0; index < scene.lights.length; index++) {
  61840. var light = scene.lights[index];
  61841. if (!light.isEnabled()) {
  61842. continue;
  61843. }
  61844. if (!light.canAffectMesh(mesh)) {
  61845. continue;
  61846. }
  61847. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  61848. // GAMMA CORRECTION.
  61849. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  61850. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  61851. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  61852. if (defines["SPECULARTERM"]) {
  61853. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  61854. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  61855. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  61856. }
  61857. // Shadows
  61858. if (scene.shadowsEnabled) {
  61859. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  61860. }
  61861. lightIndex++;
  61862. if (lightIndex === maxSimultaneousLights)
  61863. break;
  61864. }
  61865. };
  61866. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  61867. if (this.checkReadyOnlyOnce) {
  61868. if (this._wasPreviouslyReady) {
  61869. return true;
  61870. }
  61871. }
  61872. var scene = this.getScene();
  61873. if (!this.checkReadyOnEveryCall) {
  61874. if (this._renderId === scene.getRenderId()) {
  61875. if (this._checkCache(scene, mesh, useInstances)) {
  61876. return true;
  61877. }
  61878. }
  61879. }
  61880. var engine = scene.getEngine();
  61881. var needNormals = false;
  61882. var needUVs = false;
  61883. this._defines.reset();
  61884. if (scene.texturesEnabled) {
  61885. // Textures
  61886. if (scene.texturesEnabled) {
  61887. if (scene.getEngine().getCaps().textureLOD) {
  61888. this._defines.LODBASEDMICROSFURACE = true;
  61889. }
  61890. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61891. if (!this.albedoTexture.isReady()) {
  61892. return false;
  61893. }
  61894. else {
  61895. needUVs = true;
  61896. this._defines.ALBEDO = true;
  61897. }
  61898. }
  61899. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61900. if (!this.ambientTexture.isReady()) {
  61901. return false;
  61902. }
  61903. else {
  61904. needUVs = true;
  61905. this._defines.AMBIENT = true;
  61906. }
  61907. }
  61908. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61909. if (!this.opacityTexture.isReady()) {
  61910. return false;
  61911. }
  61912. else {
  61913. needUVs = true;
  61914. this._defines.OPACITY = true;
  61915. if (this.opacityTexture.getAlphaFromRGB) {
  61916. this._defines.OPACITYRGB = true;
  61917. }
  61918. }
  61919. }
  61920. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61921. if (!this.reflectionTexture.isReady()) {
  61922. return false;
  61923. }
  61924. else {
  61925. needNormals = true;
  61926. this._defines.REFLECTION = true;
  61927. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61928. this._defines.INVERTCUBICMAP = true;
  61929. }
  61930. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61931. switch (this.reflectionTexture.coordinatesMode) {
  61932. case BABYLON.Texture.CUBIC_MODE:
  61933. case BABYLON.Texture.INVCUBIC_MODE:
  61934. this._defines.REFLECTIONMAP_CUBIC = true;
  61935. break;
  61936. case BABYLON.Texture.EXPLICIT_MODE:
  61937. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61938. break;
  61939. case BABYLON.Texture.PLANAR_MODE:
  61940. this._defines.REFLECTIONMAP_PLANAR = true;
  61941. break;
  61942. case BABYLON.Texture.PROJECTION_MODE:
  61943. this._defines.REFLECTIONMAP_PROJECTION = true;
  61944. break;
  61945. case BABYLON.Texture.SKYBOX_MODE:
  61946. this._defines.REFLECTIONMAP_SKYBOX = true;
  61947. break;
  61948. case BABYLON.Texture.SPHERICAL_MODE:
  61949. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61950. break;
  61951. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61952. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61953. break;
  61954. }
  61955. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61956. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61957. needNormals = true;
  61958. if (this.reflectionTexture.isPMREM) {
  61959. this._defines.USEPMREMREFLECTION = true;
  61960. }
  61961. }
  61962. }
  61963. }
  61964. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61965. if (!this.lightmapTexture.isReady()) {
  61966. return false;
  61967. }
  61968. else {
  61969. needUVs = true;
  61970. this._defines.LIGHTMAP = true;
  61971. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61972. }
  61973. }
  61974. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61975. if (!this.emissiveTexture.isReady()) {
  61976. return false;
  61977. }
  61978. else {
  61979. needUVs = true;
  61980. this._defines.EMISSIVE = true;
  61981. }
  61982. }
  61983. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61984. if (!this.reflectivityTexture.isReady()) {
  61985. return false;
  61986. }
  61987. else {
  61988. needUVs = true;
  61989. this._defines.REFLECTIVITY = true;
  61990. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61991. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61992. }
  61993. }
  61994. }
  61995. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61996. if (!this.bumpTexture.isReady()) {
  61997. return false;
  61998. }
  61999. else {
  62000. needUVs = true;
  62001. this._defines.BUMP = true;
  62002. if (this.useParallax) {
  62003. this._defines.PARALLAX = true;
  62004. if (this.useParallaxOcclusion) {
  62005. this._defines.PARALLAXOCCLUSION = true;
  62006. }
  62007. }
  62008. if (this.invertNormalMapX) {
  62009. this._defines.INVERTNORMALMAPX = true;
  62010. }
  62011. if (this.invertNormalMapY) {
  62012. this._defines.INVERTNORMALMAPY = true;
  62013. }
  62014. }
  62015. }
  62016. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  62017. if (!this.refractionTexture.isReady()) {
  62018. return false;
  62019. }
  62020. else {
  62021. needUVs = true;
  62022. this._defines.REFRACTION = true;
  62023. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  62024. if (this.linkRefractionWithTransparency) {
  62025. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  62026. }
  62027. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  62028. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  62029. if (this.refractionTexture.isPMREM) {
  62030. this._defines.USEPMREMREFRACTION = true;
  62031. }
  62032. }
  62033. }
  62034. }
  62035. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  62036. if (!this.cameraColorGradingTexture.isReady()) {
  62037. return false;
  62038. }
  62039. else {
  62040. this._defines.CAMERACOLORGRADING = true;
  62041. }
  62042. }
  62043. }
  62044. // Effect
  62045. if (scene.clipPlane) {
  62046. this._defines.CLIPPLANE = true;
  62047. }
  62048. if (engine.getAlphaTesting()) {
  62049. this._defines.ALPHATEST = true;
  62050. }
  62051. if (this._shouldUseAlphaFromAlbedoTexture()) {
  62052. this._defines.ALPHAFROMALBEDO = true;
  62053. }
  62054. if (this.useEmissiveAsIllumination) {
  62055. this._defines.EMISSIVEASILLUMINATION = true;
  62056. }
  62057. if (this.linkEmissiveWithAlbedo) {
  62058. this._defines.LINKEMISSIVEWITHALBEDO = true;
  62059. }
  62060. if (this.useLogarithmicDepth) {
  62061. this._defines.LOGARITHMICDEPTH = true;
  62062. }
  62063. if (this.cameraContrast != 1) {
  62064. this._defines.CAMERACONTRAST = true;
  62065. }
  62066. if (this.cameraExposure != 1) {
  62067. this._defines.CAMERATONEMAP = true;
  62068. }
  62069. if (this.cameraColorCurves) {
  62070. this._defines.CAMERACOLORCURVES = true;
  62071. }
  62072. if (this.overloadedShadeIntensity != 1 ||
  62073. this.overloadedShadowIntensity != 1) {
  62074. this._defines.OVERLOADEDSHADOWVALUES = true;
  62075. }
  62076. if (this.overloadedMicroSurfaceIntensity > 0 ||
  62077. this.overloadedEmissiveIntensity > 0 ||
  62078. this.overloadedReflectivityIntensity > 0 ||
  62079. this.overloadedAlbedoIntensity > 0 ||
  62080. this.overloadedAmbientIntensity > 0 ||
  62081. this.overloadedReflectionIntensity > 0) {
  62082. this._defines.OVERLOADEDVALUES = true;
  62083. }
  62084. // Point size
  62085. if (this.pointsCloud || scene.forcePointsCloud) {
  62086. this._defines.POINTSIZE = true;
  62087. }
  62088. // Fog
  62089. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  62090. this._defines.FOG = true;
  62091. }
  62092. if (scene.lightsEnabled && !this.disableLighting) {
  62093. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  62094. }
  62095. if (BABYLON.StandardMaterial.FresnelEnabled) {
  62096. // Fresnel
  62097. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  62098. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  62099. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  62100. this._defines.OPACITYFRESNEL = true;
  62101. }
  62102. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  62103. this._defines.EMISSIVEFRESNEL = true;
  62104. }
  62105. needNormals = true;
  62106. this._defines.FRESNEL = true;
  62107. }
  62108. }
  62109. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  62110. this._defines.SPECULAROVERALPHA = true;
  62111. }
  62112. if (this.usePhysicalLightFalloff) {
  62113. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  62114. }
  62115. if (this.useRadianceOverAlpha) {
  62116. this._defines.RADIANCEOVERALPHA = true;
  62117. }
  62118. // Attribs
  62119. if (mesh) {
  62120. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62121. this._defines.NORMAL = true;
  62122. }
  62123. if (needUVs) {
  62124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62125. this._defines.UV1 = true;
  62126. }
  62127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62128. this._defines.UV2 = true;
  62129. }
  62130. }
  62131. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62132. this._defines.VERTEXCOLOR = true;
  62133. if (mesh.hasVertexAlpha) {
  62134. this._defines.VERTEXALPHA = true;
  62135. }
  62136. }
  62137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62138. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  62139. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  62140. }
  62141. // Instances
  62142. if (useInstances) {
  62143. this._defines.INSTANCES = true;
  62144. }
  62145. }
  62146. // Get correct effect
  62147. if (!this._defines.isEqual(this._cachedDefines)) {
  62148. this._defines.cloneTo(this._cachedDefines);
  62149. scene.resetCachedMaterial();
  62150. // Fallbacks
  62151. var fallbacks = new BABYLON.EffectFallbacks();
  62152. if (this._defines.REFLECTION) {
  62153. fallbacks.addFallback(0, "REFLECTION");
  62154. }
  62155. if (this._defines.REFRACTION) {
  62156. fallbacks.addFallback(0, "REFRACTION");
  62157. }
  62158. if (this._defines.REFLECTIVITY) {
  62159. fallbacks.addFallback(0, "REFLECTIVITY");
  62160. }
  62161. if (this._defines.BUMP) {
  62162. fallbacks.addFallback(0, "BUMP");
  62163. }
  62164. if (this._defines.PARALLAX) {
  62165. fallbacks.addFallback(1, "PARALLAX");
  62166. }
  62167. if (this._defines.PARALLAXOCCLUSION) {
  62168. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  62169. }
  62170. if (this._defines.SPECULAROVERALPHA) {
  62171. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  62172. }
  62173. if (this._defines.FOG) {
  62174. fallbacks.addFallback(1, "FOG");
  62175. }
  62176. if (this._defines.POINTSIZE) {
  62177. fallbacks.addFallback(0, "POINTSIZE");
  62178. }
  62179. if (this._defines.LOGARITHMICDEPTH) {
  62180. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  62181. }
  62182. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  62183. if (this._defines.SPECULARTERM) {
  62184. fallbacks.addFallback(0, "SPECULARTERM");
  62185. }
  62186. if (this._defines.OPACITYFRESNEL) {
  62187. fallbacks.addFallback(1, "OPACITYFRESNEL");
  62188. }
  62189. if (this._defines.EMISSIVEFRESNEL) {
  62190. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  62191. }
  62192. if (this._defines.FRESNEL) {
  62193. fallbacks.addFallback(3, "FRESNEL");
  62194. }
  62195. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  62196. fallbacks.addCPUSkinningFallback(0, mesh);
  62197. }
  62198. //Attributes
  62199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62200. if (this._defines.NORMAL) {
  62201. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62202. }
  62203. if (this._defines.UV1) {
  62204. attribs.push(BABYLON.VertexBuffer.UVKind);
  62205. }
  62206. if (this._defines.UV2) {
  62207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62208. }
  62209. if (this._defines.VERTEXCOLOR) {
  62210. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62211. }
  62212. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  62213. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  62214. // Legacy browser patch
  62215. var shaderName = "pbr";
  62216. if (!scene.getEngine().getCaps().standardDerivatives) {
  62217. shaderName = "legacypbr";
  62218. }
  62219. var join = this._defines.toString();
  62220. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  62221. "vFogInfos", "vFogColor", "pointSize",
  62222. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  62223. "mBones",
  62224. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  62225. "depthValues",
  62226. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  62227. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  62228. "logarithmicDepthConstant",
  62229. "vSphericalX", "vSphericalY", "vSphericalZ",
  62230. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  62231. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  62232. "vMicrosurfaceTextureLods",
  62233. "vCameraInfos"
  62234. ];
  62235. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  62236. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  62237. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  62238. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  62239. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  62240. }
  62241. if (!this._effect.isReady()) {
  62242. return false;
  62243. }
  62244. this._renderId = scene.getRenderId();
  62245. this._wasPreviouslyReady = true;
  62246. if (mesh) {
  62247. if (!mesh._materialDefines) {
  62248. mesh._materialDefines = new PBRMaterialDefines();
  62249. }
  62250. this._defines.cloneTo(mesh._materialDefines);
  62251. }
  62252. return true;
  62253. };
  62254. PBRMaterial.prototype.unbind = function () {
  62255. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  62256. this._effect.setTexture("reflection2DSampler", null);
  62257. }
  62258. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  62259. this._effect.setTexture("refraction2DSampler", null);
  62260. }
  62261. _super.prototype.unbind.call(this);
  62262. };
  62263. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62264. this._effect.setMatrix("world", world);
  62265. };
  62266. PBRMaterial.prototype.bind = function (world, mesh) {
  62267. this._myScene = this.getScene();
  62268. // Matrices
  62269. this.bindOnlyWorldMatrix(world);
  62270. // Bones
  62271. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62272. if (this._myScene.getCachedMaterial() !== this) {
  62273. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  62274. if (BABYLON.StandardMaterial.FresnelEnabled) {
  62275. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  62276. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  62277. }
  62278. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  62279. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  62280. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  62281. }
  62282. }
  62283. // Textures
  62284. if (this._myScene.texturesEnabled) {
  62285. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  62286. this._effect.setTexture("albedoSampler", this.albedoTexture);
  62287. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  62288. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  62289. }
  62290. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  62291. this._effect.setTexture("ambientSampler", this.ambientTexture);
  62292. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  62293. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  62294. }
  62295. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  62296. this._effect.setTexture("opacitySampler", this.opacityTexture);
  62297. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  62298. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  62299. }
  62300. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  62301. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  62302. if (this.reflectionTexture.isCube) {
  62303. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  62304. }
  62305. else {
  62306. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  62307. }
  62308. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  62309. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  62310. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  62311. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  62312. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  62313. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  62314. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  62315. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  62316. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  62317. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  62318. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  62319. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  62320. }
  62321. }
  62322. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  62323. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  62324. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  62325. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  62326. }
  62327. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  62328. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  62329. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  62330. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  62331. }
  62332. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  62333. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  62334. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  62335. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  62336. }
  62337. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  62338. this._effect.setTexture("bumpSampler", this.bumpTexture);
  62339. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  62340. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  62341. }
  62342. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  62343. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  62344. var depth = 1.0;
  62345. if (this.refractionTexture.isCube) {
  62346. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  62347. }
  62348. else {
  62349. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  62350. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  62351. if (this.refractionTexture.depth) {
  62352. depth = this.refractionTexture.depth;
  62353. }
  62354. }
  62355. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  62356. }
  62357. if ((this.reflectionTexture || this.refractionTexture)) {
  62358. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  62359. }
  62360. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  62361. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  62362. }
  62363. }
  62364. // Clip plane
  62365. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  62366. // Point size
  62367. if (this.pointsCloud) {
  62368. this._effect.setFloat("pointSize", this.pointSize);
  62369. }
  62370. // Colors
  62371. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  62372. // GAMMA CORRECTION.
  62373. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  62374. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  62375. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  62376. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  62377. // GAMMA CORRECTION.
  62378. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  62379. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  62380. // GAMMA CORRECTION.
  62381. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  62382. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  62383. }
  62384. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  62385. // GAMMA CORRECTION.
  62386. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  62387. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  62388. // Lights
  62389. if (this._myScene.lightsEnabled && !this.disableLighting) {
  62390. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  62391. }
  62392. // View
  62393. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  62394. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  62395. }
  62396. // Fog
  62397. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  62398. this._lightingInfos.x = this.directIntensity;
  62399. this._lightingInfos.y = this.emissiveIntensity;
  62400. this._lightingInfos.z = this.environmentIntensity;
  62401. this._lightingInfos.w = this.specularIntensity;
  62402. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  62403. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  62404. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  62405. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  62406. this._cameraInfos.x = this.cameraExposure;
  62407. this._cameraInfos.y = this.cameraContrast;
  62408. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  62409. if (this.cameraColorCurves) {
  62410. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  62411. }
  62412. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  62413. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  62414. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  62415. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  62416. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  62417. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  62418. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  62419. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  62420. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  62421. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  62422. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  62423. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  62424. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  62425. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  62426. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  62427. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  62428. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  62429. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  62430. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  62431. // Log. depth
  62432. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  62433. }
  62434. _super.prototype.bind.call(this, world, mesh);
  62435. this._myScene = null;
  62436. };
  62437. PBRMaterial.prototype.getAnimatables = function () {
  62438. var results = [];
  62439. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  62440. results.push(this.albedoTexture);
  62441. }
  62442. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  62443. results.push(this.ambientTexture);
  62444. }
  62445. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  62446. results.push(this.opacityTexture);
  62447. }
  62448. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  62449. results.push(this.reflectionTexture);
  62450. }
  62451. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  62452. results.push(this.emissiveTexture);
  62453. }
  62454. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  62455. results.push(this.reflectivityTexture);
  62456. }
  62457. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  62458. results.push(this.bumpTexture);
  62459. }
  62460. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  62461. results.push(this.lightmapTexture);
  62462. }
  62463. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  62464. results.push(this.refractionTexture);
  62465. }
  62466. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  62467. results.push(this.cameraColorGradingTexture);
  62468. }
  62469. return results;
  62470. };
  62471. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62472. if (forceDisposeTextures) {
  62473. if (this.albedoTexture) {
  62474. this.albedoTexture.dispose();
  62475. }
  62476. if (this.ambientTexture) {
  62477. this.ambientTexture.dispose();
  62478. }
  62479. if (this.opacityTexture) {
  62480. this.opacityTexture.dispose();
  62481. }
  62482. if (this.reflectionTexture) {
  62483. this.reflectionTexture.dispose();
  62484. }
  62485. if (this.emissiveTexture) {
  62486. this.emissiveTexture.dispose();
  62487. }
  62488. if (this.reflectivityTexture) {
  62489. this.reflectivityTexture.dispose();
  62490. }
  62491. if (this.bumpTexture) {
  62492. this.bumpTexture.dispose();
  62493. }
  62494. if (this.lightmapTexture) {
  62495. this.lightmapTexture.dispose();
  62496. }
  62497. if (this.refractionTexture) {
  62498. this.refractionTexture.dispose();
  62499. }
  62500. if (this.cameraColorGradingTexture) {
  62501. this.cameraColorGradingTexture.dispose();
  62502. }
  62503. }
  62504. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62505. };
  62506. PBRMaterial.prototype.clone = function (name) {
  62507. var _this = this;
  62508. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  62509. };
  62510. PBRMaterial.prototype.serialize = function () {
  62511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62512. serializationObject.customType = "BABYLON.PBRMaterial";
  62513. return serializationObject;
  62514. };
  62515. // Statics
  62516. PBRMaterial.Parse = function (source, scene, rootUrl) {
  62517. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  62518. };
  62519. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  62520. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  62521. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  62522. PBRMaterial._scaledReflection = new BABYLON.Color3();
  62523. __decorate([
  62524. BABYLON.serialize()
  62525. ], PBRMaterial.prototype, "directIntensity", void 0);
  62526. __decorate([
  62527. BABYLON.serialize()
  62528. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  62529. __decorate([
  62530. BABYLON.serialize()
  62531. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  62532. __decorate([
  62533. BABYLON.serialize()
  62534. ], PBRMaterial.prototype, "specularIntensity", void 0);
  62535. __decorate([
  62536. BABYLON.serialize()
  62537. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  62538. __decorate([
  62539. BABYLON.serialize()
  62540. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  62541. __decorate([
  62542. BABYLON.serialize()
  62543. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  62544. __decorate([
  62545. BABYLON.serialize()
  62546. ], PBRMaterial.prototype, "cameraExposure", void 0);
  62547. __decorate([
  62548. BABYLON.serialize()
  62549. ], PBRMaterial.prototype, "cameraContrast", void 0);
  62550. __decorate([
  62551. BABYLON.serializeAsTexture()
  62552. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  62553. __decorate([
  62554. BABYLON.serializeAsColorCurves()
  62555. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  62556. __decorate([
  62557. BABYLON.serializeAsColor3()
  62558. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  62559. __decorate([
  62560. BABYLON.serialize()
  62561. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  62562. __decorate([
  62563. BABYLON.serializeAsColor3()
  62564. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  62565. __decorate([
  62566. BABYLON.serialize()
  62567. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  62568. __decorate([
  62569. BABYLON.serializeAsColor3()
  62570. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  62571. __decorate([
  62572. BABYLON.serialize()
  62573. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  62574. __decorate([
  62575. BABYLON.serializeAsColor3()
  62576. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  62577. __decorate([
  62578. BABYLON.serialize()
  62579. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  62580. __decorate([
  62581. BABYLON.serializeAsColor3()
  62582. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  62583. __decorate([
  62584. BABYLON.serialize()
  62585. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  62586. __decorate([
  62587. BABYLON.serialize()
  62588. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  62589. __decorate([
  62590. BABYLON.serialize()
  62591. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  62592. __decorate([
  62593. BABYLON.serializeAsTexture()
  62594. ], PBRMaterial.prototype, "albedoTexture", void 0);
  62595. __decorate([
  62596. BABYLON.serializeAsTexture()
  62597. ], PBRMaterial.prototype, "ambientTexture", void 0);
  62598. __decorate([
  62599. BABYLON.serializeAsTexture()
  62600. ], PBRMaterial.prototype, "opacityTexture", void 0);
  62601. __decorate([
  62602. BABYLON.serializeAsTexture()
  62603. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  62604. __decorate([
  62605. BABYLON.serializeAsTexture()
  62606. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  62607. __decorate([
  62608. BABYLON.serializeAsTexture()
  62609. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  62610. __decorate([
  62611. BABYLON.serializeAsTexture()
  62612. ], PBRMaterial.prototype, "bumpTexture", void 0);
  62613. __decorate([
  62614. BABYLON.serializeAsTexture()
  62615. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  62616. __decorate([
  62617. BABYLON.serializeAsTexture()
  62618. ], PBRMaterial.prototype, "refractionTexture", void 0);
  62619. __decorate([
  62620. BABYLON.serializeAsColor3("ambient")
  62621. ], PBRMaterial.prototype, "ambientColor", void 0);
  62622. __decorate([
  62623. BABYLON.serializeAsColor3("albedo")
  62624. ], PBRMaterial.prototype, "albedoColor", void 0);
  62625. __decorate([
  62626. BABYLON.serializeAsColor3("reflectivity")
  62627. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  62628. __decorate([
  62629. BABYLON.serializeAsColor3("reflection")
  62630. ], PBRMaterial.prototype, "reflectionColor", void 0);
  62631. __decorate([
  62632. BABYLON.serializeAsColor3("emissive")
  62633. ], PBRMaterial.prototype, "emissiveColor", void 0);
  62634. __decorate([
  62635. BABYLON.serialize()
  62636. ], PBRMaterial.prototype, "microSurface", void 0);
  62637. __decorate([
  62638. BABYLON.serialize()
  62639. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  62640. __decorate([
  62641. BABYLON.serialize()
  62642. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  62643. __decorate([
  62644. BABYLON.serializeAsFresnelParameters()
  62645. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  62646. __decorate([
  62647. BABYLON.serializeAsFresnelParameters()
  62648. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  62649. __decorate([
  62650. BABYLON.serialize()
  62651. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  62652. __decorate([
  62653. BABYLON.serialize()
  62654. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  62655. __decorate([
  62656. BABYLON.serialize()
  62657. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  62658. __decorate([
  62659. BABYLON.serialize()
  62660. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  62661. __decorate([
  62662. BABYLON.serialize()
  62663. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  62664. __decorate([
  62665. BABYLON.serialize()
  62666. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  62667. __decorate([
  62668. BABYLON.serialize()
  62669. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  62670. __decorate([
  62671. BABYLON.serialize()
  62672. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  62673. __decorate([
  62674. BABYLON.serialize()
  62675. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  62676. __decorate([
  62677. BABYLON.serialize()
  62678. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  62679. __decorate([
  62680. BABYLON.serialize()
  62681. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  62682. __decorate([
  62683. BABYLON.serialize()
  62684. ], PBRMaterial.prototype, "useParallax", void 0);
  62685. __decorate([
  62686. BABYLON.serialize()
  62687. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  62688. __decorate([
  62689. BABYLON.serialize()
  62690. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  62691. __decorate([
  62692. BABYLON.serialize()
  62693. ], PBRMaterial.prototype, "disableLighting", void 0);
  62694. __decorate([
  62695. BABYLON.serialize()
  62696. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  62697. __decorate([
  62698. BABYLON.serialize()
  62699. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  62700. __decorate([
  62701. BABYLON.serialize()
  62702. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  62703. __decorate([
  62704. BABYLON.serialize()
  62705. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  62706. return PBRMaterial;
  62707. }(BABYLON.Material));
  62708. BABYLON.PBRMaterial = PBRMaterial;
  62709. })(BABYLON || (BABYLON = {}));
  62710. var BABYLON;
  62711. (function (BABYLON) {
  62712. var DebugLayer = (function () {
  62713. function DebugLayer(scene) {
  62714. var _this = this;
  62715. this._transformationMatrix = BABYLON.Matrix.Identity();
  62716. this._enabled = false;
  62717. this._labelsEnabled = false;
  62718. this._displayStatistics = true;
  62719. this._displayTree = false;
  62720. this._displayLogs = false;
  62721. this._skeletonViewers = new Array();
  62722. this._identityMatrix = BABYLON.Matrix.Identity();
  62723. this.axisRatio = 0.02;
  62724. this.accentColor = "orange";
  62725. this._scene = scene;
  62726. this._syncPositions = function () {
  62727. var engine = _this._scene.getEngine();
  62728. var canvasRect = engine.getRenderingCanvasClientRect();
  62729. if (_this._showUI) {
  62730. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  62731. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  62732. _this._statsDiv.style.width = "400px";
  62733. _this._statsDiv.style.height = "auto";
  62734. _this._statsSubsetDiv.style.maxHeight = "240px";
  62735. _this._optionsDiv.style.left = "0px";
  62736. _this._optionsDiv.style.top = "10px";
  62737. _this._optionsDiv.style.width = "200px";
  62738. _this._optionsDiv.style.height = "auto";
  62739. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  62740. _this._logDiv.style.left = "0px";
  62741. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  62742. _this._logDiv.style.width = "600px";
  62743. _this._logDiv.style.height = "160px";
  62744. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  62745. _this._treeDiv.style.top = "10px";
  62746. _this._treeDiv.style.width = "300px";
  62747. _this._treeDiv.style.height = "auto";
  62748. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  62749. }
  62750. _this._globalDiv.style.left = canvasRect.left + "px";
  62751. _this._globalDiv.style.top = canvasRect.top + "px";
  62752. _this._drawingCanvas.style.left = "0px";
  62753. _this._drawingCanvas.style.top = "0px";
  62754. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  62755. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  62756. var devicePixelRatio = window.devicePixelRatio || 1;
  62757. var context = _this._drawingContext;
  62758. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  62759. context.mozBackingStorePixelRatio ||
  62760. context.msBackingStorePixelRatio ||
  62761. context.oBackingStorePixelRatio ||
  62762. context.backingStorePixelRatio || 1;
  62763. _this._ratio = devicePixelRatio / backingStoreRatio;
  62764. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  62765. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  62766. };
  62767. this._onCanvasClick = function (evt) {
  62768. _this._clickPosition = {
  62769. x: evt.clientX * _this._ratio,
  62770. y: evt.clientY * _this._ratio
  62771. };
  62772. };
  62773. this._syncUI = function () {
  62774. if (_this._showUI) {
  62775. if (_this._displayStatistics) {
  62776. _this._displayStats();
  62777. _this._statsDiv.style.display = "";
  62778. }
  62779. else {
  62780. _this._statsDiv.style.display = "none";
  62781. }
  62782. if (_this._displayLogs) {
  62783. _this._logDiv.style.display = "";
  62784. }
  62785. else {
  62786. _this._logDiv.style.display = "none";
  62787. }
  62788. if (_this._displayTree) {
  62789. _this._treeDiv.style.display = "";
  62790. if (_this._needToRefreshMeshesTree) {
  62791. _this._needToRefreshMeshesTree = false;
  62792. _this._refreshMeshesTreeContent();
  62793. }
  62794. }
  62795. else {
  62796. _this._treeDiv.style.display = "none";
  62797. }
  62798. }
  62799. };
  62800. this._syncData = function () {
  62801. if (_this._labelsEnabled || !_this._showUI) {
  62802. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  62803. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  62804. var engine = _this._scene.getEngine();
  62805. var viewport = _this._camera.viewport;
  62806. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62807. // Meshes
  62808. var meshes = _this._camera.getActiveMeshes();
  62809. var index;
  62810. var projectedPosition;
  62811. for (index = 0; index < meshes.length; index++) {
  62812. var mesh = meshes.data[index];
  62813. var position = mesh.getBoundingInfo().boundingSphere.center;
  62814. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  62815. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  62816. _this._renderAxis(projectedPosition, mesh, globalViewport);
  62817. }
  62818. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  62819. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  62820. }
  62821. }
  62822. // Cameras
  62823. var cameras = _this._scene.cameras;
  62824. for (index = 0; index < cameras.length; index++) {
  62825. var camera = cameras[index];
  62826. if (camera === _this._camera) {
  62827. continue;
  62828. }
  62829. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  62830. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  62831. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  62832. _this._camera.detachControl(engine.getRenderingCanvas());
  62833. _this._camera = camera;
  62834. _this._camera.attachControl(engine.getRenderingCanvas());
  62835. }, function () { return "purple"; });
  62836. }
  62837. }
  62838. // Lights
  62839. var lights = _this._scene.lights;
  62840. for (index = 0; index < lights.length; index++) {
  62841. var light = lights[index];
  62842. if (light.position) {
  62843. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  62844. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  62845. _this._renderLabel(light.name, projectedPosition, -20, function () {
  62846. light.setEnabled(!light.isEnabled());
  62847. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  62848. }
  62849. }
  62850. }
  62851. }
  62852. _this._clickPosition = undefined;
  62853. };
  62854. }
  62855. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  62856. while (this._treeSubsetDiv.hasChildNodes()) {
  62857. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  62858. }
  62859. // Add meshes
  62860. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  62861. sortedArray.sort(function (a, b) {
  62862. if (a.name === b.name) {
  62863. return 0;
  62864. }
  62865. return (a.name > b.name) ? 1 : -1;
  62866. });
  62867. for (var index = 0; index < sortedArray.length; index++) {
  62868. var mesh = sortedArray[index];
  62869. if (!mesh.isEnabled()) {
  62870. continue;
  62871. }
  62872. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  62873. m.isVisible = element.checked;
  62874. }, mesh);
  62875. }
  62876. };
  62877. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  62878. this._drawingContext.beginPath();
  62879. this._drawingContext.moveTo(zero.x, zero.y);
  62880. this._drawingContext.lineTo(unit.x, unit.y);
  62881. this._drawingContext.strokeStyle = color;
  62882. this._drawingContext.lineWidth = 4;
  62883. this._drawingContext.stroke();
  62884. this._drawingContext.font = "normal 14px Segoe UI";
  62885. this._drawingContext.fillStyle = color;
  62886. this._drawingContext.fillText(label, unitText.x, unitText.y);
  62887. };
  62888. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  62889. var position = mesh.getBoundingInfo().boundingSphere.center;
  62890. var worldMatrix = mesh.getWorldMatrix();
  62891. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  62892. var unit = (unprojectedVector.subtract(position)).length();
  62893. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62894. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62895. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  62896. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62897. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  62898. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  62899. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  62900. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  62901. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  62902. };
  62903. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  62904. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  62905. this._drawingContext.font = "normal 12px Segoe UI";
  62906. var textMetrics = this._drawingContext.measureText(text);
  62907. var centerX = projectedPosition.x - textMetrics.width / 2;
  62908. var centerY = projectedPosition.y;
  62909. var clientRect = this._drawingCanvas.getBoundingClientRect();
  62910. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  62911. onClick();
  62912. }
  62913. this._drawingContext.beginPath();
  62914. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  62915. this._drawingContext.fillStyle = getFillStyle();
  62916. this._drawingContext.globalAlpha = 0.5;
  62917. this._drawingContext.fill();
  62918. this._drawingContext.globalAlpha = 1.0;
  62919. this._drawingContext.strokeStyle = '#FFFFFF';
  62920. this._drawingContext.lineWidth = 1;
  62921. this._drawingContext.stroke();
  62922. this._drawingContext.fillStyle = "#FFFFFF";
  62923. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  62924. this._drawingContext.beginPath();
  62925. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  62926. this._drawingContext.fill();
  62927. }
  62928. };
  62929. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  62930. if (!this._clickPosition) {
  62931. return false;
  62932. }
  62933. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  62934. return false;
  62935. }
  62936. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  62937. return false;
  62938. }
  62939. return true;
  62940. };
  62941. DebugLayer.prototype.isVisible = function () {
  62942. return this._enabled;
  62943. };
  62944. DebugLayer.prototype.hide = function () {
  62945. if (!this._enabled) {
  62946. return;
  62947. }
  62948. this._enabled = false;
  62949. var engine = this._scene.getEngine();
  62950. this._scene.unregisterBeforeRender(this._syncData);
  62951. this._scene.unregisterAfterRender(this._syncUI);
  62952. this._rootElement.removeChild(this._globalDiv);
  62953. this._scene.forceShowBoundingBoxes = false;
  62954. this._scene.forceWireframe = false;
  62955. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  62956. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  62957. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  62958. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  62959. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  62960. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  62961. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  62962. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  62963. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  62964. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  62965. this._scene.shadowsEnabled = true;
  62966. this._scene.particlesEnabled = true;
  62967. this._scene.postProcessesEnabled = true;
  62968. this._scene.collisionsEnabled = true;
  62969. this._scene.lightsEnabled = true;
  62970. this._scene.texturesEnabled = true;
  62971. this._scene.lensFlaresEnabled = true;
  62972. this._scene.proceduralTexturesEnabled = true;
  62973. this._scene.renderTargetsEnabled = true;
  62974. this._scene.probesEnabled = true;
  62975. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  62976. this._clearSkeletonViewers();
  62977. };
  62978. DebugLayer.prototype._clearSkeletonViewers = function () {
  62979. for (var index = 0; index < this._skeletonViewers.length; index++) {
  62980. this._skeletonViewers[index].dispose();
  62981. }
  62982. this._skeletonViewers = [];
  62983. };
  62984. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  62985. if (showUI === void 0) { showUI = true; }
  62986. if (camera === void 0) { camera = null; }
  62987. if (rootElement === void 0) { rootElement = null; }
  62988. if (this._enabled) {
  62989. return;
  62990. }
  62991. this._enabled = true;
  62992. if (camera) {
  62993. this._camera = camera;
  62994. }
  62995. else {
  62996. this._camera = this._scene.activeCamera;
  62997. }
  62998. this._showUI = showUI;
  62999. var engine = this._scene.getEngine();
  63000. this._globalDiv = document.createElement("div");
  63001. this._rootElement = rootElement || document.body;
  63002. this._rootElement.appendChild(this._globalDiv);
  63003. this._generateDOMelements();
  63004. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  63005. this._syncPositions();
  63006. this._scene.registerBeforeRender(this._syncData);
  63007. this._scene.registerAfterRender(this._syncUI);
  63008. };
  63009. DebugLayer.prototype._clearLabels = function () {
  63010. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  63011. for (var index = 0; index < this._scene.meshes.length; index++) {
  63012. var mesh = this._scene.meshes[index];
  63013. mesh.renderOverlay = false;
  63014. }
  63015. };
  63016. DebugLayer.prototype._generateheader = function (root, text) {
  63017. var header = document.createElement("div");
  63018. header.innerHTML = text + "&nbsp;";
  63019. header.style.textAlign = "right";
  63020. header.style.width = "100%";
  63021. header.style.color = "white";
  63022. header.style.backgroundColor = "Black";
  63023. header.style.padding = "5px 5px 4px 0px";
  63024. header.style.marginLeft = "-5px";
  63025. header.style.fontWeight = "bold";
  63026. root.appendChild(header);
  63027. };
  63028. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  63029. var label = document.createElement("label");
  63030. label.style.display = "inline";
  63031. label.innerHTML = title;
  63032. label.style.color = color;
  63033. root.appendChild(label);
  63034. root.appendChild(document.createElement("br"));
  63035. };
  63036. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  63037. if (tag === void 0) { tag = null; }
  63038. var label = document.createElement("label");
  63039. label.style.display = "inline";
  63040. var boundingBoxesCheckbox = document.createElement("input");
  63041. boundingBoxesCheckbox.type = "checkbox";
  63042. boundingBoxesCheckbox.checked = initialState;
  63043. boundingBoxesCheckbox.style.display = "inline";
  63044. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  63045. boundingBoxesCheckbox.style.verticalAlign = "sub";
  63046. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  63047. task(evt.target, tag);
  63048. });
  63049. label.appendChild(boundingBoxesCheckbox);
  63050. var container = document.createElement("span");
  63051. var leftPart = document.createElement("span");
  63052. var rightPart = document.createElement("span");
  63053. rightPart.style.cssFloat = "right";
  63054. leftPart.innerHTML = leftTitle;
  63055. rightPart.innerHTML = rightTitle;
  63056. rightPart.style.fontSize = "12px";
  63057. rightPart.style.maxWidth = "200px";
  63058. container.appendChild(leftPart);
  63059. container.appendChild(rightPart);
  63060. label.appendChild(container);
  63061. root.appendChild(label);
  63062. root.appendChild(document.createElement("br"));
  63063. };
  63064. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  63065. if (tag === void 0) { tag = null; }
  63066. var label = document.createElement("label");
  63067. label.style.display = "inline";
  63068. var checkBox = document.createElement("input");
  63069. checkBox.type = "checkbox";
  63070. checkBox.checked = initialState;
  63071. checkBox.style.display = "inline";
  63072. checkBox.style.margin = "0px 5px 0px 0px";
  63073. checkBox.style.verticalAlign = "sub";
  63074. checkBox.addEventListener("change", function (evt) {
  63075. task(evt.target, tag);
  63076. });
  63077. label.appendChild(checkBox);
  63078. label.appendChild(document.createTextNode(title));
  63079. root.appendChild(label);
  63080. root.appendChild(document.createElement("br"));
  63081. };
  63082. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  63083. if (tag === void 0) { tag = null; }
  63084. var button = document.createElement("button");
  63085. button.innerHTML = title;
  63086. button.style.height = "24px";
  63087. button.style.width = "150px";
  63088. button.style.marginBottom = "5px";
  63089. button.style.color = "#444444";
  63090. button.style.border = "1px solid white";
  63091. button.className = "debugLayerButton";
  63092. button.addEventListener("click", function (evt) {
  63093. task(evt.target, tag);
  63094. });
  63095. root.appendChild(button);
  63096. root.appendChild(document.createElement("br"));
  63097. };
  63098. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  63099. if (tag === void 0) { tag = null; }
  63100. var label = document.createElement("label");
  63101. label.style.display = "inline";
  63102. var boundingBoxesRadio = document.createElement("input");
  63103. boundingBoxesRadio.type = "radio";
  63104. boundingBoxesRadio.name = name;
  63105. boundingBoxesRadio.checked = initialState;
  63106. boundingBoxesRadio.style.display = "inline";
  63107. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  63108. boundingBoxesRadio.style.verticalAlign = "sub";
  63109. boundingBoxesRadio.addEventListener("change", function (evt) {
  63110. task(evt.target, tag);
  63111. });
  63112. label.appendChild(boundingBoxesRadio);
  63113. label.appendChild(document.createTextNode(title));
  63114. root.appendChild(label);
  63115. root.appendChild(document.createElement("br"));
  63116. };
  63117. DebugLayer.prototype._generateDOMelements = function () {
  63118. var _this = this;
  63119. this._globalDiv.id = "DebugLayer";
  63120. this._globalDiv.style.position = "absolute";
  63121. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  63122. this._globalDiv.style.fontSize = "14px";
  63123. this._globalDiv.style.color = "white";
  63124. // Drawing canvas
  63125. this._drawingCanvas = document.createElement("canvas");
  63126. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  63127. this._drawingCanvas.style.position = "absolute";
  63128. this._drawingCanvas.style.pointerEvents = "none";
  63129. this._drawingCanvas.style.backgroundColor = "transparent";
  63130. this._drawingContext = this._drawingCanvas.getContext("2d");
  63131. this._globalDiv.appendChild(this._drawingCanvas);
  63132. if (this._showUI) {
  63133. var background = "rgba(128, 128, 128, 0.4)";
  63134. var border = "rgb(180, 180, 180) solid 1px";
  63135. // Stats
  63136. this._statsDiv = document.createElement("div");
  63137. this._statsDiv.id = "DebugLayerStats";
  63138. this._statsDiv.style.border = border;
  63139. this._statsDiv.style.position = "absolute";
  63140. this._statsDiv.style.background = background;
  63141. this._statsDiv.style.padding = "0px 0px 0px 5px";
  63142. this._generateheader(this._statsDiv, "STATISTICS");
  63143. this._statsSubsetDiv = document.createElement("div");
  63144. this._statsSubsetDiv.style.paddingTop = "5px";
  63145. this._statsSubsetDiv.style.paddingBottom = "5px";
  63146. this._statsSubsetDiv.style.overflowY = "auto";
  63147. this._statsDiv.appendChild(this._statsSubsetDiv);
  63148. // Tree
  63149. this._treeDiv = document.createElement("div");
  63150. this._treeDiv.id = "DebugLayerTree";
  63151. this._treeDiv.style.border = border;
  63152. this._treeDiv.style.position = "absolute";
  63153. this._treeDiv.style.background = background;
  63154. this._treeDiv.style.padding = "0px 0px 0px 5px";
  63155. this._treeDiv.style.display = "none";
  63156. this._generateheader(this._treeDiv, "MESHES TREE");
  63157. this._treeSubsetDiv = document.createElement("div");
  63158. this._treeSubsetDiv.style.paddingTop = "5px";
  63159. this._treeSubsetDiv.style.paddingRight = "5px";
  63160. this._treeSubsetDiv.style.overflowY = "auto";
  63161. this._treeSubsetDiv.style.maxHeight = "300px";
  63162. this._treeDiv.appendChild(this._treeSubsetDiv);
  63163. this._needToRefreshMeshesTree = true;
  63164. // Logs
  63165. this._logDiv = document.createElement("div");
  63166. this._logDiv.style.border = border;
  63167. this._logDiv.id = "DebugLayerLogs";
  63168. this._logDiv.style.position = "absolute";
  63169. this._logDiv.style.background = background;
  63170. this._logDiv.style.padding = "0px 0px 0px 5px";
  63171. this._logDiv.style.display = "none";
  63172. this._generateheader(this._logDiv, "LOGS");
  63173. this._logSubsetDiv = document.createElement("div");
  63174. this._logSubsetDiv.style.height = "127px";
  63175. this._logSubsetDiv.style.paddingTop = "5px";
  63176. this._logSubsetDiv.style.overflowY = "auto";
  63177. this._logSubsetDiv.style.fontSize = "12px";
  63178. this._logSubsetDiv.style.fontFamily = "consolas";
  63179. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  63180. this._logDiv.appendChild(this._logSubsetDiv);
  63181. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  63182. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  63183. };
  63184. // Options
  63185. this._optionsDiv = document.createElement("div");
  63186. this._optionsDiv.id = "DebugLayerOptions";
  63187. this._optionsDiv.style.border = border;
  63188. this._optionsDiv.style.position = "absolute";
  63189. this._optionsDiv.style.background = background;
  63190. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  63191. this._optionsDiv.style.overflowY = "auto";
  63192. this._generateheader(this._optionsDiv, "OPTIONS");
  63193. this._optionsSubsetDiv = document.createElement("div");
  63194. this._optionsSubsetDiv.style.paddingTop = "5px";
  63195. this._optionsSubsetDiv.style.paddingBottom = "5px";
  63196. this._optionsSubsetDiv.style.overflowY = "auto";
  63197. this._optionsSubsetDiv.style.maxHeight = "200px";
  63198. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  63199. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  63200. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  63201. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  63202. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  63203. _this._displayTree = element.checked;
  63204. _this._needToRefreshMeshesTree = true;
  63205. });
  63206. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63207. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  63208. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  63209. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  63210. _this._labelsEnabled = element.checked;
  63211. if (!_this._labelsEnabled) {
  63212. _this._clearLabels();
  63213. }
  63214. });
  63215. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  63216. if (element.checked) {
  63217. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  63218. }
  63219. else {
  63220. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  63221. }
  63222. });
  63223. ;
  63224. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63225. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  63226. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  63227. if (element.checked) {
  63228. _this._scene.forceWireframe = false;
  63229. _this._scene.forcePointsCloud = false;
  63230. }
  63231. });
  63232. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  63233. if (element.checked) {
  63234. _this._scene.forceWireframe = true;
  63235. _this._scene.forcePointsCloud = false;
  63236. }
  63237. });
  63238. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  63239. if (element.checked) {
  63240. _this._scene.forceWireframe = false;
  63241. _this._scene.forcePointsCloud = true;
  63242. }
  63243. });
  63244. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63245. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  63246. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  63247. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  63248. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  63249. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  63250. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  63251. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  63252. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  63253. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  63254. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  63255. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  63256. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  63257. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63258. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  63259. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  63260. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  63261. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  63262. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  63263. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  63264. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  63265. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  63266. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  63267. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  63268. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  63269. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  63270. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  63271. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  63272. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  63273. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63274. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63275. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  63276. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  63277. if (element.checked) {
  63278. _this._scene.headphone = true;
  63279. }
  63280. });
  63281. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  63282. if (element.checked) {
  63283. _this._scene.headphone = false;
  63284. }
  63285. });
  63286. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  63287. _this._scene.audioEnabled = !element.checked;
  63288. });
  63289. }
  63290. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63291. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  63292. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  63293. if (!element.checked) {
  63294. _this._clearSkeletonViewers();
  63295. return;
  63296. }
  63297. for (var index = 0; index < _this._scene.meshes.length; index++) {
  63298. var mesh = _this._scene.meshes[index];
  63299. if (mesh.skeleton) {
  63300. var found = false;
  63301. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  63302. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  63303. found = true;
  63304. break;
  63305. }
  63306. }
  63307. if (found) {
  63308. continue;
  63309. }
  63310. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  63311. viewer.isEnabled = true;
  63312. _this._skeletonViewers.push(viewer);
  63313. }
  63314. }
  63315. });
  63316. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63317. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  63318. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  63319. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  63320. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  63321. if (_this._camera) {
  63322. console.log(_this._camera);
  63323. }
  63324. else {
  63325. console.warn("No camera defined, or debug layer created before camera creation!");
  63326. }
  63327. });
  63328. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  63329. this._globalDiv.appendChild(this._statsDiv);
  63330. this._globalDiv.appendChild(this._logDiv);
  63331. this._globalDiv.appendChild(this._optionsDiv);
  63332. this._globalDiv.appendChild(this._treeDiv);
  63333. }
  63334. };
  63335. DebugLayer.prototype._displayStats = function () {
  63336. var scene = this._scene;
  63337. var engine = scene.getEngine();
  63338. var glInfo = engine.getGlInfo();
  63339. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  63340. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63341. + "<b>Count</b><br>"
  63342. + "Total meshes: " + scene.meshes.length + "<br>"
  63343. + "Total lights: " + scene.lights.length + "<br>"
  63344. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  63345. + "Total materials: " + scene.materials.length + "<br>"
  63346. + "Total textures: " + scene.textures.length + "<br>"
  63347. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  63348. + "Active indices: " + scene.getActiveIndices() + "<br>"
  63349. + "Active bones: " + scene.getActiveBones() + "<br>"
  63350. + "Active particles: " + scene.getActiveParticles() + "<br>"
  63351. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  63352. + "<b>Duration</b><br>"
  63353. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  63354. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  63355. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  63356. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  63357. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  63358. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  63359. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  63360. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  63361. + "</div>"
  63362. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63363. + "<b>Extensions</b><br>"
  63364. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  63365. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  63366. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  63367. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  63368. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  63369. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  63370. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  63371. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  63372. + "</div><br>"
  63373. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  63374. + "<b>Caps.</b><br>"
  63375. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  63376. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  63377. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  63378. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  63379. + "<b>Info</b><br>"
  63380. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  63381. + glInfo.version + "<br>"
  63382. + "</div><br>"
  63383. + glInfo.renderer + "<br>";
  63384. if (this.customStatsFunction) {
  63385. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  63386. }
  63387. };
  63388. return DebugLayer;
  63389. }());
  63390. BABYLON.DebugLayer = DebugLayer;
  63391. })(BABYLON || (BABYLON = {}));
  63392. var BABYLON;
  63393. (function (BABYLON) {
  63394. var StandardRenderingPipeline = (function (_super) {
  63395. __extends(StandardRenderingPipeline, _super);
  63396. /**
  63397. * @constructor
  63398. * @param {string} name - The rendering pipeline name
  63399. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63400. * @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)
  63401. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63402. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63403. */
  63404. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63405. var _this = this;
  63406. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63407. _super.call(this, scene.getEngine(), name);
  63408. this.downSampleX4PostProcess = null;
  63409. this.brightPassPostProcess = null;
  63410. this.gaussianBlurHPostProcesses = [];
  63411. this.gaussianBlurVPostProcesses = [];
  63412. this.textureAdderPostProcess = null;
  63413. this.textureAdderFinalPostProcess = null;
  63414. this.lensFlarePostProcess = null;
  63415. this.lensFlareShiftPostProcess = null;
  63416. this.lensFlareComposePostProcess = null;
  63417. this.depthOfFieldPostProcess = null;
  63418. this.motionBlurPostProcess = null;
  63419. // Values
  63420. this.brightThreshold = 1.0;
  63421. this.gaussianCoefficient = 0.25;
  63422. this.gaussianMean = 1.0;
  63423. this.gaussianStandardDeviation = 1.0;
  63424. this.exposure = 1.0;
  63425. this.lensTexture = null;
  63426. this.lensColorTexture = null;
  63427. this.lensFlareStrength = 1.0;
  63428. this.lensFlareGhostDispersal = 1.0;
  63429. this.lensFlareHaloWidth = 0.4;
  63430. this.lensFlareDistortionStrength = 4.0;
  63431. this.lensStarTexture = null;
  63432. this.lensFlareDirtTexture = null;
  63433. this.depthOfFieldDistance = 10.0;
  63434. this._depthRenderer = null;
  63435. // Getters and setters
  63436. this._depthOfFieldEnabled = true;
  63437. this._lensFlareEnabled = true;
  63438. // Initialize
  63439. this._scene = scene;
  63440. // Create pass post-processe
  63441. if (!originalPostProcess) {
  63442. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  63443. }
  63444. else {
  63445. this.originalPostProcess = originalPostProcess;
  63446. }
  63447. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63448. // Create down sample X4 post-process
  63449. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63450. // Create bright pass post-process
  63451. this._createBrightPassPostProcess(scene, ratio / 2);
  63452. // Create gaussian blur post-processes (down sampling blurs)
  63453. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  63454. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  63455. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  63456. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  63457. // Create texture adder post-process
  63458. this._createTextureAdderPostProcess(scene, ratio);
  63459. // Create depth-of-field source post-process
  63460. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRTextureAdderPostProcess", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63462. // Create lens flare post-process
  63463. this._createLensFlarePostProcess(scene, ratio);
  63464. // Create gaussian blur used by depth-of-field
  63465. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  63466. // Create depth-of-field post-process
  63467. this._createDepthOfFieldPostProcess(scene, ratio);
  63468. // Finish
  63469. scene.postProcessRenderPipelineManager.addPipeline(this);
  63470. if (cameras !== null) {
  63471. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63472. }
  63473. // Deactivate
  63474. this.LensFlareEnabled = false;
  63475. this.DepthOfFieldEnabled = false;
  63476. }
  63477. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63478. get: function () {
  63479. return this._depthOfFieldEnabled;
  63480. },
  63481. set: function (enabled) {
  63482. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  63483. if (enabled && !this._depthOfFieldEnabled) {
  63484. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  63485. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  63486. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  63487. this._depthRenderer = this._scene.enableDepthRenderer();
  63488. }
  63489. else if (!enabled && this._depthOfFieldEnabled) {
  63490. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  63491. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  63492. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  63493. }
  63494. this._depthOfFieldEnabled = enabled;
  63495. },
  63496. enumerable: true,
  63497. configurable: true
  63498. });
  63499. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63500. get: function () {
  63501. return this._lensFlareEnabled;
  63502. },
  63503. set: function (enabled) {
  63504. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  63505. if (enabled && !this._lensFlareEnabled) {
  63506. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  63507. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  63508. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  63509. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  63510. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  63511. this._depthRenderer = this._scene.enableDepthRenderer();
  63512. }
  63513. else if (!enabled && this._lensFlareEnabled) {
  63514. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  63515. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  63516. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  63517. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  63518. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  63519. }
  63520. this._lensFlareEnabled = enabled;
  63521. },
  63522. enumerable: true,
  63523. configurable: true
  63524. });
  63525. // Down Sample X4 Post-Processs
  63526. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63527. var _this = this;
  63528. var downSampleX4Offsets = new Array(32);
  63529. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63530. this.downSampleX4PostProcess.onApply = function (effect) {
  63531. var id = 0;
  63532. for (var i = -2; i < 2; i++) {
  63533. for (var j = -2; j < 2; j++) {
  63534. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  63535. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  63536. id += 2;
  63537. }
  63538. }
  63539. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63540. };
  63541. // Add to pipeline
  63542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63543. };
  63544. // Brightpass Post-Process
  63545. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63546. var _this = this;
  63547. var brightOffsets = new Array(8);
  63548. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63549. this.brightPassPostProcess.onApply = function (effect) {
  63550. var sU = (1.0 / _this.brightPassPostProcess.width);
  63551. var sV = (1.0 / _this.brightPassPostProcess.height);
  63552. brightOffsets[0] = -0.5 * sU;
  63553. brightOffsets[1] = 0.5 * sV;
  63554. brightOffsets[2] = 0.5 * sU;
  63555. brightOffsets[3] = 0.5 * sV;
  63556. brightOffsets[4] = -0.5 * sU;
  63557. brightOffsets[5] = -0.5 * sV;
  63558. brightOffsets[6] = 0.5 * sU;
  63559. brightOffsets[7] = -0.5 * sV;
  63560. effect.setArray2("dsOffsets", brightOffsets);
  63561. effect.setFloat("brightThreshold", _this.brightThreshold);
  63562. };
  63563. // Add to pipeline
  63564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63565. };
  63566. // Create gaussian blur H&V post-processes
  63567. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  63568. var _this = this;
  63569. var blurOffsets = new Array(9);
  63570. var blurWeights = new Array(9);
  63571. var uniforms = ["blurOffsets", "blurWeights"];
  63572. var callback = function (height) {
  63573. return function (effect) {
  63574. // Weights
  63575. var x = 0.0;
  63576. for (var i = 0; i < 9; i++) {
  63577. x = (i - 4.0) / 4.0;
  63578. blurWeights[i] =
  63579. _this.gaussianCoefficient
  63580. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  63581. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  63582. }
  63583. var lastOutputDimensions = {
  63584. width: scene.getEngine().getRenderWidth(),
  63585. height: scene.getEngine().getRenderHeight()
  63586. };
  63587. for (var i = 0; i < 9; i++) {
  63588. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  63589. blurOffsets[i] = value;
  63590. }
  63591. effect.setArray("blurOffsets", blurOffsets);
  63592. effect.setArray("blurWeights", blurWeights);
  63593. };
  63594. };
  63595. // Create horizontal gaussian blur post-processes
  63596. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63597. gaussianBlurHPostProcess.onApply = callback(false);
  63598. // Create vertical gaussian blur post-process
  63599. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63600. gaussianBlurVPostProcess.onApply = callback(true);
  63601. // Add to pipeline
  63602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  63603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  63604. // Finish
  63605. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  63606. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  63607. };
  63608. // Create texture adder post-process
  63609. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63610. var _this = this;
  63611. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  63612. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63613. this.textureAdderPostProcess.onApply = function (effect) {
  63614. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  63615. effect.setTexture("lensSampler", _this.lensTexture);
  63616. effect.setFloat("exposure", _this.exposure);
  63617. };
  63618. // Add to pipeline
  63619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63620. };
  63621. // Create lens flare post-process
  63622. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63623. var _this = this;
  63624. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth"], ["lensColorSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63625. this.lensFlareShiftPostProcess = new BABYLON.PostProcess("HDRLensFlareShift", "standard", ["resolution", "distortionStrength"], [], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_SHIFT", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63626. this._createGaussianBlurPostProcesses(scene, ratio / 8, 4);
  63627. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["viewMatrix", "scaleBias1", "scaleBias2"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63628. var resolution = new BABYLON.Vector2(0, 0);
  63629. // Lens flare
  63630. this.lensFlarePostProcess.onApply = function (effect) {
  63631. effect.setTextureFromPostProcess("textureSampler", _this.textureAdderPostProcess);
  63632. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63633. effect.setFloat("strength", _this.lensFlareStrength);
  63634. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63635. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63636. };
  63637. // Shift
  63638. this.lensFlareShiftPostProcess.onApply = function (effect) {
  63639. resolution.x = _this.lensFlareShiftPostProcess.width;
  63640. resolution.y = _this.lensFlareShiftPostProcess.height;
  63641. effect.setVector2("resolution", resolution);
  63642. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63643. };
  63644. // Compose
  63645. var scaleBias1 = BABYLON.Matrix.GetAsMatrix3x3(BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0));
  63646. var scaleBias2 = BABYLON.Matrix.GetAsMatrix3x3(BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0));
  63647. this.lensFlareComposePostProcess.onApply = function (effect) {
  63648. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  63649. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63650. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63651. effect.setMatrix("viewMatrix", _this._scene.activeCamera.getViewMatrix());
  63652. effect.setMatrix3x3("scaleBias1", scaleBias1);
  63653. effect.setMatrix3x3("scaleBias2", scaleBias2);
  63654. };
  63655. // Add to pipeline
  63656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  63657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareShift", function () { return _this.lensFlareShiftPostProcess; }, false));
  63658. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  63659. };
  63660. // Create depth-of-field post-process
  63661. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63662. var _this = this;
  63663. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63664. this.depthOfFieldPostProcess.onApply = function (effect) {
  63665. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  63666. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  63667. effect.setFloat("distance", _this.depthOfFieldDistance);
  63668. };
  63669. // Add to pipeline
  63670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63671. };
  63672. return StandardRenderingPipeline;
  63673. }(BABYLON.PostProcessRenderPipeline));
  63674. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63675. })(BABYLON || (BABYLON = {}));
  63676. 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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\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}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","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.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform 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 bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\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 scaleFactor;\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);\nvec2 sfSizeUV=sizeUV*scaleFactor;\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*sfSizeUV.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*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.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","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nfloat hash(vec2 p) {\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p) {\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p) {\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec4 result=vec4(0.0);\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*float(i));\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=texture2D(textureSampler,offset)*weight;\n}\nfloat patternWeight=0.4*length(vec2(0.5)-uv);\nresult=mix(result,result*vec4(pattern(uv),1.0),0.6);\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-vUV)/length(vec2(0.5))));\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,5.0);\nvec4 halo=texture2D(textureSampler,uv+haloVec)*weight;\ngl_FragColor=(result+halo)*strength;\n}\n#endif\n#if defined(LENS_FLARE_SHIFT)\nuniform vec2 resolution;\nuniform float distortionStrength;\nvoid main(void)\n{\nconst float dispersion=0.15;\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-vUV);\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec2 direction=vec2(normalize(ghostDir));\nvec4 rgbShift=vec4(\ntexture2D(textureSampler,vUV+direction*distortion.r).r,\ntexture2D(textureSampler,vUV+direction*distortion.g).g,\ntexture2D(textureSampler,vUV+direction*distortion.b).b,\n1.0\n);\ngl_FragColor=rgbShift;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 viewMatrix;\nuniform mat3 scaleBias1;\nuniform mat3 scaleBias2;\nvoid main(void)\n{\nvec3 camerax=viewMatrix[0].xyz;\nvec3 cameraz=viewMatrix[1].xyz;\nfloat camRot=dot(camerax,vec3(0.0,0.0,1.0))+dot(cameraz,vec3(0.0,1.0,0.0));\nmat3 rotation=mat3(\ncos(camRot),-sin(camRot),0.0,\nsin(camRot),cos(camRot),0.0,\n0.0,0.0,1.0\n);\nmat3 lensMatrix=scaleBias2*rotation*scaleBias1;\nvec2 lensFlareCoords=(lensMatrix*vec3(vUV,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,lensFlareCoords);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\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}"};
  63677. 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#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-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#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  63678. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}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!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",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-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){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,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,r.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,A),A.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(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)},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),u<-.499&&(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(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}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]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],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;t<16;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;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;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],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*D)*b,t.m[7]=(i*I-n*q+o*V)*b,t.m[11]=-(i*H-r*q+o*N)*b,t.m[15]=(i*D-r*V+n*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.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;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){\nreturn 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],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+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;i<16;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;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;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,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){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]=x,z.m[15]=l,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;e<16;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.LookAtRH=function(i,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,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/(e-o),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/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-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);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=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.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},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 r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.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;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,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=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.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 R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var 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={}));";
  63679. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  63680. module.exports = BABYLON;
  63681. };