nativeEngine.ts 58 KB

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