nativeEngine.ts 70 KB

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