screenshotTools.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. var renderingCanvas = engine.getRenderingCanvas();
  54. if (renderContext && renderingCanvas) {
  55. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  56. }
  57. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  58. }
  59. /**
  60. * Captures a screenshot of the current rendering
  61. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  62. * @param engine defines the rendering engine
  63. * @param camera defines the source camera
  64. * @param size This parameter can be set to a single number or to an object with the
  65. * following (optional) properties: precision, width, height. If a single number is passed,
  66. * it will be used for both width and height. If an object is passed, the screenshot size
  67. * will be derived from the parameters. The precision property is a multiplier allowing
  68. * rendering at a higher or lower resolution
  69. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  70. * Check your browser for supported MIME types
  71. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  72. * to the src parameter of an <img> to display it
  73. */
  74. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: any, mimeType: string = "image/png"): Promise<string> {
  75. return new Promise((resolve, reject) => {
  76. ScreenshotTools.CreateScreenshot(engine, camera, size, (data) => {
  77. if (typeof(data) !== "undefined") {
  78. resolve(data);
  79. } else {
  80. reject(new Error("Data is undefined"));
  81. }
  82. }, mimeType);
  83. });
  84. }
  85. /**
  86. * Generates an image screenshot from the specified camera.
  87. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  88. * @param engine The engine to use for rendering
  89. * @param camera The camera to use for rendering
  90. * @param size This parameter can be set to a single number or to an object with the
  91. * following (optional) properties: precision, width, height. If a single number is passed,
  92. * it will be used for both width and height. If an object is passed, the screenshot size
  93. * will be derived from the parameters. The precision property is a multiplier allowing
  94. * rendering at a higher or lower resolution
  95. * @param successCallback The callback receives a single parameter which contains the
  96. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  97. * src parameter of an <img> to display it
  98. * @param mimeType The MIME type of the screenshot image (default: image/png).
  99. * Check your browser for supported MIME types
  100. * @param samples Texture samples (default: 1)
  101. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  102. * @param fileName A name for for the downloaded file.
  103. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  104. */
  105. 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): void {
  106. const { height, width } = ScreenshotTools._getScreenshotSize(engine, camera, size);
  107. let targetTextureSize = { width, height };
  108. if (!(height && width)) {
  109. Logger.Error("Invalid 'size' parameter !");
  110. return;
  111. }
  112. var scene = camera.getScene();
  113. var previousCamera: Nullable<Camera> = null;
  114. if (scene.activeCamera !== camera) {
  115. previousCamera = scene.activeCamera;
  116. scene.activeCamera = camera;
  117. }
  118. var renderCanvas = engine.getRenderingCanvas();
  119. if (!renderCanvas) {
  120. Logger.Error("No rendering canvas found !");
  121. return;
  122. }
  123. var originalSize = { width: renderCanvas.width, height: renderCanvas.height };
  124. engine.setSize(width, height);
  125. scene.render();
  126. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  127. var texture = new RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, Constants.TEXTURETYPE_UNSIGNED_INT, false, Texture.NEAREST_SAMPLINGMODE);
  128. texture.renderList = null;
  129. texture.samples = samples;
  130. texture.renderSprites = renderSprites;
  131. texture.onAfterRenderObservable.add(() => {
  132. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  133. });
  134. const renderToTexture = () => {
  135. scene.incrementRenderId();
  136. scene.resetCachedMaterial();
  137. texture.render(true);
  138. texture.dispose();
  139. if (previousCamera) {
  140. scene.activeCamera = previousCamera;
  141. }
  142. engine.setSize(originalSize.width, originalSize.height);
  143. camera.getProjectionMatrix(true); // Force cache refresh;
  144. };
  145. if (antialiasing) {
  146. const fxaaPostProcess = new FxaaPostProcess('antialiasing', 1.0, scene.activeCamera);
  147. texture.addPostProcess(fxaaPostProcess);
  148. // Async Shader Compilation can lead to none ready effects in synchronous code
  149. if (!fxaaPostProcess.getEffect().isReady()) {
  150. fxaaPostProcess.getEffect().onCompiled = () => {
  151. renderToTexture();
  152. };
  153. }
  154. // The effect is ready we can render
  155. else {
  156. renderToTexture();
  157. }
  158. }
  159. else {
  160. // No need to wait for extra resources to be ready
  161. renderToTexture();
  162. }
  163. }
  164. /**
  165. * Generates an image screenshot from the specified camera.
  166. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  167. * @param engine The engine to use for rendering
  168. * @param camera The camera to use for rendering
  169. * @param size This parameter can be set to a single number or to an object with the
  170. * following (optional) properties: precision, width, height. If a single number is passed,
  171. * it will be used for both width and height. If an object is passed, the screenshot size
  172. * will be derived from the parameters. The precision property is a multiplier allowing
  173. * rendering at a higher or lower resolution
  174. * @param mimeType The MIME type of the screenshot image (default: image/png).
  175. * Check your browser for supported MIME types
  176. * @param samples Texture samples (default: 1)
  177. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  178. * @param fileName A name for for the downloaded file.
  179. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  180. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  181. * to the src parameter of an <img> to display it
  182. */
  183. 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> {
  184. return new Promise((resolve, reject) => {
  185. ScreenshotTools.CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {
  186. if (typeof(data) !== "undefined") {
  187. resolve(data);
  188. } else {
  189. reject(new Error("Data is undefined"));
  190. }
  191. }, mimeType, samples, antialiasing, fileName, renderSprites);
  192. });
  193. }
  194. /**
  195. * Gets height and width for screenshot size
  196. * @private
  197. */
  198. private static _getScreenshotSize(engine: Engine, camera: Camera, size: IScreenshotSize | number): {height: number, width: number} {
  199. let height = 0;
  200. let width = 0;
  201. //If a size value defined as object
  202. if (typeof(size) === 'object') {
  203. const precision = size.precision
  204. ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height
  205. : 1;
  206. //If a width and height values is specified
  207. if (size.width && size.height) {
  208. height = size.height * precision;
  209. width = size.width * precision;
  210. }
  211. //If passing only width, computing height to keep display canvas ratio.
  212. else if (size.width && !size.height) {
  213. width = size.width * precision;
  214. height = Math.round(width / engine.getAspectRatio(camera));
  215. }
  216. //If passing only height, computing width to keep display canvas ratio.
  217. else if (size.height && !size.width) {
  218. height = size.height * precision;
  219. width = Math.round(height * engine.getAspectRatio(camera));
  220. }
  221. else {
  222. width = Math.round(engine.getRenderWidth() * precision);
  223. height = Math.round(width / engine.getAspectRatio(camera));
  224. }
  225. }
  226. //Assuming here that "size" parameter is a number
  227. else if (!isNaN(size)) {
  228. height = size;
  229. width = size;
  230. }
  231. // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context
  232. // 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
  233. // 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
  234. // to resolve this, we truncate the floats here to ensure the same size
  235. if (width) {
  236. width = Math.floor(width);
  237. }
  238. if (height) {
  239. height = Math.floor(height);
  240. }
  241. return { height: height | 0, width: width | 0 };
  242. }
  243. }
  244. Tools.CreateScreenshot = ScreenshotTools.CreateScreenshot;
  245. Tools.CreateScreenshotAsync = ScreenshotTools.CreateScreenshotAsync;
  246. Tools.CreateScreenshotUsingRenderTarget = ScreenshotTools.CreateScreenshotUsingRenderTarget;
  247. Tools.CreateScreenshotUsingRenderTargetAsync = ScreenshotTools.CreateScreenshotUsingRenderTargetAsync;