nativeEngine.ts 57 KB

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