12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392 |
- module BABYLON {
- var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
- var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
- gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
- gl.compileShader(shader);
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
- throw new Error(gl.getShaderInfoLog(shader));
- }
- return shader;
- };
- var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
- var magFilter = gl.NEAREST;
- var minFilter = gl.NEAREST;
- if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_NEAREST;
- } else {
- minFilter = gl.LINEAR;
- }
- } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
- magFilter = gl.LINEAR;
- if (generateMipMaps) {
- minFilter = gl.LINEAR_MIPMAP_LINEAR;
- } else {
- minFilter = gl.LINEAR;
- }
- } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
- magFilter = gl.NEAREST;
- if (generateMipMaps) {
- minFilter = gl.NEAREST_MIPMAP_LINEAR;
- } else {
- minFilter = gl.NEAREST;
- }
- }
- return {
- min: minFilter,
- mag: magFilter
- }
- }
- var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
- processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
- var engine = scene.getEngine();
- var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
- var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
- engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = potWidth;
- texture._height = potHeight;
- texture.isReady = true;
- processFunction(potWidth, potHeight);
- var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- if (!noMipmap && !isCompressed) {
- gl.generateMipmap(gl.TEXTURE_2D);
- }
- engine._bindTextureDirectly(gl.TEXTURE_2D, null);
- engine.resetTextureCache();
- scene._removePendingData(texture);
- texture.onLoadedCallbacks.forEach(callback => {
- callback();
- });
- texture.onLoadedCallbacks = [];
- };
- var partialLoad = (url: string, index: number, loadedImages: any, scene,
- onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
- var img: HTMLImageElement;
- var onload = () => {
- loadedImages[index] = img;
- loadedImages._internalCount++;
- scene._removePendingData(img);
- if (loadedImages._internalCount === 6) {
- onfinish(loadedImages);
- }
- };
- var onerror = () => {
- scene._removePendingData(img);
- if (onErrorCallBack) {
- onErrorCallBack();
- }
- };
- img = Tools.LoadImage(url, onload, onerror, scene.database);
- scene._addPendingData(img);
- }
- var cascadeLoad = (rootUrl: string, scene,
- onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
- var loadedImages: any = [];
- loadedImages._internalCount = 0;
- for (var index = 0; index < 6; index++) {
- partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
- }
- };
- export class InstancingAttributeInfo {
- /**
- * Index/offset of the attribute in the vertex shader
- */
- index: number;
- /**
- * size of the attribute, 1, 2, 3 or 4
- */
- attributeSize: number;
- /**
- * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
- * default is FLOAT
- */
- attribyteType: number;
- /**
- * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
- */
- normalized: boolean;
- /**
- * Offset of the data in the Vertex Buffer acting as the instancing buffer
- */
- offset: number;
- /**
- * Name of the GLSL attribute, for debugging purpose only
- */
- attributeName: string;
- }
- export class EngineCapabilities {
- public maxTexturesImageUnits: number;
- public maxTextureSize: number;
- public maxCubemapTextureSize: number;
- public maxRenderTextureSize: number;
- public maxVertexAttribs: number;
- public maxVaryingVectors: number;
- public maxVertexUniformVectors: number;
- public maxFragmentUniformVectors: number;
- public standardDerivatives: boolean;
- public s3tc: WEBGL_compressed_texture_s3tc;
- public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
- public etc1: any; //WEBGL_compressed_texture_etc1;
- public etc2: any; //WEBGL_compressed_texture_etc;
- public astc: any; //WEBGL_compressed_texture_astc;
- public atc: any; //WEBGL_compressed_texture_atc;
- public textureFloat: boolean;
- public vertexArrayObject: boolean;
- public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
- public maxAnisotropy: number;
- public instancedArrays: boolean;
- public uintIndices: boolean;
- public highPrecisionShaderSupported: boolean;
- public fragmentDepthSupported: boolean;
- public textureFloatLinearFiltering: boolean;
- public textureFloatRender: boolean;
- public textureHalfFloat: boolean;
- public textureHalfFloatLinearFiltering: boolean;
- public textureHalfFloatRender: boolean;
- public textureLOD: boolean;
- public drawBuffersExtension;
- public colorBufferFloat: boolean;
- }
- export interface EngineOptions extends WebGLContextAttributes {
- limitDeviceRatio?: number;
- autoEnableWebVR?: boolean;
- disableWebGL2Support?: boolean;
- }
- /**
- * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
- */
- export class Engine {
- // Const statics
- private static _ALPHA_DISABLE = 0;
- private static _ALPHA_ADD = 1;
- private static _ALPHA_COMBINE = 2;
- private static _ALPHA_SUBTRACT = 3;
- private static _ALPHA_MULTIPLY = 4;
- private static _ALPHA_MAXIMIZED = 5;
- private static _ALPHA_ONEONE = 6;
- private static _ALPHA_PREMULTIPLIED = 7;
- private static _DELAYLOADSTATE_NONE = 0;
- private static _DELAYLOADSTATE_LOADED = 1;
- private static _DELAYLOADSTATE_LOADING = 2;
- private static _DELAYLOADSTATE_NOTLOADED = 4;
- private static _TEXTUREFORMAT_ALPHA = 0;
- private static _TEXTUREFORMAT_LUMINANCE = 1;
- private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
- private static _TEXTUREFORMAT_RGB = 4;
- private static _TEXTUREFORMAT_RGBA = 5;
- private static _TEXTURETYPE_UNSIGNED_INT = 0;
- private static _TEXTURETYPE_FLOAT = 1;
- private static _TEXTURETYPE_HALF_FLOAT = 2;
- // Depht or Stencil test Constants.
- private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- private static HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
- private static RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
- private static RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
- public static get NEVER(): number {
- return Engine._NEVER;
- }
- public static get ALWAYS(): number {
- return Engine._ALWAYS;
- }
- public static get LESS(): number {
- return Engine._LESS;
- }
- public static get EQUAL(): number {
- return Engine._EQUAL;
- }
- public static get LEQUAL(): number {
- return Engine._LEQUAL;
- }
- public static get GREATER(): number {
- return Engine._GREATER;
- }
- public static get GEQUAL(): number {
- return Engine._GEQUAL;
- }
- public static get NOTEQUAL(): number {
- return Engine._NOTEQUAL;
- }
- // Stencil Actions Constants.
- private static _KEEP = 0x1E00;
- private static _REPLACE = 0x1E01;
- private static _INCR = 0x1E02;
- private static _DECR = 0x1E03;
- private static _INVERT = 0x150A;
- private static _INCR_WRAP = 0x8507;
- private static _DECR_WRAP = 0x8508;
- public static get KEEP(): number {
- return Engine._KEEP;
- }
- public static get REPLACE(): number {
- return Engine._REPLACE;
- }
- public static get INCR(): number {
- return Engine._INCR;
- }
- public static get DECR(): number {
- return Engine._DECR;
- }
- public static get INVERT(): number {
- return Engine._INVERT;
- }
- public static get INCR_WRAP(): number {
- return Engine._INCR_WRAP;
- }
- public static get DECR_WRAP(): number {
- return Engine._DECR_WRAP;
- }
- public static get ALPHA_DISABLE(): number {
- return Engine._ALPHA_DISABLE;
- }
- public static get ALPHA_ONEONE(): number {
- return Engine._ALPHA_ONEONE;
- }
- public static get ALPHA_ADD(): number {
- return Engine._ALPHA_ADD;
- }
- public static get ALPHA_COMBINE(): number {
- return Engine._ALPHA_COMBINE;
- }
- public static get ALPHA_SUBTRACT(): number {
- return Engine._ALPHA_SUBTRACT;
- }
- public static get ALPHA_MULTIPLY(): number {
- return Engine._ALPHA_MULTIPLY;
- }
- public static get ALPHA_MAXIMIZED(): number {
- return Engine._ALPHA_MAXIMIZED;
- }
- public static get ALPHA_PREMULTIPLIED(): number {
- return Engine._ALPHA_PREMULTIPLIED;
- }
- public static get DELAYLOADSTATE_NONE(): number {
- return Engine._DELAYLOADSTATE_NONE;
- }
- public static get DELAYLOADSTATE_LOADED(): number {
- return Engine._DELAYLOADSTATE_LOADED;
- }
- public static get DELAYLOADSTATE_LOADING(): number {
- return Engine._DELAYLOADSTATE_LOADING;
- }
- public static get DELAYLOADSTATE_NOTLOADED(): number {
- return Engine._DELAYLOADSTATE_NOTLOADED;
- }
- public static get TEXTUREFORMAT_ALPHA(): number {
- return Engine._TEXTUREFORMAT_ALPHA;
- }
- public static get TEXTUREFORMAT_LUMINANCE(): number {
- return Engine._TEXTUREFORMAT_LUMINANCE;
- }
- public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
- return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
- }
- public static get TEXTUREFORMAT_RGB(): number {
- return Engine._TEXTUREFORMAT_RGB;
- }
- public static get TEXTUREFORMAT_RGBA(): number {
- return Engine._TEXTUREFORMAT_RGBA;
- }
- public static get TEXTURETYPE_UNSIGNED_INT(): number {
- return Engine._TEXTURETYPE_UNSIGNED_INT;
- }
- public static get TEXTURETYPE_FLOAT(): number {
- return Engine._TEXTURETYPE_FLOAT;
- }
- public static get TEXTURETYPE_HALF_FLOAT(): number {
- return Engine._TEXTURETYPE_HALF_FLOAT;
- }
- public static get Version(): string {
- return "2.6-alpha";
- }
- // Updatable statics so stick with vars here
- public static CollisionsEpsilon = 0.001;
- public static CodeRepository = "src/";
- public static ShadersRepository = "src/Shaders/";
- // Public members
- public isFullscreen = false;
- public isPointerLock = false;
- public cullBackFaces = true;
- public renderEvenInBackground = true;
- // To enable/disable IDB support and avoid XHR on .manifest
- public enableOfflineSupport = true;
- public scenes = new Array<Scene>();
- //WebVR
- //The new WebVR uses promises.
- //this promise resolves with the current devices available.
- public vrDisplaysPromise;
- private _vrDisplays;
- private _vrDisplayEnabled;
- private _oldSize: BABYLON.Size;
- private _oldHardwareScaleFactor: number;
- private _vrAnimationFrameHandler: number;
- // Private Members
- public _gl: WebGLRenderingContext;
- private _renderingCanvas: HTMLCanvasElement;
- private _windowIsBackground = false;
- private _webGLVersion = 1.0;
- private _badOS = false;
- public static audioEngine: AudioEngine;
- private _onBlur: () => void;
- private _onFocus: () => void;
- private _onFullscreenChange: () => void;
- private _onPointerLockChange: () => void;
- private _hardwareScalingLevel: number;
- private _caps: EngineCapabilities;
- private _pointerLockRequested: boolean;
- private _alphaTest: boolean;
- private _isStencilEnable: boolean;
- private _loadingScreen: ILoadingScreen;
- public _drawCalls = new PerfCounter();
- private _glVersion: string;
- private _glRenderer: string;
- private _glVendor: string;
- private _videoTextureSupported: boolean;
- private _renderingQueueLaunched = false;
- private _activeRenderLoops = [];
- // FPS
- private fpsRange = 60;
- private previousFramesDuration = [];
- private fps = 60;
- private deltaTime = 0;
- // States
- private _depthCullingState = new Internals._DepthCullingState();
- private _stencilState = new Internals._StencilState();
- private _alphaState = new Internals._AlphaState();
- private _alphaMode = Engine.ALPHA_DISABLE;
- // Cache
- private _loadedTexturesCache = new Array<WebGLTexture>();
- private _maxTextureChannels = 16;
- private _activeTexture: number;
- private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
- private _currentEffect: Effect;
- private _currentProgram: WebGLProgram;
- private _compiledEffects = {};
- private _vertexAttribArraysEnabled: boolean[] = [];
- private _cachedViewport: Viewport;
- private _cachedVertexArrayObject: WebGLVertexArrayObject;
- private _cachedVertexBuffers: any;
- private _cachedIndexBuffer: WebGLBuffer;
- private _cachedEffectForVertexBuffers: Effect;
- private _currentRenderTarget: WebGLTexture;
- private _uintIndicesCurrentlySet = false;
- private _currentBoundBuffer = new Array<WebGLBuffer>();
- private _currentFramebuffer: WebGLFramebuffer;
- private _currentBufferPointers: Array<{ indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number, buffer: WebGLBuffer }> = [];
- private _currentInstanceLocations = new Array<number>();
- private _currentInstanceBuffers = new Array<WebGLBuffer>();
- private _textureUnits: Int32Array;
- private _workingCanvas: HTMLCanvasElement;
- private _workingContext: CanvasRenderingContext2D;
- private _externalData: StringDictionary<Object>;
- private _bindedRenderFunction: any;
- private _vaoRecordInProgress = false;
- private _mustWipeVertexAttributes = false;
-
- // Hardware supported Compressed Textures
- private _texturesSupported = new Array<string>();
- private _textureFormatInUse : string;
-
- public get texturesSupported(): Array<string> {
- return this._texturesSupported;
- }
-
- public get textureFormatInUse(): string {
- return this._textureFormatInUse;
- }
-
- /**
- * @constructor
- * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
- * @param {boolean} [antialias] - enable antialias
- * @param options - further options to be sent to the getContext function
- */
- constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
- this._renderingCanvas = canvas;
- this._externalData = new StringDictionary<Object>();
- options = options || {};
- if (antialias != null) {
- options.antialias = antialias;
- }
- if (options.preserveDrawingBuffer === undefined) {
- options.preserveDrawingBuffer = false;
- }
- // GL
- if (!options.disableWebGL2Support) {
- try {
- this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
- if (this._gl) {
- this._webGLVersion = 2.0;
- }
- } catch (e) {
- // Do nothing
- }
- }
- if (!this._gl) {
- if (!canvas) {
- throw new Error("The provided canvas is null or undefined.");
- }
- try {
- this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
- } catch (e) {
- throw new Error("WebGL not supported");
- }
- }
- if (!this._gl) {
- throw new Error("WebGL not supported");
- }
-
- this._onBlur = () => {
- this._windowIsBackground = true;
- };
- this._onFocus = () => {
- this._windowIsBackground = false;
- };
- window.addEventListener("blur", this._onBlur);
- window.addEventListener("focus", this._onFocus);
- // Viewport
- var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
- this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
- this.resize();
- // Caps
- this._isStencilEnable = options.stencil;
- this._caps = new EngineCapabilities();
- this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
- this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
- this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
- this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
- this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
- this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
- this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
- this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
- // Infos
- this._glVersion = this._gl.getParameter(this._gl.VERSION);
- var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
- if (rendererInfo != null) {
- this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
- this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
- }
- if (!this._glVendor) {
- this._glVendor = "Unknown vendor";
- }
- if (!this._glRenderer) {
- this._glRenderer = "Unknown renderer";
- }
- // Extensions
- this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
-
- this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc' );
- this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc' );
- this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
- this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1' );
- this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc' ) ||
- this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
- this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc' );
-
- 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');
- this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
- this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
- this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
- this._caps.highPrecisionShaderSupported = true;
- this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
- // Checks if some of the format renders first to allow the use of webgl inspector.
- this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float')
- this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
- this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
- this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
- this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
- this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
- this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
-
- this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
- // Vertex array object
- if ( this._webGLVersion > 1) {
- this._caps.vertexArrayObject = true;
- } else{
- var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
- if (vertexArrayObjectExtension != null) {
- this._caps.vertexArrayObject = true;
- this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
- this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
- this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
- } else{
- this._caps.vertexArrayObject = false;
- }
- }
- // Instances count
- if ( this._webGLVersion > 1) {
- this._caps.instancedArrays = true;
- } else{
- var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
- if (instanceExtension != null) {
- this._caps.instancedArrays = true;
- this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
- this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
- this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
- } else{
- this._caps.instancedArrays = false;
- }
- }
-
- // Intelligently add supported compressed formats in order to check for.
- // Check for ASTC support first as it is most powerful and to be very cross platform.
- // Next PVRTC & DXT, which are probably superior to ETC1/2.
- // Likely no hardware which supports both PVR & DXT, so order matters little.
- // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
- // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
- if (this._caps.astc ) this.texturesSupported.push('-astc.ktx');
- if (this._caps.s3tc ) this.texturesSupported.push('-dxt.ktx');
- if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
- if (this._caps.etc2 ) this.texturesSupported.push('-etc2.ktx');
- if (this._caps.atc ) this.texturesSupported.push('-atc.ktx');
- if (this._caps.etc1 ) this.texturesSupported.push('-etc1.ktx');
-
- if (this._gl.getShaderPrecisionFormat) {
- var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
- this._caps.highPrecisionShaderSupported = highp.precision !== 0;
- }
- // Depth buffer
- this.setDepthBuffer(true);
- this.setDepthFunctionToLessOrEqual();
- this.setDepthWrite(true);
- // Fullscreen
- this._onFullscreenChange = () => {
- if (document.fullscreen !== undefined) {
- this.isFullscreen = document.fullscreen;
- } else if (document.mozFullScreen !== undefined) {
- this.isFullscreen = document.mozFullScreen;
- } else if (document.webkitIsFullScreen !== undefined) {
- this.isFullscreen = document.webkitIsFullScreen;
- } else if (document.msIsFullScreen !== undefined) {
- this.isFullscreen = document.msIsFullScreen;
- }
- // Pointer lock
- if (this.isFullscreen && this._pointerLockRequested) {
- canvas.requestPointerLock = canvas.requestPointerLock ||
- canvas.msRequestPointerLock ||
- canvas.mozRequestPointerLock ||
- canvas.webkitRequestPointerLock;
- if (canvas.requestPointerLock) {
- canvas.requestPointerLock();
- }
- }
- };
- document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
- document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
- // Pointer lock
- this._onPointerLockChange = () => {
- this.isPointerLock = (document.mozPointerLockElement === canvas ||
- document.webkitPointerLockElement === canvas ||
- document.msPointerLockElement === canvas ||
- document.pointerLockElement === canvas
- );
- };
- document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
- document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
- if (AudioEngine && !Engine.audioEngine) {
- Engine.audioEngine = new AudioEngine();
- }
- //default loading screen
- this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
- //Load WebVR Devices
- if (options.autoEnableWebVR) {
- this.initWebVR();
- }
- //Detect if we are running on a faulty buggy OS.
- var regexp = /AppleWebKit.*10.[\d] Mobile/
- //ua sniffing is the tool of the devil.
- this._badOS = regexp.test(navigator.userAgent);
- Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
- }
- public get webGLVersion(): number {
- return this._webGLVersion;
- }
- /**
- * Returns true if the stencil buffer has been enabled through the creation option of the context.
- */
- public get isStencilEnable(): boolean {
- return this._isStencilEnable;
- }
- private _prepareWorkingCanvas(): void {
- if (this._workingCanvas) {
- return;
- }
- this._workingCanvas = document.createElement("canvas");
- this._workingContext = this._workingCanvas.getContext("2d");
- }
- public resetTextureCache() {
- for (var index = 0; index < this._maxTextureChannels; index++) {
- this._activeTexturesCache[index] = null;
- }
- }
- public getGlInfo() {
- return {
- vendor: this._glVendor,
- renderer: this._glRenderer,
- version: this._glVersion
- }
- }
- public getAspectRatio(camera: Camera, useScreen = false): number {
- var viewport = camera.viewport;
- return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
- }
- public getRenderWidth(useScreen = false): number {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._width;
- }
- return this._renderingCanvas.width;
- }
- public getRenderHeight(useScreen = false): number {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget._height;
- }
- return this._renderingCanvas.height;
- }
- public getRenderingCanvas(): HTMLCanvasElement {
- return this._renderingCanvas;
- }
- public getRenderingCanvasClientRect(): ClientRect {
- return this._renderingCanvas.getBoundingClientRect();
- }
- public setHardwareScalingLevel(level: number): void {
- this._hardwareScalingLevel = level;
- this.resize();
- }
- public getHardwareScalingLevel(): number {
- return this._hardwareScalingLevel;
- }
- public getLoadedTexturesCache(): WebGLTexture[] {
- return this._loadedTexturesCache;
- }
- public getCaps(): EngineCapabilities {
- return this._caps;
- }
- public get drawCalls(): number {
- return this._drawCalls.current;
- }
- public get drawCallsPerfCounter(): PerfCounter {
- return this._drawCalls;
- }
- public getDepthFunction(): number {
- return this._depthCullingState.depthFunc;
- }
- public setDepthFunction(depthFunc: number) {
- this._depthCullingState.depthFunc = depthFunc;
- }
- public setDepthFunctionToGreater(): void {
- this._depthCullingState.depthFunc = this._gl.GREATER;
- }
- public setDepthFunctionToGreaterOrEqual(): void {
- this._depthCullingState.depthFunc = this._gl.GEQUAL;
- }
- public setDepthFunctionToLess(): void {
- this._depthCullingState.depthFunc = this._gl.LESS;
- }
- public setDepthFunctionToLessOrEqual(): void {
- this._depthCullingState.depthFunc = this._gl.LEQUAL;
- }
- public getStencilBuffer(): boolean {
- return this._stencilState.stencilTest;
- }
- public setStencilBuffer(enable: boolean): void {
- this._stencilState.stencilTest = enable;
- }
- public getStencilMask(): number {
- return this._stencilState.stencilMask;
- }
- public setStencilMask(mask: number): void {
- this._stencilState.stencilMask = mask;
- }
- public getStencilFunction(): number {
- return this._stencilState.stencilFunc;
- }
- public getStencilFunctionReference(): number {
- return this._stencilState.stencilFuncRef;
- }
- public getStencilFunctionMask(): number {
- return this._stencilState.stencilFuncMask;
- }
- public setStencilFunction(stencilFunc: number) {
- this._stencilState.stencilFunc = stencilFunc;
- }
- public setStencilFunctionReference(reference: number) {
- this._stencilState.stencilFuncRef = reference;
- }
- public setStencilFunctionMask(mask: number) {
- this._stencilState.stencilFuncMask = mask;
- }
- public getStencilOperationFail(): number {
- return this._stencilState.stencilOpStencilFail;
- }
- public getStencilOperationDepthFail(): number {
- return this._stencilState.stencilOpDepthFail;
- }
- public getStencilOperationPass(): number {
- return this._stencilState.stencilOpStencilDepthPass;
- }
- public setStencilOperationFail(operation: number): void {
- this._stencilState.stencilOpStencilFail = operation;
- }
- public setStencilOperationDepthFail(operation: number): void {
- this._stencilState.stencilOpDepthFail = operation;
- }
- public setStencilOperationPass(operation: number): void {
- this._stencilState.stencilOpStencilDepthPass = operation;
- }
- /**
- * stop executing a render loop function and remove it from the execution array
- * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
- */
- public stopRenderLoop(renderFunction?: () => void): void {
- if (!renderFunction) {
- this._activeRenderLoops = [];
- return;
- }
- var index = this._activeRenderLoops.indexOf(renderFunction);
- if (index >= 0) {
- this._activeRenderLoops.splice(index, 1);
- }
- }
- public _renderLoop(): void {
- var shouldRender = true;
- if (!this.renderEvenInBackground && this._windowIsBackground) {
- shouldRender = false;
- }
- if (shouldRender) {
- // Start new frame
- this.beginFrame();
- for (var index = 0; index < this._activeRenderLoops.length; index++) {
- var renderFunction = this._activeRenderLoops[index];
- renderFunction();
- }
- // Present
- this.endFrame();
- }
- if (this._activeRenderLoops.length > 0) {
- // Register new frame
- Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
- } else {
- this._renderingQueueLaunched = false;
- }
- }
- /**
- * Register and execute a render loop. The engine can have more than one render function.
- * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
- * @example
- * engine.runRenderLoop(function () {
- * scene.render()
- * })
- */
- public runRenderLoop(renderFunction: () => void): void {
- if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
- return;
- }
- this._activeRenderLoops.push(renderFunction);
- if (!this._renderingQueueLaunched) {
- this._renderingQueueLaunched = true;
- this._bindedRenderFunction = this._renderLoop.bind(this);
- Tools.QueueNewFrame(this._bindedRenderFunction);
- }
- }
- /**
- * Toggle full screen mode.
- * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
- * @param {any} options - an options object to be sent to the requestFullscreen function
- */
- public switchFullscreen(requestPointerLock: boolean): void {
- if (this.isFullscreen) {
- Tools.ExitFullscreen();
- } else {
- this._pointerLockRequested = requestPointerLock;
- Tools.RequestFullscreen(this._renderingCanvas);
- }
- }
- public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
- this.applyStates();
- var mode = 0;
- if (backBuffer && color) {
- this._gl.clearColor(color.r, color.g, color.b, color.a);
- mode |= this._gl.COLOR_BUFFER_BIT;
- }
- if (depth) {
- this._gl.clearDepth(1.0);
- mode |= this._gl.DEPTH_BUFFER_BIT;
- }
- if (stencil) {
- this._gl.clearStencil(0);
- mode |= this._gl.STENCIL_BUFFER_BIT;
- }
- this._gl.clear(mode);
- }
- public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
- let gl = this._gl;
- // Save state
- var curScissor = gl.getParameter(gl.SCISSOR_TEST);
- var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
- // Change state
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(x, y, width, height);
- // Clear
- this.clear(clearColor, true, true, true);
- // Restore state
- gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
- if (curScissor === true) {
- gl.enable(gl.SCISSOR_TEST);
- } else {
- gl.disable(gl.SCISSOR_TEST);
- }
- }
- /**
- * Set the WebGL's viewport
- * @param {BABYLON.Viewport} viewport - the viewport element to be used.
- * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
- * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
- */
- public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
- var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
- var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
- var x = viewport.x || 0;
- var y = viewport.y || 0;
- this._cachedViewport = viewport;
- this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
- }
- /**
- * Directly set the WebGL Viewport
- * The x, y, width & height are directly passed to the WebGL call
- * @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.
- */
- public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
- let currentViewport = this._cachedViewport;
- this._cachedViewport = null;
- this._gl.viewport(x, y, width, height);
- return currentViewport;
- }
- public beginFrame(): void {
- this._measureFps();
- }
- public endFrame(): void {
- //force a flush in case we are using a bad OS.
- if (this._badOS) {
- this.flushFramebuffer();
- }
- //submit frame to the vr device, if enabled
- if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
- this._vrDisplayEnabled.submitFrame()
- }
- }
- /**
- * resize the view according to the canvas' size.
- * @example
- * window.addEventListener("resize", function () {
- * engine.resize();
- * });
- */
- public resize(): void {
- var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
- var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
- this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
- }
- /**
- * force a specific size of the canvas
- * @param {number} width - the new canvas' width
- * @param {number} height - the new canvas' height
- */
- public setSize(width: number, height: number): void {
- this._renderingCanvas.width = width;
- this._renderingCanvas.height = height;
- for (var index = 0; index < this.scenes.length; index++) {
- var scene = this.scenes[index];
- for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
- var cam = scene.cameras[camIndex];
- cam._currentRenderId = 0;
- }
- }
- }
- //WebVR functions
- public initWebVR() {
- if (!this.vrDisplaysPromise) {
- this._getVRDisplays();
- }
- }
- public enableVR(vrDevice) {
- this._vrDisplayEnabled = vrDevice;
- this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
- }
- public disableVR() {
- if (this._vrDisplayEnabled) {
- this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
- }
- }
- private _onVRFullScreenTriggered = () => {
- if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
- //get the old size before we change
- this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
- this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
- //according to the WebVR specs, requestAnimationFrame should be triggered only once.
- //But actually, no browser follow the specs...
- //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
- //get the width and height, change the render size
- var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
- var width, height;
- this.setHardwareScalingLevel(1);
- this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
- } else {
- //When the specs are implemented, need to uncomment this.
- //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
- this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
- this.setSize(this._oldSize.width, this._oldSize.height);
- this._vrDisplayEnabled = undefined;
- }
- }
- private _getVRDisplays() {
- var getWebVRDevices = (devices: Array<any>) => {
- var size = devices.length;
- var i = 0;
- this._vrDisplays = devices.filter(function (device) {
- return devices[i] instanceof VRDisplay;
- });
- return this._vrDisplays;
- }
- //using a key due to typescript
- if (navigator.getVRDisplays) {
- this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
- }
- }
- public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
- this._currentRenderTarget = texture;
- this.bindUnboundFramebuffer(texture._framebuffer);
- var gl = this._gl;
- if (texture.isCube) {
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
- }
- gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
- this.wipeCaches();
- }
- private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
- if (this._currentFramebuffer !== framebuffer) {
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
- this._currentFramebuffer = framebuffer;
- }
- }
- public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false): void {
- this._currentRenderTarget = null;
- if (texture.generateMipMaps && !disableGenerateMipMaps) {
- var gl = this._gl;
- this._bindTextureDirectly(gl.TEXTURE_2D, texture);
- gl.generateMipmap(gl.TEXTURE_2D);
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- }
- this.bindUnboundFramebuffer(null);
- }
- public generateMipMapsForCubemap(texture: WebGLTexture) {
- if (texture.generateMipMaps) {
- var gl = this._gl;
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- }
- }
- public flushFramebuffer(): void {
- this._gl.flush();
- }
- public restoreDefaultFramebuffer(): void {
- this._currentRenderTarget = null;
- this.bindUnboundFramebuffer(null);
- this.setViewport(this._cachedViewport);
- this.wipeCaches();
- }
- // VBOs
- private _resetVertexBufferBinding(): void {
- this.bindArrayBuffer(null);
- this._cachedVertexBuffers = null;
- }
- public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
- var vbo = this._gl.createBuffer();
- this.bindArrayBuffer(vbo);
- if (vertices instanceof Float32Array) {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
- } else {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
- }
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- }
- public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
- var vbo = this._gl.createBuffer();
- this.bindArrayBuffer(vbo);
- if (vertices instanceof Float32Array) {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
- } else {
- this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
- }
- this._resetVertexBufferBinding();
- vbo.references = 1;
- return vbo;
- }
- public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
- this.bindArrayBuffer(vertexBuffer);
- if (offset === undefined) {
- offset = 0;
- }
- if (count === undefined) {
- if (vertices instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
- } else {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
- }
- } else {
- if (vertices instanceof Float32Array) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
- } else {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
- }
- }
- this._resetVertexBufferBinding();
- }
- private _resetIndexBufferBinding(): void {
- this.bindIndexBuffer(null);
- this._cachedIndexBuffer = null;
- }
- public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
- var vbo = this._gl.createBuffer();
- this.bindIndexBuffer(vbo);
- // Check for 32 bits indices
- var arrayBuffer;
- var need32Bits = false;
- if (indices instanceof Uint16Array) {
- arrayBuffer = indices;
- } else {
- //check 32 bit support
- if (this._caps.uintIndices) {
- if (indices instanceof Uint32Array) {
- arrayBuffer = indices;
- need32Bits = true;
- } else {
- //number[] or Int32Array, check if 32 bit is necessary
- for (var index = 0; index < indices.length; index++) {
- if (indices[index] > 65535) {
- need32Bits = true;
- break;
- }
- }
- arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
- }
- } else {
- //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
- arrayBuffer = new Uint16Array(indices);
- }
- }
- this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
- this._resetIndexBufferBinding();
- vbo.references = 1;
- vbo.is32Bits = need32Bits;
- return vbo;
- }
- public bindArrayBuffer(buffer: WebGLBuffer): void {
- if (!this._vaoRecordInProgress) {
- this._unBindVertexArrayObject();
- }
- this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
- }
- private bindIndexBuffer(buffer: WebGLBuffer): void {
- if (!this._vaoRecordInProgress) {
- this._unBindVertexArrayObject();
- }
- this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
- }
- private bindBuffer(buffer: WebGLBuffer, target: number): void {
- if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
- this._gl.bindBuffer(target, buffer);
- this._currentBoundBuffer[target] = buffer;
- }
- }
- public updateArrayBuffer(data: Float32Array): void {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- }
- private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
- var pointer = this._currentBufferPointers[indx];
- var changed = false;
- if (!pointer) {
- changed = true;
- this._currentBufferPointers[indx] = { indx, size, type, normalized, stride, offset, buffer: buffer };
- } else {
- if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
- if (pointer.size !== size) { pointer.size = size; changed = true; }
- if (pointer.type !== type) { pointer.type = type; changed = true; }
- if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
- if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
- if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
- }
- if (changed || this._vaoRecordInProgress) {
- this.bindArrayBuffer(buffer);
- this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
- }
- }
- private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
- if (indexBuffer == null) {
- return;
- }
- if (this._cachedIndexBuffer !== indexBuffer) {
- this._cachedIndexBuffer = indexBuffer;
- this.bindIndexBuffer(indexBuffer);
- this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
- }
- }
- private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
- var attributes = effect.getAttributesNames();
- if (!this._vaoRecordInProgress) {
- this._unBindVertexArrayObject();
- }
- this.unbindAllAttributes();
- for (var index = 0; index < attributes.length; index++) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- var vertexBuffer = vertexBuffers[attributes[index]];
- if (!vertexBuffer) {
- continue;
- }
- this._gl.enableVertexAttribArray(order);
- if (!this._vaoRecordInProgress) {
- this._vertexAttribArraysEnabled[order] = true;
- }
- var buffer = vertexBuffer.getBuffer();
- this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
- if (vertexBuffer.getIsInstanced()) {
- this._gl.vertexAttribDivisor(order, 1);
- if (!this._vaoRecordInProgress) {
- this._currentInstanceLocations.push(order);
- this._currentInstanceBuffers.push(buffer);
- }
- }
- }
- }
- }
- public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
- var vao = this._gl.createVertexArray();
- this._vaoRecordInProgress = true;
-
- this._gl.bindVertexArray(vao);
-
- this._mustWipeVertexAttributes = true;
- this._bindVertexBuffersAttributes(vertexBuffers, effect);
- this.bindIndexBuffer(indexBuffer);
- this._vaoRecordInProgress = false;
- this._gl.bindVertexArray(null);
- return vao;
- }
- public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
- if (this._cachedVertexArrayObject !== vertexArrayObject) {
- this._cachedVertexArrayObject = vertexArrayObject;
- this._gl.bindVertexArray(vertexArrayObject);
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
- this._mustWipeVertexAttributes = true;
- }
- }
- public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
- if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffer;
- this._cachedEffectForVertexBuffers = effect;
- let attributesCount = effect.getAttributesCount();
- this._unBindVertexArrayObject();
- this.unbindAllAttributes();
- var offset = 0;
- for (var index = 0; index < attributesCount; index++) {
- if (index < vertexDeclaration.length) {
- var order = effect.getAttributeLocation(index);
- if (order >= 0) {
- this._gl.enableVertexAttribArray(order);
- this._vertexAttribArraysEnabled[order] = true;
- this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
- }
- offset += vertexDeclaration[index] * 4;
- }
- }
- }
- this._bindIndexBufferWithCache(indexBuffer);
- }
- private _unBindVertexArrayObject(): void {
- if (!this._cachedVertexArrayObject) {
- return;
- }
- this._cachedVertexArrayObject = null;
- this._gl.bindVertexArray(null);
- }
- public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
- if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
- this._cachedVertexBuffers = vertexBuffers;
- this._cachedEffectForVertexBuffers = effect;
-
- this._bindVertexBuffersAttributes(vertexBuffers, effect);
- }
- this._bindIndexBufferWithCache(indexBuffer);
- }
- public unbindInstanceAttributes() {
- var boundBuffer;
- for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
- var instancesBuffer = this._currentInstanceBuffers[i];
- if (boundBuffer != instancesBuffer) {
- boundBuffer = instancesBuffer;
- this.bindArrayBuffer(instancesBuffer);
- }
- var offsetLocation = this._currentInstanceLocations[i];
- this._gl.vertexAttribDivisor(offsetLocation, 0);
- }
- this._currentInstanceBuffers.length = 0;
- this._currentInstanceLocations.length = 0;
- }
- public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
- this._gl.deleteVertexArray(vao);
- }
- public _releaseBuffer(buffer: WebGLBuffer): boolean {
- buffer.references--;
- if (buffer.references === 0) {
- this._gl.deleteBuffer(buffer);
- return true;
- }
- return false;
- }
- public createInstancesBuffer(capacity: number): WebGLBuffer {
- var buffer = this._gl.createBuffer();
- buffer.capacity = capacity;
- this.bindArrayBuffer(buffer);
- this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
- return buffer;
- }
- public deleteInstancesBuffer(buffer: WebGLBuffer): void {
- this._gl.deleteBuffer(buffer);
- }
- public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
- this.bindArrayBuffer(instancesBuffer);
- if (data) {
- this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
- }
- if ((<any>offsetLocations[0]).index !== undefined) {
- let stride = 0;
- for (let i = 0; i < offsetLocations.length; i++) {
- let ai = <InstancingAttributeInfo>offsetLocations[i];
- stride += ai.attributeSize * 4;
- }
- for (let i = 0; i < offsetLocations.length; i++) {
- let ai = <InstancingAttributeInfo>offsetLocations[i];
- if (!this._vertexAttribArraysEnabled[ai.index]) {
- this._gl.enableVertexAttribArray(ai.index);
- this._vertexAttribArraysEnabled[ai.index] = true;
- }
- this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
- this._gl.vertexAttribDivisor(ai.index, 1);
- this._currentInstanceLocations.push(ai.index);
- this._currentInstanceBuffers.push(instancesBuffer);
- }
- } else {
- for (let index = 0; index < 4; index++) {
- let offsetLocation = <number>offsetLocations[index];
- if (!this._vertexAttribArraysEnabled[offsetLocation]) {
- this._gl.enableVertexAttribArray(offsetLocation);
- this._vertexAttribArraysEnabled[offsetLocation] = true;
- }
- this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
- this._gl.vertexAttribDivisor(offsetLocation, 1);
- this._currentInstanceLocations.push(offsetLocation);
- this._currentInstanceBuffers.push(instancesBuffer);
- }
- }
- }
- public applyStates() {
- this._depthCullingState.apply(this._gl);
- this._stencilState.apply(this._gl);
- this._alphaState.apply(this._gl);
- }
- public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
- // Apply states
- this.applyStates();
- this._drawCalls.addCount(1, false);
- // Render
- var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
- var mult = this._uintIndicesCurrentlySet ? 4 : 2;
- if (instancesCount) {
- this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
- return;
- }
- this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
- }
- public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
- // Apply states
- this.applyStates();
- this._drawCalls.addCount(1, false);
- if (instancesCount) {
- this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
- }
- public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
- // Apply states
- this.applyStates();
- this._drawCalls.addCount(1, false);
- if (instancesCount) {
- this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
- return;
- }
- this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
- }
- // Shaders
- public _releaseEffect(effect: Effect): void {
- if (this._compiledEffects[effect._key]) {
- delete this._compiledEffects[effect._key];
- if (effect.getProgram()) {
- this._gl.deleteProgram(effect.getProgram());
- }
- }
- }
- public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
- onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
- var vertex = baseName.vertexElement || baseName.vertex || baseName;
- var fragment = baseName.fragmentElement || baseName.fragment || baseName;
- var name = vertex + "+" + fragment + "@" + defines;
- if (this._compiledEffects[name]) {
- return this._compiledEffects[name];
- }
- var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
- effect._key = name;
- this._compiledEffects[name] = effect;
- return effect;
- }
- public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
- onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
- return this.createEffect(
- {
- vertex: "particles",
- fragmentElement: fragmentName
- },
- ["position", "color", "options"],
- ["view", "projection"].concat(uniformsNames),
- ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
- }
- public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
- context = context || this._gl;
- var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
- var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
- var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
- var shaderProgram = context.createProgram();
- context.attachShader(shaderProgram, vertexShader);
- context.attachShader(shaderProgram, fragmentShader);
- context.linkProgram(shaderProgram);
- var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
- if (!linked) {
- var error = context.getProgramInfoLog(shaderProgram);
- if (error) {
- throw new Error(error);
- }
- }
- context.deleteShader(vertexShader);
- context.deleteShader(fragmentShader);
- return shaderProgram;
- }
- public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
- var results = [];
- for (var index = 0; index < uniformsNames.length; index++) {
- results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
- }
- return results;
- }
- public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
- var results = [];
- for (var index = 0; index < attributesNames.length; index++) {
- try {
- results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
- } catch (e) {
- results.push(-1);
- }
- }
- return results;
- }
- public enableEffect(effect: Effect): void {
- // Use program
- this.setProgram(effect.getProgram());
- this._currentEffect = effect;
- if (effect.onBind) {
- effect.onBind(effect);
- }
- }
- public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform)
- return;
- this._gl.uniform1iv(uniform, array);
- }
- public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2iv(uniform, array);
- }
- public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3iv(uniform, array);
- }
- public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4iv(uniform, array);
- }
- public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform)
- return;
- this._gl.uniform1fv(uniform, array);
- }
- public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2fv(uniform, array);
- }
- public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3fv(uniform, array);
- }
- public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4fv(uniform, array);
- }
- public setArray(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform)
- return;
- this._gl.uniform1fv(uniform, <any>array);
- }
- public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform || array.length % 2 !== 0)
- return;
- this._gl.uniform2fv(uniform, <any>array);
- }
- public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform || array.length % 3 !== 0)
- return;
- this._gl.uniform3fv(uniform, <any>array);
- }
- public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
- if (!uniform || array.length % 4 !== 0)
- return;
- this._gl.uniform4fv(uniform, <any>array);
- }
- public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrices);
- }
- public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
- if (!uniform)
- return;
- this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
- }
- public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
- if (!uniform)
- return;
- this._gl.uniformMatrix3fv(uniform, false, matrix);
- }
- public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
- if (!uniform)
- return;
- this._gl.uniformMatrix2fv(uniform, false, matrix);
- }
- public setFloat(uniform: WebGLUniformLocation, value: number): void {
- if (!uniform)
- return;
- this._gl.uniform1f(uniform, value);
- }
- public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
- if (!uniform)
- return;
- this._gl.uniform2f(uniform, x, y);
- }
- public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, x, y, z);
- }
- public setBool(uniform: WebGLUniformLocation, bool: number): void {
- if (!uniform)
- return;
- this._gl.uniform1i(uniform, bool);
- }
- public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, x, y, z, w);
- }
- public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
- if (!uniform)
- return;
- this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
- }
- public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
- if (!uniform)
- return;
- this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
- }
- // States
- public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
- // Culling
- var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
- var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
- var cullFace = this.cullBackFaces ? showSide : hideSide;
- if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
- if (culling) {
- this._depthCullingState.cullFace = cullFace;
- this._depthCullingState.cull = true;
- } else {
- this._depthCullingState.cull = false;
- }
- }
- // Z offset
- this._depthCullingState.zOffset = zOffset;
- }
- public setDepthBuffer(enable: boolean): void {
- this._depthCullingState.depthTest = enable;
- }
- public getDepthWrite(): boolean {
- return this._depthCullingState.depthMask;
- }
- public setDepthWrite(enable: boolean): void {
- this._depthCullingState.depthMask = enable;
- }
- public setColorWrite(enable: boolean): void {
- this._gl.colorMask(enable, enable, enable, enable);
- }
- public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
- if (this._alphaMode === mode) {
- return;
- }
- switch (mode) {
- case Engine.ALPHA_DISABLE:
- this._alphaState.alphaBlend = false;
- break;
- case Engine.ALPHA_PREMULTIPLIED:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_COMBINE:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ONEONE:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_ADD:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_SUBTRACT:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MULTIPLY:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- case Engine.ALPHA_MAXIMIZED:
- this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
- this._alphaState.alphaBlend = true;
- break;
- }
- if (!noDepthWriteChange) {
- this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
- }
- this._alphaMode = mode;
- }
- public getAlphaMode(): number {
- return this._alphaMode;
- }
- public setAlphaTesting(enable: boolean): void {
- this._alphaTest = enable;
- }
- public getAlphaTesting(): boolean {
- return this._alphaTest;
- }
- // Textures
- public wipeCaches(): void {
- this.resetTextureCache();
- this._currentEffect = null;
- this._stencilState.reset();
- this._depthCullingState.reset();
- this.setDepthFunctionToLessOrEqual();
- this._alphaState.reset();
- this._cachedVertexBuffers = null;
- this._cachedIndexBuffer = null;
- this._cachedEffectForVertexBuffers = null;
- this._unBindVertexArrayObject();
- this.bindIndexBuffer(null);
- this.bindArrayBuffer(null);
- }
- /**
- * Set the compressed texture format to use, based on the formats you have, and the formats
- * supported by the hardware / browser.
- *
- * Khronos Texture Container (.ktx) files are used to support this. This format has the
- * advantage of being specifically designed for OpenGL. Header elements directly correspond
- * to API arguments needed to compressed textures. This puts the burden on the container
- * generator to house the arcane code for determining these for current & future formats.
- *
- * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
- * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
- *
- * Note: The result of this call is not taken into account when a texture is base64.
- *
- * @param {Array<string>} formatsAvailable- The list of those format families you have created
- * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
- *
- * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
- * @returns The extension selected.
- */
- public setTextureFormatToUse(formatsAvailable : Array<string>) : string {
- for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
- for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
- if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
- return this._textureFormatInUse = this._texturesSupported[i];
- }
- }
- }
- // actively set format to nothing, to allow this to be called more than once
- // and possibly fail the 2nd time
- return this._textureFormatInUse = null;
- }
- public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: any = null, fallBack?: WebGLTexture): WebGLTexture {
- var texture = fallBack ? fallBack : this._gl.createTexture();
- var extension: string;
- var isKTX = false;
- var fromData: any = false;
- var url = String(urlArg);
- if (url.substr(0, 5) === "data:") {
- fromData = true;
- }
- if (!fromData) {
- var lastDot = url.lastIndexOf('.')
- extension = url.substring(lastDot).toLowerCase();
- if (this._textureFormatInUse && !fromData && !fallBack) {
- extension = this._textureFormatInUse;
- url = url.substring(0, lastDot) + this._textureFormatInUse;
- isKTX = true;
-
- }
- } else {
- var oldUrl = url;
- fromData = oldUrl.split(':');
- url = oldUrl;
- extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
- }
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- var isTGA = (extension === ".tga");
- scene._addPendingData(texture);
- texture.url = url;
- texture.noMipmap = noMipmap;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- texture.onLoadedCallbacks = [];
- if (onLoad) {
- texture.onLoadedCallbacks.push(onLoad);
- }
- if (!fallBack) this._loadedTexturesCache.push(texture);
- var onerror = () => {
- scene._removePendingData(texture);
- // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
- if (isKTX) {
- this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
- } else if (onError) {
- onError();
- }
- };
- var callback: (arrayBuffer: any) => void;
- if (isKTX || isTGA || isDDS){
- if (isKTX) {
- callback = (data) => {
- var ktx = new Internals.KhronosTextureContainer(data, 1);
-
- prepareWebGLTexture(texture, this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
- ktx.uploadLevels(this._gl, !noMipmap);
- }, samplingMode);
- };
- } else if (isTGA) {
- callback = (arrayBuffer) => {
- var data = new Uint8Array(arrayBuffer);
- var header = Internals.TGATools.GetTGAHeader(data);
- prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
- Internals.TGATools.UploadContent(this._gl, data);
- }, samplingMode);
- };
- } else if (isDDS) {
- callback = (data) => {
- var info = Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
- prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
- Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
- }, samplingMode);
- };
- }
- if (!(fromData instanceof Array))
- Tools.LoadFile(url, data => {
- callback(data);
- }, null, scene.database, true, onerror);
- else
- callback(buffer);
- } else {
- var onload = (img) => {
- prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
- var isPot = (img.width === potWidth && img.height === potHeight);
- if (!isPot) {
- this._prepareWorkingCanvas();
- this._workingCanvas.width = potWidth;
- this._workingCanvas.height = potHeight;
- if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
- this._workingContext.imageSmoothingEnabled = false;
- this._workingContext.mozImageSmoothingEnabled = false;
- this._workingContext.oImageSmoothingEnabled = false;
- this._workingContext.webkitImageSmoothingEnabled = false;
- this._workingContext.msImageSmoothingEnabled = false;
- }
- this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
- if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
- this._workingContext.imageSmoothingEnabled = true;
- this._workingContext.mozImageSmoothingEnabled = true;
- this._workingContext.oImageSmoothingEnabled = true;
- this._workingContext.webkitImageSmoothingEnabled = true;
- this._workingContext.msImageSmoothingEnabled = true;
- }
- }
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
- }, samplingMode);
- };
- if (!(fromData instanceof Array))
- Tools.LoadImage(url, onload, onerror, scene.database);
- else
- Tools.LoadImage(buffer, onload, onerror, scene.database);
- }
- return texture;
- }
- private _getInternalFormat(format: number): number {
- var internalFormat = this._gl.RGBA;
- switch (format) {
- case Engine.TEXTUREFORMAT_ALPHA:
- internalFormat = this._gl.ALPHA;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE:
- internalFormat = this._gl.LUMINANCE;
- break;
- case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
- internalFormat = this._gl.LUMINANCE_ALPHA;
- break;
- case Engine.TEXTUREFORMAT_RGB:
- internalFormat = this._gl.RGB;
- break;
- case Engine.TEXTUREFORMAT_RGBA:
- internalFormat = this._gl.RGBA;
- break;
- }
- return internalFormat;
- }
- public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
- var internalFormat = this._getInternalFormat(format);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
- if (texture._width % 4 !== 0) {
- this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
- }
- if (compression) {
- this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
- } else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- }
- public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = width;
- texture._height = height;
- texture.references = 1;
- this.updateRawTexture(texture, data, format, invertY, compression);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- // Filters
- var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- texture.samplingMode = samplingMode;
- this._loadedTexturesCache.push(texture);
- return texture;
- }
- public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
- var texture = this._gl.createTexture();
- texture._baseWidth = width;
- texture._baseHeight = height;
- if (generateMipMaps) {
- width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
- height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
- }
- this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = false;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- this.updateTextureSamplingMode(samplingMode, texture);
- this._loadedTexturesCache.push(texture);
- return texture;
- }
- public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
- var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
-
- if (texture.isCube) {
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- } else {
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- }
- texture.samplingMode = samplingMode;
- }
- public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false): void {
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
- if (premulAlpha) {
- this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
- }
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- if (premulAlpha) {
- this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
- }
- this.resetTextureCache();
- texture.isReady = true;
- }
- public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
- if (texture._isDisabled) {
- return;
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
- try {
- // Testing video texture support
- if (this._videoTextureSupported === undefined) {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- if (this._gl.getError() !== 0) {
- this._videoTextureSupported = false;
- } else {
- this._videoTextureSupported = true;
- }
- }
- // Copy video through the current working canvas if video texture is not supported
- if (!this._videoTextureSupported) {
- if (!texture._workingCanvas) {
- texture._workingCanvas = document.createElement("canvas");
- texture._workingContext = texture._workingCanvas.getContext("2d");
- texture._workingCanvas.width = texture._width;
- texture._workingCanvas.height = texture._height;
- }
- texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
- } else {
- this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
- }
- if (texture.generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this.resetTextureCache();
- texture.isReady = true;
- } catch (ex) {
- // Something unexpected
- // Let's disable the texture
- texture._isDisabled = true;
- }
- }
- public createRenderTargetTexture(size: any, options): WebGLTexture {
- // old version had a "generateMipMaps" arg instead of options.
- // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
- // in the same way, generateDepthBuffer is defaulted to true
- var generateMipMaps = false;
- var generateDepthBuffer = true;
- var generateStencilBuffer = false;
- var type = Engine.TEXTURETYPE_UNSIGNED_INT;
- var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
- type = options.type === undefined ? type : options.type;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
- // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = Texture.NEAREST_SAMPLINGMODE;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
- // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
- samplingMode = Texture.NEAREST_SAMPLINGMODE;
- }
- }
- var gl = this._gl;
- var texture = gl.createTexture();
- this._bindTextureDirectly(gl.TEXTURE_2D, texture);
- var width = size.width || size;
- var height = size.height || size;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
- type = Engine.TEXTURETYPE_UNSIGNED_INT;
- Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
- }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
- var depthStencilBuffer: WebGLRenderbuffer;
- // Create the depth/stencil buffer
- if (generateStencilBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
- }
- else if (generateDepthBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
- }
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- this.bindUnboundFramebuffer(framebuffer);
- // Manage attachments
- if (generateStencilBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- else if (generateDepthBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
- if (generateMipMaps) {
- this._gl.generateMipmap(this._gl.TEXTURE_2D);
- }
- // Unbind
- this._bindTextureDirectly(gl.TEXTURE_2D, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- texture._framebuffer = framebuffer;
- if (generateDepthBuffer) {
- texture._depthBuffer = depthStencilBuffer;
- }
- texture._baseWidth = width;
- texture._baseHeight = height;
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- texture.type = type;
- this.resetTextureCache();
- this._loadedTexturesCache.push(texture);
- return texture;
- }
- public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
- var gl = this._gl;
- var texture = gl.createTexture();
- var generateMipMaps = true;
- var generateDepthBuffer = true;
- var generateStencilBuffer = false;
- var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
- if (options !== undefined) {
- generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
- generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
- generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
- if (options.samplingMode !== undefined) {
- samplingMode = options.samplingMode;
- }
- }
- texture.isCube = true;
- texture.references = 1;
- texture.generateMipMaps = generateMipMaps;
- texture.references = 1;
- texture.samplingMode = samplingMode;
- var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- for (var face = 0; face < 6; face++) {
- gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- // Create the depth buffer
- var depthStencilBuffer: WebGLRenderbuffer;
- // Create the depth/stencil buffer
- if (generateStencilBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
- }
- else if (generateDepthBuffer) {
- depthStencilBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
- }
- // Create the framebuffer
- var framebuffer = gl.createFramebuffer();
- this.bindUnboundFramebuffer(framebuffer);
- // Manage attachments
- if (generateStencilBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- else if (generateDepthBuffer) {
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
- }
- // Mipmaps
- if (texture.generateMipMaps) {
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- // Unbind
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- gl.bindRenderbuffer(gl.RENDERBUFFER, null);
- this.bindUnboundFramebuffer(null);
- texture._framebuffer = framebuffer;
- if (generateDepthBuffer) {
- texture._depthBuffer = depthStencilBuffer;
- }
- texture._width = size;
- texture._height = size;
- texture.isReady = true;
- this.resetTextureCache();
- this._loadedTexturesCache.push(texture);
- return texture;
- }
- public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: () => void = null, onError: () => void = null): WebGLTexture {
- var gl = this._gl;
- var texture = gl.createTexture();
- texture.isCube = true;
- texture.url = rootUrl;
- texture.references = 1;
- texture.onLoadedCallbacks = [];
- var isKTX = false;
- var lastDot = rootUrl.lastIndexOf('.');
- var extension = rootUrl.substring(lastDot).toLowerCase();
- if (this._textureFormatInUse) {
- extension = this._textureFormatInUse;
- rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
- isKTX = true;
- }
- var isDDS = this.getCaps().s3tc && (extension === ".dds");
- if (isKTX) {
- Tools.LoadFile(rootUrl, data => {
- var ktx = new Internals.KhronosTextureContainer(data, 6);
- var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
-
- ktx.uploadLevels(this._gl, !noMipmap);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- this.resetTextureCache();
- texture._width = ktx.pixelWidth;
- texture._height = ktx.pixelHeight;
- texture.isReady = true;
- }, null, null, true, onError);
- } else if (isDDS) {
- Tools.LoadFile(rootUrl, data => {
- var info = Internals.DDSTools.GetDDSInfo(data);
- var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
- Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
- if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- this.resetTextureCache();
- texture._width = info.width;
- texture._height = info.height;
- texture.isReady = true;
- }, null, null, true, onError);
- } else {
- cascadeLoad(rootUrl, scene, imgs => {
- var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
- var height = width;
- this._prepareWorkingCanvas();
- this._workingCanvas.width = width;
- this._workingCanvas.height = height;
- var faces = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- for (var index = 0; index < faces.length; index++) {
- this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
- gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
- }
- if (!noMipmap) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- this.resetTextureCache();
- texture._width = width;
- texture._height = height;
- texture.isReady = true;
- texture.onLoadedCallbacks.forEach(callback => {
- callback();
- });
- if (onLoad) {
- onLoad();
- }
- }, files, onError);
- }
- this._loadedTexturesCache.push(texture);
- return texture;
- }
- public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
- texture._width = width;
- texture._height = height;
- texture._size = width * height;
- texture._baseWidth = width;
- texture._baseHeight = height;
- }
- public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
- callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
- mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][])): WebGLTexture {
- var gl = this._gl;
- var texture = gl.createTexture();
- scene._addPendingData(texture);
- texture.isCube = true;
- texture.references = 1;
- texture.url = url;
- var textureType = gl.UNSIGNED_BYTE;
- if (type === Engine.TEXTURETYPE_FLOAT) {
- textureType = gl.FLOAT;
- }
- var internalFormat = this._getInternalFormat(format);
- var needConversion = false;
- if (internalFormat === gl.RGB) {
- internalFormat = gl.RGBA;
- needConversion = true;
- }
- var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
- var width = size;
- var height = width;
- var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
- texture._width = width;
- texture._height = height;
- var onerror = () => {
- scene._removePendingData(texture);
- };
- var internalCallback = (data) => {
- var rgbeDataArrays = callback(data);
- var facesIndex = [
- gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
- gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
- ];
- width = texture._width;
- height = texture._height;
- isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
- if (mipmmapGenerator) {
- var arrayTemp: ArrayBufferView[] = [];
- // Data are known to be in +X +Y +Z -X -Y -Z
- // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
- arrayTemp.push(rgbeDataArrays[0]); // +X
- arrayTemp.push(rgbeDataArrays[3]); // -X
- arrayTemp.push(rgbeDataArrays[1]); // +Y
- arrayTemp.push(rgbeDataArrays[4]); // -Y
- arrayTemp.push(rgbeDataArrays[2]); // +Z
- arrayTemp.push(rgbeDataArrays[5]); // -Z
- var mipData = mipmmapGenerator(arrayTemp);
- // mipData is order in +X -X +Y -Y +Z -Z
- var mipFaces = [0, 2, 4, 1, 3, 5];
- for (var level = 0; level < mipData.length; level++) {
- var mipSize = width >> level;
- for (let mipIndex in mipFaces) {
- let mipFaceData = mipData[level][mipFaces[mipIndex]];
- if (needConversion) {
- mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
- }
- gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
- }
- }
- }
- else {
- // Data are known to be in +X +Y +Z -X -Y -Z
- for (let index = 0; index < facesIndex.length; index++) {
- let faceData = rgbeDataArrays[index];
- if (needConversion) {
- faceData = this._convertRGBtoRGBATextureData(faceData, width, height, type);
- }
- gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
- }
- if (!noMipmap && isPot) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- else {
- noMipmap = true;
- }
- }
- if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- }
- else {
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
- }
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
- texture.isReady = true;
- this.resetTextureCache();
- scene._removePendingData(texture);
- };
- Tools.LoadFile(url, data => {
- internalCallback(data);
- }, onerror, scene.database, true);
- return texture;
- };
- private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
- // Create new RGBA data container.
- var rgbaData: ArrayBufferView;
- if (textureType === Engine.TEXTURETYPE_FLOAT) {
- rgbaData = new Float32Array(width * height * 4);
- }
- else {
- rgbaData = new Uint32Array(width * height * 4);
- }
- // Convert each pixel.
- for (let x = 0; x < width; x++) {
- for (let y = 0; y < height; y++) {
- let index = (y * width + x) * 3;
- let newIndex = (y * width + x) * 4;
- // Map Old Value to new value.
- rgbaData[newIndex + 0] = rgbData[index + 0];
- rgbaData[newIndex + 1] = rgbData[index + 1];
- rgbaData[newIndex + 2] = rgbData[index + 2];
- // Add fully opaque alpha channel.
- rgbaData[newIndex + 3] = 1;
- }
- }
- return rgbaData;
- }
- public _releaseTexture(texture: WebGLTexture): void {
- var gl = this._gl;
- if (texture._framebuffer) {
- gl.deleteFramebuffer(texture._framebuffer);
- }
- if (texture._depthBuffer) {
- gl.deleteRenderbuffer(texture._depthBuffer);
- }
- gl.deleteTexture(texture);
- // Unbind channels
- this.unbindAllTextures();
- var index = this._loadedTexturesCache.indexOf(texture);
- if (index !== -1) {
- this._loadedTexturesCache.splice(index, 1);
- }
- }
- private setProgram(program: WebGLProgram): void {
- if (this._currentProgram !== program) {
- this._gl.useProgram(program);
- this._currentProgram = program;
- }
- }
- public bindSamplers(effect: Effect): void {
- this.setProgram(effect.getProgram());
- var samplers = effect.getSamplers();
- for (var index = 0; index < samplers.length; index++) {
- var uniform = effect.getUniform(samplers[index]);
- this._gl.uniform1i(uniform, index);
- }
- this._currentEffect = null;
- }
- private activateTexture(texture: number): void {
- if (this._activeTexture !== texture) {
- this._gl.activeTexture(texture);
- this._activeTexture = texture;
- }
- }
- public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
- if (this._activeTexturesCache[this._activeTexture] !== texture) {
- this._gl.bindTexture(target, texture);
- this._activeTexturesCache[this._activeTexture] = texture;
- }
- }
- public _bindTexture(channel: number, texture: WebGLTexture): void {
- if (channel < 0) {
- return;
- }
- this.activateTexture(this._gl.TEXTURE0 + channel);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
- }
- public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
- this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
- }
- public unbindAllTextures(): void {
- for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
- this.activateTexture(this._gl["TEXTURE" + channel]);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- }
- }
- public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
- if (channel < 0) {
- return;
- }
- this._gl.uniform1i(uniform, channel);
- this._setTexture(channel, texture);
- }
- private _setTexture(channel: number, texture: BaseTexture): void {
- // Not ready?
- if (!texture || !texture.isReady()) {
- if (this._activeTexturesCache[channel] != null) {
- this.activateTexture(this._gl["TEXTURE" + channel]);
- this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
- }
- return;
- }
- // Video
- var alreadyActivated = false;
- if (texture instanceof VideoTexture) {
- this.activateTexture(this._gl["TEXTURE" + channel]);
- alreadyActivated = true;
- texture.update();
- } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
- texture.delayLoad();
- return;
- }
- var internalTexture = texture.getInternalTexture();
- if (this._activeTexturesCache[channel] === internalTexture) {
- return;
- }
- if (!alreadyActivated) {
- this.activateTexture(this._gl["TEXTURE" + channel]);
- }
- if (internalTexture.isCube) {
- this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
- if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
- internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
- // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
- var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
- this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
- } else {
- this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
- if (internalTexture._cachedWrapU !== texture.wrapU) {
- internalTexture._cachedWrapU = texture.wrapU;
- switch (texture.wrapU) {
- case Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
- break;
- case Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
- break;
- case Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- if (internalTexture._cachedWrapV !== texture.wrapV) {
- internalTexture._cachedWrapV = texture.wrapV;
- switch (texture.wrapV) {
- case Texture.WRAP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
- break;
- case Texture.CLAMP_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
- break;
- case Texture.MIRROR_ADDRESSMODE:
- this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
- break;
- }
- }
- this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
- }
- }
- public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
- if (channel < 0) {
- return;
- }
- if (!this._textureUnits || this._textureUnits.length !== textures.length) {
- this._textureUnits = new Int32Array(textures.length);
- }
- for (let i = 0; i < textures.length; i++) {
- this._textureUnits[i] = channel + i;
- }
- this._gl.uniform1iv(uniform, this._textureUnits);
- for (var index = 0; index < textures.length; index++) {
- this._setTexture(channel + index, textures[index]);
- }
- }
- public _setAnisotropicLevel(key: number, texture: BaseTexture) {
- var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
- var value = texture.anisotropicFilteringLevel;
- if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
- value = 1;
- }
- if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
- this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
- texture._cachedAnisotropicFilteringLevel = value;
- }
- }
- public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
- var data = new Uint8Array(height * width * 4);
- this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
- return data;
- }
- /**
- * Add an externaly attached data from its key.
- * This method call will fail and return false, if such key already exists.
- * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
- * @param key the unique key that identifies the data
- * @param data the data object to associate to the key for this Engine instance
- * @return true if no such key were already present and the data was added successfully, false otherwise
- */
- public addExternalData<T>(key: string, data: T): boolean {
- return this._externalData.add(key, data);
- }
- /**
- * Get an externaly attached data from its key
- * @param key the unique key that identifies the data
- * @return the associated data, if present (can be null), or undefined if not present
- */
- public getExternalData<T>(key: string): T {
- return <T>this._externalData.get(key);
- }
- /**
- * Get an externaly attached data from its key, create it using a factory if it's not already present
- * @param key the unique key that identifies the data
- * @param factory the factory that will be called to create the instance if and only if it doesn't exists
- * @return the associated data, can be null if the factory returned null.
- */
- public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
- return <T>this._externalData.getOrAddWithFactory(key, factory);
- }
- /**
- * Remove an externaly attached data from the Engine instance
- * @param key the unique key that identifies the data
- * @return true if the data was successfully removed, false if it doesn't exist
- */
- public removeExternalData(key): boolean {
- return this._externalData.remove(key);
- }
- public releaseInternalTexture(texture: WebGLTexture): void {
- if (!texture) {
- return;
- }
- texture.references--;
- // Final reference ?
- if (texture.references === 0) {
- var texturesCache = this.getLoadedTexturesCache();
- var index = texturesCache.indexOf(texture);
- if (index > -1) {
- texturesCache.splice(index, 1);
- }
- this._releaseTexture(texture);
- }
- }
- public unbindAllAttributes() {
- if (this._mustWipeVertexAttributes) {
- this._mustWipeVertexAttributes = false;
- for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
- this._gl.disableVertexAttribArray(i);
- this._vertexAttribArraysEnabled[i] = false;
- this._currentBufferPointers[i] = null;
- }
- return;
- }
- for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
- if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
- continue;
- }
- this._gl.disableVertexAttribArray(i);
- this._vertexAttribArraysEnabled[i] = false;
- this._currentBufferPointers[i] = null;
- }
- }
- // Dispose
- public dispose(): void {
- this.hideLoadingUI();
- this.stopRenderLoop();
- // Release scenes
- while (this.scenes.length) {
- this.scenes[0].dispose();
- }
- // Release audio engine
- Engine.audioEngine.dispose();
- // Release effects
- for (var name in this._compiledEffects) {
- this._gl.deleteProgram(this._compiledEffects[name]._program);
- }
- // Unbind
- this.unbindAllAttributes();
- this._gl = null;
- //WebVR
- this.disableVR();
- // Events
- window.removeEventListener("blur", this._onBlur);
- window.removeEventListener("focus", this._onFocus);
- document.removeEventListener("fullscreenchange", this._onFullscreenChange);
- document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
- document.removeEventListener("pointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
- document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
- document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
- }
- // Loading screen
- public displayLoadingUI(): void {
- this._loadingScreen.displayLoadingUI();
- }
- public hideLoadingUI(): void {
- this._loadingScreen.hideLoadingUI();
- }
- public get loadingScreen(): ILoadingScreen {
- return this._loadingScreen;
- }
- public set loadingScreen(loadingScreen: ILoadingScreen) {
- this._loadingScreen = loadingScreen;
- }
- public set loadingUIText(text: string) {
- this._loadingScreen.loadingUIText = text;
- }
- public set loadingUIBackgroundColor(color: string) {
- this._loadingScreen.loadingUIBackgroundColor = color;
- }
- public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
- this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
- }
- public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
- this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
- }
- public getVertexShaderSource(program: WebGLProgram): string {
- var shaders = this._gl.getAttachedShaders(program);
- return this._gl.getShaderSource(shaders[0]);
- }
- public getFragmentShaderSource(program: WebGLProgram): string {
- var shaders = this._gl.getAttachedShaders(program);
- return this._gl.getShaderSource(shaders[1]);
- }
- // FPS
- public getFps(): number {
- return this.fps;
- }
- public getDeltaTime(): number {
- return this.deltaTime;
- }
- private _measureFps(): void {
- this.previousFramesDuration.push(Tools.Now);
- var length = this.previousFramesDuration.length;
- if (length >= 2) {
- this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
- }
- if (length >= this.fpsRange) {
- if (length > this.fpsRange) {
- this.previousFramesDuration.splice(0, 1);
- length = this.previousFramesDuration.length;
- }
- var sum = 0;
- for (var id = 0; id < length - 1; id++) {
- sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
- }
- this.fps = 1000.0 / (sum / (length - 1));
- }
- }
- private _canRenderToFloatFramebuffer(): boolean {
- if (this._webGLVersion > 1) {
- return this._caps.colorBufferFloat;
- }
- return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
- }
- private _canRenderToHalfFloatFramebuffer(): boolean {
- if (this._webGLVersion > 1) {
- return this._caps.colorBufferFloat;
- }
- return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
- }
- // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
- private _canRenderToFramebuffer(type: number): boolean {
- let gl = this._gl;
- //clear existing errors
- while(gl.getError() !== gl.NO_ERROR){}
- let successful = true;
- let texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- let fb = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
- let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- //try render by clearing frame buffer's color buffer
- if(successful){
- gl.clear(gl.COLOR_BUFFER_BIT);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- }
- //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
- if(successful){
- //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- let readFormat = gl.RGBA;
- let readType = gl.UNSIGNED_BYTE;
- let buffer = new Uint8Array(4);
- gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
- successful = successful && (gl.getError() === gl.NO_ERROR);
- }
- //clean up
- gl.deleteTexture(texture);
- gl.deleteFramebuffer(fb);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- //clear accumulated errors
- while(!successful && (gl.getError() !== gl.NO_ERROR)) { }
- return successful;
- }
- private _getWebGLTextureType(type: number) : number {
- if (type === Engine.TEXTURETYPE_FLOAT) {
- return this._gl.FLOAT;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
- // Add Half Float Constant.
- return Engine.HALF_FLOAT_OES;
- }
- return this._gl.UNSIGNED_BYTE;
- };
- private _getRGBABufferInternalSizedFormat(type: number) : number {
- if (this._webGLVersion === 1) {
- return this._gl.RGBA;
- }
- if (type === Engine.TEXTURETYPE_FLOAT) {
- return Engine.RGBA32F;
- }
- else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
- return Engine.RGBA16F;
- }
- return this._gl.RGBA;
- };
- // Statics
- public static isSupported(): boolean {
- try {
- // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
- if (navigator.isCocoonJS) {
- return true;
- }
- var tempcanvas = document.createElement("canvas");
- var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
- return gl != null && !!window.WebGLRenderingContext;
- } catch (e) {
- return false;
- }
- }
- }
- }
|