babylon.engine.ts 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  12. var magFilter = gl.NEAREST;
  13. var minFilter = gl.NEAREST;
  14. switch (samplingMode) {
  15. case Texture.BILINEAR_SAMPLINGMODE:
  16. magFilter = gl.LINEAR;
  17. if (generateMipMaps) {
  18. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  19. } else {
  20. minFilter = gl.LINEAR;
  21. }
  22. break;
  23. case Texture.TRILINEAR_SAMPLINGMODE:
  24. magFilter = gl.LINEAR;
  25. if (generateMipMaps) {
  26. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  27. } else {
  28. minFilter = gl.LINEAR;
  29. }
  30. break;
  31. case Texture.NEAREST_SAMPLINGMODE:
  32. magFilter = gl.NEAREST;
  33. if (generateMipMaps) {
  34. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  35. } else {
  36. minFilter = gl.NEAREST;
  37. }
  38. break;
  39. case Texture.NEAREST_NEAREST_MIPNEAREST:
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  43. } else {
  44. minFilter = gl.NEAREST;
  45. }
  46. break;
  47. case Texture.NEAREST_LINEAR_MIPNEAREST:
  48. magFilter = gl.NEAREST;
  49. if (generateMipMaps) {
  50. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  51. } else {
  52. minFilter = gl.LINEAR;
  53. }
  54. break;
  55. case Texture.NEAREST_LINEAR_MIPLINEAR:
  56. magFilter = gl.NEAREST;
  57. if (generateMipMaps) {
  58. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  59. } else {
  60. minFilter = gl.LINEAR;
  61. }
  62. break;
  63. case Texture.NEAREST_LINEAR:
  64. magFilter = gl.NEAREST;
  65. minFilter = gl.LINEAR;
  66. break;
  67. case Texture.NEAREST_NEAREST:
  68. magFilter = gl.NEAREST;
  69. minFilter = gl.NEAREST;
  70. break;
  71. case Texture.LINEAR_NEAREST_MIPNEAREST:
  72. magFilter = gl.LINEAR;
  73. if (generateMipMaps) {
  74. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  75. } else {
  76. minFilter = gl.NEAREST;
  77. }
  78. break;
  79. case Texture.LINEAR_NEAREST_MIPLINEAR:
  80. magFilter = gl.LINEAR;
  81. if (generateMipMaps) {
  82. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  83. } else {
  84. minFilter = gl.NEAREST;
  85. }
  86. break;
  87. case Texture.LINEAR_LINEAR:
  88. magFilter = gl.LINEAR;
  89. minFilter = gl.LINEAR;
  90. break;
  91. case Texture.LINEAR_NEAREST:
  92. magFilter = gl.LINEAR;
  93. minFilter = gl.NEAREST;
  94. break;
  95. }
  96. return {
  97. min: minFilter,
  98. mag: magFilter
  99. }
  100. }
  101. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  102. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  103. var img: HTMLImageElement;
  104. var onload = () => {
  105. loadedImages[index] = img;
  106. loadedImages._internalCount++;
  107. if (scene) {
  108. scene._removePendingData(img);
  109. }
  110. if (loadedImages._internalCount === 6) {
  111. onfinish(loadedImages);
  112. }
  113. };
  114. var onerror = () => {
  115. if (scene) {
  116. scene._removePendingData(img);
  117. }
  118. if (onErrorCallBack) {
  119. onErrorCallBack();
  120. }
  121. };
  122. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  123. if (scene) {
  124. scene._addPendingData(img);
  125. }
  126. }
  127. var cascadeLoad = (rootUrl: string, scene,
  128. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  129. var loadedImages: any = [];
  130. loadedImages._internalCount = 0;
  131. for (var index = 0; index < 6; index++) {
  132. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  133. }
  134. };
  135. class BufferPointer {
  136. public active: boolean;
  137. public index: number;
  138. public size: number;
  139. public type: number;
  140. public normalized: boolean;
  141. public stride: number;
  142. public offset: number;
  143. public buffer: WebGLBuffer;
  144. }
  145. export class InstancingAttributeInfo {
  146. /**
  147. * Index/offset of the attribute in the vertex shader
  148. */
  149. index: number;
  150. /**
  151. * size of the attribute, 1, 2, 3 or 4
  152. */
  153. attributeSize: number;
  154. /**
  155. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  156. * default is FLOAT
  157. */
  158. attribyteType: number;
  159. /**
  160. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  161. */
  162. normalized: boolean;
  163. /**
  164. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  165. */
  166. offset: number;
  167. /**
  168. * Name of the GLSL attribute, for debugging purpose only
  169. */
  170. attributeName: string;
  171. }
  172. /**
  173. * Define options used to create a render target texture
  174. */
  175. export class RenderTargetCreationOptions {
  176. generateMipMaps?: boolean;
  177. generateDepthBuffer?: boolean;
  178. generateStencilBuffer?: boolean;
  179. type?: number;
  180. samplingMode?: number;
  181. }
  182. /**
  183. * Regroup several parameters relative to the browser in use
  184. */
  185. export class EngineCapabilities {
  186. /** The maximum textures image */
  187. public maxTexturesImageUnits: number;
  188. public maxVertexTextureImageUnits: number;
  189. /** The maximum texture size */
  190. public maxTextureSize: number;
  191. public maxCubemapTextureSize: number;
  192. public maxRenderTextureSize: number;
  193. public maxVertexAttribs: number;
  194. public maxVaryingVectors: number;
  195. public maxVertexUniformVectors: number;
  196. public maxFragmentUniformVectors: number;
  197. public standardDerivatives: boolean;
  198. public s3tc: WEBGL_compressed_texture_s3tc;
  199. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  200. public etc1: any; //WEBGL_compressed_texture_etc1;
  201. public etc2: any; //WEBGL_compressed_texture_etc;
  202. public astc: any; //WEBGL_compressed_texture_astc;
  203. public textureFloat: boolean;
  204. public vertexArrayObject: boolean;
  205. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  206. public maxAnisotropy: number;
  207. public instancedArrays: boolean;
  208. public uintIndices: boolean;
  209. public highPrecisionShaderSupported: boolean;
  210. public fragmentDepthSupported: boolean;
  211. public textureFloatLinearFiltering: boolean;
  212. public textureFloatRender: boolean;
  213. public textureHalfFloat: boolean;
  214. public textureHalfFloatLinearFiltering: boolean;
  215. public textureHalfFloatRender: boolean;
  216. public textureLOD: boolean;
  217. public drawBuffersExtension;
  218. public colorBufferFloat: boolean;
  219. }
  220. export interface EngineOptions extends WebGLContextAttributes {
  221. limitDeviceRatio?: number;
  222. autoEnableWebVR?: boolean;
  223. disableWebGL2Support?: boolean;
  224. audioEngine?: boolean;
  225. deterministicLockstep?: boolean;
  226. lockstepMaxSteps?: number;
  227. doNotHandleContextLost?: boolean;
  228. }
  229. /**
  230. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  231. */
  232. export class Engine {
  233. public static Instances = new Array<Engine>();
  234. public static get LastCreatedEngine(): Engine {
  235. if (Engine.Instances.length === 0) {
  236. return null;
  237. }
  238. return Engine.Instances[Engine.Instances.length - 1];
  239. }
  240. public static get LastCreatedScene(): Scene {
  241. var lastCreatedEngine = Engine.LastCreatedEngine;
  242. if (!lastCreatedEngine) {
  243. return null;
  244. }
  245. if (lastCreatedEngine.scenes.length === 0) {
  246. return null;
  247. }
  248. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  249. }
  250. /**
  251. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  252. */
  253. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  254. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  255. var engine = Engine.Instances[engineIndex];
  256. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  257. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  258. }
  259. }
  260. }
  261. // Const statics
  262. private static _ALPHA_DISABLE = 0;
  263. private static _ALPHA_ADD = 1;
  264. private static _ALPHA_COMBINE = 2;
  265. private static _ALPHA_SUBTRACT = 3;
  266. private static _ALPHA_MULTIPLY = 4;
  267. private static _ALPHA_MAXIMIZED = 5;
  268. private static _ALPHA_ONEONE = 6;
  269. private static _ALPHA_PREMULTIPLIED = 7;
  270. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  271. private static _ALPHA_INTERPOLATE = 9;
  272. private static _ALPHA_SCREENMODE = 10;
  273. private static _DELAYLOADSTATE_NONE = 0;
  274. private static _DELAYLOADSTATE_LOADED = 1;
  275. private static _DELAYLOADSTATE_LOADING = 2;
  276. private static _DELAYLOADSTATE_NOTLOADED = 4;
  277. private static _TEXTUREFORMAT_ALPHA = 0;
  278. private static _TEXTUREFORMAT_LUMINANCE = 1;
  279. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  280. private static _TEXTUREFORMAT_RGB = 4;
  281. private static _TEXTUREFORMAT_RGBA = 5;
  282. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  283. private static _TEXTURETYPE_FLOAT = 1;
  284. private static _TEXTURETYPE_HALF_FLOAT = 2;
  285. // Depht or Stencil test Constants.
  286. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  287. private static _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.
  288. private static _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.
  289. private static _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.
  290. private static _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.
  291. private static _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.
  292. private static _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.
  293. private static _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.
  294. public static get NEVER(): number {
  295. return Engine._NEVER;
  296. }
  297. public static get ALWAYS(): number {
  298. return Engine._ALWAYS;
  299. }
  300. public static get LESS(): number {
  301. return Engine._LESS;
  302. }
  303. public static get EQUAL(): number {
  304. return Engine._EQUAL;
  305. }
  306. public static get LEQUAL(): number {
  307. return Engine._LEQUAL;
  308. }
  309. public static get GREATER(): number {
  310. return Engine._GREATER;
  311. }
  312. public static get GEQUAL(): number {
  313. return Engine._GEQUAL;
  314. }
  315. public static get NOTEQUAL(): number {
  316. return Engine._NOTEQUAL;
  317. }
  318. // Stencil Actions Constants.
  319. private static _KEEP = 0x1E00;
  320. private static _REPLACE = 0x1E01;
  321. private static _INCR = 0x1E02;
  322. private static _DECR = 0x1E03;
  323. private static _INVERT = 0x150A;
  324. private static _INCR_WRAP = 0x8507;
  325. private static _DECR_WRAP = 0x8508;
  326. public static get KEEP(): number {
  327. return Engine._KEEP;
  328. }
  329. public static get REPLACE(): number {
  330. return Engine._REPLACE;
  331. }
  332. public static get INCR(): number {
  333. return Engine._INCR;
  334. }
  335. public static get DECR(): number {
  336. return Engine._DECR;
  337. }
  338. public static get INVERT(): number {
  339. return Engine._INVERT;
  340. }
  341. public static get INCR_WRAP(): number {
  342. return Engine._INCR_WRAP;
  343. }
  344. public static get DECR_WRAP(): number {
  345. return Engine._DECR_WRAP;
  346. }
  347. public static get ALPHA_DISABLE(): number {
  348. return Engine._ALPHA_DISABLE;
  349. }
  350. public static get ALPHA_ONEONE(): number {
  351. return Engine._ALPHA_ONEONE;
  352. }
  353. public static get ALPHA_ADD(): number {
  354. return Engine._ALPHA_ADD;
  355. }
  356. public static get ALPHA_COMBINE(): number {
  357. return Engine._ALPHA_COMBINE;
  358. }
  359. public static get ALPHA_SUBTRACT(): number {
  360. return Engine._ALPHA_SUBTRACT;
  361. }
  362. public static get ALPHA_MULTIPLY(): number {
  363. return Engine._ALPHA_MULTIPLY;
  364. }
  365. public static get ALPHA_MAXIMIZED(): number {
  366. return Engine._ALPHA_MAXIMIZED;
  367. }
  368. public static get ALPHA_PREMULTIPLIED(): number {
  369. return Engine._ALPHA_PREMULTIPLIED;
  370. }
  371. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  372. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  373. }
  374. public static get ALPHA_INTERPOLATE(): number {
  375. return Engine._ALPHA_INTERPOLATE;
  376. }
  377. public static get ALPHA_SCREENMODE(): number {
  378. return Engine._ALPHA_SCREENMODE;
  379. }
  380. public static get DELAYLOADSTATE_NONE(): number {
  381. return Engine._DELAYLOADSTATE_NONE;
  382. }
  383. public static get DELAYLOADSTATE_LOADED(): number {
  384. return Engine._DELAYLOADSTATE_LOADED;
  385. }
  386. public static get DELAYLOADSTATE_LOADING(): number {
  387. return Engine._DELAYLOADSTATE_LOADING;
  388. }
  389. public static get DELAYLOADSTATE_NOTLOADED(): number {
  390. return Engine._DELAYLOADSTATE_NOTLOADED;
  391. }
  392. public static get TEXTUREFORMAT_ALPHA(): number {
  393. return Engine._TEXTUREFORMAT_ALPHA;
  394. }
  395. public static get TEXTUREFORMAT_LUMINANCE(): number {
  396. return Engine._TEXTUREFORMAT_LUMINANCE;
  397. }
  398. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  399. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  400. }
  401. public static get TEXTUREFORMAT_RGB(): number {
  402. return Engine._TEXTUREFORMAT_RGB;
  403. }
  404. public static get TEXTUREFORMAT_RGBA(): number {
  405. return Engine._TEXTUREFORMAT_RGBA;
  406. }
  407. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  408. return Engine._TEXTURETYPE_UNSIGNED_INT;
  409. }
  410. public static get TEXTURETYPE_FLOAT(): number {
  411. return Engine._TEXTURETYPE_FLOAT;
  412. }
  413. public static get TEXTURETYPE_HALF_FLOAT(): number {
  414. return Engine._TEXTURETYPE_HALF_FLOAT;
  415. }
  416. // Texture rescaling mode
  417. private static _SCALEMODE_FLOOR = 1;
  418. private static _SCALEMODE_NEAREST = 2;
  419. private static _SCALEMODE_CEILING = 3;
  420. public static get SCALEMODE_FLOOR(): number {
  421. return Engine._SCALEMODE_FLOOR;
  422. }
  423. public static get SCALEMODE_NEAREST(): number {
  424. return Engine._SCALEMODE_NEAREST;
  425. }
  426. public static get SCALEMODE_CEILING(): number {
  427. return Engine._SCALEMODE_CEILING;
  428. }
  429. public static get Version(): string {
  430. return "3.1-alpha";
  431. }
  432. // Updatable statics so stick with vars here
  433. public static CollisionsEpsilon = 0.001;
  434. public static CodeRepository = "src/";
  435. public static ShadersRepository = "src/Shaders/";
  436. // Public members
  437. public forcePOTTextures = false;
  438. public isFullscreen = false;
  439. public isPointerLock = false;
  440. public cullBackFaces = true;
  441. public renderEvenInBackground = true;
  442. public preventCacheWipeBetweenFrames = false;
  443. // To enable/disable IDB support and avoid XHR on .manifest
  444. public enableOfflineSupport = false;
  445. public scenes = new Array<Scene>();
  446. public postProcesses = new Array<PostProcess>();
  447. // Observables
  448. /**
  449. * Observable event triggered each time the rendering canvas is resized
  450. */
  451. public onResizeObservable = new Observable<Engine>();
  452. /**
  453. * Observable event triggered each time the canvas lost focus
  454. */
  455. public onCanvasBlurObservable = new Observable<Engine>();
  456. //WebVR
  457. //The new WebVR uses promises.
  458. //this promise resolves with the current devices available.
  459. public vrDisplaysPromise;
  460. private _vrDisplays;
  461. private _vrDisplayEnabled;
  462. private _oldSize: BABYLON.Size;
  463. private _oldHardwareScaleFactor: number;
  464. private _vrAnimationFrameHandler: number;
  465. // Uniform buffers list
  466. public _uniformBuffers = new Array<UniformBuffer>();
  467. // Private Members
  468. private _gl: WebGLRenderingContext;
  469. private _renderingCanvas: HTMLCanvasElement;
  470. private _windowIsBackground = false;
  471. private _webGLVersion = 1.0;
  472. public get needPOTTextures(): boolean {
  473. return this._webGLVersion < 2 || this.forcePOTTextures;
  474. }
  475. private _badOS = false;
  476. public get badOS(): boolean {
  477. return this._badOS;
  478. }
  479. private _badDesktopOS = false;
  480. public get badDesktopOS(): boolean {
  481. return this._badDesktopOS;
  482. }
  483. public static audioEngine: AudioEngine;
  484. private _onCanvasBlur: () => void;
  485. private _onBlur: () => void;
  486. private _onFocus: () => void;
  487. private _onFullscreenChange: () => void;
  488. private _onPointerLockChange: () => void;
  489. private _onVRDisplayPointerRestricted: () => void;
  490. private _onVRDisplayPointerUnrestricted: () => void;
  491. private _hardwareScalingLevel: number;
  492. private _caps: EngineCapabilities;
  493. private _pointerLockRequested: boolean;
  494. private _alphaTest: boolean;
  495. private _isStencilEnable: boolean;
  496. private _loadingScreen: ILoadingScreen;
  497. public _drawCalls = new PerfCounter();
  498. private _glVersion: string;
  499. private _glRenderer: string;
  500. private _glVendor: string;
  501. private _videoTextureSupported: boolean;
  502. private _renderingQueueLaunched = false;
  503. private _activeRenderLoops = [];
  504. // Deterministic lockstepMaxSteps
  505. private _deterministicLockstep: boolean = false;
  506. private _lockstepMaxSteps: number = 4;
  507. // Lost context
  508. private _onContextLost: (evt: Event) => void;
  509. private _onContextRestored: (evt: Event) => void;
  510. private _contextWasLost = false;
  511. private _doNotHandleContextLost = false;
  512. // FPS
  513. private _performanceMonitor = new PerformanceMonitor();
  514. private _fps = 60;
  515. private _deltaTime = 0;
  516. /**
  517. * Turn this value on if you want to pause FPS computation when in background
  518. */
  519. public disablePerformanceMonitorInBackground = false;
  520. public get performanceMonitor(): PerformanceMonitor {
  521. return this._performanceMonitor;
  522. }
  523. // States
  524. private _depthCullingState = new Internals._DepthCullingState();
  525. private _stencilState = new Internals._StencilState();
  526. private _alphaState = new Internals._AlphaState();
  527. private _alphaMode = Engine.ALPHA_DISABLE;
  528. // Cache
  529. private _internalTexturesCache = new Array<InternalTexture>();
  530. private _maxTextureChannels = 16;
  531. private _activeTexture: number;
  532. private _activeTexturesCache: { [key: string]: WebGLTexture } = {};
  533. private _currentEffect: Effect;
  534. private _currentProgram: WebGLProgram;
  535. private _compiledEffects = {};
  536. private _vertexAttribArraysEnabled: boolean[] = [];
  537. private _cachedViewport: Viewport;
  538. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  539. private _cachedVertexBuffers: any;
  540. private _cachedIndexBuffer: WebGLBuffer;
  541. private _cachedEffectForVertexBuffers: Effect;
  542. private _currentRenderTarget: InternalTexture;
  543. private _uintIndicesCurrentlySet = false;
  544. private _currentBoundBuffer = new Array<WebGLBuffer>();
  545. private _currentFramebuffer: WebGLFramebuffer;
  546. private _currentBufferPointers = new Array<BufferPointer>();
  547. private _currentInstanceLocations = new Array<number>();
  548. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  549. private _textureUnits: Int32Array;
  550. private _workingCanvas: HTMLCanvasElement;
  551. private _workingContext: CanvasRenderingContext2D;
  552. private _rescalePostProcess: PassPostProcess;
  553. private _dummyFramebuffer: WebGLFramebuffer;
  554. private _externalData: StringDictionary<Object>;
  555. private _bindedRenderFunction: any;
  556. private _vaoRecordInProgress = false;
  557. private _mustWipeVertexAttributes = false;
  558. private _emptyTexture: InternalTexture;
  559. private _emptyCubeTexture: InternalTexture;
  560. // Hardware supported Compressed Textures
  561. private _texturesSupported = new Array<string>();
  562. private _textureFormatInUse: string;
  563. public get texturesSupported(): Array<string> {
  564. return this._texturesSupported;
  565. }
  566. public get textureFormatInUse(): string {
  567. return this._textureFormatInUse;
  568. }
  569. // Empty texture
  570. public get emptyTexture(): InternalTexture {
  571. if (!this._emptyTexture) {
  572. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  573. }
  574. return this._emptyTexture;
  575. }
  576. public get emptyCubeTexture(): InternalTexture {
  577. if (!this._emptyCubeTexture) {
  578. var faceData = new Uint8Array(4);
  579. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  580. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  581. }
  582. return this._emptyCubeTexture;
  583. }
  584. /**
  585. * @constructor
  586. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  587. * @param {boolean} [antialias] - enable antialias
  588. * @param options - further options to be sent to the getContext function
  589. */
  590. constructor(canvasOrContext: HTMLCanvasElement | WebGLRenderingContext, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  591. var canvas: HTMLCanvasElement;
  592. Engine.Instances.push(this);
  593. options = options || {};
  594. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  595. canvas = <HTMLCanvasElement>canvasOrContext;
  596. this._renderingCanvas = canvas;
  597. if (antialias != null) {
  598. options.antialias = antialias;
  599. }
  600. if (options.deterministicLockstep === undefined) {
  601. options.deterministicLockstep = false;
  602. }
  603. if (options.lockstepMaxSteps === undefined) {
  604. options.lockstepMaxSteps = 4;
  605. }
  606. if (options.preserveDrawingBuffer === undefined) {
  607. options.preserveDrawingBuffer = false;
  608. }
  609. if (options.audioEngine === undefined) {
  610. options.audioEngine = true;
  611. }
  612. if (options.stencil === undefined) {
  613. options.stencil = true;
  614. }
  615. this._deterministicLockstep = options.deterministicLockstep;
  616. this._lockstepMaxSteps = options.lockstepMaxSteps;
  617. this._doNotHandleContextLost = options.doNotHandleContextLost;
  618. // GL
  619. if (!options.disableWebGL2Support) {
  620. try {
  621. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  622. if (this._gl) {
  623. this._webGLVersion = 2.0;
  624. }
  625. } catch (e) {
  626. // Do nothing
  627. }
  628. }
  629. if (!this._gl) {
  630. if (!canvas) {
  631. throw new Error("The provided canvas is null or undefined.");
  632. }
  633. try {
  634. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  635. } catch (e) {
  636. throw new Error("WebGL not supported");
  637. }
  638. }
  639. if (!this._gl) {
  640. throw new Error("WebGL not supported");
  641. }
  642. this._onBlur = () => {
  643. if (this.disablePerformanceMonitorInBackground) {
  644. this._performanceMonitor.disable();
  645. }
  646. this._windowIsBackground = true;
  647. };
  648. this._onFocus = () => {
  649. if (this.disablePerformanceMonitorInBackground) {
  650. this._performanceMonitor.enable();
  651. }
  652. this._windowIsBackground = false;
  653. };
  654. this._onCanvasBlur = () => {
  655. this.onCanvasBlurObservable.notifyObservers(this);
  656. };
  657. window.addEventListener("blur", this._onBlur);
  658. window.addEventListener("focus", this._onFocus);
  659. canvas.addEventListener("pointerout", this._onCanvasBlur);
  660. } else {
  661. this._gl = <WebGLRenderingContext>canvasOrContext;
  662. this._renderingCanvas = this._gl.canvas
  663. if (this._gl.renderbufferStorageMultisample) {
  664. this._webGLVersion = 2.0;
  665. }
  666. options.stencil = this._gl.getContextAttributes().stencil;
  667. }
  668. // Context lost
  669. if (!this._doNotHandleContextLost) {
  670. this._onContextLost = (evt: Event) => {
  671. evt.preventDefault();
  672. this._contextWasLost = true;
  673. Tools.Warn("WebGL context lost.");
  674. };
  675. this._onContextRestored = (evt: Event) => {
  676. // Rebuild gl context
  677. this._initGLContext();
  678. // Rebuild effects
  679. this._rebuildEffects();
  680. // Rebuild textures
  681. this._rebuildInternalTextures();
  682. // Rebuild buffers
  683. this._rebuildBuffers();
  684. // Cache
  685. this.wipeCaches(true);
  686. Tools.Warn("WebGL context successfully restored.");
  687. this._contextWasLost = false;
  688. };
  689. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  690. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  691. }
  692. // Viewport
  693. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  694. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  695. this.resize();
  696. this._isStencilEnable = options.stencil;
  697. this._initGLContext();
  698. if (canvas) {
  699. // Fullscreen
  700. this._onFullscreenChange = () => {
  701. if (document.fullscreen !== undefined) {
  702. this.isFullscreen = document.fullscreen;
  703. } else if (document.mozFullScreen !== undefined) {
  704. this.isFullscreen = document.mozFullScreen;
  705. } else if (document.webkitIsFullScreen !== undefined) {
  706. this.isFullscreen = document.webkitIsFullScreen;
  707. } else if (document.msIsFullScreen !== undefined) {
  708. this.isFullscreen = document.msIsFullScreen;
  709. }
  710. // Pointer lock
  711. if (this.isFullscreen && this._pointerLockRequested) {
  712. canvas.requestPointerLock = canvas.requestPointerLock ||
  713. canvas.msRequestPointerLock ||
  714. canvas.mozRequestPointerLock ||
  715. canvas.webkitRequestPointerLock;
  716. if (canvas.requestPointerLock) {
  717. canvas.requestPointerLock();
  718. }
  719. }
  720. };
  721. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  722. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  723. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  724. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  725. // Pointer lock
  726. this._onPointerLockChange = () => {
  727. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  728. document.webkitPointerLockElement === canvas ||
  729. document.msPointerLockElement === canvas ||
  730. document.pointerLockElement === canvas
  731. );
  732. };
  733. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  734. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  735. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  736. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  737. this._onVRDisplayPointerRestricted = () => {
  738. canvas.requestPointerLock();
  739. }
  740. this._onVRDisplayPointerUnrestricted = () => {
  741. document.exitPointerLock();
  742. }
  743. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  744. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  745. }
  746. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  747. Engine.audioEngine = new AudioEngine();
  748. }
  749. // Prepare buffer pointers
  750. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  751. this._currentBufferPointers[i] = new BufferPointer();
  752. }
  753. // Load WebVR Devices
  754. if (options.autoEnableWebVR) {
  755. this.initWebVR();
  756. }
  757. // Detect if we are running on a faulty buggy OS.
  758. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  759. // Detect if we are running on a faulty buggy desktop OS.
  760. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  761. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  762. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  763. }
  764. private _rebuildInternalTextures(): void {
  765. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  766. for (var internalTexture of currentState) {
  767. internalTexture._rebuild();
  768. }
  769. }
  770. private _rebuildEffects(): void {
  771. for (var key in this._compiledEffects) {
  772. let effect = <Effect>this._compiledEffects[key];
  773. effect._prepareEffect();
  774. }
  775. Effect.ResetCache();
  776. }
  777. private _rebuildBuffers(): void {
  778. // Index / Vertex
  779. for (var scene of this.scenes) {
  780. scene.resetCachedMaterial();
  781. scene._rebuildGeometries();
  782. scene._rebuildTextures();
  783. }
  784. for (var postprocess of this.postProcesses) {
  785. postprocess._rebuild();
  786. }
  787. // Uniforms
  788. for (var uniformBuffer of this._uniformBuffers) {
  789. uniformBuffer._rebuild();
  790. }
  791. }
  792. private _initGLContext(): void {
  793. // Caps
  794. this._caps = new EngineCapabilities();
  795. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  796. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  797. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  798. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  799. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  800. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  801. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  802. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  803. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  804. // Infos
  805. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  806. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  807. if (rendererInfo != null) {
  808. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  809. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  810. }
  811. if (!this._glVendor) {
  812. this._glVendor = "Unknown vendor";
  813. }
  814. if (!this._glRenderer) {
  815. this._glRenderer = "Unknown renderer";
  816. }
  817. // Constants
  818. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  819. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  820. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  821. this._gl.DEPTH24_STENCIL8 = 35056;
  822. // Extensions
  823. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  824. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  825. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  826. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  827. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  828. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  829. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  830. 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');
  831. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  832. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  833. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  834. this._caps.highPrecisionShaderSupported = true;
  835. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  836. // Checks if some of the format renders first to allow the use of webgl inspector.
  837. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  838. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  839. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  840. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  841. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  842. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  843. if (this._webGLVersion > 1) {
  844. this._gl.HALF_FLOAT_OES = 0x140B;
  845. }
  846. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  847. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  848. // Vertex array object
  849. if (this._webGLVersion > 1) {
  850. this._caps.vertexArrayObject = true;
  851. } else {
  852. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  853. if (vertexArrayObjectExtension != null) {
  854. this._caps.vertexArrayObject = true;
  855. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  856. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  857. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  858. } else {
  859. this._caps.vertexArrayObject = false;
  860. }
  861. }
  862. // Instances count
  863. if (this._webGLVersion > 1) {
  864. this._caps.instancedArrays = true;
  865. } else {
  866. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  867. if (instanceExtension != null) {
  868. this._caps.instancedArrays = true;
  869. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  870. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  871. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  872. } else {
  873. this._caps.instancedArrays = false;
  874. }
  875. }
  876. // Intelligently add supported compressed formats in order to check for.
  877. // Check for ASTC support first as it is most powerful and to be very cross platform.
  878. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  879. // Likely no hardware which supports both PVR & DXT, so order matters little.
  880. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  881. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  882. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  883. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  884. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  885. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  886. if (this._gl.getShaderPrecisionFormat) {
  887. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  888. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  889. }
  890. // Depth buffer
  891. this.setDepthBuffer(true);
  892. this.setDepthFunctionToLessOrEqual();
  893. this.setDepthWrite(true);
  894. }
  895. public get webGLVersion(): number {
  896. return this._webGLVersion;
  897. }
  898. /**
  899. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  900. */
  901. public get isStencilEnable(): boolean {
  902. return this._isStencilEnable;
  903. }
  904. private _prepareWorkingCanvas(): void {
  905. if (this._workingCanvas) {
  906. return;
  907. }
  908. this._workingCanvas = document.createElement("canvas");
  909. this._workingContext = this._workingCanvas.getContext("2d");
  910. }
  911. public resetTextureCache() {
  912. for (var key in this._activeTexturesCache) {
  913. this._activeTexturesCache[key] = null;
  914. }
  915. }
  916. public isDeterministicLockStep(): boolean {
  917. return this._deterministicLockstep;
  918. }
  919. public getLockstepMaxSteps(): number {
  920. return this._lockstepMaxSteps;
  921. }
  922. public getGlInfo() {
  923. return {
  924. vendor: this._glVendor,
  925. renderer: this._glRenderer,
  926. version: this._glVersion
  927. }
  928. }
  929. public getAspectRatio(camera: Camera, useScreen = false): number {
  930. var viewport = camera.viewport;
  931. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  932. }
  933. public getRenderWidth(useScreen = false): number {
  934. if (!useScreen && this._currentRenderTarget) {
  935. return this._currentRenderTarget.width;
  936. }
  937. return this._gl.drawingBufferWidth;
  938. }
  939. public getRenderHeight(useScreen = false): number {
  940. if (!useScreen && this._currentRenderTarget) {
  941. return this._currentRenderTarget.height;
  942. }
  943. return this._gl.drawingBufferHeight;
  944. }
  945. public getRenderingCanvas(): HTMLCanvasElement {
  946. return this._renderingCanvas;
  947. }
  948. public getRenderingCanvasClientRect(): ClientRect {
  949. return this._renderingCanvas.getBoundingClientRect();
  950. }
  951. public setHardwareScalingLevel(level: number): void {
  952. this._hardwareScalingLevel = level;
  953. this.resize();
  954. }
  955. public getHardwareScalingLevel(): number {
  956. return this._hardwareScalingLevel;
  957. }
  958. public getLoadedTexturesCache(): InternalTexture[] {
  959. return this._internalTexturesCache;
  960. }
  961. public getCaps(): EngineCapabilities {
  962. return this._caps;
  963. }
  964. /** The number of draw calls submitted last frame */
  965. public get drawCalls(): number {
  966. return this._drawCalls.current;
  967. }
  968. public get drawCallsPerfCounter(): PerfCounter {
  969. return this._drawCalls;
  970. }
  971. public getDepthFunction(): number {
  972. return this._depthCullingState.depthFunc;
  973. }
  974. public setDepthFunction(depthFunc: number) {
  975. this._depthCullingState.depthFunc = depthFunc;
  976. }
  977. public setDepthFunctionToGreater(): void {
  978. this._depthCullingState.depthFunc = this._gl.GREATER;
  979. }
  980. public setDepthFunctionToGreaterOrEqual(): void {
  981. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  982. }
  983. public setDepthFunctionToLess(): void {
  984. this._depthCullingState.depthFunc = this._gl.LESS;
  985. }
  986. public setDepthFunctionToLessOrEqual(): void {
  987. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  988. }
  989. public getStencilBuffer(): boolean {
  990. return this._stencilState.stencilTest;
  991. }
  992. public setStencilBuffer(enable: boolean): void {
  993. this._stencilState.stencilTest = enable;
  994. }
  995. public getStencilMask(): number {
  996. return this._stencilState.stencilMask;
  997. }
  998. public setStencilMask(mask: number): void {
  999. this._stencilState.stencilMask = mask;
  1000. }
  1001. public getStencilFunction(): number {
  1002. return this._stencilState.stencilFunc;
  1003. }
  1004. public getStencilFunctionReference(): number {
  1005. return this._stencilState.stencilFuncRef;
  1006. }
  1007. public getStencilFunctionMask(): number {
  1008. return this._stencilState.stencilFuncMask;
  1009. }
  1010. public setStencilFunction(stencilFunc: number) {
  1011. this._stencilState.stencilFunc = stencilFunc;
  1012. }
  1013. public setStencilFunctionReference(reference: number) {
  1014. this._stencilState.stencilFuncRef = reference;
  1015. }
  1016. public setStencilFunctionMask(mask: number) {
  1017. this._stencilState.stencilFuncMask = mask;
  1018. }
  1019. public getStencilOperationFail(): number {
  1020. return this._stencilState.stencilOpStencilFail;
  1021. }
  1022. public getStencilOperationDepthFail(): number {
  1023. return this._stencilState.stencilOpDepthFail;
  1024. }
  1025. public getStencilOperationPass(): number {
  1026. return this._stencilState.stencilOpStencilDepthPass;
  1027. }
  1028. public setStencilOperationFail(operation: number): void {
  1029. this._stencilState.stencilOpStencilFail = operation;
  1030. }
  1031. public setStencilOperationDepthFail(operation: number): void {
  1032. this._stencilState.stencilOpDepthFail = operation;
  1033. }
  1034. public setStencilOperationPass(operation: number): void {
  1035. this._stencilState.stencilOpStencilDepthPass = operation;
  1036. }
  1037. public setDitheringState(value: boolean): void {
  1038. if (value) {
  1039. this._gl.enable(this._gl.DITHER);
  1040. } else {
  1041. this._gl.disable(this._gl.DITHER);
  1042. }
  1043. }
  1044. /**
  1045. * stop executing a render loop function and remove it from the execution array
  1046. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1047. */
  1048. public stopRenderLoop(renderFunction?: () => void): void {
  1049. if (!renderFunction) {
  1050. this._activeRenderLoops = [];
  1051. return;
  1052. }
  1053. var index = this._activeRenderLoops.indexOf(renderFunction);
  1054. if (index >= 0) {
  1055. this._activeRenderLoops.splice(index, 1);
  1056. }
  1057. }
  1058. public _renderLoop(): void {
  1059. if (this._contextWasLost) {
  1060. return;
  1061. }
  1062. var shouldRender = true;
  1063. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1064. shouldRender = false;
  1065. }
  1066. if (shouldRender) {
  1067. // Start new frame
  1068. this.beginFrame();
  1069. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1070. var renderFunction = this._activeRenderLoops[index];
  1071. renderFunction();
  1072. }
  1073. // Present
  1074. this.endFrame();
  1075. }
  1076. if (this._activeRenderLoops.length > 0) {
  1077. // Register new frame
  1078. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  1079. } else {
  1080. this._renderingQueueLaunched = false;
  1081. }
  1082. }
  1083. /**
  1084. * Register and execute a render loop. The engine can have more than one render function.
  1085. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1086. * @example
  1087. * engine.runRenderLoop(function () {
  1088. * scene.render()
  1089. * })
  1090. */
  1091. public runRenderLoop(renderFunction: () => void): void {
  1092. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1093. return;
  1094. }
  1095. this._activeRenderLoops.push(renderFunction);
  1096. if (!this._renderingQueueLaunched) {
  1097. this._renderingQueueLaunched = true;
  1098. this._bindedRenderFunction = this._renderLoop.bind(this);
  1099. Tools.QueueNewFrame(this._bindedRenderFunction);
  1100. }
  1101. }
  1102. /**
  1103. * Toggle full screen mode.
  1104. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1105. * @param {any} options - an options object to be sent to the requestFullscreen function
  1106. */
  1107. public switchFullscreen(requestPointerLock: boolean): void {
  1108. if (this.isFullscreen) {
  1109. Tools.ExitFullscreen();
  1110. } else {
  1111. this._pointerLockRequested = requestPointerLock;
  1112. Tools.RequestFullscreen(this._renderingCanvas);
  1113. }
  1114. }
  1115. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1116. this.applyStates();
  1117. var mode = 0;
  1118. if (backBuffer && color) {
  1119. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1120. mode |= this._gl.COLOR_BUFFER_BIT;
  1121. }
  1122. if (depth) {
  1123. this._gl.clearDepth(1.0);
  1124. mode |= this._gl.DEPTH_BUFFER_BIT;
  1125. }
  1126. if (stencil) {
  1127. this._gl.clearStencil(0);
  1128. mode |= this._gl.STENCIL_BUFFER_BIT;
  1129. }
  1130. this._gl.clear(mode);
  1131. }
  1132. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1133. let gl = this._gl;
  1134. // Save state
  1135. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1136. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1137. // Change state
  1138. gl.enable(gl.SCISSOR_TEST);
  1139. gl.scissor(x, y, width, height);
  1140. // Clear
  1141. this.clear(clearColor, true, true, true);
  1142. // Restore state
  1143. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1144. if (curScissor === true) {
  1145. gl.enable(gl.SCISSOR_TEST);
  1146. } else {
  1147. gl.disable(gl.SCISSOR_TEST);
  1148. }
  1149. }
  1150. /**
  1151. * Set the WebGL's viewport
  1152. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1153. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1154. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1155. */
  1156. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1157. var width = requiredWidth || this.getRenderWidth();
  1158. var height = requiredHeight || this.getRenderHeight();
  1159. var x = viewport.x || 0;
  1160. var y = viewport.y || 0;
  1161. this._cachedViewport = viewport;
  1162. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1163. }
  1164. /**
  1165. * Directly set the WebGL Viewport
  1166. * The x, y, width & height are directly passed to the WebGL call
  1167. * @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.
  1168. */
  1169. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  1170. let currentViewport = this._cachedViewport;
  1171. this._cachedViewport = null;
  1172. this._gl.viewport(x, y, width, height);
  1173. return currentViewport;
  1174. }
  1175. public beginFrame(): void {
  1176. this._measureFps();
  1177. }
  1178. public endFrame(): void {
  1179. //force a flush in case we are using a bad OS.
  1180. if (this._badOS) {
  1181. this.flushFramebuffer();
  1182. }
  1183. //submit frame to the vr device, if enabled
  1184. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1185. this._vrDisplayEnabled.submitFrame()
  1186. }
  1187. }
  1188. /**
  1189. * resize the view according to the canvas' size.
  1190. * @example
  1191. * window.addEventListener("resize", function () {
  1192. * engine.resize();
  1193. * });
  1194. */
  1195. public resize(): void {
  1196. // We're not resizing the size of the canvas while in VR mode & presenting
  1197. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  1198. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  1199. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  1200. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1201. }
  1202. }
  1203. /**
  1204. * force a specific size of the canvas
  1205. * @param {number} width - the new canvas' width
  1206. * @param {number} height - the new canvas' height
  1207. */
  1208. public setSize(width: number, height: number): void {
  1209. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1210. return;
  1211. }
  1212. this._renderingCanvas.width = width;
  1213. this._renderingCanvas.height = height;
  1214. for (var index = 0; index < this.scenes.length; index++) {
  1215. var scene = this.scenes[index];
  1216. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1217. var cam = scene.cameras[camIndex];
  1218. cam._currentRenderId = 0;
  1219. }
  1220. }
  1221. if (this.onResizeObservable.hasObservers) {
  1222. this.onResizeObservable.notifyObservers(this);
  1223. }
  1224. }
  1225. //WebVR functions
  1226. public isVRDevicePresent(callback: (result: boolean) => void) {
  1227. this.getVRDevice(null, (device) => {
  1228. callback(device !== null);
  1229. });
  1230. }
  1231. public getVRDevice(name: string, callback: (device: any) => void) {
  1232. if (!this.vrDisplaysPromise) {
  1233. callback(null);
  1234. return;
  1235. }
  1236. this.vrDisplaysPromise.then((devices) => {
  1237. if (devices.length > 0) {
  1238. if (name) {
  1239. var found = devices.some(device => {
  1240. if (device.displayName === name) {
  1241. callback(device);
  1242. return true;
  1243. } else {
  1244. return false;
  1245. }
  1246. });
  1247. if (!found) {
  1248. Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  1249. callback(devices[0]);
  1250. }
  1251. } else {
  1252. //choose the first one
  1253. callback(devices[0]);
  1254. }
  1255. } else {
  1256. Tools.Error("No WebVR devices found!");
  1257. callback(null);
  1258. }
  1259. });
  1260. }
  1261. public initWebVR(): void {
  1262. if (!this.vrDisplaysPromise) {
  1263. this._getVRDisplays();
  1264. }
  1265. }
  1266. public enableVR(vrDevice) {
  1267. this._vrDisplayEnabled = vrDevice;
  1268. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  1269. }
  1270. public disableVR() {
  1271. if (this._vrDisplayEnabled) {
  1272. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  1273. }
  1274. }
  1275. private _onVRFullScreenTriggered = () => {
  1276. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1277. //get the old size before we change
  1278. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  1279. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1280. //get the width and height, change the render size
  1281. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  1282. var width, height;
  1283. this.setHardwareScalingLevel(1);
  1284. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1285. } else {
  1286. //When the specs are implemented, need to uncomment this.
  1287. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  1288. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1289. this.setSize(this._oldSize.width, this._oldSize.height);
  1290. this._vrDisplayEnabled = undefined;
  1291. }
  1292. }
  1293. private _getVRDisplays() {
  1294. var getWebVRDevices = (devices: Array<any>) => {
  1295. this._vrDisplays = devices.filter(function (device) {
  1296. return device instanceof VRDisplay;
  1297. });
  1298. return this._vrDisplays;
  1299. }
  1300. if (navigator.getVRDisplays) {
  1301. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  1302. }
  1303. }
  1304. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1305. if (this._currentRenderTarget) {
  1306. this.unBindFramebuffer(this._currentRenderTarget);
  1307. }
  1308. this._currentRenderTarget = texture;
  1309. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1310. var gl = this._gl;
  1311. if (texture.isCube) {
  1312. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1313. }
  1314. if (this._cachedViewport && !forceFullscreenViewport) {
  1315. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1316. } else {
  1317. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1318. }
  1319. this.wipeCaches();
  1320. }
  1321. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1322. if (this._currentFramebuffer !== framebuffer) {
  1323. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1324. this._currentFramebuffer = framebuffer;
  1325. }
  1326. }
  1327. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1328. this._currentRenderTarget = null;
  1329. // If MSAA, we need to bitblt back to main texture
  1330. var gl = this._gl;
  1331. if (texture._MSAAFramebuffer) {
  1332. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1333. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1334. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1335. 0, 0, texture.width, texture.height,
  1336. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1337. }
  1338. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1339. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1340. gl.generateMipmap(gl.TEXTURE_2D);
  1341. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1342. }
  1343. if (onBeforeUnbind) {
  1344. if (texture._MSAAFramebuffer) {
  1345. // Bind the correct framebuffer
  1346. this.bindUnboundFramebuffer(texture._framebuffer);
  1347. }
  1348. onBeforeUnbind();
  1349. }
  1350. this.bindUnboundFramebuffer(null);
  1351. }
  1352. public generateMipMapsForCubemap(texture: InternalTexture) {
  1353. if (texture.generateMipMaps) {
  1354. var gl = this._gl;
  1355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1356. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1357. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1358. }
  1359. }
  1360. public flushFramebuffer(): void {
  1361. this._gl.flush();
  1362. }
  1363. public restoreDefaultFramebuffer(): void {
  1364. if (this._currentRenderTarget) {
  1365. this.unBindFramebuffer(this._currentRenderTarget);
  1366. } else {
  1367. this.bindUnboundFramebuffer(null);
  1368. }
  1369. if (this._cachedViewport) {
  1370. this.setViewport(this._cachedViewport);
  1371. }
  1372. this.wipeCaches();
  1373. }
  1374. // UBOs
  1375. public createUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1376. var ubo = this._gl.createBuffer();
  1377. this.bindUniformBuffer(ubo);
  1378. if (elements instanceof Float32Array) {
  1379. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1380. } else {
  1381. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1382. }
  1383. this.bindUniformBuffer(null);
  1384. ubo.references = 1;
  1385. return ubo;
  1386. }
  1387. public createDynamicUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1388. var ubo = this._gl.createBuffer();
  1389. this.bindUniformBuffer(ubo);
  1390. if (elements instanceof Float32Array) {
  1391. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1392. } else {
  1393. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1394. }
  1395. this.bindUniformBuffer(null);
  1396. ubo.references = 1;
  1397. return ubo;
  1398. }
  1399. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: number[] | Float32Array, offset?: number, count?: number): void {
  1400. this.bindUniformBuffer(uniformBuffer);
  1401. if (offset === undefined) {
  1402. offset = 0;
  1403. }
  1404. if (count === undefined) {
  1405. if (elements instanceof Float32Array) {
  1406. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1407. } else {
  1408. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1409. }
  1410. } else {
  1411. if (elements instanceof Float32Array) {
  1412. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1413. } else {
  1414. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1415. }
  1416. }
  1417. this.bindUniformBuffer(null);
  1418. }
  1419. // VBOs
  1420. private _resetVertexBufferBinding(): void {
  1421. this.bindArrayBuffer(null);
  1422. this._cachedVertexBuffers = null;
  1423. }
  1424. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1425. var vbo = this._gl.createBuffer();
  1426. this.bindArrayBuffer(vbo);
  1427. if (vertices instanceof Float32Array) {
  1428. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1429. } else {
  1430. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1431. }
  1432. this._resetVertexBufferBinding();
  1433. vbo.references = 1;
  1434. return vbo;
  1435. }
  1436. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1437. var vbo = this._gl.createBuffer();
  1438. this.bindArrayBuffer(vbo);
  1439. if (vertices instanceof Float32Array) {
  1440. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1441. } else {
  1442. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1443. }
  1444. this._resetVertexBufferBinding();
  1445. vbo.references = 1;
  1446. return vbo;
  1447. }
  1448. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1449. this.bindArrayBuffer(vertexBuffer);
  1450. if (offset === undefined) {
  1451. offset = 0;
  1452. }
  1453. if (count === undefined) {
  1454. if (vertices instanceof Float32Array) {
  1455. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1456. } else {
  1457. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1458. }
  1459. } else {
  1460. if (vertices instanceof Float32Array) {
  1461. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1462. } else {
  1463. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1464. }
  1465. }
  1466. this._resetVertexBufferBinding();
  1467. }
  1468. private _resetIndexBufferBinding(): void {
  1469. this.bindIndexBuffer(null);
  1470. this._cachedIndexBuffer = null;
  1471. }
  1472. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1473. var vbo = this._gl.createBuffer();
  1474. this.bindIndexBuffer(vbo);
  1475. // Check for 32 bits indices
  1476. var arrayBuffer;
  1477. var need32Bits = false;
  1478. if (indices instanceof Uint16Array) {
  1479. arrayBuffer = indices;
  1480. } else {
  1481. //check 32 bit support
  1482. if (this._caps.uintIndices) {
  1483. if (indices instanceof Uint32Array) {
  1484. arrayBuffer = indices;
  1485. need32Bits = true;
  1486. } else {
  1487. //number[] or Int32Array, check if 32 bit is necessary
  1488. for (var index = 0; index < indices.length; index++) {
  1489. if (indices[index] > 65535) {
  1490. need32Bits = true;
  1491. break;
  1492. }
  1493. }
  1494. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1495. }
  1496. } else {
  1497. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1498. arrayBuffer = new Uint16Array(indices);
  1499. }
  1500. }
  1501. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1502. this._resetIndexBufferBinding();
  1503. vbo.references = 1;
  1504. vbo.is32Bits = need32Bits;
  1505. return vbo;
  1506. }
  1507. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1508. if (!this._vaoRecordInProgress) {
  1509. this._unbindVertexArrayObject();
  1510. }
  1511. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1512. }
  1513. public bindUniformBuffer(buffer?: WebGLBuffer): void {
  1514. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1515. }
  1516. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1517. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1518. }
  1519. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1520. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1521. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1522. };
  1523. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1524. if (!this._vaoRecordInProgress) {
  1525. this._unbindVertexArrayObject();
  1526. }
  1527. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1528. }
  1529. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1530. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1531. this._gl.bindBuffer(target, buffer);
  1532. this._currentBoundBuffer[target] = buffer;
  1533. }
  1534. }
  1535. public updateArrayBuffer(data: Float32Array): void {
  1536. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1537. }
  1538. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1539. var pointer = this._currentBufferPointers[indx];
  1540. var changed = false;
  1541. if (!pointer.active) {
  1542. changed = true;
  1543. pointer.active = true;
  1544. pointer.index = indx;
  1545. pointer.size = size;
  1546. pointer.type = type;
  1547. pointer.normalized = normalized;
  1548. pointer.stride = stride;
  1549. pointer.offset = offset;
  1550. pointer.buffer = buffer;
  1551. } else {
  1552. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1553. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1554. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1555. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1556. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1557. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1558. }
  1559. if (changed || this._vaoRecordInProgress) {
  1560. this.bindArrayBuffer(buffer);
  1561. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1562. }
  1563. }
  1564. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1565. if (indexBuffer == null) {
  1566. return;
  1567. }
  1568. if (this._cachedIndexBuffer !== indexBuffer) {
  1569. this._cachedIndexBuffer = indexBuffer;
  1570. this.bindIndexBuffer(indexBuffer);
  1571. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1572. }
  1573. }
  1574. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1575. var attributes = effect.getAttributesNames();
  1576. if (!this._vaoRecordInProgress) {
  1577. this._unbindVertexArrayObject();
  1578. }
  1579. this.unbindAllAttributes();
  1580. for (var index = 0; index < attributes.length; index++) {
  1581. var order = effect.getAttributeLocation(index);
  1582. if (order >= 0) {
  1583. var vertexBuffer = vertexBuffers[attributes[index]];
  1584. if (!vertexBuffer) {
  1585. continue;
  1586. }
  1587. this._gl.enableVertexAttribArray(order);
  1588. if (!this._vaoRecordInProgress) {
  1589. this._vertexAttribArraysEnabled[order] = true;
  1590. }
  1591. var buffer = vertexBuffer.getBuffer();
  1592. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1593. if (vertexBuffer.getIsInstanced()) {
  1594. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1595. if (!this._vaoRecordInProgress) {
  1596. this._currentInstanceLocations.push(order);
  1597. this._currentInstanceBuffers.push(buffer);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. }
  1603. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1604. var vao = this._gl.createVertexArray();
  1605. this._vaoRecordInProgress = true;
  1606. this._gl.bindVertexArray(vao);
  1607. this._mustWipeVertexAttributes = true;
  1608. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1609. this.bindIndexBuffer(indexBuffer);
  1610. this._vaoRecordInProgress = false;
  1611. this._gl.bindVertexArray(null);
  1612. return vao;
  1613. }
  1614. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1615. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1616. this._cachedVertexArrayObject = vertexArrayObject;
  1617. this._gl.bindVertexArray(vertexArrayObject);
  1618. this._cachedVertexBuffers = null;
  1619. this._cachedIndexBuffer = null;
  1620. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1621. this._mustWipeVertexAttributes = true;
  1622. }
  1623. }
  1624. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1625. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1626. this._cachedVertexBuffers = vertexBuffer;
  1627. this._cachedEffectForVertexBuffers = effect;
  1628. let attributesCount = effect.getAttributesCount();
  1629. this._unbindVertexArrayObject();
  1630. this.unbindAllAttributes();
  1631. var offset = 0;
  1632. for (var index = 0; index < attributesCount; index++) {
  1633. if (index < vertexDeclaration.length) {
  1634. var order = effect.getAttributeLocation(index);
  1635. if (order >= 0) {
  1636. this._gl.enableVertexAttribArray(order);
  1637. this._vertexAttribArraysEnabled[order] = true;
  1638. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1639. }
  1640. offset += vertexDeclaration[index] * 4;
  1641. }
  1642. }
  1643. }
  1644. this._bindIndexBufferWithCache(indexBuffer);
  1645. }
  1646. private _unbindVertexArrayObject(): void {
  1647. if (!this._cachedVertexArrayObject) {
  1648. return;
  1649. }
  1650. this._cachedVertexArrayObject = null;
  1651. this._gl.bindVertexArray(null);
  1652. }
  1653. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1654. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1655. this._cachedVertexBuffers = vertexBuffers;
  1656. this._cachedEffectForVertexBuffers = effect;
  1657. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1658. }
  1659. this._bindIndexBufferWithCache(indexBuffer);
  1660. }
  1661. public unbindInstanceAttributes() {
  1662. var boundBuffer;
  1663. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1664. var instancesBuffer = this._currentInstanceBuffers[i];
  1665. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1666. boundBuffer = instancesBuffer;
  1667. this.bindArrayBuffer(instancesBuffer);
  1668. }
  1669. var offsetLocation = this._currentInstanceLocations[i];
  1670. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1671. }
  1672. this._currentInstanceBuffers.length = 0;
  1673. this._currentInstanceLocations.length = 0;
  1674. }
  1675. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1676. this._gl.deleteVertexArray(vao);
  1677. }
  1678. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1679. buffer.references--;
  1680. if (buffer.references === 0) {
  1681. this._gl.deleteBuffer(buffer);
  1682. return true;
  1683. }
  1684. return false;
  1685. }
  1686. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1687. var buffer = this._gl.createBuffer();
  1688. buffer.capacity = capacity;
  1689. this.bindArrayBuffer(buffer);
  1690. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1691. return buffer;
  1692. }
  1693. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1694. this._gl.deleteBuffer(buffer);
  1695. }
  1696. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1697. this.bindArrayBuffer(instancesBuffer);
  1698. if (data) {
  1699. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1700. }
  1701. if ((<any>offsetLocations[0]).index !== undefined) {
  1702. let stride = 0;
  1703. for (let i = 0; i < offsetLocations.length; i++) {
  1704. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1705. stride += ai.attributeSize * 4;
  1706. }
  1707. for (let i = 0; i < offsetLocations.length; i++) {
  1708. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1709. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1710. this._gl.enableVertexAttribArray(ai.index);
  1711. this._vertexAttribArraysEnabled[ai.index] = true;
  1712. }
  1713. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1714. this._gl.vertexAttribDivisor(ai.index, 1);
  1715. this._currentInstanceLocations.push(ai.index);
  1716. this._currentInstanceBuffers.push(instancesBuffer);
  1717. }
  1718. } else {
  1719. for (let index = 0; index < 4; index++) {
  1720. let offsetLocation = <number>offsetLocations[index];
  1721. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1722. this._gl.enableVertexAttribArray(offsetLocation);
  1723. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1724. }
  1725. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1726. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1727. this._currentInstanceLocations.push(offsetLocation);
  1728. this._currentInstanceBuffers.push(instancesBuffer);
  1729. }
  1730. }
  1731. }
  1732. public applyStates() {
  1733. this._depthCullingState.apply(this._gl);
  1734. this._stencilState.apply(this._gl);
  1735. this._alphaState.apply(this._gl);
  1736. }
  1737. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1738. // Apply states
  1739. this.applyStates();
  1740. this._drawCalls.addCount(1, false);
  1741. // Render
  1742. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1743. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1744. if (instancesCount) {
  1745. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1746. return;
  1747. }
  1748. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1749. }
  1750. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1751. // Apply states
  1752. this.applyStates();
  1753. this._drawCalls.addCount(1, false);
  1754. if (instancesCount) {
  1755. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1756. return;
  1757. }
  1758. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1759. }
  1760. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1761. // Apply states
  1762. this.applyStates();
  1763. this._drawCalls.addCount(1, false);
  1764. if (instancesCount) {
  1765. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1766. return;
  1767. }
  1768. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1769. }
  1770. // Shaders
  1771. public _releaseEffect(effect: Effect): void {
  1772. if (this._compiledEffects[effect._key]) {
  1773. delete this._compiledEffects[effect._key];
  1774. if (effect.getProgram()) {
  1775. this._gl.deleteProgram(effect.getProgram());
  1776. }
  1777. }
  1778. }
  1779. /**
  1780. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1781. * @param samplers An array of string used to represent textures
  1782. */
  1783. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  1784. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1785. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1786. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1787. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1788. if (this._compiledEffects[name]) {
  1789. var compiledEffect = <Effect>this._compiledEffects[name];
  1790. if (onCompiled && compiledEffect.isReady()) {
  1791. onCompiled(compiledEffect);
  1792. }
  1793. return compiledEffect;
  1794. }
  1795. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1796. effect._key = name;
  1797. this._compiledEffects[name] = effect;
  1798. return effect;
  1799. }
  1800. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1801. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1802. return this.createEffect(
  1803. {
  1804. vertex: "particles",
  1805. fragmentElement: fragmentName
  1806. },
  1807. ["position", "color", "options"],
  1808. ["view", "projection"].concat(uniformsNames),
  1809. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1810. }
  1811. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1812. context = context || this._gl;
  1813. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1814. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1815. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1816. var shaderProgram = context.createProgram();
  1817. context.attachShader(shaderProgram, vertexShader);
  1818. context.attachShader(shaderProgram, fragmentShader);
  1819. context.linkProgram(shaderProgram);
  1820. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1821. if (!linked) {
  1822. context.validateProgram(shaderProgram);
  1823. var error = context.getProgramInfoLog(shaderProgram);
  1824. if (error) {
  1825. throw new Error(error);
  1826. }
  1827. }
  1828. context.deleteShader(vertexShader);
  1829. context.deleteShader(fragmentShader);
  1830. return shaderProgram;
  1831. }
  1832. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1833. var results = [];
  1834. for (var index = 0; index < uniformsNames.length; index++) {
  1835. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1836. }
  1837. return results;
  1838. }
  1839. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1840. var results = [];
  1841. for (var index = 0; index < attributesNames.length; index++) {
  1842. try {
  1843. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1844. } catch (e) {
  1845. results.push(-1);
  1846. }
  1847. }
  1848. return results;
  1849. }
  1850. public enableEffect(effect: Effect): void {
  1851. // Use program
  1852. this.setProgram(effect.getProgram());
  1853. this._currentEffect = effect;
  1854. if (effect.onBind) {
  1855. effect.onBind(effect);
  1856. }
  1857. effect.onBindObservable.notifyObservers(effect);
  1858. }
  1859. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1860. if (!uniform)
  1861. return;
  1862. this._gl.uniform1iv(uniform, array);
  1863. }
  1864. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1865. if (!uniform || array.length % 2 !== 0)
  1866. return;
  1867. this._gl.uniform2iv(uniform, array);
  1868. }
  1869. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1870. if (!uniform || array.length % 3 !== 0)
  1871. return;
  1872. this._gl.uniform3iv(uniform, array);
  1873. }
  1874. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1875. if (!uniform || array.length % 4 !== 0)
  1876. return;
  1877. this._gl.uniform4iv(uniform, array);
  1878. }
  1879. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1880. if (!uniform)
  1881. return;
  1882. this._gl.uniform1fv(uniform, array);
  1883. }
  1884. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1885. if (!uniform || array.length % 2 !== 0)
  1886. return;
  1887. this._gl.uniform2fv(uniform, array);
  1888. }
  1889. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1890. if (!uniform || array.length % 3 !== 0)
  1891. return;
  1892. this._gl.uniform3fv(uniform, array);
  1893. }
  1894. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1895. if (!uniform || array.length % 4 !== 0)
  1896. return;
  1897. this._gl.uniform4fv(uniform, array);
  1898. }
  1899. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1900. if (!uniform)
  1901. return;
  1902. this._gl.uniform1fv(uniform, <any>array);
  1903. }
  1904. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1905. if (!uniform || array.length % 2 !== 0)
  1906. return;
  1907. this._gl.uniform2fv(uniform, <any>array);
  1908. }
  1909. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1910. if (!uniform || array.length % 3 !== 0)
  1911. return;
  1912. this._gl.uniform3fv(uniform, <any>array);
  1913. }
  1914. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1915. if (!uniform || array.length % 4 !== 0)
  1916. return;
  1917. this._gl.uniform4fv(uniform, <any>array);
  1918. }
  1919. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1920. if (!uniform)
  1921. return;
  1922. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1923. }
  1924. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1925. if (!uniform)
  1926. return;
  1927. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1928. }
  1929. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1930. if (!uniform)
  1931. return;
  1932. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1933. }
  1934. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1935. if (!uniform)
  1936. return;
  1937. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1938. }
  1939. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1940. if (!uniform)
  1941. return;
  1942. this._gl.uniform1f(uniform, value);
  1943. }
  1944. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1945. if (!uniform)
  1946. return;
  1947. this._gl.uniform2f(uniform, x, y);
  1948. }
  1949. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1950. if (!uniform)
  1951. return;
  1952. this._gl.uniform3f(uniform, x, y, z);
  1953. }
  1954. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1955. if (!uniform)
  1956. return;
  1957. this._gl.uniform1i(uniform, bool);
  1958. }
  1959. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1960. if (!uniform)
  1961. return;
  1962. this._gl.uniform4f(uniform, x, y, z, w);
  1963. }
  1964. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1965. if (!uniform)
  1966. return;
  1967. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1968. }
  1969. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1970. if (!uniform)
  1971. return;
  1972. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1973. }
  1974. // States
  1975. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1976. // Culling
  1977. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1978. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1979. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1980. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1981. if (culling) {
  1982. this._depthCullingState.cullFace = cullFace;
  1983. this._depthCullingState.cull = true;
  1984. } else {
  1985. this._depthCullingState.cull = false;
  1986. }
  1987. }
  1988. // Z offset
  1989. this.setZOffset(zOffset);
  1990. }
  1991. public setZOffset(value: number): void {
  1992. this._depthCullingState.zOffset = value;
  1993. }
  1994. public getZOffset(): number {
  1995. return this._depthCullingState.zOffset;
  1996. }
  1997. public setDepthBuffer(enable: boolean): void {
  1998. this._depthCullingState.depthTest = enable;
  1999. }
  2000. public getDepthWrite(): boolean {
  2001. return this._depthCullingState.depthMask;
  2002. }
  2003. public setDepthWrite(enable: boolean): void {
  2004. this._depthCullingState.depthMask = enable;
  2005. }
  2006. public setColorWrite(enable: boolean): void {
  2007. this._gl.colorMask(enable, enable, enable, enable);
  2008. }
  2009. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2010. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2011. }
  2012. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2013. if (this._alphaMode === mode) {
  2014. return;
  2015. }
  2016. switch (mode) {
  2017. case Engine.ALPHA_DISABLE:
  2018. this._alphaState.alphaBlend = false;
  2019. break;
  2020. case Engine.ALPHA_PREMULTIPLIED:
  2021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2022. this._alphaState.alphaBlend = true;
  2023. break;
  2024. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2025. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2026. this._alphaState.alphaBlend = true;
  2027. break;
  2028. case Engine.ALPHA_COMBINE:
  2029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2030. this._alphaState.alphaBlend = true;
  2031. break;
  2032. case Engine.ALPHA_ONEONE:
  2033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2034. this._alphaState.alphaBlend = true;
  2035. break;
  2036. case Engine.ALPHA_ADD:
  2037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2038. this._alphaState.alphaBlend = true;
  2039. break;
  2040. case Engine.ALPHA_SUBTRACT:
  2041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2042. this._alphaState.alphaBlend = true;
  2043. break;
  2044. case Engine.ALPHA_MULTIPLY:
  2045. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2046. this._alphaState.alphaBlend = true;
  2047. break;
  2048. case Engine.ALPHA_MAXIMIZED:
  2049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2050. this._alphaState.alphaBlend = true;
  2051. break;
  2052. case Engine.ALPHA_INTERPOLATE:
  2053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2054. this._alphaState.alphaBlend = true;
  2055. break;
  2056. case Engine.ALPHA_SCREENMODE:
  2057. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2058. this._alphaState.alphaBlend = true;
  2059. break;
  2060. }
  2061. if (!noDepthWriteChange) {
  2062. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2063. }
  2064. this._alphaMode = mode;
  2065. }
  2066. public getAlphaMode(): number {
  2067. return this._alphaMode;
  2068. }
  2069. public setAlphaTesting(enable: boolean): void {
  2070. this._alphaTest = enable;
  2071. }
  2072. public getAlphaTesting(): boolean {
  2073. return !!this._alphaTest;
  2074. }
  2075. // Textures
  2076. public wipeCaches(bruteForce?: boolean): void {
  2077. if (this.preventCacheWipeBetweenFrames) {
  2078. return;
  2079. }
  2080. this.resetTextureCache();
  2081. this._currentEffect = null;
  2082. // 6/8/2017: deltakosh: Should not be required anymore.
  2083. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  2084. if (bruteForce) {
  2085. this._currentProgram = null;
  2086. this._stencilState.reset();
  2087. this._depthCullingState.reset();
  2088. this.setDepthFunctionToLessOrEqual();
  2089. this._alphaState.reset();
  2090. }
  2091. this._cachedVertexBuffers = null;
  2092. this._cachedIndexBuffer = null;
  2093. this._cachedEffectForVertexBuffers = null;
  2094. this._unbindVertexArrayObject();
  2095. this.bindIndexBuffer(null);
  2096. this.bindArrayBuffer(null);
  2097. }
  2098. /**
  2099. * Set the compressed texture format to use, based on the formats you have, and the formats
  2100. * supported by the hardware / browser.
  2101. *
  2102. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2103. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2104. * to API arguments needed to compressed textures. This puts the burden on the container
  2105. * generator to house the arcane code for determining these for current & future formats.
  2106. *
  2107. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2108. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2109. *
  2110. * Note: The result of this call is not taken into account when a texture is base64.
  2111. *
  2112. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2113. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2114. *
  2115. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2116. * @returns The extension selected.
  2117. */
  2118. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  2119. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2120. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2121. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2122. return this._textureFormatInUse = this._texturesSupported[i];
  2123. }
  2124. }
  2125. }
  2126. // actively set format to nothing, to allow this to be called more than once
  2127. // and possibly fail the 2nd time
  2128. return this._textureFormatInUse = null;
  2129. }
  2130. public _createTexture(): WebGLTexture {
  2131. return this._gl.createTexture();
  2132. }
  2133. /**
  2134. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2135. * @param {string} urlArg- This contains one of the following:
  2136. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2137. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2138. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2139. *
  2140. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2141. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2142. * @param {Scene} scene- Needed for loading to the correct scene.
  2143. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2144. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2145. * @param {callback} onError- Optional callback to be called upon failure.
  2146. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2147. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2148. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2149. *
  2150. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2151. */
  2152. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: ArrayBuffer | HTMLImageElement = null, fallBack?: InternalTexture, format?: number): InternalTexture {
  2153. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2154. var fromData = url.substr(0, 5) === "data:";
  2155. var fromBlob = url.substr(0, 5) === "blob:";
  2156. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2157. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2158. // establish the file extension, if possible
  2159. var lastDot = url.lastIndexOf('.');
  2160. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2161. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2162. var isTGA = (extension === ".tga");
  2163. // determine if a ktx file should be substituted
  2164. var isKTX = false;
  2165. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2166. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2167. isKTX = true;
  2168. }
  2169. if (scene) {
  2170. scene._addPendingData(texture);
  2171. }
  2172. texture.url = url;
  2173. texture.generateMipMaps = !noMipmap;
  2174. texture.samplingMode = samplingMode;
  2175. texture.invertY = invertY;
  2176. if (!this._doNotHandleContextLost) {
  2177. // Keep a link to the buffer only if we plan to handle context lost
  2178. texture._buffer = buffer;
  2179. }
  2180. if (onLoad) {
  2181. texture.onLoadedObservable.add(onLoad);
  2182. }
  2183. if (!fallBack) this._internalTexturesCache.push(texture);
  2184. var onerror = () => {
  2185. if (scene) {
  2186. scene._removePendingData(texture);
  2187. }
  2188. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2189. if (isKTX) {
  2190. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2191. } else if (onError) {
  2192. onError();
  2193. }
  2194. };
  2195. var callback: (arrayBuffer: any) => void;
  2196. // processing for non-image formats
  2197. if (isKTX || isTGA || isDDS) {
  2198. if (isKTX) {
  2199. callback = (data) => {
  2200. var ktx = new Internals.KhronosTextureContainer(data, 1);
  2201. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2202. ktx.uploadLevels(this._gl, !noMipmap);
  2203. return false;
  2204. }, samplingMode);
  2205. };
  2206. } else if (isTGA) {
  2207. callback = (arrayBuffer) => {
  2208. var data = new Uint8Array(arrayBuffer);
  2209. var header = Internals.TGATools.GetTGAHeader(data);
  2210. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2211. Internals.TGATools.UploadContent(this._gl, data);
  2212. return false;
  2213. }, samplingMode);
  2214. };
  2215. } else if (isDDS) {
  2216. callback = (data) => {
  2217. var info = Internals.DDSTools.GetDDSInfo(data);
  2218. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2219. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2220. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2221. return false;
  2222. }, samplingMode);
  2223. };
  2224. }
  2225. if (!buffer) {
  2226. Tools.LoadFile(url, data => {
  2227. callback(data);
  2228. }, null, scene ? scene.database : null, true, onerror);
  2229. } else {
  2230. callback(buffer);
  2231. }
  2232. // image format processing
  2233. } else {
  2234. var onload = (img) => {
  2235. if (fromBlob && !this._doNotHandleContextLost) {
  2236. // We need to store the image if we need to rebuild the texture
  2237. // in case of a webgl context lost
  2238. texture._buffer = img;
  2239. }
  2240. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2241. let gl = this._gl;
  2242. var isPot = (img.width === potWidth && img.height === potHeight);
  2243. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2244. if (isPot) {
  2245. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2246. return false;
  2247. }
  2248. // Using shaders to rescale because canvas.drawImage is lossy
  2249. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2250. this._bindTextureDirectly(gl.TEXTURE_2D, source);
  2251. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2256. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2257. this._releaseTexture(source);
  2258. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2259. continuationCallback();
  2260. });
  2261. return true;
  2262. }, samplingMode);
  2263. };
  2264. if (!fromData || isBase64)
  2265. if (buffer instanceof HTMLImageElement) {
  2266. onload(buffer);
  2267. } else {
  2268. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2269. }
  2270. else if (buffer instanceof Array || typeof buffer === "string")
  2271. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2272. else
  2273. onload(buffer);
  2274. }
  2275. return texture;
  2276. }
  2277. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Scene, internalFormat: number, onComplete: () => void): void {
  2278. let rtt = this.createRenderTargetTexture({
  2279. width: destination.width,
  2280. height: destination.height,
  2281. }, {
  2282. generateMipMaps: false,
  2283. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2284. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2285. generateDepthBuffer: false,
  2286. generateStencilBuffer: false
  2287. }
  2288. );
  2289. if (!this._rescalePostProcess) {
  2290. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2291. }
  2292. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2293. this._rescalePostProcess.onApply = function (effect) {
  2294. effect._bindTexture("textureSampler", source);
  2295. }
  2296. scene.postProcessManager.directRender([this._rescalePostProcess], rtt);
  2297. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination);
  2298. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2299. this.unBindFramebuffer(rtt);
  2300. this._releaseTexture(rtt);
  2301. if (onComplete) {
  2302. onComplete();
  2303. }
  2304. });
  2305. }
  2306. private _getInternalFormat(format: number): number {
  2307. var internalFormat = this._gl.RGBA;
  2308. switch (format) {
  2309. case Engine.TEXTUREFORMAT_ALPHA:
  2310. internalFormat = this._gl.ALPHA;
  2311. break;
  2312. case Engine.TEXTUREFORMAT_LUMINANCE:
  2313. internalFormat = this._gl.LUMINANCE;
  2314. break;
  2315. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2316. internalFormat = this._gl.LUMINANCE_ALPHA;
  2317. break;
  2318. case Engine.TEXTUREFORMAT_RGB:
  2319. internalFormat = this._gl.RGB;
  2320. break;
  2321. case Engine.TEXTUREFORMAT_RGBA:
  2322. internalFormat = this._gl.RGBA;
  2323. break;
  2324. }
  2325. return internalFormat;
  2326. }
  2327. public updateRawTexture(texture: InternalTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  2328. var internalFormat = this._getInternalFormat(format);
  2329. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2330. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2331. if (!this._doNotHandleContextLost) {
  2332. texture._bufferView = data;
  2333. texture.format = format;
  2334. texture.invertY = invertY;
  2335. texture._compression = compression;
  2336. }
  2337. if (texture.width % 4 !== 0) {
  2338. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2339. }
  2340. if (compression) {
  2341. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  2342. } else {
  2343. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  2344. }
  2345. if (texture.generateMipMaps) {
  2346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2347. }
  2348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2349. this.resetTextureCache();
  2350. texture.isReady = true;
  2351. }
  2352. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  2353. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2354. texture.baseWidth = width;
  2355. texture.baseHeight = height;
  2356. texture.width = width;
  2357. texture.height = height;
  2358. texture.format = format;
  2359. texture.generateMipMaps = generateMipMaps;
  2360. texture.samplingMode = samplingMode;
  2361. texture.invertY = invertY;
  2362. texture._compression = compression;
  2363. if (!this._doNotHandleContextLost) {
  2364. texture._bufferView = data;
  2365. }
  2366. this.updateRawTexture(texture, data, format, invertY, compression);
  2367. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2368. // Filters
  2369. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2370. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2371. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2372. if (generateMipMaps) {
  2373. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2374. }
  2375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2376. this._internalTexturesCache.push(texture);
  2377. return texture;
  2378. }
  2379. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2380. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2381. texture.baseWidth = width;
  2382. texture.baseHeight = height;
  2383. if (generateMipMaps) {
  2384. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2385. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2386. }
  2387. this.resetTextureCache();
  2388. texture.width = width;
  2389. texture.height = height;
  2390. texture.isReady = false;
  2391. texture.generateMipMaps = generateMipMaps;
  2392. texture.samplingMode = samplingMode;
  2393. this.updateTextureSamplingMode(samplingMode, texture);
  2394. this._internalTexturesCache.push(texture);
  2395. return texture;
  2396. }
  2397. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2398. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2399. if (texture.isCube) {
  2400. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  2401. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2402. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2403. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2404. } else {
  2405. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2407. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2409. }
  2410. texture.samplingMode = samplingMode;
  2411. }
  2412. public updateDynamicTexture(texture: InternalTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2413. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2414. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2415. if (premulAlpha) {
  2416. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2417. }
  2418. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2419. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2420. if (texture.generateMipMaps) {
  2421. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2422. }
  2423. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2424. if (premulAlpha) {
  2425. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2426. }
  2427. this.resetTextureCache();
  2428. texture.isReady = true;
  2429. }
  2430. public updateVideoTexture(texture: InternalTexture, video: HTMLVideoElement, invertY: boolean): void {
  2431. if (texture._isDisabled) {
  2432. return;
  2433. }
  2434. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2435. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2436. try {
  2437. // Testing video texture support
  2438. if (this._videoTextureSupported === undefined) {
  2439. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2440. if (this._gl.getError() !== 0) {
  2441. this._videoTextureSupported = false;
  2442. } else {
  2443. this._videoTextureSupported = true;
  2444. }
  2445. }
  2446. // Copy video through the current working canvas if video texture is not supported
  2447. if (!this._videoTextureSupported) {
  2448. if (!texture._workingCanvas) {
  2449. texture._workingCanvas = document.createElement("canvas");
  2450. texture._workingContext = texture._workingCanvas.getContext("2d");
  2451. texture._workingCanvas.width = texture.width;
  2452. texture._workingCanvas.height = texture.height;
  2453. }
  2454. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2456. } else {
  2457. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2458. }
  2459. if (texture.generateMipMaps) {
  2460. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2461. }
  2462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2463. this.resetTextureCache();
  2464. texture.isReady = true;
  2465. } catch (ex) {
  2466. // Something unexpected
  2467. // Let's disable the texture
  2468. texture._isDisabled = true;
  2469. }
  2470. }
  2471. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2472. let fullOptions = new RenderTargetCreationOptions();
  2473. if (options !== undefined && typeof options === "object") {
  2474. fullOptions.generateMipMaps = options.generateMipMaps;
  2475. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2476. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2477. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2478. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2479. } else {
  2480. fullOptions.generateMipMaps = <boolean>options;
  2481. fullOptions.generateDepthBuffer = true;
  2482. fullOptions.generateStencilBuffer = false;
  2483. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2484. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2485. }
  2486. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2487. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2488. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2489. }
  2490. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2491. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2492. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2493. }
  2494. var gl = this._gl;
  2495. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2496. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2497. var width = size.width || size;
  2498. var height = size.height || size;
  2499. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  2500. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2501. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2502. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2503. }
  2504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2508. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  2509. // Create the framebuffer
  2510. var framebuffer = gl.createFramebuffer();
  2511. this.bindUnboundFramebuffer(framebuffer);
  2512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2513. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  2514. if (fullOptions.generateMipMaps) {
  2515. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2516. }
  2517. // Unbind
  2518. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2519. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2520. this.bindUnboundFramebuffer(null);
  2521. texture._framebuffer = framebuffer;
  2522. texture.baseWidth = width;
  2523. texture.baseHeight = height;
  2524. texture.width = width;
  2525. texture.height = height;
  2526. texture.isReady = true;
  2527. texture.samples = 1;
  2528. texture.generateMipMaps = fullOptions.generateMipMaps;
  2529. texture.samplingMode = fullOptions.samplingMode;
  2530. texture.type = fullOptions.type;
  2531. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2532. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  2533. this.resetTextureCache();
  2534. this._internalTexturesCache.push(texture);
  2535. return texture;
  2536. }
  2537. public createMultipleRenderTarget(size: any, options): InternalTexture[] {
  2538. var generateMipMaps = false;
  2539. var generateDepthBuffer = true;
  2540. var generateStencilBuffer = false;
  2541. var generateDepthTexture = false;
  2542. var textureCount = 1;
  2543. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2544. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2545. var types = [], samplingModes = [];
  2546. if (options !== undefined) {
  2547. generateMipMaps = options.generateMipMaps;
  2548. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2549. generateStencilBuffer = options.generateStencilBuffer;
  2550. generateDepthTexture = options.generateDepthTexture;
  2551. textureCount = options.textureCount || 1;
  2552. if (options.types) {
  2553. types = options.types;
  2554. }
  2555. if (options.samplingModes) {
  2556. samplingModes = options.samplingModes;
  2557. }
  2558. }
  2559. var gl = this._gl;
  2560. // Create the framebuffer
  2561. var framebuffer = gl.createFramebuffer();
  2562. this.bindUnboundFramebuffer(framebuffer);
  2563. var width = size.width || size;
  2564. var height = size.height || size;
  2565. var textures = [];
  2566. var attachments = []
  2567. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2568. for (var i = 0; i < textureCount; i++) {
  2569. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2570. var type = types[i] || defaultType;
  2571. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2572. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2573. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2574. }
  2575. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2576. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2577. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2578. }
  2579. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2580. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2581. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2582. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2583. }
  2584. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2585. var attachment = gl["COLOR_ATTACHMENT" + i];
  2586. textures.push(texture);
  2587. attachments.push(attachment);
  2588. gl.activeTexture(gl["TEXTURE" + i]);
  2589. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  2590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2591. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2592. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2593. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2594. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2595. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2596. if (generateMipMaps) {
  2597. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2598. }
  2599. // Unbind
  2600. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2601. texture._framebuffer = framebuffer;
  2602. texture._depthStencilBuffer = depthStencilBuffer;
  2603. texture.baseWidth = width;
  2604. texture.baseHeight = height;
  2605. texture.width = width;
  2606. texture.height = height;
  2607. texture.isReady = true;
  2608. texture.samples = 1;
  2609. texture.generateMipMaps = generateMipMaps;
  2610. texture.samplingMode = samplingMode;
  2611. texture.type = type;
  2612. texture._generateDepthBuffer = generateDepthBuffer;
  2613. texture._generateStencilBuffer = generateStencilBuffer;
  2614. this._internalTexturesCache.push(texture);
  2615. }
  2616. if (generateDepthTexture) {
  2617. // Depth texture
  2618. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2619. gl.activeTexture(gl.TEXTURE0);
  2620. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  2621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2625. gl.texImage2D(
  2626. gl.TEXTURE_2D,
  2627. 0,
  2628. gl.DEPTH_COMPONENT16,
  2629. width,
  2630. height,
  2631. 0,
  2632. gl.DEPTH_COMPONENT,
  2633. gl.UNSIGNED_SHORT,
  2634. null
  2635. );
  2636. gl.framebufferTexture2D(
  2637. gl.FRAMEBUFFER,
  2638. gl.DEPTH_ATTACHMENT,
  2639. gl.TEXTURE_2D,
  2640. depthTexture._webGLTexture,
  2641. 0
  2642. );
  2643. depthTexture._framebuffer = framebuffer;
  2644. depthTexture.baseWidth = width;
  2645. depthTexture.baseHeight = height;
  2646. depthTexture.width = width;
  2647. depthTexture.height = height;
  2648. depthTexture.isReady = true;
  2649. depthTexture.samples = 1;
  2650. depthTexture.generateMipMaps = generateMipMaps;
  2651. depthTexture.samplingMode = gl.NEAREST;
  2652. depthTexture._generateDepthBuffer = generateDepthBuffer;
  2653. depthTexture._generateStencilBuffer = generateStencilBuffer;
  2654. textures.push(depthTexture)
  2655. this._internalTexturesCache.push(depthTexture);
  2656. }
  2657. gl.drawBuffers(attachments);
  2658. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2659. this.bindUnboundFramebuffer(null);
  2660. this.resetTextureCache();
  2661. return textures;
  2662. }
  2663. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2664. var depthStencilBuffer: WebGLRenderbuffer = null;
  2665. var gl = this._gl;
  2666. // Create the depth/stencil buffer
  2667. if (generateStencilBuffer) {
  2668. depthStencilBuffer = gl.createRenderbuffer();
  2669. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2670. if (samples > 1) {
  2671. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  2672. } else {
  2673. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2674. }
  2675. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2676. }
  2677. else if (generateDepthBuffer) {
  2678. depthStencilBuffer = gl.createRenderbuffer();
  2679. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2680. if (samples > 1) {
  2681. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2682. } else {
  2683. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2684. }
  2685. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2686. }
  2687. return depthStencilBuffer;
  2688. }
  2689. public updateRenderTargetTextureSampleCount(texture: InternalTexture, samples: number): number {
  2690. if (this.webGLVersion < 2) {
  2691. return 1;
  2692. }
  2693. if (texture.samples === samples) {
  2694. return samples;
  2695. }
  2696. var gl = this._gl;
  2697. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2698. // Dispose previous render buffers
  2699. if (texture._depthStencilBuffer) {
  2700. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2701. }
  2702. if (texture._MSAAFramebuffer) {
  2703. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2704. }
  2705. if (texture._MSAARenderBuffer) {
  2706. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2707. }
  2708. if (samples > 1) {
  2709. texture._MSAAFramebuffer = gl.createFramebuffer();
  2710. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2711. var colorRenderbuffer = gl.createRenderbuffer();
  2712. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2713. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  2714. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2715. texture._MSAARenderBuffer = colorRenderbuffer;
  2716. } else {
  2717. this.bindUnboundFramebuffer(texture._framebuffer);
  2718. }
  2719. texture.samples = samples;
  2720. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  2721. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2722. this.bindUnboundFramebuffer(null);
  2723. return samples;
  2724. }
  2725. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  2726. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  2727. }
  2728. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  2729. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  2730. }
  2731. public createRenderTargetCubeTexture(size: number, options?: RenderTargetCreationOptions): InternalTexture {
  2732. var gl = this._gl;
  2733. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2734. var generateMipMaps = true;
  2735. var generateDepthBuffer = true;
  2736. var generateStencilBuffer = false;
  2737. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2738. if (options !== undefined) {
  2739. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  2740. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2741. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2742. if (options.samplingMode !== undefined) {
  2743. samplingMode = options.samplingMode;
  2744. }
  2745. }
  2746. texture.isCube = true;
  2747. texture.generateMipMaps = generateMipMaps;
  2748. texture.samples = 1;
  2749. texture.samplingMode = samplingMode;
  2750. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2752. for (var face = 0; face < 6; face++) {
  2753. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2754. }
  2755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2759. // Create the framebuffer
  2760. var framebuffer = gl.createFramebuffer();
  2761. this.bindUnboundFramebuffer(framebuffer);
  2762. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2763. // Mipmaps
  2764. if (texture.generateMipMaps) {
  2765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2766. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2767. }
  2768. // Unbind
  2769. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2770. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2771. this.bindUnboundFramebuffer(null);
  2772. texture._framebuffer = framebuffer;
  2773. texture.width = size;
  2774. texture.height = size;
  2775. texture.isReady = true;
  2776. this.resetTextureCache();
  2777. this._internalTexturesCache.push(texture);
  2778. return texture;
  2779. }
  2780. public createPrefilteredCubeTexture(rootUrl: string, scene: Scene, scale: number, offset: number, onLoad: (internalTexture: InternalTexture) => void, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2781. var callback = (loadData) => {
  2782. if (!loadData) {
  2783. if (onLoad) {
  2784. onLoad(null);
  2785. }
  2786. return;
  2787. }
  2788. let texture = loadData.texture as InternalTexture;
  2789. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  2790. texture._lodGenerationScale = scale;
  2791. texture._lodGenerationOffset = offset;
  2792. if (this._caps.textureLOD) {
  2793. // Do not add extra process if texture lod is supported.
  2794. if (onLoad) {
  2795. onLoad(texture);
  2796. }
  2797. return;
  2798. }
  2799. const mipSlices = 3;
  2800. var gl = this._gl;
  2801. const width = loadData.width;
  2802. if (!width) {
  2803. return;
  2804. }
  2805. const textures: BaseTexture[] = [];
  2806. for (let i = 0; i < mipSlices; i++) {
  2807. //compute LOD from even spacing in smoothness (matching shader calculation)
  2808. let smoothness = i / (mipSlices - 1);
  2809. let roughness = 1 - smoothness;
  2810. let minLODIndex = offset; // roughness = 0
  2811. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  2812. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  2813. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  2814. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2815. glTextureFromLod.isCube = true;
  2816. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  2817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2821. if (loadData.isDDS) {
  2822. var info: Internals.DDSInfo = loadData.info;
  2823. var data: any = loadData.data;
  2824. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2825. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  2826. }
  2827. else {
  2828. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  2829. }
  2830. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2831. // Wrap in a base texture for easy binding.
  2832. const lodTexture = new BaseTexture(scene);
  2833. lodTexture.isCube = true;
  2834. lodTexture._texture = glTextureFromLod;
  2835. glTextureFromLod.isReady = true;
  2836. textures.push(lodTexture);
  2837. }
  2838. texture._lodTextureHigh = textures[2];
  2839. texture._lodTextureMid = textures[1];
  2840. texture._lodTextureLow = textures[0];
  2841. if (onLoad) {
  2842. onLoad(texture);
  2843. }
  2844. };
  2845. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  2846. }
  2847. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: (data?: any) => void = null, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2848. var gl = this._gl;
  2849. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  2850. texture.isCube = true;
  2851. texture.url = rootUrl;
  2852. texture.generateMipMaps = !noMipmap;
  2853. if (!this._doNotHandleContextLost) {
  2854. texture._extension = forcedExtension;
  2855. texture._files = files;
  2856. }
  2857. var isKTX = false;
  2858. var isDDS = false;
  2859. var lastDot = rootUrl.lastIndexOf('.');
  2860. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  2861. if (this._textureFormatInUse) {
  2862. extension = this._textureFormatInUse;
  2863. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2864. isKTX = true;
  2865. } else {
  2866. isDDS = (extension === ".dds");
  2867. }
  2868. if (isKTX) {
  2869. Tools.LoadFile(rootUrl, data => {
  2870. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2871. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2872. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2873. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2874. ktx.uploadLevels(this._gl, !noMipmap);
  2875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2879. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2880. this.resetTextureCache();
  2881. texture.width = ktx.pixelWidth;
  2882. texture.height = ktx.pixelHeight;
  2883. texture.isReady = true;
  2884. }, null, null, true, onError);
  2885. } else if (isDDS) {
  2886. Tools.LoadFile(rootUrl, data => {
  2887. var info = Internals.DDSTools.GetDDSInfo(data);
  2888. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2889. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2891. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  2892. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2894. }
  2895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2900. this.resetTextureCache();
  2901. texture.width = info.width;
  2902. texture.height = info.height;
  2903. texture.isReady = true;
  2904. texture.type = info.textureType;
  2905. if (onLoad) {
  2906. onLoad({ isDDS: true, width: info.width, info, data, texture });
  2907. }
  2908. }, null, null, true, onError);
  2909. } else {
  2910. cascadeLoad(rootUrl, scene, imgs => {
  2911. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  2912. var height = width;
  2913. this._prepareWorkingCanvas();
  2914. this._workingCanvas.width = width;
  2915. this._workingCanvas.height = height;
  2916. var faces = [
  2917. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2918. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2919. ];
  2920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2922. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2923. for (var index = 0; index < faces.length; index++) {
  2924. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2925. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2926. }
  2927. if (!noMipmap) {
  2928. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2929. }
  2930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2935. this.resetTextureCache();
  2936. texture.width = width;
  2937. texture.height = height;
  2938. texture.isReady = true;
  2939. texture.format = format;
  2940. texture.onLoadedObservable.notifyObservers(texture);
  2941. texture.onLoadedObservable.clear();
  2942. if (onLoad) {
  2943. onLoad();
  2944. }
  2945. }, files, onError);
  2946. }
  2947. this._internalTexturesCache.push(texture);
  2948. return texture;
  2949. }
  2950. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: string = null, level = 0): void {
  2951. var gl = this._gl;
  2952. var textureType = this._getWebGLTextureType(type);
  2953. var internalFormat = this._getInternalFormat(format);
  2954. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2955. var needConversion = false;
  2956. if (internalFormat === gl.RGB) {
  2957. internalFormat = gl.RGBA;
  2958. needConversion = true;
  2959. }
  2960. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2961. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2962. if (texture.width % 4 !== 0) {
  2963. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  2964. }
  2965. // Data are known to be in +X +Y +Z -X -Y -Z
  2966. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  2967. let faceData = data[faceIndex];
  2968. if (compression) {
  2969. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  2970. } else {
  2971. if (needConversion) {
  2972. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  2973. }
  2974. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  2975. }
  2976. }
  2977. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  2978. if (isPot && texture.generateMipMaps && level === 0) {
  2979. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  2980. }
  2981. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2982. this.resetTextureCache();
  2983. texture.isReady = true;
  2984. }
  2985. public createRawCubeTexture(data: ArrayBufferView[], size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  2986. var gl = this._gl;
  2987. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  2988. texture.isCube = true;
  2989. texture.generateMipMaps = generateMipMaps;
  2990. texture.format = format;
  2991. texture.type = type;
  2992. var textureType = this._getWebGLTextureType(type);
  2993. var internalFormat = this._getInternalFormat(format);
  2994. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2995. var needConversion = false;
  2996. if (internalFormat === gl.RGB) {
  2997. internalFormat = gl.RGBA;
  2998. needConversion = true;
  2999. }
  3000. var width = size;
  3001. var height = width;
  3002. texture.width = width;
  3003. texture.height = height;
  3004. // Double check on POT to generate Mips.
  3005. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3006. if (!isPot) {
  3007. generateMipMaps = false;
  3008. }
  3009. // Upload data if needed. The texture won t be ready until then.
  3010. if (data) {
  3011. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3012. }
  3013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  3014. // Filters
  3015. if (data && generateMipMaps) {
  3016. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3017. }
  3018. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3019. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3020. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3021. }
  3022. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3023. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3025. }
  3026. else {
  3027. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3030. }
  3031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3033. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3034. return texture;
  3035. }
  3036. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3037. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  3038. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]),
  3039. onLoad: () => void = null,
  3040. onError: () => void = null,
  3041. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3042. invertY = false): InternalTexture {
  3043. var gl = this._gl;
  3044. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3045. scene._addPendingData(texture);
  3046. texture.url = url;
  3047. this._internalTexturesCache.push(texture);
  3048. var onerror = () => {
  3049. scene._removePendingData(texture);
  3050. if (onError) {
  3051. onError();
  3052. }
  3053. };
  3054. var internalCallback = (data) => {
  3055. var width = texture.width;
  3056. var height = texture.height;
  3057. var faceDataArrays = callback(data);
  3058. if (mipmmapGenerator) {
  3059. var textureType = this._getWebGLTextureType(type);
  3060. var internalFormat = this._getInternalFormat(format);
  3061. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3062. var needConversion = false;
  3063. if (internalFormat === gl.RGB) {
  3064. internalFormat = gl.RGBA;
  3065. needConversion = true;
  3066. }
  3067. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  3068. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3069. var mipData = mipmmapGenerator(faceDataArrays);
  3070. for (var level = 0; level < mipData.length; level++) {
  3071. var mipSize = width >> level;
  3072. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3073. let mipFaceData = mipData[level][faceIndex];
  3074. if (needConversion) {
  3075. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3076. }
  3077. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3078. }
  3079. }
  3080. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3081. }
  3082. else {
  3083. texture.generateMipMaps = !noMipmap;
  3084. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3085. }
  3086. texture.isReady = true;
  3087. this.resetTextureCache();
  3088. scene._removePendingData(texture);
  3089. if (onLoad) {
  3090. onLoad();
  3091. }
  3092. };
  3093. Tools.LoadFile(url, data => {
  3094. internalCallback(data);
  3095. }, onerror, scene.database, true);
  3096. return texture;
  3097. };
  3098. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Scene, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3099. var gl = this._gl;
  3100. if (!gl) {
  3101. return;
  3102. }
  3103. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3106. if (!noMipmap && !isCompressed) {
  3107. gl.generateMipmap(gl.TEXTURE_2D);
  3108. }
  3109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3110. this.resetTextureCache();
  3111. if (scene) {
  3112. scene._removePendingData(texture);
  3113. }
  3114. texture.onLoadedObservable.notifyObservers(texture);
  3115. texture.onLoadedObservable.clear();
  3116. }
  3117. private _prepareWebGLTexture(texture: InternalTexture, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3118. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3119. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3120. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3121. var gl = this._gl;
  3122. if (!gl) {
  3123. return;
  3124. }
  3125. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  3126. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3127. texture.baseWidth = width;
  3128. texture.baseHeight = height;
  3129. texture.width = potWidth;
  3130. texture.height = potHeight;
  3131. texture.isReady = true;
  3132. if (processFunction(potWidth, potHeight, () => {
  3133. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3134. })) {
  3135. // Returning as texture needs extra async steps
  3136. return;
  3137. }
  3138. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3139. }
  3140. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  3141. // Create new RGBA data container.
  3142. var rgbaData: ArrayBufferView;
  3143. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3144. rgbaData = new Float32Array(width * height * 4);
  3145. }
  3146. else {
  3147. rgbaData = new Uint32Array(width * height * 4);
  3148. }
  3149. // Convert each pixel.
  3150. for (let x = 0; x < width; x++) {
  3151. for (let y = 0; y < height; y++) {
  3152. let index = (y * width + x) * 3;
  3153. let newIndex = (y * width + x) * 4;
  3154. // Map Old Value to new value.
  3155. rgbaData[newIndex + 0] = rgbData[index + 0];
  3156. rgbaData[newIndex + 1] = rgbData[index + 1];
  3157. rgbaData[newIndex + 2] = rgbData[index + 2];
  3158. // Add fully opaque alpha channel.
  3159. rgbaData[newIndex + 3] = 1;
  3160. }
  3161. }
  3162. return rgbaData;
  3163. }
  3164. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3165. var gl = this._gl;
  3166. if (texture._framebuffer) {
  3167. gl.deleteFramebuffer(texture._framebuffer);
  3168. texture._framebuffer = null;
  3169. }
  3170. if (texture._depthStencilBuffer) {
  3171. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3172. texture._depthStencilBuffer = null;
  3173. }
  3174. if (texture._MSAAFramebuffer) {
  3175. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3176. texture._MSAAFramebuffer = null;
  3177. }
  3178. if (texture._MSAARenderBuffer) {
  3179. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3180. texture._MSAARenderBuffer = null;
  3181. }
  3182. }
  3183. public _releaseTexture(texture: InternalTexture): void {
  3184. var gl = this._gl;
  3185. this._releaseFramebufferObjects(texture);
  3186. gl.deleteTexture(texture._webGLTexture);
  3187. // Unbind channels
  3188. this.unbindAllTextures();
  3189. var index = this._internalTexturesCache.indexOf(texture);
  3190. if (index !== -1) {
  3191. this._internalTexturesCache.splice(index, 1);
  3192. }
  3193. // Integrated fixed lod samplers.
  3194. if (texture._lodTextureHigh) {
  3195. texture._lodTextureHigh.dispose();
  3196. }
  3197. if (texture._lodTextureMid) {
  3198. texture._lodTextureMid.dispose();
  3199. }
  3200. if (texture._lodTextureLow) {
  3201. texture._lodTextureLow.dispose();
  3202. }
  3203. }
  3204. private setProgram(program: WebGLProgram): void {
  3205. if (this._currentProgram !== program) {
  3206. this._gl.useProgram(program);
  3207. this._currentProgram = program;
  3208. }
  3209. }
  3210. public bindSamplers(effect: Effect): void {
  3211. this.setProgram(effect.getProgram());
  3212. var samplers = effect.getSamplers();
  3213. for (var index = 0; index < samplers.length; index++) {
  3214. var uniform = effect.getUniform(samplers[index]);
  3215. this._gl.uniform1i(uniform, index);
  3216. }
  3217. this._currentEffect = null;
  3218. }
  3219. private activateTexture(texture: number): void {
  3220. if (this._activeTexture !== texture) {
  3221. this._gl.activeTexture(texture);
  3222. this._activeTexture = texture;
  3223. }
  3224. }
  3225. public _bindTextureDirectly(target: number, texture: InternalTexture): void {
  3226. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  3227. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3228. this._activeTexturesCache[this._activeTexture] = texture;
  3229. }
  3230. }
  3231. public _bindTexture(channel: number, texture: InternalTexture): void {
  3232. if (channel < 0) {
  3233. return;
  3234. }
  3235. this.activateTexture(this._gl.TEXTURE0 + channel);
  3236. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3237. }
  3238. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  3239. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3240. }
  3241. public unbindAllTextures(): void {
  3242. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3243. this.activateTexture(this._gl["TEXTURE" + channel]);
  3244. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3245. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3246. }
  3247. }
  3248. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  3249. if (channel < 0) {
  3250. return;
  3251. }
  3252. this._gl.uniform1i(uniform, channel);
  3253. this._setTexture(channel, texture);
  3254. }
  3255. private _setTexture(channel: number, texture: BaseTexture): void {
  3256. // Not ready?
  3257. if (!texture) {
  3258. if (this._activeTexturesCache[channel] != null) {
  3259. this.activateTexture(this._gl["TEXTURE" + channel]);
  3260. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3261. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3262. }
  3263. return;
  3264. }
  3265. // Video
  3266. var alreadyActivated = false;
  3267. if ((<VideoTexture>texture).video) {
  3268. this.activateTexture(this._gl["TEXTURE" + channel]);
  3269. alreadyActivated = true;
  3270. (<VideoTexture>texture).update();
  3271. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3272. texture.delayLoad();
  3273. return;
  3274. }
  3275. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  3276. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  3277. if (this._activeTexturesCache[channel] === internalTexture) {
  3278. return;
  3279. }
  3280. if (!alreadyActivated) {
  3281. this.activateTexture(this._gl["TEXTURE" + channel]);
  3282. }
  3283. if (internalTexture.isCube) {
  3284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3285. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3286. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3287. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3288. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3289. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3290. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3291. }
  3292. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3293. } else {
  3294. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  3295. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3296. internalTexture._cachedWrapU = texture.wrapU;
  3297. switch (texture.wrapU) {
  3298. case Texture.WRAP_ADDRESSMODE:
  3299. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3300. break;
  3301. case Texture.CLAMP_ADDRESSMODE:
  3302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3303. break;
  3304. case Texture.MIRROR_ADDRESSMODE:
  3305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3306. break;
  3307. }
  3308. }
  3309. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3310. internalTexture._cachedWrapV = texture.wrapV;
  3311. switch (texture.wrapV) {
  3312. case Texture.WRAP_ADDRESSMODE:
  3313. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3314. break;
  3315. case Texture.CLAMP_ADDRESSMODE:
  3316. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3317. break;
  3318. case Texture.MIRROR_ADDRESSMODE:
  3319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3320. break;
  3321. }
  3322. }
  3323. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3324. }
  3325. }
  3326. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  3327. if (channel < 0) {
  3328. return;
  3329. }
  3330. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3331. this._textureUnits = new Int32Array(textures.length);
  3332. }
  3333. for (let i = 0; i < textures.length; i++) {
  3334. this._textureUnits[i] = channel + i;
  3335. }
  3336. this._gl.uniform1iv(uniform, this._textureUnits);
  3337. for (var index = 0; index < textures.length; index++) {
  3338. this._setTexture(channel + index, textures[index]);
  3339. }
  3340. }
  3341. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  3342. var internalTexture = texture.getInternalTexture();
  3343. if (!internalTexture) {
  3344. return;
  3345. }
  3346. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3347. var value = texture.anisotropicFilteringLevel;
  3348. if (internalTexture.samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  3349. value = 1;
  3350. }
  3351. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  3352. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  3353. internalTexture._cachedAnisotropicFilteringLevel = value;
  3354. }
  3355. }
  3356. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  3357. var data = new Uint8Array(height * width * 4);
  3358. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3359. return data;
  3360. }
  3361. /**
  3362. * Add an externaly attached data from its key.
  3363. * This method call will fail and return false, if such key already exists.
  3364. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3365. * @param key the unique key that identifies the data
  3366. * @param data the data object to associate to the key for this Engine instance
  3367. * @return true if no such key were already present and the data was added successfully, false otherwise
  3368. */
  3369. public addExternalData<T>(key: string, data: T): boolean {
  3370. if (!this._externalData) {
  3371. this._externalData = new StringDictionary<Object>();
  3372. }
  3373. return this._externalData.add(key, data);
  3374. }
  3375. /**
  3376. * Get an externaly attached data from its key
  3377. * @param key the unique key that identifies the data
  3378. * @return the associated data, if present (can be null), or undefined if not present
  3379. */
  3380. public getExternalData<T>(key: string): T {
  3381. if (!this._externalData) {
  3382. this._externalData = new StringDictionary<Object>();
  3383. }
  3384. return <T>this._externalData.get(key);
  3385. }
  3386. /**
  3387. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3388. * @param key the unique key that identifies the data
  3389. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3390. * @return the associated data, can be null if the factory returned null.
  3391. */
  3392. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3393. if (!this._externalData) {
  3394. this._externalData = new StringDictionary<Object>();
  3395. }
  3396. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3397. }
  3398. /**
  3399. * Remove an externaly attached data from the Engine instance
  3400. * @param key the unique key that identifies the data
  3401. * @return true if the data was successfully removed, false if it doesn't exist
  3402. */
  3403. public removeExternalData(key): boolean {
  3404. if (!this._externalData) {
  3405. this._externalData = new StringDictionary<Object>();
  3406. }
  3407. return this._externalData.remove(key);
  3408. }
  3409. public unbindAllAttributes() {
  3410. if (this._mustWipeVertexAttributes) {
  3411. this._mustWipeVertexAttributes = false;
  3412. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3413. this._gl.disableVertexAttribArray(i);
  3414. this._vertexAttribArraysEnabled[i] = false;
  3415. this._currentBufferPointers[i].active = false;
  3416. }
  3417. return;
  3418. }
  3419. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3420. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3421. continue;
  3422. }
  3423. this._gl.disableVertexAttribArray(i);
  3424. this._vertexAttribArraysEnabled[i] = false;
  3425. this._currentBufferPointers[i].active = false;
  3426. }
  3427. }
  3428. public releaseEffects() {
  3429. for (var name in this._compiledEffects) {
  3430. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3431. }
  3432. this._compiledEffects = {};
  3433. }
  3434. // Dispose
  3435. public dispose(): void {
  3436. this.hideLoadingUI();
  3437. this.stopRenderLoop();
  3438. // Release postProcesses
  3439. while (this.postProcesses.length) {
  3440. this.postProcesses[0].dispose();
  3441. }
  3442. // Empty texture
  3443. if (this._emptyTexture) {
  3444. this._releaseTexture(this._emptyTexture);
  3445. this._emptyTexture = null;
  3446. }
  3447. if (this._emptyCubeTexture) {
  3448. this._releaseTexture(this._emptyCubeTexture);
  3449. this._emptyCubeTexture = null;
  3450. }
  3451. // Rescale PP
  3452. if (this._rescalePostProcess) {
  3453. this._rescalePostProcess.dispose();
  3454. }
  3455. // Release scenes
  3456. while (this.scenes.length) {
  3457. this.scenes[0].dispose();
  3458. }
  3459. // Release audio engine
  3460. if (Engine.audioEngine) {
  3461. Engine.audioEngine.dispose();
  3462. }
  3463. // Release effects
  3464. this.releaseEffects();
  3465. // Unbind
  3466. this.unbindAllAttributes();
  3467. if (this._dummyFramebuffer) {
  3468. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3469. }
  3470. this._gl = null;
  3471. //WebVR
  3472. this.disableVR();
  3473. // Events
  3474. window.removeEventListener("blur", this._onBlur);
  3475. window.removeEventListener("focus", this._onFocus);
  3476. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  3477. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  3478. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  3479. if (!this._doNotHandleContextLost) {
  3480. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3481. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3482. }
  3483. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3484. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3485. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3486. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3487. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3488. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3489. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3490. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3491. // Remove from Instances
  3492. var index = Engine.Instances.indexOf(this);
  3493. if (index >= 0) {
  3494. Engine.Instances.splice(index, 1);
  3495. }
  3496. this._workingCanvas = null;
  3497. this._workingContext = null;
  3498. this._currentBufferPointers = null;
  3499. this._renderingCanvas = null;
  3500. this._currentProgram = null;
  3501. this.onResizeObservable.clear();
  3502. this.onCanvasBlurObservable.clear();
  3503. BABYLON.Effect.ResetCache();
  3504. }
  3505. // Loading screen
  3506. public displayLoadingUI(): void {
  3507. const loadingScreen = this.loadingScreen;
  3508. if (loadingScreen) {
  3509. loadingScreen.displayLoadingUI();
  3510. }
  3511. }
  3512. public hideLoadingUI(): void {
  3513. const loadingScreen = this.loadingScreen;
  3514. if (loadingScreen) {
  3515. loadingScreen.hideLoadingUI();
  3516. }
  3517. }
  3518. public get loadingScreen(): ILoadingScreen {
  3519. if (!this._loadingScreen && DefaultLoadingScreen)
  3520. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  3521. return this._loadingScreen;
  3522. }
  3523. public set loadingScreen(loadingScreen: ILoadingScreen) {
  3524. this._loadingScreen = loadingScreen;
  3525. }
  3526. public set loadingUIText(text: string) {
  3527. this.loadingScreen.loadingUIText = text;
  3528. }
  3529. public set loadingUIBackgroundColor(color: string) {
  3530. this.loadingScreen.loadingUIBackgroundColor = color;
  3531. }
  3532. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3533. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  3534. }
  3535. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3536. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  3537. }
  3538. public getVertexShaderSource(program: WebGLProgram): string {
  3539. var shaders = this._gl.getAttachedShaders(program);
  3540. return this._gl.getShaderSource(shaders[0]);
  3541. }
  3542. public getFragmentShaderSource(program: WebGLProgram): string {
  3543. var shaders = this._gl.getAttachedShaders(program);
  3544. return this._gl.getShaderSource(shaders[1]);
  3545. }
  3546. public getError(): number {
  3547. return this._gl.getError();
  3548. }
  3549. // FPS
  3550. public getFps(): number {
  3551. return this._fps;
  3552. }
  3553. public getDeltaTime(): number {
  3554. return this._deltaTime;
  3555. }
  3556. private _measureFps(): void {
  3557. this._performanceMonitor.sampleFrame();
  3558. this._fps = this._performanceMonitor.averageFPS;
  3559. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  3560. }
  3561. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  3562. let gl = this._gl;
  3563. if (!this._dummyFramebuffer) {
  3564. this._dummyFramebuffer = gl.createFramebuffer();
  3565. }
  3566. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  3567. if (faceIndex > -1) {
  3568. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  3569. } else {
  3570. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3571. }
  3572. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  3573. let buffer: ArrayBufferView;
  3574. switch (readType) {
  3575. case gl.UNSIGNED_BYTE:
  3576. buffer = new Uint8Array(4 * width * height);
  3577. readType = gl.UNSIGNED_BYTE;
  3578. break;
  3579. default:
  3580. buffer = new Float32Array(4 * width * height);
  3581. readType = gl.FLOAT;
  3582. break;
  3583. }
  3584. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  3585. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  3586. return buffer;
  3587. }
  3588. private _canRenderToFloatFramebuffer(): boolean {
  3589. if (this._webGLVersion > 1) {
  3590. return this._caps.colorBufferFloat;
  3591. }
  3592. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  3593. }
  3594. private _canRenderToHalfFloatFramebuffer(): boolean {
  3595. if (this._webGLVersion > 1) {
  3596. return this._caps.colorBufferFloat;
  3597. }
  3598. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  3599. }
  3600. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3601. private _canRenderToFramebuffer(type: number): boolean {
  3602. let gl = this._gl;
  3603. //clear existing errors
  3604. while (gl.getError() !== gl.NO_ERROR) { }
  3605. let successful = true;
  3606. let texture = gl.createTexture();
  3607. gl.bindTexture(gl.TEXTURE_2D, texture);
  3608. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3611. let fb = gl.createFramebuffer();
  3612. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3613. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3614. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3615. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3616. successful = successful && (gl.getError() === gl.NO_ERROR);
  3617. //try render by clearing frame buffer's color buffer
  3618. if (successful) {
  3619. gl.clear(gl.COLOR_BUFFER_BIT);
  3620. successful = successful && (gl.getError() === gl.NO_ERROR);
  3621. }
  3622. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3623. if (successful) {
  3624. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3625. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3626. let readFormat = gl.RGBA;
  3627. let readType = gl.UNSIGNED_BYTE;
  3628. let buffer = new Uint8Array(4);
  3629. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3630. successful = successful && (gl.getError() === gl.NO_ERROR);
  3631. }
  3632. //clean up
  3633. gl.deleteTexture(texture);
  3634. gl.deleteFramebuffer(fb);
  3635. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3636. //clear accumulated errors
  3637. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3638. return successful;
  3639. }
  3640. public _getWebGLTextureType(type: number): number {
  3641. if (type === Engine.TEXTURETYPE_FLOAT) {
  3642. return this._gl.FLOAT;
  3643. }
  3644. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3645. // Add Half Float Constant.
  3646. return this._gl.HALF_FLOAT_OES;
  3647. }
  3648. return this._gl.UNSIGNED_BYTE;
  3649. };
  3650. public _getRGBABufferInternalSizedFormat(type: number): number {
  3651. if (this._webGLVersion === 1) {
  3652. return this._gl.RGBA;
  3653. }
  3654. if (type === Engine.TEXTURETYPE_FLOAT) {
  3655. return this._gl.RGBA32F;
  3656. }
  3657. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3658. return this._gl.RGBA16F;
  3659. }
  3660. return this._gl.RGBA;
  3661. };
  3662. public createQuery(): WebGLQuery {
  3663. return this._gl.createQuery();
  3664. }
  3665. public deleteQuery(query: WebGLQuery): Engine {
  3666. this._gl.deleteQuery(query);
  3667. return this;
  3668. }
  3669. public isQueryResultAvailable(query: WebGLQuery): boolean {
  3670. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  3671. }
  3672. public getQueryResult(query: WebGLQuery): number {
  3673. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  3674. }
  3675. public beginQuery(algorithmType: number, query: WebGLQuery) {
  3676. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3677. this._gl.beginQuery(glAlgorithm, query);
  3678. }
  3679. public endQuery(algorithmType: number): Engine {
  3680. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3681. this._gl.endQuery(glAlgorithm);
  3682. return this;
  3683. }
  3684. private getGlAlgorithmType(algorithmType: number): number {
  3685. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  3686. }
  3687. // Statics
  3688. public static isSupported(): boolean {
  3689. try {
  3690. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  3691. if (navigator.isCocoonJS) {
  3692. return true;
  3693. }
  3694. var tempcanvas = document.createElement("canvas");
  3695. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3696. return gl != null && !!window.WebGLRenderingContext;
  3697. } catch (e) {
  3698. return false;
  3699. }
  3700. }
  3701. }
  3702. }