asciiArtPostProcess.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { Nullable } from "babylonjs/types";
  2. import { serialize, SerializationHelper } from "babylonjs/Misc/decorators";
  3. import { Camera } from "babylonjs/Cameras/camera";
  4. import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture";
  5. import { Texture } from "babylonjs/Materials/Textures/texture";
  6. import { Effect } from "babylonjs/Materials/effect";
  7. import { PostProcess } from "babylonjs/PostProcesses/postProcess";
  8. import { Scene } from "babylonjs/scene";
  9. import "./asciiart.fragment";
  10. /**
  11. * AsciiArtFontTexture is the helper class used to easily create your ascii art font texture.
  12. *
  13. * It basically takes care rendering the font front the given font size to a texture.
  14. * This is used later on in the postprocess.
  15. */
  16. export class AsciiArtFontTexture extends BaseTexture {
  17. @serialize("font")
  18. private _font: string;
  19. @serialize("text")
  20. private _text: string;
  21. private _charSize: number;
  22. /**
  23. * Gets the size of one char in the texture (each char fits in size * size space in the texture).
  24. */
  25. public get charSize(): number {
  26. return this._charSize;
  27. }
  28. /**
  29. * Create a new instance of the Ascii Art FontTexture class
  30. * @param name the name of the texture
  31. * @param font the font to use, use the W3C CSS notation
  32. * @param text the caracter set to use in the rendering.
  33. * @param scene the scene that owns the texture
  34. */
  35. constructor(name: string, font: string, text: string, scene: Nullable<Scene> = null) {
  36. super(scene);
  37. scene = this.getScene();
  38. if (!scene) {
  39. return;
  40. }
  41. this.name = name;
  42. this._text == text;
  43. this._font == font;
  44. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  45. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  46. //this.anisotropicFilteringLevel = 1;
  47. // Get the font specific info.
  48. var maxCharHeight = this.getFontHeight(font);
  49. var maxCharWidth = this.getFontWidth(font);
  50. this._charSize = Math.max(maxCharHeight.height, maxCharWidth);
  51. // This is an approximate size, but should always be able to fit at least the maxCharCount.
  52. var textureWidth = Math.ceil(this._charSize * text.length);
  53. var textureHeight = this._charSize;
  54. // Create the texture that will store the font characters.
  55. this._texture = scene.getEngine().createDynamicTexture(textureWidth, textureHeight, false, Texture.NEAREST_SAMPLINGMODE);
  56. //scene.getEngine().setclamp
  57. var textureSize = this.getSize();
  58. // Create a canvas with the final size: the one matching the texture.
  59. var canvas = document.createElement("canvas");
  60. canvas.width = textureSize.width;
  61. canvas.height = textureSize.height;
  62. var context = <CanvasRenderingContext2D>canvas.getContext("2d");
  63. context.textBaseline = "top";
  64. context.font = font;
  65. context.fillStyle = "white";
  66. context.imageSmoothingEnabled = false;
  67. // Sets the text in the texture.
  68. for (var i = 0; i < text.length; i++) {
  69. context.fillText(text[i], i * this._charSize, -maxCharHeight.offset);
  70. }
  71. // Flush the text in the dynamic texture.
  72. scene.getEngine().updateDynamicTexture(this._texture, canvas, false, true);
  73. }
  74. /**
  75. * Gets the max char width of a font.
  76. * @param font the font to use, use the W3C CSS notation
  77. * @return the max char width
  78. */
  79. private getFontWidth(font: string): number {
  80. var fontDraw = document.createElement("canvas");
  81. var ctx = <CanvasRenderingContext2D>fontDraw.getContext('2d');
  82. ctx.fillStyle = 'white';
  83. ctx.font = font;
  84. return ctx.measureText("W").width;
  85. }
  86. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  87. /**
  88. * Gets the max char height of a font.
  89. * @param font the font to use, use the W3C CSS notation
  90. * @return the max char height
  91. */
  92. private getFontHeight(font: string): { height: number, offset: number } {
  93. var fontDraw = document.createElement("canvas");
  94. var ctx = <CanvasRenderingContext2D>fontDraw.getContext('2d');
  95. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  96. ctx.textBaseline = 'top';
  97. ctx.fillStyle = 'white';
  98. ctx.font = font;
  99. ctx.fillText('jH|', 0, 0);
  100. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  101. var start = -1;
  102. var end = -1;
  103. for (var row = 0; row < fontDraw.height; row++) {
  104. for (var column = 0; column < fontDraw.width; column++) {
  105. var index = (row * fontDraw.width + column) * 4;
  106. if (pixels[index] === 0) {
  107. if (column === fontDraw.width - 1 && start !== -1) {
  108. end = row;
  109. row = fontDraw.height;
  110. break;
  111. }
  112. continue;
  113. }
  114. else {
  115. if (start === -1) {
  116. start = row;
  117. }
  118. break;
  119. }
  120. }
  121. }
  122. return { height: (end - start) + 1, offset: start - 1 };
  123. }
  124. /**
  125. * Clones the current AsciiArtTexture.
  126. * @return the clone of the texture.
  127. */
  128. public clone(): AsciiArtFontTexture {
  129. return new AsciiArtFontTexture(this.name, this._font, this._text, this.getScene());
  130. }
  131. /**
  132. * Parses a json object representing the texture and returns an instance of it.
  133. * @param source the source JSON representation
  134. * @param scene the scene to create the texture for
  135. * @return the parsed texture
  136. */
  137. public static Parse(source: any, scene: Scene): AsciiArtFontTexture {
  138. var texture = SerializationHelper.Parse(() => new AsciiArtFontTexture(source.name, source.font, source.text, scene),
  139. source, scene, null);
  140. return texture;
  141. }
  142. }
  143. /**
  144. * Option available in the Ascii Art Post Process.
  145. */
  146. export interface IAsciiArtPostProcessOptions {
  147. /**
  148. * The font to use following the w3c font definition.
  149. */
  150. font?: string;
  151. /**
  152. * The character set to use in the postprocess.
  153. */
  154. characterSet?: string;
  155. /**
  156. * This defines the amount you want to mix the "tile" or caracter space colored in the ascii art.
  157. * This number is defined between 0 and 1;
  158. */
  159. mixToTile?: number;
  160. /**
  161. * This defines the amount you want to mix the normal rendering pass in the ascii art.
  162. * This number is defined between 0 and 1;
  163. */
  164. mixToNormal?: number;
  165. }
  166. /**
  167. * AsciiArtPostProcess helps rendering everithing in Ascii Art.
  168. *
  169. * Simmply add it to your scene and let the nerd that lives in you have fun.
  170. * Example usage: var pp = new AsciiArtPostProcess("myAscii", "20px Monospace", camera);
  171. */
  172. export class AsciiArtPostProcess extends PostProcess {
  173. /**
  174. * The font texture used to render the char in the post process.
  175. */
  176. private _asciiArtFontTexture: AsciiArtFontTexture;
  177. /**
  178. * This defines the amount you want to mix the "tile" or caracter space colored in the ascii art.
  179. * This number is defined between 0 and 1;
  180. */
  181. public mixToTile: number = 0;
  182. /**
  183. * This defines the amount you want to mix the normal rendering pass in the ascii art.
  184. * This number is defined between 0 and 1;
  185. */
  186. public mixToNormal: number = 0;
  187. /**
  188. * Instantiates a new Ascii Art Post Process.
  189. * @param name the name to give to the postprocess
  190. * @camera the camera to apply the post process to.
  191. * @param options can either be the font name or an option object following the IAsciiArtPostProcessOptions format
  192. */
  193. constructor(name: string, camera: Camera, options?: string | IAsciiArtPostProcessOptions) {
  194. super(name,
  195. 'asciiart',
  196. ['asciiArtFontInfos', 'asciiArtOptions'],
  197. ['asciiArtFont'],
  198. {
  199. width: camera.getEngine().getRenderWidth(),
  200. height: camera.getEngine().getRenderHeight()
  201. },
  202. camera,
  203. Texture.TRILINEAR_SAMPLINGMODE,
  204. camera.getEngine(),
  205. true);
  206. // Default values.
  207. var font = "40px Monospace";
  208. var characterSet = " `-.'_:,\"=^;<+!*?/cL\\zrs7TivJtC{3F)Il(xZfY5S2eajo14[nuyE]P6V9kXpKwGhqAUbOd8#HRDB0$mgMW&Q%N@";
  209. // Use options.
  210. if (options) {
  211. if (typeof (options) === "string") {
  212. font = <string>options;
  213. }
  214. else {
  215. font = (<IAsciiArtPostProcessOptions>options).font || font;
  216. characterSet = (<IAsciiArtPostProcessOptions>options).characterSet || characterSet;
  217. this.mixToTile = (<IAsciiArtPostProcessOptions>options).mixToTile || this.mixToTile;
  218. this.mixToNormal = (<IAsciiArtPostProcessOptions>options).mixToNormal || this.mixToNormal;
  219. }
  220. }
  221. this._asciiArtFontTexture = new AsciiArtFontTexture(name, font, characterSet, camera.getScene());
  222. var textureSize = this._asciiArtFontTexture.getSize();
  223. this.onApply = (effect: Effect) => {
  224. effect.setTexture("asciiArtFont", this._asciiArtFontTexture);
  225. effect.setFloat4("asciiArtFontInfos",
  226. this._asciiArtFontTexture.charSize,
  227. characterSet.length,
  228. textureSize.width,
  229. textureSize.height);
  230. effect.setFloat4("asciiArtOptions",
  231. this.width,
  232. this.height,
  233. this.mixToNormal,
  234. this.mixToTile);
  235. };
  236. }
  237. }