equiRectangularCubeTexture.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { PanoramaToCubeMapTools } from '../../Misc/HighDynamicRange/panoramaToCubemap';
  2. import { Engine } from "../../Engines/engine";
  3. import { BaseTexture } from './baseTexture';
  4. import { Texture } from './texture';
  5. import { Scene } from "../../scene";
  6. import { Nullable } from "../../types";
  7. import { Tools } from '../../Misc/tools';
  8. /**
  9. * This represents a texture coming from an equirectangular image supported by the web browser canvas.
  10. */
  11. export class EquiRectangularCubeTexture extends BaseTexture {
  12. /** The six faces of the cube. */
  13. private static _FacesMapping = ['right', 'left', 'up', 'down', 'front', 'back'];
  14. private _noMipmap: boolean;
  15. private _onLoad: Nullable<() => void> = null;
  16. private _onError: Nullable<() => void> = null;
  17. /** The size of the cubemap. */
  18. private _size: number;
  19. /** The buffer of the image. */
  20. private _buffer: ArrayBuffer;
  21. /** The width of the input image. */
  22. private _width: number;
  23. /** The height of the input image. */
  24. private _height: number;
  25. /** The URL to the image. */
  26. public url: string;
  27. /** The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */
  28. public coordinatesMode = Texture.CUBIC_MODE;
  29. /**
  30. * Instantiates an EquiRectangularCubeTexture from the following parameters.
  31. * @param url The location of the image
  32. * @param scene The scene the texture will be used in
  33. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  34. * @param noMipmap Forces to not generate the mipmap if true
  35. * @param gammaSpace Specifies if the texture will be used in gamma or linear space
  36. * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)
  37. * @param onLoad — defines a callback called when texture is loaded
  38. * @param onError — defines a callback called if there is an error
  39. */
  40. constructor(
  41. url: string,
  42. scene: Scene,
  43. size: number,
  44. noMipmap: boolean = false,
  45. gammaSpace: boolean = true,
  46. onLoad: Nullable<() => void> = null,
  47. onError: Nullable<(message?: string, exception?: any) => void> = null
  48. ) {
  49. super(scene);
  50. if (!url) {
  51. throw new Error('Image url is not set');
  52. }
  53. this.name = url;
  54. this.url = url;
  55. this._size = size;
  56. this._noMipmap = noMipmap;
  57. this.gammaSpace = gammaSpace;
  58. this._onLoad = onLoad;
  59. this._onError = onError;
  60. this.hasAlpha = false;
  61. this.isCube = true;
  62. this._texture = this._getFromCache(url, this._noMipmap);
  63. if (!this._texture) {
  64. if (!scene.useDelayedTextureLoading) {
  65. this.loadImage(this.loadTexture.bind(this), this._onError);
  66. } else {
  67. this.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  68. }
  69. } else if (onLoad) {
  70. if (this._texture.isReady) {
  71. Tools.SetImmediate(() => onLoad());
  72. } else {
  73. this._texture.onLoadedObservable.add(onLoad);
  74. }
  75. }
  76. }
  77. /**
  78. * Load the image data, by putting the image on a canvas and extracting its buffer.
  79. */
  80. private loadImage(loadTextureCallback: () => void, onError: (message?: string, exception?: any) => void): void {
  81. const canvas = document.createElement('canvas');
  82. const image = new Image();
  83. image.addEventListener('load', () => {
  84. this._width = image.width;
  85. this._height = image.height;
  86. canvas.width = this._width;
  87. canvas.height = this._height;
  88. const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  89. ctx.drawImage(image, 0, 0);
  90. const imageData = ctx.getImageData(0, 0, image.width, image.height);
  91. this._buffer = imageData.data.buffer as ArrayBuffer;
  92. canvas.remove();
  93. loadTextureCallback();
  94. });
  95. image.addEventListener('error', (error) => {
  96. onError(`${this.getClassName()} could not be loaded`, error);
  97. });
  98. image.src = this.url;
  99. }
  100. /**
  101. * Convert the image buffer into a cubemap and create a CubeTexture.
  102. */
  103. private loadTexture(): void {
  104. const scene = this.getScene();
  105. const callback = (): Nullable<ArrayBufferView[]> => {
  106. const imageData = this.getFloat32ArrayFromArrayBuffer(this._buffer);
  107. // Extract the raw linear data.
  108. const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size);
  109. const results = [];
  110. // Push each faces.
  111. for (let i = 0; i < 6; i++) {
  112. const dataFace = (data as any)[EquiRectangularCubeTexture._FacesMapping[i]];
  113. results.push(dataFace);
  114. }
  115. return results;
  116. };
  117. if (!scene) {
  118. return;
  119. }
  120. this._texture = scene
  121. .getEngine()
  122. .createRawCubeTextureFromUrl(
  123. this.url,
  124. scene,
  125. this._size,
  126. Engine.TEXTUREFORMAT_RGB,
  127. scene.getEngine().getCaps().textureFloat
  128. ? Engine.TEXTURETYPE_FLOAT
  129. : Engine.TEXTURETYPE_UNSIGNED_INTEGER,
  130. this._noMipmap,
  131. callback,
  132. null,
  133. this._onLoad,
  134. this._onError
  135. );
  136. }
  137. /**
  138. * Convert the ArrayBuffer into a Float32Array and drop the transparency channel.
  139. * @param buffer The ArrayBuffer that should be converted.
  140. * @returns The buffer as Float32Array.
  141. */
  142. private getFloat32ArrayFromArrayBuffer(buffer: ArrayBuffer): Float32Array {
  143. const dataView = new DataView(buffer);
  144. const floatImageData = new Float32Array((buffer.byteLength * 3) / 4);
  145. let k = 0;
  146. for (let i = 0; i < buffer.byteLength; i++) {
  147. // We drop the transparency channel, because we do not need/want it
  148. if ((i + 1) % 4 !== 0) {
  149. floatImageData[k++] = dataView.getUint8(i) / 255;
  150. }
  151. }
  152. return floatImageData;
  153. }
  154. /**
  155. * Get the current class name of the texture useful for serialization or dynamic coding.
  156. * @returns "EquiRectangularCubeTexture"
  157. */
  158. public getClassName(): string {
  159. return "EquiRectangularCubeTexture";
  160. }
  161. /**
  162. * Create a clone of the current EquiRectangularCubeTexture and return it.
  163. * @returns A clone of the current EquiRectangularCubeTexture.
  164. */
  165. public clone(): EquiRectangularCubeTexture {
  166. const scene = this.getScene();
  167. if (!scene) {
  168. return this;
  169. }
  170. const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace);
  171. // Base texture
  172. newTexture.level = this.level;
  173. newTexture.wrapU = this.wrapU;
  174. newTexture.wrapV = this.wrapV;
  175. newTexture.coordinatesIndex = this.coordinatesIndex;
  176. newTexture.coordinatesMode = this.coordinatesMode;
  177. return newTexture;
  178. }
  179. }