nativeEngine.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. import { Nullable, IndicesArray, DataArray } from "../types";
  2. import { Engine } from "../Engines/engine";
  3. import { VertexBuffer } from "../Meshes/buffer";
  4. import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
  5. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  6. import { Texture } from "../Materials/Textures/texture";
  7. import { BaseTexture } from "../Materials/Textures/baseTexture";
  8. import { VideoTexture } from "../Materials/Textures/videoTexture";
  9. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  10. import { Effect } from "../Materials/effect";
  11. import { DataBuffer } from '../Meshes/dataBuffer';
  12. import { Tools } from "../Misc/tools";
  13. import { Observer } from "../Misc/observable";
  14. import { EnvironmentTextureTools, EnvironmentTextureSpecularInfoV1 } from "../Misc/environmentTextureTools";
  15. import { Color4, Matrix, Viewport, Color3 } from "../Maths/math";
  16. import { Scene } from "../scene";
  17. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  18. import { IPipelineContext } from './IPipelineContext';
  19. import { WebRequest } from '../Misc/webRequest';
  20. import { NativeShaderProcessor } from './Native/nativeShaderProcessor';
  21. import { Logger } from "../Misc/logger";
  22. import { Constants } from './constants';
  23. import { ThinEngine } from './thinEngine';
  24. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  25. interface INativeEngine {
  26. requestAnimationFrame(callback: () => void): void;
  27. createVertexArray(): any;
  28. deleteVertexArray(vertexArray: any): void;
  29. bindVertexArray(vertexArray: any): void;
  30. createIndexBuffer(data: ArrayBufferView): any;
  31. deleteIndexBuffer(buffer: any): void;
  32. recordIndexBuffer(vertexArray: any, buffer: any): void;
  33. createVertexBuffer(data: ArrayBufferView): any;
  34. deleteVertexBuffer(buffer: any): void;
  35. recordVertexBuffer(vertexArray: any, buffer: any, location: number, byteOffset: number, byteStride: number, numElements: number, type: number, normalized: boolean): void;
  36. createProgram(vertexShader: string, fragmentShader: string): any;
  37. getUniforms(shaderProgram: any, uniformsNames: string[]): WebGLUniformLocation[];
  38. getAttributes(shaderProgram: any, attributeNames: string[]): number[];
  39. setProgram(program: any): void;
  40. setState(culling: boolean, zOffset: number, reverseSide: boolean): void;
  41. setZOffset(zOffset: number): void;
  42. getZOffset(): number;
  43. setDepthTest(enable: boolean): void;
  44. getDepthWrite(): boolean;
  45. setDepthWrite(enable: boolean): void;
  46. setColorWrite(enable: boolean): void;
  47. setBlendMode(blendMode: number): void;
  48. setMatrix(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  49. setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void;
  50. setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void;
  51. setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void;
  52. setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void;
  53. setFloatArray(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  54. setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  55. setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  56. setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  57. setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void;
  58. setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  59. setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  60. setFloat(uniform: WebGLUniformLocation, value: number): void;
  61. setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void;
  62. setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void;
  63. setBool(uniform: WebGLUniformLocation, bool: number): void;
  64. setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
  65. createTexture(): WebGLTexture;
  66. loadTexture(texture: WebGLTexture, buffer: ArrayBuffer | ArrayBufferView | Blob, mipMap: boolean): any;
  67. loadCubeTexture(texture: WebGLTexture, data: Array<Array<ArrayBufferView>>, flipY : boolean): any;
  68. getTextureWidth(texture: WebGLTexture): number;
  69. getTextureHeight(texture: WebGLTexture): number;
  70. setTextureSampling(texture: WebGLTexture, filter: number): void; // filter is a NativeFilter.XXXX value.
  71. setTextureWrapMode(texture: WebGLTexture, addressModeU: number, addressModeV: number, addressModeW: number): void; // addressModes are NativeAddressMode.XXXX values.
  72. setTextureAnisotropicLevel(texture: WebGLTexture, value: number): void;
  73. setTexture(uniform: WebGLUniformLocation, texture: Nullable<WebGLTexture>): void;
  74. deleteTexture(texture: Nullable<WebGLTexture>): void;
  75. createFramebuffer(texture: WebGLTexture, width: number, height: number, format: number, samplingMode: number, generateStencilBuffer: boolean, generateDepthBuffer: boolean, generateMipMaps: boolean): WebGLFramebuffer;
  76. deleteFramebuffer(framebuffer: WebGLFramebuffer): void;
  77. bindFramebuffer(framebuffer: WebGLFramebuffer): void;
  78. unbindFramebuffer(framebuffer: WebGLFramebuffer): void;
  79. drawIndexed(fillMode: number, indexStart: number, indexCount: number): void;
  80. draw(fillMode: number, vertexStart: number, vertexCount: number): void;
  81. clear(r: number, g: number, b: number, a: number, backBuffer: boolean, depth: boolean, stencil: boolean): void;
  82. getRenderWidth(): number;
  83. getRenderHeight(): number;
  84. }
  85. class NativePipelineContext implements IPipelineContext {
  86. // TODO: async should be true?
  87. public isAsync = false;
  88. public isReady = false;
  89. // TODO: what should this do?
  90. public _handlesSpectorRebuildCallback(onCompiled: (compiledObject: any) => void): void {
  91. throw new Error("Not implemented");
  92. }
  93. public nativeProgram: any;
  94. }
  95. /**
  96. * Container for accessors for natively-stored mesh data buffers.
  97. */
  98. class NativeDataBuffer extends DataBuffer {
  99. /**
  100. * Accessor value used to identify/retrieve a natively-stored index buffer.
  101. */
  102. public nativeIndexBuffer?: any;
  103. /**
  104. * Accessor value used to identify/retrieve a natively-stored vertex buffer.
  105. */
  106. public nativeVertexBuffer?: any;
  107. }
  108. // TODO: change this to match bgfx.
  109. // Must match Filter enum in SpectreEngine.h.
  110. class NativeFilter {
  111. public static readonly POINT = 0;
  112. public static readonly MINPOINT_MAGPOINT_MIPPOINT = NativeFilter.POINT;
  113. public static readonly BILINEAR = 1;
  114. public static readonly MINLINEAR_MAGLINEAR_MIPPOINT = NativeFilter.BILINEAR;
  115. public static readonly TRILINEAR = 2;
  116. public static readonly MINLINEAR_MAGLINEAR_MIPLINEAR = NativeFilter.TRILINEAR;
  117. public static readonly ANISOTROPIC = 3;
  118. public static readonly POINT_COMPARE = 4;
  119. public static readonly TRILINEAR_COMPARE = 5;
  120. public static readonly MINBILINEAR_MAGPOINT = 6;
  121. public static readonly MINLINEAR_MAGPOINT_MIPLINEAR = NativeFilter.MINBILINEAR_MAGPOINT;
  122. public static readonly MINPOINT_MAGPOINT_MIPLINEAR = 7;
  123. public static readonly MINPOINT_MAGLINEAR_MIPPOINT = 8;
  124. public static readonly MINPOINT_MAGLINEAR_MIPLINEAR = 9;
  125. public static readonly MINLINEAR_MAGPOINT_MIPPOINT = 10;
  126. }
  127. // TODO: change this to match bgfx.
  128. // Must match AddressMode enum in SpectreEngine.h.
  129. class NativeAddressMode {
  130. public static readonly WRAP = 0;
  131. public static readonly MIRROR = 1;
  132. public static readonly CLAMP = 2;
  133. public static readonly BORDER = 3;
  134. public static readonly MIRROR_ONCE = 4;
  135. }
  136. class NativeTextureFormat {
  137. public static readonly RGBA8 = 0;
  138. public static readonly RGBA32F = 1;
  139. }
  140. /** @hidden */
  141. class NativeTexture extends InternalTexture {
  142. public getInternalTexture(): InternalTexture {
  143. return this;
  144. }
  145. public getViewCount(): number {
  146. return 1;
  147. }
  148. }
  149. /** @hidden */
  150. declare var _native: any;
  151. /** @hidden */
  152. export class NativeEngine extends Engine {
  153. private readonly _native: INativeEngine = new _native.Engine();
  154. /** Defines the invalid handle returned by bgfx when resource creation goes wrong */
  155. private readonly INVALID_HANDLE = 65535;
  156. public getHardwareScalingLevel(): number {
  157. return 1.0;
  158. }
  159. public constructor() {
  160. super(null);
  161. this._webGLVersion = 2;
  162. this.disableUniformBuffers = true;
  163. // TODO: Initialize this more correctly based on the hardware capabilities.
  164. // Init caps
  165. this._caps = {
  166. maxTexturesImageUnits: 16,
  167. maxVertexTextureImageUnits: 16,
  168. maxCombinedTexturesImageUnits: 32,
  169. maxTextureSize: 512,
  170. maxCubemapTextureSize: 512,
  171. maxRenderTextureSize: 512,
  172. maxVertexAttribs: 16,
  173. maxVaryingVectors: 16,
  174. maxFragmentUniformVectors: 16,
  175. maxVertexUniformVectors: 16,
  176. standardDerivatives: true,
  177. astc: null,
  178. pvrtc: null,
  179. etc1: null,
  180. etc2: null,
  181. maxAnisotropy: 16, // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
  182. uintIndices: false,
  183. fragmentDepthSupported: false,
  184. highPrecisionShaderSupported: true,
  185. colorBufferFloat: false,
  186. textureFloat: false,
  187. textureFloatLinearFiltering: false,
  188. textureFloatRender: false,
  189. textureHalfFloat: false,
  190. textureHalfFloatLinearFiltering: false,
  191. textureHalfFloatRender: false,
  192. textureLOD: true,
  193. drawBuffersExtension: false,
  194. depthTextureExtension: false,
  195. vertexArrayObject: true,
  196. instancedArrays: false,
  197. canUseTimestampForTimerQuery: false,
  198. blendMinMax: false,
  199. maxMSAASamples: 1
  200. };
  201. Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
  202. // Wrappers
  203. if (typeof URL === "undefined") {
  204. (window.URL as any) = {
  205. createObjectURL: function() { },
  206. revokeObjectURL: function() { }
  207. };
  208. }
  209. if (typeof Blob === "undefined") {
  210. (window.Blob as any) = function() { };
  211. }
  212. // Shader processor
  213. this._shaderProcessor = new NativeShaderProcessor();
  214. }
  215. /**
  216. * Can be used to override the current requestAnimationFrame requester.
  217. * @hidden
  218. */
  219. protected _queueNewFrame(bindedRenderFunction: any, requester?: any): number {
  220. if (requester.requestAnimationFrame) {
  221. requester.requestAnimationFrame(bindedRenderFunction);
  222. } else {
  223. this._native.requestAnimationFrame(bindedRenderFunction);
  224. }
  225. return 0;
  226. }
  227. /**
  228. * Override default engine behavior.
  229. * @param color
  230. * @param backBuffer
  231. * @param depth
  232. * @param stencil
  233. */
  234. public _bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  235. if (this._currentFramebuffer !== framebuffer) {
  236. if (this._currentFramebuffer) {
  237. this._native.unbindFramebuffer(this._currentFramebuffer!);
  238. }
  239. if (framebuffer) {
  240. this._native.bindFramebuffer(framebuffer);
  241. }
  242. this._currentFramebuffer = framebuffer;
  243. }
  244. }
  245. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  246. this._native.clear(color.r, color.g, color.b, color.a, backBuffer, depth, stencil);
  247. }
  248. public createIndexBuffer(indices: IndicesArray): NativeDataBuffer {
  249. const data = this._normalizeIndexData(indices);
  250. const buffer = new NativeDataBuffer();
  251. buffer.references = 1;
  252. buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  253. buffer.nativeIndexBuffer = this._native.createIndexBuffer(data);
  254. if (buffer.nativeVertexBuffer == this.INVALID_HANDLE) {
  255. throw new Error("Could not create a native index buffer.");
  256. }
  257. return buffer;
  258. }
  259. public createVertexBuffer(data: DataArray): NativeDataBuffer {
  260. const buffer = new NativeDataBuffer();
  261. buffer.references = 1;
  262. buffer.nativeVertexBuffer = this._native.createVertexBuffer(ArrayBuffer.isView(data) ? data : new Float32Array(data));
  263. if (buffer.nativeVertexBuffer == this.INVALID_HANDLE) {
  264. throw new Error("Could not create a native vertex buffer.");
  265. }
  266. return buffer;
  267. }
  268. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): WebGLVertexArrayObject {
  269. const vertexArray = this._native.createVertexArray();
  270. if (indexBuffer) {
  271. this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
  272. }
  273. const attributes = effect.getAttributesNames();
  274. for (let index = 0; index < attributes.length; index++) {
  275. const location = effect.getAttributeLocation(index);
  276. if (location >= 0) {
  277. const kind = attributes[index];
  278. const vertexBuffer = vertexBuffers[kind];
  279. if (vertexBuffer) {
  280. const buffer = vertexBuffer.getBuffer() as Nullable<NativeDataBuffer>;
  281. if (buffer) {
  282. this._native.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized);
  283. }
  284. }
  285. }
  286. }
  287. return vertexArray;
  288. }
  289. public bindVertexArrayObject(vertexArray: WebGLVertexArrayObject): void {
  290. this._native.bindVertexArray(vertexArray);
  291. }
  292. public releaseVertexArrayObject(vertexArray: WebGLVertexArrayObject) {
  293. this._native.deleteVertexArray(vertexArray);
  294. }
  295. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  296. const nativePipelineContext = pipelineContext as NativePipelineContext;
  297. return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames);
  298. }
  299. /**
  300. * Draw a list of indexed primitives
  301. * @param fillMode defines the primitive to use
  302. * @param indexStart defines the starting index
  303. * @param indexCount defines the number of index to draw
  304. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  305. */
  306. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  307. // Apply states
  308. this._drawCalls.addCount(1, false);
  309. // TODO: Make this implementation more robust like core Engine version.
  310. // Render
  311. //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  312. //var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  313. // if (instancesCount) {
  314. // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  315. // } else {
  316. this._native.drawIndexed(fillMode, indexStart, indexCount);
  317. // }
  318. }
  319. /**
  320. * Draw a list of unindexed primitives
  321. * @param fillMode defines the primitive to use
  322. * @param verticesStart defines the index of first vertex to draw
  323. * @param verticesCount defines the count of vertices to draw
  324. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  325. */
  326. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  327. // Apply states
  328. this._drawCalls.addCount(1, false);
  329. // TODO: Make this implementation more robust like core Engine version.
  330. // if (instancesCount) {
  331. // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  332. // } else {
  333. this._native.draw(fillMode, verticesStart, verticesCount);
  334. // }
  335. }
  336. public createPipelineContext(): IPipelineContext {
  337. return new NativePipelineContext();
  338. }
  339. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rebuildRebind: any, defines: Nullable<string>, transformFeedbackVaryings: Nullable<string[]>) {
  340. const nativePipelineContext = pipelineContext as NativePipelineContext;
  341. if (createAsRaw) {
  342. nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  343. }
  344. else {
  345. nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  346. }
  347. }
  348. /** @hidden */
  349. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  350. // TODO: support async shader compilcation
  351. return true;
  352. }
  353. /** @hidden */
  354. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  355. // TODO: support async shader compilcation
  356. action();
  357. }
  358. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  359. throw new Error("Not Supported");
  360. }
  361. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  362. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  363. const program = this._native.createProgram(
  364. ThinEngine._ConcatenateShader(vertexCode, defines),
  365. ThinEngine._ConcatenateShader(fragmentCode, defines)
  366. );
  367. this.onAfterShaderCompilationObservable.notifyObservers(this);
  368. return program;
  369. }
  370. protected _setProgram(program: WebGLProgram): void {
  371. if (this._currentProgram !== program) {
  372. this._native.setProgram(program);
  373. this._currentProgram = program;
  374. }
  375. }
  376. public _releaseEffect(effect: Effect): void {
  377. // TODO
  378. }
  379. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  380. // TODO
  381. }
  382. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): WebGLUniformLocation[] {
  383. const nativePipelineContext = pipelineContext as NativePipelineContext;
  384. return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);
  385. }
  386. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  387. // TODO
  388. throw new Error("Not Implemented");
  389. }
  390. public bindSamplers(effect: Effect): void {
  391. const nativePipelineContext = effect.getPipelineContext() as NativePipelineContext;
  392. this._setProgram(nativePipelineContext.nativeProgram);
  393. // TODO: share this with engine?
  394. var samplers = effect.getSamplers();
  395. for (var index = 0; index < samplers.length; index++) {
  396. var uniform = effect.getUniform(samplers[index]);
  397. if (uniform) {
  398. this._boundUniforms[index] = uniform;
  399. }
  400. }
  401. this._currentEffect = null;
  402. }
  403. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  404. if (!uniform) {
  405. return;
  406. }
  407. this._native.setMatrix(uniform, matrix.toArray() as Float32Array);
  408. }
  409. public getRenderWidth(useScreen = false): number {
  410. if (!useScreen && this._currentRenderTarget) {
  411. return this._currentRenderTarget.width;
  412. }
  413. return this._native.getRenderWidth();
  414. }
  415. public getRenderHeight(useScreen = false): number {
  416. if (!useScreen && this._currentRenderTarget) {
  417. return this._currentRenderTarget.height;
  418. }
  419. return this._native.getRenderHeight();
  420. }
  421. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  422. // TODO: Implement.
  423. this._cachedViewport = viewport;
  424. }
  425. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  426. this._native.setState(culling, zOffset, reverseSide);
  427. }
  428. /**
  429. * Set the z offset to apply to current rendering
  430. * @param value defines the offset to apply
  431. */
  432. public setZOffset(value: number): void {
  433. this._native.setZOffset(value);
  434. }
  435. /**
  436. * Gets the current value of the zOffset
  437. * @returns the current zOffset state
  438. */
  439. public getZOffset(): number {
  440. return this._native.getZOffset();
  441. }
  442. /**
  443. * Enable or disable depth buffering
  444. * @param enable defines the state to set
  445. */
  446. public setDepthBuffer(enable: boolean): void {
  447. this._native.setDepthTest(enable);
  448. }
  449. /**
  450. * Gets a boolean indicating if depth writing is enabled
  451. * @returns the current depth writing state
  452. */
  453. public getDepthWrite(): boolean {
  454. return this._native.getDepthWrite();
  455. }
  456. /**
  457. * Enable or disable depth writing
  458. * @param enable defines the state to set
  459. */
  460. public setDepthWrite(enable: boolean): void {
  461. this._native.setDepthWrite(enable);
  462. }
  463. /**
  464. * Enable or disable color writing
  465. * @param enable defines the state to set
  466. */
  467. public setColorWrite(enable: boolean): void {
  468. this._native.setColorWrite(enable);
  469. this._colorWrite = enable;
  470. }
  471. /**
  472. * Gets a boolean indicating if color writing is enabled
  473. * @returns the current color writing state
  474. */
  475. public getColorWrite(): boolean {
  476. return this._colorWrite;
  477. }
  478. /**
  479. * Sets alpha constants used by some alpha blending modes
  480. * @param r defines the red component
  481. * @param g defines the green component
  482. * @param b defines the blue component
  483. * @param a defines the alpha component
  484. */
  485. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  486. throw new Error("Setting alpha blend constant color not yet implemented.");
  487. }
  488. /**
  489. * Sets the current alpha mode
  490. * @param mode defines the mode to use (one of the BABYLON.Constants.ALPHA_XXX)
  491. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  492. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  493. */
  494. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  495. if (this._alphaMode === mode) {
  496. return;
  497. }
  498. this._native.setBlendMode(mode);
  499. if (!noDepthWriteChange) {
  500. this.setDepthWrite(mode === Constants.ALPHA_DISABLE);
  501. }
  502. this._alphaMode = mode;
  503. }
  504. /**
  505. * Gets the current alpha mode
  506. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  507. * @returns the current alpha mode
  508. */
  509. public getAlphaMode(): number {
  510. return this._alphaMode;
  511. }
  512. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  513. if (!uniform) {
  514. return;
  515. }
  516. this._native.setIntArray(uniform, array);
  517. }
  518. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  519. if (!uniform) {
  520. return;
  521. }
  522. this._native.setIntArray2(uniform, array);
  523. }
  524. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  525. if (!uniform) {
  526. return;
  527. }
  528. this._native.setIntArray3(uniform, array);
  529. }
  530. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  531. if (!uniform) {
  532. return;
  533. }
  534. this._native.setIntArray4(uniform, array);
  535. }
  536. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  537. if (!uniform) {
  538. return;
  539. }
  540. this._native.setFloatArray(uniform, array);
  541. }
  542. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  543. if (!uniform) {
  544. return;
  545. }
  546. this._native.setFloatArray2(uniform, array);
  547. }
  548. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  549. if (!uniform) {
  550. return;
  551. }
  552. this._native.setFloatArray3(uniform, array);
  553. }
  554. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  555. if (!uniform) {
  556. return;
  557. }
  558. this._native.setFloatArray4(uniform, array);
  559. }
  560. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  561. if (!uniform) {
  562. return;
  563. }
  564. this._native.setFloatArray(uniform, array);
  565. }
  566. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  567. if (!uniform) {
  568. return;
  569. }
  570. this._native.setFloatArray2(uniform, array);
  571. }
  572. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  573. if (!uniform) {
  574. return;
  575. }
  576. this._native.setFloatArray3(uniform, array);
  577. }
  578. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  579. if (!uniform) {
  580. return;
  581. }
  582. this._native.setFloatArray4(uniform, array);
  583. }
  584. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  585. if (!uniform) {
  586. return;
  587. }
  588. this._native.setMatrices(uniform, matrices);
  589. }
  590. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  591. if (!uniform) {
  592. return;
  593. }
  594. this._native.setMatrix3x3(uniform, matrix);
  595. }
  596. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  597. if (!uniform) {
  598. return;
  599. }
  600. this._native.setMatrix2x2(uniform, matrix);
  601. }
  602. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  603. if (!uniform) {
  604. return;
  605. }
  606. this._native.setFloat(uniform, value);
  607. }
  608. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  609. if (!uniform) {
  610. return;
  611. }
  612. this._native.setFloat2(uniform, x, y);
  613. }
  614. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  615. if (!uniform) {
  616. return;
  617. }
  618. this._native.setFloat3(uniform, x, y, z);
  619. }
  620. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  621. if (!uniform) {
  622. return;
  623. }
  624. this._native.setBool(uniform, bool);
  625. }
  626. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  627. if (!uniform) {
  628. return;
  629. }
  630. this._native.setFloat4(uniform, x, y, z, w);
  631. }
  632. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  633. if (!uniform) {
  634. return;
  635. }
  636. this._native.setFloat3(uniform, color3.r, color3.g, color3.b);
  637. }
  638. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  639. if (!uniform) {
  640. return;
  641. }
  642. this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
  643. }
  644. public wipeCaches(bruteForce?: boolean): void {
  645. if (this.preventCacheWipeBetweenFrames) {
  646. return;
  647. }
  648. this.resetTextureCache();
  649. this._currentEffect = null;
  650. if (bruteForce) {
  651. this._currentProgram = null;
  652. this._stencilState.reset();
  653. this._depthCullingState.reset();
  654. this._alphaState.reset();
  655. }
  656. this._cachedVertexBuffers = null;
  657. this._cachedIndexBuffer = null;
  658. this._cachedEffectForVertexBuffers = null;
  659. }
  660. public _createTexture(): WebGLTexture {
  661. return this._native.createTexture();
  662. }
  663. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  664. this._native.deleteTexture(texture);
  665. }
  666. // TODO: Refactor to share more logic with babylon.engine.ts version.
  667. /**
  668. * Usually called from BABYLON.Texture.ts.
  669. * Passed information to create a WebGLTexture
  670. * @param urlArg defines a value which contains one of the following:
  671. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  672. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  673. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  674. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  675. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  676. * @param scene needed for loading to the correct scene
  677. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  678. * @param onLoad optional callback to be called upon successful completion
  679. * @param onError optional callback to be called upon failure
  680. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), or a Blob
  681. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  682. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  683. * @param forcedExtension defines the extension to use to pick the right loader
  684. * @returns a InternalTexture for assignment back into BABYLON.Texture
  685. */
  686. public createTexture(
  687. urlArg: Nullable<string>,
  688. noMipmap: boolean,
  689. invertY: boolean,
  690. scene: Nullable<Scene>,
  691. samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  692. onLoad: Nullable<() => void> = null,
  693. onError: Nullable<(message: string, exception: any) => void> = null,
  694. buffer: Nullable<string | ArrayBuffer | Blob> = null,
  695. fallback: Nullable<InternalTexture> = null,
  696. format: Nullable<number> = null,
  697. forcedExtension: Nullable<string> = null): InternalTexture {
  698. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  699. var fromData = url.substr(0, 5) === "data:";
  700. var fromBlob = url.substr(0, 5) === "blob:";
  701. var isBase64 = fromData && url.indexOf("base64") !== -1;
  702. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  703. // establish the file extension, if possible
  704. var lastDot = url.lastIndexOf('.');
  705. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  706. // TODO: Add support for compressed texture formats.
  707. var textureFormatInUse: Nullable<string> = null;
  708. let loader: Nullable<IInternalTextureLoader> = null;
  709. for (let availableLoader of Engine._TextureLoaders) {
  710. if (availableLoader.canLoad(extension, textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  711. loader = availableLoader;
  712. break;
  713. }
  714. }
  715. if (loader) {
  716. url = loader.transformUrl(url, textureFormatInUse);
  717. }
  718. if (scene) {
  719. scene._addPendingData(texture);
  720. }
  721. texture.url = url;
  722. texture.generateMipMaps = !noMipmap;
  723. texture.samplingMode = samplingMode;
  724. texture.invertY = invertY;
  725. if (!this.doNotHandleContextLost) {
  726. // Keep a link to the buffer only if we plan to handle context lost
  727. texture._buffer = buffer;
  728. }
  729. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  730. if (onLoad && !fallback) {
  731. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  732. }
  733. if (!fallback) { this._internalTexturesCache.push(texture); }
  734. let onInternalError = (message?: string, exception?: any) => {
  735. if (scene) {
  736. scene._removePendingData(texture);
  737. }
  738. let customFallback = false;
  739. if (loader) {
  740. const fallbackUrl = loader.getFallbackTextureUrl(url, textureFormatInUse);
  741. if (fallbackUrl) {
  742. // Add Back
  743. customFallback = true;
  744. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  745. }
  746. }
  747. if (!customFallback) {
  748. if (onLoadObserver) {
  749. texture.onLoadedObservable.remove(onLoadObserver);
  750. }
  751. if (Tools.UseFallbackTexture) {
  752. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  753. }
  754. }
  755. if (onError) {
  756. onError(message || "Unknown error", exception);
  757. }
  758. };
  759. // processing for non-image formats
  760. if (loader) {
  761. throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
  762. // var callback = (data: string | ArrayBuffer) => {
  763. // loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
  764. // this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  765. // done();
  766. // return false;
  767. // },
  768. // samplingMode);
  769. // });
  770. // }
  771. // if (!buffer) {
  772. // this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  773. // onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  774. // });
  775. // } else {
  776. // callback(buffer as ArrayBuffer);
  777. // }
  778. } else {
  779. var onload = (data: string | ArrayBuffer | Blob, responseURL?: string) => {
  780. if (typeof (data) === "string") {
  781. throw new Error("Loading textures from string data not yet implemented.");
  782. }
  783. if (fromBlob && !this.doNotHandleContextLost) {
  784. // We need to store the image if we need to rebuild the texture
  785. // in case of a webgl context lost
  786. texture._buffer = data;
  787. }
  788. let webGLTexture = texture._webGLTexture;
  789. if (!webGLTexture) {
  790. // this.resetTextureCache();
  791. if (scene) {
  792. scene._removePendingData(texture);
  793. }
  794. return;
  795. }
  796. let nativeHandle = this._native.loadTexture(webGLTexture, data, !noMipmap);
  797. if (nativeHandle == this.INVALID_HANDLE) {
  798. throw new Error("Could not load a native texture.");
  799. }
  800. if (invertY) {
  801. throw new Error("Support for textures with inverted Y coordinates not yet implemented.");
  802. }
  803. //this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  804. texture.baseWidth = this._native.getTextureWidth(webGLTexture);
  805. texture.baseHeight = this._native.getTextureHeight(webGLTexture);
  806. texture.width = texture.baseWidth;
  807. texture.height = texture.baseHeight;
  808. texture.isReady = true;
  809. var filter = this._getSamplingFilter(samplingMode);
  810. this._native.setTextureSampling(webGLTexture, filter);
  811. // this.resetTextureCache();
  812. if (scene) {
  813. scene._removePendingData(texture);
  814. }
  815. texture.onLoadedObservable.notifyObservers(texture);
  816. texture.onLoadedObservable.clear();
  817. };
  818. if (buffer instanceof ArrayBuffer) {
  819. onload(buffer);
  820. } else if (ArrayBuffer.isView(buffer)) {
  821. onload(buffer.buffer);
  822. } else if (buffer instanceof Blob) {
  823. throw new Error("Loading texture from Blob not yet implemented.");
  824. } else if (!fromData) {
  825. let onLoadFileError = (request?: WebRequest, exception?: any) => {
  826. onInternalError("Failed to retrieve " + url + ".", exception);
  827. };
  828. Tools.LoadFile(url, onload, undefined, undefined, /*useArrayBuffer*/true, onLoadFileError);
  829. } else {
  830. onload(Tools.DecodeBase64(buffer as string));
  831. }
  832. }
  833. return texture;
  834. }
  835. /**
  836. * Creates a cube texture
  837. * @param rootUrl defines the url where the files to load is located
  838. * @param scene defines the current scene
  839. * @param files defines the list of files to load (1 per face)
  840. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  841. * @param onLoad defines an optional callback raised when the texture is loaded
  842. * @param onError defines an optional callback raised if there is an issue to load the texture
  843. * @param format defines the format of the data
  844. * @param forcedExtension defines the extension to use to pick the right loader
  845. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  846. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  847. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  848. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  849. * @returns the cube texture as an InternalTexture
  850. */
  851. public createCubeTexture(
  852. rootUrl: string,
  853. scene: Nullable<Scene>,
  854. files: Nullable<string[]>,
  855. noMipmap?: boolean,
  856. onLoad: Nullable<(data?: any) => void> = null,
  857. onError: Nullable<(message?: string, exception?: any) => void> = null,
  858. format?: number,
  859. forcedExtension: any = null,
  860. createPolynomials = false,
  861. lodScale: number = 0,
  862. lodOffset: number = 0,
  863. fallback: Nullable<InternalTexture> = null): InternalTexture
  864. {
  865. var texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);
  866. texture.isCube = true;
  867. texture.url = rootUrl;
  868. texture.generateMipMaps = !noMipmap;
  869. texture._lodGenerationScale = lodScale;
  870. texture._lodGenerationOffset = lodOffset;
  871. if (!this._doNotHandleContextLost) {
  872. texture._extension = forcedExtension;
  873. texture._files = files;
  874. }
  875. var lastDot = rootUrl.lastIndexOf('.');
  876. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  877. if (extension === ".env") {
  878. const onloaddata = (data: any) => {
  879. data = data as ArrayBuffer;
  880. var info = EnvironmentTextureTools.GetEnvInfo(data)!;
  881. texture.width = info.width;
  882. texture.height = info.width;
  883. EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  884. if (info.version !== 1) {
  885. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  886. }
  887. let specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  888. if (!specularInfo) {
  889. throw new Error(`Nothing else parsed so far`);
  890. }
  891. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  892. const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(data, info);
  893. texture.format = Constants.TEXTUREFORMAT_RGBA;
  894. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  895. texture.generateMipMaps = true;
  896. texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
  897. texture._isRGBD = true;
  898. texture.invertY = true;
  899. this._native.loadCubeTexture(texture._webGLTexture!, imageData, true);
  900. texture.isReady = true;
  901. if (onLoad) {
  902. onLoad();
  903. }
  904. };
  905. if (files && files.length === 6) {
  906. throw new Error(`Multi-file loading not yet supported.`);
  907. }
  908. else {
  909. let onInternalError = (request?: IWebRequest, exception?: any) => {
  910. if (onError && request) {
  911. onError(request.status + " " + request.statusText, exception);
  912. }
  913. };
  914. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  915. }
  916. }
  917. else {
  918. throw new Error("Cannot load cubemap: non-ENV format not supported.");
  919. }
  920. this._internalTexturesCache.push(texture);
  921. return texture;
  922. }
  923. // Returns a NativeFilter.XXXX value.
  924. private _getSamplingFilter(samplingMode: number): number {
  925. switch (samplingMode) {
  926. case Constants.TEXTURE_BILINEAR_SAMPLINGMODE:
  927. return NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT;
  928. case Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:
  929. return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
  930. case Constants.TEXTURE_NEAREST_SAMPLINGMODE:
  931. return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR;
  932. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  933. return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
  934. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  935. return NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT;
  936. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  937. return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
  938. case Constants.TEXTURE_NEAREST_LINEAR:
  939. return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
  940. case Constants.TEXTURE_NEAREST_NEAREST:
  941. return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
  942. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  943. return NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT;
  944. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  945. return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
  946. case Constants.TEXTURE_LINEAR_LINEAR:
  947. return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
  948. case Constants.TEXTURE_LINEAR_NEAREST:
  949. return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
  950. default:
  951. throw new Error("Unexpected sampling mode: " + samplingMode + ".");
  952. }
  953. }
  954. private static _GetNativeTextureFormat(format: number, type: number): number {
  955. if (format == Constants.TEXTUREFORMAT_RGBA && type == Constants.TEXTURETYPE_UNSIGNED_INT) {
  956. return NativeTextureFormat.RGBA8;
  957. }
  958. else if (format == Constants.TEXTUREFORMAT_RGBA && type == Constants.TEXTURETYPE_FLOAT) {
  959. return NativeTextureFormat.RGBA32F;
  960. }
  961. else {
  962. throw new Error("Unexpected texture format or type: format " + format + ", type " + type + ".");
  963. }
  964. }
  965. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): NativeTexture {
  966. let fullOptions = new RenderTargetCreationOptions();
  967. if (options !== undefined && typeof options === "object") {
  968. fullOptions.generateMipMaps = options.generateMipMaps;
  969. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  970. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  971. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  972. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  973. fullOptions.format = options.format === undefined ? Constants.TEXTUREFORMAT_RGBA : options.format;
  974. } else {
  975. fullOptions.generateMipMaps = <boolean>options;
  976. fullOptions.generateDepthBuffer = true;
  977. fullOptions.generateStencilBuffer = false;
  978. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  979. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  980. fullOptions.format = Constants.TEXTUREFORMAT_RGBA;
  981. }
  982. if (fullOptions.type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  983. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  984. fullOptions.samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  985. }
  986. else if (fullOptions.type === Constants.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  987. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  988. fullOptions.samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  989. }
  990. var texture = new NativeTexture(this, InternalTextureSource.RenderTarget);
  991. var width = (<{ width: number, height: number }>size).width || <number>size;
  992. var height = (<{ width: number, height: number }>size).height || <number>size;
  993. if (fullOptions.type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  994. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  995. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  996. }
  997. var framebuffer = this._native.createFramebuffer(
  998. texture._webGLTexture!,
  999. width,
  1000. height,
  1001. NativeEngine._GetNativeTextureFormat(fullOptions.format, fullOptions.type),
  1002. fullOptions.samplingMode!,
  1003. fullOptions.generateStencilBuffer ? true : false,
  1004. fullOptions.generateDepthBuffer,
  1005. fullOptions.generateMipMaps ? true : false);
  1006. texture._framebuffer = framebuffer;
  1007. texture.baseWidth = width;
  1008. texture.baseHeight = height;
  1009. texture.width = width;
  1010. texture.height = height;
  1011. texture.isReady = true;
  1012. texture.samples = 1;
  1013. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1014. texture.samplingMode = fullOptions.samplingMode;
  1015. texture.type = fullOptions.type;
  1016. texture.format = fullOptions.format;
  1017. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1018. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1019. this._internalTexturesCache.push(texture);
  1020. return texture;
  1021. }
  1022. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  1023. if (texture._webGLTexture) {
  1024. var filter = this._getSamplingFilter(samplingMode);
  1025. this._native.setTextureSampling(texture._webGLTexture, filter);
  1026. }
  1027. texture.samplingMode = samplingMode;
  1028. }
  1029. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1030. if (faceIndex) {
  1031. throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
  1032. }
  1033. if (requiredWidth || requiredHeight) {
  1034. throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
  1035. }
  1036. if (forceFullscreenViewport) {
  1037. throw new Error("forceFullscreenViewport for frame buffers not yet supported in NativeEngine.");
  1038. }
  1039. this._bindUnboundFramebuffer(texture._framebuffer);
  1040. }
  1041. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1042. if (disableGenerateMipMaps) {
  1043. Logger.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring.");
  1044. }
  1045. if (onBeforeUnbind) {
  1046. onBeforeUnbind();
  1047. }
  1048. this._bindUnboundFramebuffer(null);
  1049. }
  1050. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1051. throw new Error("createDynamicVertexBuffer not yet implemented.");
  1052. }
  1053. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  1054. throw new Error("updateDynamicIndexBuffer not yet implemented.");
  1055. }
  1056. /**
  1057. * Updates a dynamic vertex buffer.
  1058. * @param vertexBuffer the vertex buffer to update
  1059. * @param data the data used to update the vertex buffer
  1060. * @param byteOffset the byte offset of the data (optional)
  1061. * @param byteLength the byte length of the data (optional)
  1062. */
  1063. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  1064. throw new Error("updateDynamicVertexBuffer not yet implemented.");
  1065. }
  1066. // TODO: Refactor to share more logic with base Engine implementation.
  1067. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  1068. let uniform = this._boundUniforms[channel];
  1069. if (!uniform) {
  1070. return false;
  1071. }
  1072. // Not ready?
  1073. if (!texture) {
  1074. if (this._boundTexturesCache[channel] != null) {
  1075. this._activeChannel = channel;
  1076. this._native.setTexture(uniform, null);
  1077. }
  1078. return false;
  1079. }
  1080. // Video
  1081. if ((<VideoTexture>texture).video) {
  1082. this._activeChannel = channel;
  1083. (<VideoTexture>texture).update();
  1084. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1085. texture.delayLoad();
  1086. return false;
  1087. }
  1088. let internalTexture: InternalTexture;
  1089. if (depthStencilTexture) {
  1090. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  1091. } else if (texture.isReady()) {
  1092. internalTexture = <InternalTexture>texture.getInternalTexture();
  1093. } else if (texture.isCube) {
  1094. internalTexture = this.emptyCubeTexture;
  1095. } else if (texture.is3D) {
  1096. internalTexture = this.emptyTexture3D;
  1097. } else if (texture.is2DArray) {
  1098. internalTexture = this.emptyTexture2DArray;
  1099. } else {
  1100. internalTexture = this.emptyTexture;
  1101. }
  1102. this._activeChannel = channel;
  1103. if (!internalTexture ||
  1104. !internalTexture._webGLTexture) {
  1105. return false;
  1106. }
  1107. this._native.setTextureWrapMode(
  1108. internalTexture._webGLTexture,
  1109. this._getAddressMode(texture.wrapU),
  1110. this._getAddressMode(texture.wrapV),
  1111. this._getAddressMode(texture.wrapR));
  1112. this._updateAnisotropicLevel(texture);
  1113. this._native.setTexture(uniform, internalTexture._webGLTexture);
  1114. return true;
  1115. }
  1116. // TODO: Share more of this logic with the base implementation.
  1117. // TODO: Rename to match naming in base implementation once refactoring allows different parameters.
  1118. private _updateAnisotropicLevel(texture: BaseTexture) {
  1119. var internalTexture = texture.getInternalTexture();
  1120. var value = texture.anisotropicFilteringLevel;
  1121. if (!internalTexture || !internalTexture._webGLTexture) {
  1122. return;
  1123. }
  1124. if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
  1125. this._native.setTextureAnisotropicLevel(internalTexture._webGLTexture, value);
  1126. internalTexture._cachedAnisotropicFilteringLevel = value;
  1127. }
  1128. }
  1129. // Returns a NativeAddressMode.XXX value.
  1130. private _getAddressMode(wrapMode: number): number {
  1131. switch (wrapMode) {
  1132. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  1133. return NativeAddressMode.WRAP;
  1134. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  1135. return NativeAddressMode.CLAMP;
  1136. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  1137. return NativeAddressMode.MIRROR;
  1138. default:
  1139. throw new Error("Unexpected wrap mode: " + wrapMode + ".");
  1140. }
  1141. }
  1142. /** @hidden */
  1143. public _bindTexture(channel: number, texture: InternalTexture): void {
  1144. throw new Error("_bindTexture not implemented.");
  1145. }
  1146. protected _deleteBuffer(buffer: NativeDataBuffer): void {
  1147. if (buffer.nativeIndexBuffer) {
  1148. this._native.deleteIndexBuffer(buffer.nativeIndexBuffer);
  1149. delete buffer.nativeIndexBuffer;
  1150. }
  1151. if (buffer.nativeVertexBuffer) {
  1152. this._native.deleteVertexBuffer(buffer.nativeVertexBuffer);
  1153. delete buffer.nativeVertexBuffer;
  1154. }
  1155. }
  1156. public releaseEffects() {
  1157. // TODO
  1158. }
  1159. /** @hidden */
  1160. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1161. throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
  1162. }
  1163. /** @hidden */
  1164. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1165. throw new Error("_uploadDataToTextureDirectly not implemented.");
  1166. }
  1167. /** @hidden */
  1168. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1169. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1170. }
  1171. /** @hidden */
  1172. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1173. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1174. }
  1175. }