screenshotTools.ts 13 KB

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