copyTools.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { Nullable } from "../types";
  2. declare type BaseTexture = import("../Materials/Textures/baseTexture").BaseTexture;
  3. /**
  4. * Class used to host copy specific utilities
  5. */
  6. export class CopyTools {
  7. /**
  8. * Reads the pixels stored in the webgl texture and returns them as a base64 string
  9. * @param texture defines the texture to read pixels from
  10. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  11. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  12. * @returns The base64 encoded string or null
  13. */
  14. public static GenerateBase64StringFromTexture(texture: BaseTexture, faceIndex = 0, level = 0): Nullable<string> {
  15. var internalTexture = texture.getInternalTexture();
  16. if (!internalTexture) {
  17. return null;
  18. }
  19. var pixels = texture.readPixels(faceIndex, level);
  20. if (!pixels) {
  21. return null;
  22. }
  23. var size = texture.getSize();
  24. var width = size.width;
  25. var height = size.height;
  26. if (pixels instanceof Float32Array) {
  27. var len = pixels.byteLength / pixels.BYTES_PER_ELEMENT;
  28. var npixels = new Uint8Array(len);
  29. while (--len >= 0) {
  30. var val = pixels[len];
  31. if (val < 0) {
  32. val = 0;
  33. } else if (val > 1) {
  34. val = 1;
  35. }
  36. npixels[len] = val * 255;
  37. }
  38. pixels = npixels;
  39. }
  40. var canvas = document.createElement('canvas');
  41. canvas.width = width;
  42. canvas.height = height;
  43. var ctx = canvas.getContext('2d');
  44. if (!ctx) {
  45. return null;
  46. }
  47. var imageData = ctx.createImageData(width, height);
  48. var castData = <any>imageData.data;
  49. castData.set(pixels);
  50. ctx.putImageData(imageData, 0, 0);
  51. if (internalTexture.invertY) {
  52. var canvas2 = document.createElement('canvas');
  53. canvas2.width = width;
  54. canvas2.height = height;
  55. var ctx2 = canvas2.getContext('2d');
  56. if (!ctx2) {
  57. return null;
  58. }
  59. ctx2.translate(0, height);
  60. ctx2.scale(1, -1);
  61. ctx2.drawImage(canvas, 0, 0);
  62. return canvas2.toDataURL('image/png');
  63. }
  64. return canvas.toDataURL('image/png');
  65. }
  66. }