nativeEngine.ts 79 KB

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