nativeEngine.ts 66 KB

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