nativeEngine.ts 56 KB

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