nativeEngine.ts 81 KB

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