babylon.text2d.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11. };
  12. var BABYLON;
  13. (function (BABYLON) {
  14. var Text2DRenderCache = (function (_super) {
  15. __extends(Text2DRenderCache, _super);
  16. function Text2DRenderCache() {
  17. _super.apply(this, arguments);
  18. this.effectsReady = false;
  19. this.vb = null;
  20. this.ib = null;
  21. this.instancingAttributes = null;
  22. this.fontTexture = null;
  23. this.effect = null;
  24. this.effectInstanced = null;
  25. }
  26. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  27. // Do nothing if the shader is still loading/preparing
  28. if (!this.effectsReady) {
  29. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  30. return false;
  31. }
  32. this.effectsReady = true;
  33. }
  34. var canvas = instanceInfo.owner.owner;
  35. var engine = canvas.engine;
  36. this.fontTexture.update();
  37. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  38. engine.enableEffect(effect);
  39. effect.setTexture("diffuseSampler", this.fontTexture);
  40. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  41. var curAlphaMode = engine.getAlphaMode();
  42. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43. var pid = context.groupInfoPartData[0];
  44. if (context.useInstancing) {
  45. if (!this.instancingAttributes) {
  46. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  47. }
  48. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  49. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  50. canvas._addDrawCallCount(1, context.renderMode);
  51. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  52. engine.draw(true, 0, 6, count);
  53. engine.unbindInstanceAttributes();
  54. }
  55. else {
  56. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  57. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  58. this.setupUniforms(effect, 0, pid._partData, i);
  59. engine.draw(true, 0, 6);
  60. }
  61. }
  62. engine.setAlphaMode(curAlphaMode);
  63. return true;
  64. };
  65. Text2DRenderCache.prototype.dispose = function () {
  66. if (!_super.prototype.dispose.call(this)) {
  67. return false;
  68. }
  69. if (this.vb) {
  70. this._engine._releaseBuffer(this.vb);
  71. this.vb = null;
  72. }
  73. if (this.ib) {
  74. this._engine._releaseBuffer(this.ib);
  75. this.ib = null;
  76. }
  77. if (this.fontTexture) {
  78. this.fontTexture.dispose();
  79. this.fontTexture = null;
  80. }
  81. if (this.effect) {
  82. this._engine._releaseEffect(this.effect);
  83. this.effect = null;
  84. }
  85. if (this.effectInstanced) {
  86. this._engine._releaseEffect(this.effectInstanced);
  87. this.effectInstanced = null;
  88. }
  89. return true;
  90. };
  91. return Text2DRenderCache;
  92. }(BABYLON.ModelRenderCache));
  93. BABYLON.Text2DRenderCache = Text2DRenderCache;
  94. var Text2DInstanceData = (function (_super) {
  95. __extends(Text2DInstanceData, _super);
  96. function Text2DInstanceData(partId, dataElementCount) {
  97. _super.call(this, partId, dataElementCount);
  98. }
  99. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  100. get: function () {
  101. return null;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  107. get: function () {
  108. return null;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  114. get: function () {
  115. return null;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  121. get: function () {
  122. return null;
  123. },
  124. enumerable: true,
  125. configurable: true
  126. });
  127. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  128. get: function () {
  129. return null;
  130. },
  131. enumerable: true,
  132. configurable: true
  133. });
  134. __decorate([
  135. BABYLON.instanceData()
  136. ], Text2DInstanceData.prototype, "topLeftUV", null);
  137. __decorate([
  138. BABYLON.instanceData()
  139. ], Text2DInstanceData.prototype, "sizeUV", null);
  140. __decorate([
  141. BABYLON.instanceData()
  142. ], Text2DInstanceData.prototype, "textureSize", null);
  143. __decorate([
  144. BABYLON.instanceData()
  145. ], Text2DInstanceData.prototype, "color", null);
  146. __decorate([
  147. BABYLON.instanceData()
  148. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  149. return Text2DInstanceData;
  150. }(BABYLON.InstanceDataBase));
  151. BABYLON.Text2DInstanceData = Text2DInstanceData;
  152. var Text2D = (function (_super) {
  153. __extends(Text2D, _super);
  154. /**
  155. * Create a Text primitive
  156. * @param text the text to display
  157. * @param settings a combination of settings, possible ones are
  158. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  159. * - children: an array of direct children
  160. * - id a text identifier, for information purpose
  161. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  162. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  163. * - scale: the initial scale of the primitive. default is 1
  164. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  165. * - origin: define the normalized origin point location, default [0.5;0.5]
  166. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  167. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  168. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  169. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  170. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  171. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  172. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  173. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  174. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  175. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  176. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  177. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  178. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  179. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  180. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  181. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  182. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  183. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  184. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  185. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  186. */
  187. function Text2D(text, settings) {
  188. if (!settings) {
  189. settings = {};
  190. }
  191. _super.call(this, settings);
  192. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  193. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  194. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  195. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  196. this._textSize = null;
  197. this.text = text;
  198. this.size = (settings.size == null) ? null : settings.size;
  199. this.isTransparent = true;
  200. }
  201. Object.defineProperty(Text2D.prototype, "fontName", {
  202. get: function () {
  203. return this._fontName;
  204. },
  205. set: function (value) {
  206. if (this._fontName) {
  207. throw new Error("Font Name change is not supported right now.");
  208. }
  209. this._fontName = value;
  210. },
  211. enumerable: true,
  212. configurable: true
  213. });
  214. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  215. get: function () {
  216. return this._defaultFontColor;
  217. },
  218. set: function (value) {
  219. this._defaultFontColor = value;
  220. },
  221. enumerable: true,
  222. configurable: true
  223. });
  224. Object.defineProperty(Text2D.prototype, "text", {
  225. get: function () {
  226. return this._text;
  227. },
  228. set: function (value) {
  229. this._text = value;
  230. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  231. this._size = null;
  232. this._updateCharCount();
  233. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  234. var s = this.textSize;
  235. },
  236. enumerable: true,
  237. configurable: true
  238. });
  239. Object.defineProperty(Text2D.prototype, "size", {
  240. get: function () {
  241. if (this._size != null) {
  242. return this._size;
  243. }
  244. return this.textSize;
  245. },
  246. set: function (value) {
  247. this._size = value;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. Object.defineProperty(Text2D.prototype, "actualSize", {
  253. /**
  254. * Get the actual size of the Text2D primitive
  255. */
  256. get: function () {
  257. if (this._actualSize) {
  258. return this._actualSize;
  259. }
  260. return this.size;
  261. },
  262. enumerable: true,
  263. configurable: true
  264. });
  265. Object.defineProperty(Text2D.prototype, "textSize", {
  266. /**
  267. * Get the area that bounds the text associated to the primitive
  268. */
  269. get: function () {
  270. if (!this._textSize) {
  271. if (this.owner) {
  272. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  273. if (!newSize.equals(this._textSize)) {
  274. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  275. this._positioningDirty();
  276. }
  277. this._textSize = newSize;
  278. }
  279. else {
  280. return Text2D.nullSize;
  281. }
  282. }
  283. return this._textSize;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. Object.defineProperty(Text2D.prototype, "fontTexture", {
  289. get: function () {
  290. if (this._fontTexture) {
  291. return this._fontTexture;
  292. }
  293. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  294. return this._fontTexture;
  295. },
  296. enumerable: true,
  297. configurable: true
  298. });
  299. /**
  300. * Dispose the primitive, remove it from its parent
  301. */
  302. Text2D.prototype.dispose = function () {
  303. if (!_super.prototype.dispose.call(this)) {
  304. return false;
  305. }
  306. if (this._fontTexture) {
  307. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  308. this._fontTexture = null;
  309. }
  310. return true;
  311. };
  312. Text2D.prototype.updateLevelBoundingInfo = function () {
  313. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  314. };
  315. Text2D.prototype.levelIntersect = function (intersectInfo) {
  316. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  317. return true;
  318. };
  319. Text2D.prototype.createModelRenderCache = function (modelKey) {
  320. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  321. return renderCache;
  322. };
  323. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  324. var renderCache = modelRenderCache;
  325. var engine = this.owner.engine;
  326. renderCache.fontTexture = this.fontTexture;
  327. var vb = new Float32Array(4);
  328. for (var i = 0; i < 4; i++) {
  329. vb[i] = i;
  330. }
  331. renderCache.vb = engine.createVertexBuffer(vb);
  332. var ib = new Float32Array(6);
  333. ib[0] = 0;
  334. ib[1] = 2;
  335. ib[2] = 1;
  336. ib[3] = 0;
  337. ib[4] = 3;
  338. ib[5] = 2;
  339. renderCache.ib = engine.createIndexBuffer(ib);
  340. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  341. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  342. if (ei) {
  343. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  344. }
  345. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  346. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  347. return renderCache;
  348. };
  349. Text2D.prototype.createInstanceDataParts = function () {
  350. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  351. };
  352. // Looks like a hack!? Yes! Because that's what it is!
  353. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  354. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  355. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  356. if (!this._charCount) {
  357. var curText = this._text;
  358. this.text = "A";
  359. return curText;
  360. }
  361. };
  362. // if obj contains something, we restore the _text property
  363. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  364. if (obj !== undefined) {
  365. this.text = obj;
  366. }
  367. };
  368. Text2D.prototype.refreshInstanceDataPart = function (part) {
  369. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  370. return false;
  371. }
  372. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  373. var d = part;
  374. var texture = this.fontTexture;
  375. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  376. var ts = texture.getSize();
  377. var offset = BABYLON.Vector2.Zero();
  378. var lh = this.fontTexture.lineHeight;
  379. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  380. var charxpos = 0;
  381. d.dataElementCount = this._charCount;
  382. d.curElement = 0;
  383. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  384. var char = _a[_i];
  385. // Line feed
  386. if (char === "\n") {
  387. offset.x = 0;
  388. offset.y -= texture.lineHeight;
  389. }
  390. // Tabulation ?
  391. if (char === "\t") {
  392. var nextPos = charxpos + this._tabulationSize;
  393. nextPos = nextPos - (nextPos % this._tabulationSize);
  394. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  395. charxpos = nextPos;
  396. continue;
  397. }
  398. if (char < " ") {
  399. continue;
  400. }
  401. this.updateInstanceDataPart(d, offset);
  402. var ci = texture.getChar(char);
  403. offset.x += ci.charWidth;
  404. d.topLeftUV = ci.topLeftUV;
  405. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  406. d.sizeUV = suv;
  407. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  408. d.color = this.defaultFontColor;
  409. d.superSampleFactor = superSampleFactor;
  410. ++d.curElement;
  411. }
  412. }
  413. return true;
  414. };
  415. Text2D.prototype._updateCharCount = function () {
  416. var count = 0;
  417. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  418. var char = _a[_i];
  419. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  420. continue;
  421. }
  422. ++count;
  423. }
  424. this._charCount = count;
  425. };
  426. Text2D.TEXT2D_MAINPARTID = 1;
  427. __decorate([
  428. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  429. ], Text2D.prototype, "fontName", null);
  430. __decorate([
  431. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  432. ], Text2D.prototype, "defaultFontColor", null);
  433. __decorate([
  434. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  435. ], Text2D.prototype, "text", null);
  436. __decorate([
  437. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  438. ], Text2D.prototype, "size", null);
  439. Text2D = __decorate([
  440. BABYLON.className("Text2D")
  441. ], Text2D);
  442. return Text2D;
  443. }(BABYLON.RenderablePrim2D));
  444. BABYLON.Text2D = Text2D;
  445. })(BABYLON || (BABYLON = {}));