screenshotTools.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { Nullable } from "../types";
  2. import { Camera } from "../Cameras/camera";
  3. import { Texture } from "../Materials/Textures/texture";
  4. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  5. import { FxaaPostProcess } from "../PostProcesses/fxaaPostProcess";
  6. import { Constants } from "../Engines/constants";
  7. import { Logger } from "./logger";
  8. import { _TypeStore } from "./typeStore";
  9. import { Tools } from "./tools";
  10. import { IScreenshotSize } from './interfaces/screenshotSize';
  11. declare type Engine = import("../Engines/engine").Engine;
  12. /**
  13. * Class containing a set of static utilities functions for screenshots
  14. */
  15. export class ScreenshotTools {
  16. /**
  17. * Captures a screenshot of the current rendering
  18. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  19. * @param engine defines the rendering engine
  20. * @param camera defines the source camera
  21. * @param size This parameter can be set to a single number or to an object with the
  22. * following (optional) properties: precision, width, height. If a single number is passed,
  23. * it will be used for both width and height. If an object is passed, the screenshot size
  24. * will be derived from the parameters. The precision property is a multiplier allowing
  25. * rendering at a higher or lower resolution
  26. * @param successCallback defines the callback receives a single parameter which contains the
  27. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  28. * src parameter of an <img> to display it
  29. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  30. * Check your browser for supported MIME types
  31. */
  32. public static CreateScreenshot(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  33. const { height, width } = ScreenshotTools._getScreenshotSize(engine, camera, size);
  34. if (!(height && width)) {
  35. Logger.Error("Invalid 'size' parameter !");
  36. return;
  37. }
  38. if (!Tools._ScreenshotCanvas) {
  39. Tools._ScreenshotCanvas = document.createElement('canvas');
  40. }
  41. Tools._ScreenshotCanvas.width = width;
  42. Tools._ScreenshotCanvas.height = height;
  43. var renderContext = Tools._ScreenshotCanvas.getContext("2d");
  44. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  45. var newWidth = width;
  46. var newHeight = newWidth / ratio;
  47. if (newHeight > height) {
  48. newHeight = height;
  49. newWidth = newHeight * ratio;
  50. }
  51. var offsetX = Math.max(0, width - newWidth) / 2;
  52. var offsetY = Math.max(0, height - newHeight) / 2;
  53. engine.onEndFrameObservable.addOnce(() => {
  54. var renderingCanvas = engine.getRenderingCanvas();
  55. if (renderContext && renderingCanvas) {
  56. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  57. }
  58. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  59. });
  60. }
  61. /**
  62. * Captures a screenshot of the current rendering
  63. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  64. * @param engine defines the rendering engine
  65. * @param camera defines the source camera
  66. * @param size This parameter can be set to a single number or to an object with the
  67. * following (optional) properties: precision, width, height. If a single number is passed,
  68. * it will be used for both width and height. If an object is passed, the screenshot size
  69. * will be derived from the parameters. The precision property is a multiplier allowing
  70. * rendering at a higher or lower resolution
  71. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  72. * Check your browser for supported MIME types
  73. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  74. * to the src parameter of an <img> to display it
  75. */
  76. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: any, mimeType: string = "image/png"): Promise<string> {
  77. return new Promise((resolve, reject) => {
  78. ScreenshotTools.CreateScreenshot(engine, camera, size, (data) => {
  79. if (typeof(data) !== "undefined") {
  80. resolve(data);
  81. } else {
  82. reject(new Error("Data is undefined"));
  83. }
  84. }, mimeType);
  85. });
  86. }
  87. /**
  88. * Generates an image screenshot from the specified camera.
  89. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  90. * @param engine The engine to use for rendering
  91. * @param camera The camera to use for rendering
  92. * @param size This parameter can be set to a single number or to an object with the
  93. * following (optional) properties: precision, width, height. If a single number is passed,
  94. * it will be used for both width and height. If an object is passed, the screenshot size
  95. * will be derived from the parameters. The precision property is a multiplier allowing
  96. * rendering at a higher or lower resolution
  97. * @param successCallback The callback receives a single parameter which contains the
  98. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  99. * src parameter of an <img> to display it
  100. * @param mimeType The MIME type of the screenshot image (default: image/png).
  101. * Check your browser for supported MIME types
  102. * @param samples Texture samples (default: 1)
  103. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  104. * @param fileName A name for for the downloaded file.
  105. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  106. * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)
  107. */
  108. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string, renderSprites: boolean = false, enableStencilBuffer: boolean = false): void {
  109. const { height, width } = ScreenshotTools._getScreenshotSize(engine, camera, size);
  110. let targetTextureSize = { width, height };
  111. if (!(height && width)) {
  112. Logger.Error("Invalid 'size' parameter !");
  113. return;
  114. }
  115. var scene = camera.getScene();
  116. var previousCamera: Nullable<Camera> = null;
  117. if (scene.activeCamera !== camera) {
  118. previousCamera = scene.activeCamera;
  119. scene.activeCamera = camera;
  120. }
  121. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  122. var texture = new RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, Constants.TEXTURETYPE_UNSIGNED_INT, false, Texture.NEAREST_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples);
  123. texture.renderList = null;
  124. texture.samples = samples;
  125. texture.renderSprites = renderSprites;
  126. engine.onEndFrameObservable.addOnce(() => {
  127. texture.readPixels()!.then((data) => {
  128. Tools.DumpData(width, height, data, successCallback, mimeType, fileName, true);
  129. texture.dispose();
  130. if (previousCamera) {
  131. scene.activeCamera = previousCamera;
  132. }
  133. camera.getProjectionMatrix(true); // Force cache refresh;
  134. });
  135. });
  136. const renderToTexture = () => {
  137. scene.incrementRenderId();
  138. scene.resetCachedMaterial();
  139. texture.render(true);
  140. };
  141. if (antialiasing) {
  142. const fxaaPostProcess = new FxaaPostProcess('antialiasing', 1.0, scene.activeCamera);
  143. texture.addPostProcess(fxaaPostProcess);
  144. // Async Shader Compilation can lead to none ready effects in synchronous code
  145. if (!fxaaPostProcess.getEffect().isReady()) {
  146. fxaaPostProcess.getEffect().onCompiled = () => {
  147. renderToTexture();
  148. };
  149. }
  150. // The effect is ready we can render
  151. else {
  152. renderToTexture();
  153. }
  154. }
  155. else {
  156. // No need to wait for extra resources to be ready
  157. renderToTexture();
  158. }
  159. }
  160. /**
  161. * Generates an image screenshot from the specified camera.
  162. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  163. * @param engine The engine to use for rendering
  164. * @param camera The camera to use for rendering
  165. * @param size This parameter can be set to a single number or to an object with the
  166. * following (optional) properties: precision, width, height. If a single number is passed,
  167. * it will be used for both width and height. If an object is passed, the screenshot size
  168. * will be derived from the parameters. The precision property is a multiplier allowing
  169. * rendering at a higher or lower resolution
  170. * @param mimeType The MIME type of the screenshot image (default: image/png).
  171. * Check your browser for supported MIME types
  172. * @param samples Texture samples (default: 1)
  173. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  174. * @param fileName A name for for the downloaded file.
  175. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  176. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  177. * to the src parameter of an <img> to display it
  178. */
  179. public static CreateScreenshotUsingRenderTargetAsync(engine: Engine, camera: Camera, size: any, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string, renderSprites: boolean = false): Promise<string> {
  180. return new Promise((resolve, reject) => {
  181. ScreenshotTools.CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {
  182. if (typeof(data) !== "undefined") {
  183. resolve(data);
  184. } else {
  185. reject(new Error("Data is undefined"));
  186. }
  187. }, mimeType, samples, antialiasing, fileName, renderSprites);
  188. });
  189. }
  190. /**
  191. * Gets height and width for screenshot size
  192. * @private
  193. */
  194. private static _getScreenshotSize(engine: Engine, camera: Camera, size: IScreenshotSize | number): {height: number, width: number} {
  195. let height = 0;
  196. let width = 0;
  197. //If a size value defined as object
  198. if (typeof(size) === 'object') {
  199. const precision = size.precision
  200. ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height
  201. : 1;
  202. //If a width and height values is specified
  203. if (size.width && size.height) {
  204. height = size.height * precision;
  205. width = size.width * precision;
  206. }
  207. //If passing only width, computing height to keep display canvas ratio.
  208. else if (size.width && !size.height) {
  209. width = size.width * precision;
  210. height = Math.round(width / engine.getAspectRatio(camera));
  211. }
  212. //If passing only height, computing width to keep display canvas ratio.
  213. else if (size.height && !size.width) {
  214. height = size.height * precision;
  215. width = Math.round(height * engine.getAspectRatio(camera));
  216. }
  217. else {
  218. width = Math.round(engine.getRenderWidth() * precision);
  219. height = Math.round(width / engine.getAspectRatio(camera));
  220. }
  221. }
  222. //Assuming here that "size" parameter is a number
  223. else if (!isNaN(size)) {
  224. height = size;
  225. width = size;
  226. }
  227. // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context
  228. // On certain GPUs, it seems as if the _gl context truncates to an integer automatically. Therefore, if a user tries to pass the width of their canvas element
  229. // and it happens to be a float (1000.5 x 600.5 px), the engine.readPixels will return a different size array than context.createImageData
  230. // to resolve this, we truncate the floats here to ensure the same size
  231. if (width) {
  232. width = Math.floor(width);
  233. }
  234. if (height) {
  235. height = Math.floor(height);
  236. }
  237. return { height: height | 0, width: width | 0 };
  238. }
  239. }
  240. Tools.CreateScreenshot = ScreenshotTools.CreateScreenshot;
  241. Tools.CreateScreenshotAsync = ScreenshotTools.CreateScreenshotAsync;
  242. Tools.CreateScreenshotUsingRenderTarget = ScreenshotTools.CreateScreenshotUsingRenderTarget;
  243. Tools.CreateScreenshotUsingRenderTargetAsync = ScreenshotTools.CreateScreenshotUsingRenderTargetAsync;