LabelCollection.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. import BoundingRectangle from "../Core/BoundingRectangle.js";
  2. import Cartesian2 from "../Core/Cartesian2.js";
  3. import Color from "../Core/Color.js";
  4. import defaultValue from "../Core/defaultValue.js";
  5. import defined from "../Core/defined.js";
  6. import destroyObject from "../Core/destroyObject.js";
  7. import DeveloperError from "../Core/DeveloperError.js";
  8. import Matrix4 from "../Core/Matrix4.js";
  9. import writeTextToCanvas from "../Core/writeTextToCanvas.js";
  10. import bitmapSDF from "../ThirdParty/bitmap-sdf.js";
  11. import BillboardCollection from "./BillboardCollection.js";
  12. import BlendOption from "./BlendOption.js";
  13. import HeightReference from "./HeightReference.js";
  14. import HorizontalOrigin from "./HorizontalOrigin.js";
  15. import Label from "./Label.js";
  16. import LabelStyle from "./LabelStyle.js";
  17. import SDFSettings from "./SDFSettings.js";
  18. import TextureAtlas from "./TextureAtlas.js";
  19. import VerticalOrigin from "./VerticalOrigin.js";
  20. import GraphemeSplitter from "../ThirdParty/grapheme-splitter.js";
  21. // A glyph represents a single character in a particular label. It may or may
  22. // not have a billboard, depending on whether the texture info has an index into
  23. // the the label collection's texture atlas. Invisible characters have no texture, and
  24. // no billboard. However, it always has a valid dimensions object.
  25. function Glyph() {
  26. this.textureInfo = undefined;
  27. this.dimensions = undefined;
  28. this.billboard = undefined;
  29. }
  30. // GlyphTextureInfo represents a single character, drawn in a particular style,
  31. // shared and reference counted across all labels. It may or may not have an
  32. // index into the label collection's texture atlas, depending on whether the character
  33. // has both width and height, but it always has a valid dimensions object.
  34. function GlyphTextureInfo(labelCollection, index, dimensions) {
  35. this.labelCollection = labelCollection;
  36. this.index = index;
  37. this.dimensions = dimensions;
  38. }
  39. // Traditionally, leading is %20 of the font size.
  40. const defaultLineSpacingPercent = 1.2;
  41. const whitePixelCanvasId = "ID_WHITE_PIXEL";
  42. const whitePixelSize = new Cartesian2(4, 4);
  43. const whitePixelBoundingRegion = new BoundingRectangle(1, 1, 1, 1);
  44. function addWhitePixelCanvas(textureAtlas, labelCollection) {
  45. const canvas = document.createElement("canvas");
  46. canvas.width = whitePixelSize.x;
  47. canvas.height = whitePixelSize.y;
  48. const context2D = canvas.getContext("2d");
  49. context2D.fillStyle = "#fff";
  50. context2D.fillRect(0, 0, canvas.width, canvas.height);
  51. const index = textureAtlas.addImageSync(whitePixelCanvasId, canvas);
  52. labelCollection._whitePixelIndex = index;
  53. }
  54. // reusable object for calling writeTextToCanvas
  55. const writeTextToCanvasParameters = {};
  56. function createGlyphCanvas(
  57. character,
  58. font,
  59. fillColor,
  60. outlineColor,
  61. outlineWidth,
  62. style,
  63. verticalOrigin
  64. ) {
  65. writeTextToCanvasParameters.font = font;
  66. writeTextToCanvasParameters.fillColor = fillColor;
  67. writeTextToCanvasParameters.strokeColor = outlineColor;
  68. writeTextToCanvasParameters.strokeWidth = outlineWidth;
  69. // Setting the padding to something bigger is necessary to get enough space for the outlining.
  70. writeTextToCanvasParameters.padding = SDFSettings.PADDING;
  71. if (verticalOrigin === VerticalOrigin.CENTER) {
  72. writeTextToCanvasParameters.textBaseline = "middle";
  73. } else if (verticalOrigin === VerticalOrigin.TOP) {
  74. writeTextToCanvasParameters.textBaseline = "top";
  75. } else {
  76. // VerticalOrigin.BOTTOM and VerticalOrigin.BASELINE
  77. writeTextToCanvasParameters.textBaseline = "bottom";
  78. }
  79. writeTextToCanvasParameters.fill =
  80. style === LabelStyle.FILL || style === LabelStyle.FILL_AND_OUTLINE;
  81. writeTextToCanvasParameters.stroke =
  82. style === LabelStyle.OUTLINE || style === LabelStyle.FILL_AND_OUTLINE;
  83. writeTextToCanvasParameters.backgroundColor = Color.BLACK;
  84. return writeTextToCanvas(character, writeTextToCanvasParameters);
  85. }
  86. function unbindGlyph(labelCollection, glyph) {
  87. glyph.textureInfo = undefined;
  88. glyph.dimensions = undefined;
  89. const billboard = glyph.billboard;
  90. if (defined(billboard)) {
  91. billboard.show = false;
  92. billboard.image = undefined;
  93. if (defined(billboard._removeCallbackFunc)) {
  94. billboard._removeCallbackFunc();
  95. billboard._removeCallbackFunc = undefined;
  96. }
  97. labelCollection._spareBillboards.push(billboard);
  98. glyph.billboard = undefined;
  99. }
  100. }
  101. function addGlyphToTextureAtlas(textureAtlas, id, canvas, glyphTextureInfo) {
  102. glyphTextureInfo.index = textureAtlas.addImageSync(id, canvas);
  103. }
  104. const splitter = new GraphemeSplitter();
  105. function rebindAllGlyphs(labelCollection, label) {
  106. const text = label._renderedText;
  107. const graphemes = splitter.splitGraphemes(text);
  108. const textLength = graphemes.length;
  109. const glyphs = label._glyphs;
  110. const glyphsLength = glyphs.length;
  111. let glyph;
  112. let glyphIndex;
  113. let textIndex;
  114. // Compute a font size scale relative to the sdf font generated size.
  115. label._relativeSize = label._fontSize / SDFSettings.FONT_SIZE;
  116. // if we have more glyphs than needed, unbind the extras.
  117. if (textLength < glyphsLength) {
  118. for (glyphIndex = textLength; glyphIndex < glyphsLength; ++glyphIndex) {
  119. unbindGlyph(labelCollection, glyphs[glyphIndex]);
  120. }
  121. }
  122. // presize glyphs to match the new text length
  123. glyphs.length = textLength;
  124. const showBackground =
  125. label._showBackground && text.split("\n").join("").length > 0;
  126. let backgroundBillboard = label._backgroundBillboard;
  127. const backgroundBillboardCollection =
  128. labelCollection._backgroundBillboardCollection;
  129. if (!showBackground) {
  130. if (defined(backgroundBillboard)) {
  131. backgroundBillboardCollection.remove(backgroundBillboard);
  132. label._backgroundBillboard = backgroundBillboard = undefined;
  133. }
  134. } else {
  135. if (!defined(backgroundBillboard)) {
  136. backgroundBillboard = backgroundBillboardCollection.add({
  137. collection: labelCollection,
  138. image: whitePixelCanvasId,
  139. imageSubRegion: whitePixelBoundingRegion,
  140. });
  141. label._backgroundBillboard = backgroundBillboard;
  142. }
  143. backgroundBillboard.color = label._backgroundColor;
  144. backgroundBillboard.show = label._show;
  145. backgroundBillboard.position = label._position;
  146. backgroundBillboard.eyeOffset = label._eyeOffset;
  147. backgroundBillboard.pixelOffset = label._pixelOffset;
  148. backgroundBillboard.horizontalOrigin = HorizontalOrigin.LEFT;
  149. backgroundBillboard.verticalOrigin = label._verticalOrigin;
  150. backgroundBillboard.heightReference = label._heightReference;
  151. backgroundBillboard.scale = label.totalScale;
  152. backgroundBillboard.pickPrimitive = label;
  153. backgroundBillboard.id = label._id;
  154. backgroundBillboard.translucencyByDistance = label._translucencyByDistance;
  155. backgroundBillboard.pixelOffsetScaleByDistance =
  156. label._pixelOffsetScaleByDistance;
  157. backgroundBillboard.scaleByDistance = label._scaleByDistance;
  158. backgroundBillboard.distanceDisplayCondition =
  159. label._distanceDisplayCondition;
  160. backgroundBillboard.disableDepthTestDistance =
  161. label._disableDepthTestDistance;
  162. }
  163. const glyphTextureCache = labelCollection._glyphTextureCache;
  164. // walk the text looking for new characters (creating new glyphs for each)
  165. // or changed characters (rebinding existing glyphs)
  166. for (textIndex = 0; textIndex < textLength; ++textIndex) {
  167. const character = graphemes[textIndex];
  168. const verticalOrigin = label._verticalOrigin;
  169. const id = JSON.stringify([
  170. character,
  171. label._fontFamily,
  172. label._fontStyle,
  173. label._fontWeight,
  174. +verticalOrigin,
  175. ]);
  176. let glyphTextureInfo = glyphTextureCache[id];
  177. if (!defined(glyphTextureInfo)) {
  178. const glyphFont = `${label._fontStyle} ${label._fontWeight} ${SDFSettings.FONT_SIZE}px ${label._fontFamily}`;
  179. const canvas = createGlyphCanvas(
  180. character,
  181. glyphFont,
  182. Color.WHITE,
  183. Color.WHITE,
  184. 0.0,
  185. LabelStyle.FILL,
  186. verticalOrigin
  187. );
  188. glyphTextureInfo = new GlyphTextureInfo(
  189. labelCollection,
  190. -1,
  191. canvas.dimensions
  192. );
  193. glyphTextureCache[id] = glyphTextureInfo;
  194. if (canvas.width > 0 && canvas.height > 0) {
  195. const sdfValues = bitmapSDF(canvas, {
  196. cutoff: SDFSettings.CUTOFF,
  197. radius: SDFSettings.RADIUS,
  198. });
  199. const ctx = canvas.getContext("2d");
  200. const canvasWidth = canvas.width;
  201. const canvasHeight = canvas.height;
  202. const imgData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
  203. for (let i = 0; i < canvasWidth; i++) {
  204. for (let j = 0; j < canvasHeight; j++) {
  205. const baseIndex = j * canvasWidth + i;
  206. const alpha = sdfValues[baseIndex] * 255;
  207. const imageIndex = baseIndex * 4;
  208. imgData.data[imageIndex + 0] = alpha;
  209. imgData.data[imageIndex + 1] = alpha;
  210. imgData.data[imageIndex + 2] = alpha;
  211. imgData.data[imageIndex + 3] = alpha;
  212. }
  213. }
  214. ctx.putImageData(imgData, 0, 0);
  215. if (character !== " ") {
  216. addGlyphToTextureAtlas(
  217. labelCollection._textureAtlas,
  218. id,
  219. canvas,
  220. glyphTextureInfo
  221. );
  222. }
  223. }
  224. }
  225. glyph = glyphs[textIndex];
  226. if (defined(glyph)) {
  227. // clean up leftover information from the previous glyph
  228. if (glyphTextureInfo.index === -1) {
  229. // no texture, and therefore no billboard, for this glyph.
  230. // so, completely unbind glyph.
  231. unbindGlyph(labelCollection, glyph);
  232. } else if (defined(glyph.textureInfo)) {
  233. // we have a texture and billboard. If we had one before, release
  234. // our reference to that texture info, but reuse the billboard.
  235. glyph.textureInfo = undefined;
  236. }
  237. } else {
  238. // create a glyph object
  239. glyph = new Glyph();
  240. glyphs[textIndex] = glyph;
  241. }
  242. glyph.textureInfo = glyphTextureInfo;
  243. glyph.dimensions = glyphTextureInfo.dimensions;
  244. // if we have a texture, configure the existing billboard, or obtain one
  245. if (glyphTextureInfo.index !== -1) {
  246. let billboard = glyph.billboard;
  247. const spareBillboards = labelCollection._spareBillboards;
  248. if (!defined(billboard)) {
  249. if (spareBillboards.length > 0) {
  250. billboard = spareBillboards.pop();
  251. } else {
  252. billboard = labelCollection._billboardCollection.add({
  253. collection: labelCollection,
  254. });
  255. billboard._labelDimensions = new Cartesian2();
  256. billboard._labelTranslate = new Cartesian2();
  257. }
  258. glyph.billboard = billboard;
  259. }
  260. billboard.show = label._show;
  261. billboard.position = label._position;
  262. billboard.eyeOffset = label._eyeOffset;
  263. billboard.pixelOffset = label._pixelOffset;
  264. billboard.horizontalOrigin = HorizontalOrigin.LEFT;
  265. billboard.verticalOrigin = label._verticalOrigin;
  266. billboard.heightReference = label._heightReference;
  267. billboard.scale = label.totalScale;
  268. billboard.pickPrimitive = label;
  269. billboard.id = label._id;
  270. billboard.image = id;
  271. billboard.translucencyByDistance = label._translucencyByDistance;
  272. billboard.pixelOffsetScaleByDistance = label._pixelOffsetScaleByDistance;
  273. billboard.scaleByDistance = label._scaleByDistance;
  274. billboard.distanceDisplayCondition = label._distanceDisplayCondition;
  275. billboard.disableDepthTestDistance = label._disableDepthTestDistance;
  276. billboard._batchIndex = label._batchIndex;
  277. billboard.outlineColor = label.outlineColor;
  278. if (label.style === LabelStyle.FILL_AND_OUTLINE) {
  279. billboard.color = label._fillColor;
  280. billboard.outlineWidth = label.outlineWidth;
  281. } else if (label.style === LabelStyle.FILL) {
  282. billboard.color = label._fillColor;
  283. billboard.outlineWidth = 0.0;
  284. } else if (label.style === LabelStyle.OUTLINE) {
  285. billboard.color = Color.TRANSPARENT;
  286. billboard.outlineWidth = label.outlineWidth;
  287. }
  288. }
  289. }
  290. // changing glyphs will cause the position of the
  291. // glyphs to change, since different characters have different widths
  292. label._repositionAllGlyphs = true;
  293. }
  294. function calculateWidthOffset(lineWidth, horizontalOrigin, backgroundPadding) {
  295. if (horizontalOrigin === HorizontalOrigin.CENTER) {
  296. return -lineWidth / 2;
  297. } else if (horizontalOrigin === HorizontalOrigin.RIGHT) {
  298. return -(lineWidth + backgroundPadding.x);
  299. }
  300. return backgroundPadding.x;
  301. }
  302. // reusable Cartesian2 instances
  303. const glyphPixelOffset = new Cartesian2();
  304. const scratchBackgroundPadding = new Cartesian2();
  305. function repositionAllGlyphs(label) {
  306. const glyphs = label._glyphs;
  307. const text = label._renderedText;
  308. let glyph;
  309. let dimensions;
  310. let lastLineWidth = 0;
  311. let maxLineWidth = 0;
  312. const lineWidths = [];
  313. let maxGlyphDescent = Number.NEGATIVE_INFINITY;
  314. let maxGlyphY = 0;
  315. let numberOfLines = 1;
  316. let glyphIndex;
  317. const glyphLength = glyphs.length;
  318. const backgroundBillboard = label._backgroundBillboard;
  319. const backgroundPadding = Cartesian2.clone(
  320. defined(backgroundBillboard) ? label._backgroundPadding : Cartesian2.ZERO,
  321. scratchBackgroundPadding
  322. );
  323. // We need to scale the background padding, which is specified in pixels by the inverse of the relative size so it is scaled properly.
  324. backgroundPadding.x /= label._relativeSize;
  325. backgroundPadding.y /= label._relativeSize;
  326. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  327. if (text.charAt(glyphIndex) === "\n") {
  328. lineWidths.push(lastLineWidth);
  329. ++numberOfLines;
  330. lastLineWidth = 0;
  331. } else {
  332. glyph = glyphs[glyphIndex];
  333. dimensions = glyph.dimensions;
  334. maxGlyphY = Math.max(maxGlyphY, dimensions.height - dimensions.descent);
  335. maxGlyphDescent = Math.max(maxGlyphDescent, dimensions.descent);
  336. //Computing the line width must also account for the kerning that occurs between letters.
  337. lastLineWidth += dimensions.width - dimensions.minx;
  338. if (glyphIndex < glyphLength - 1) {
  339. lastLineWidth += glyphs[glyphIndex + 1].dimensions.minx;
  340. }
  341. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  342. }
  343. }
  344. lineWidths.push(lastLineWidth);
  345. const maxLineHeight = maxGlyphY + maxGlyphDescent;
  346. const scale = label.totalScale;
  347. const horizontalOrigin = label._horizontalOrigin;
  348. const verticalOrigin = label._verticalOrigin;
  349. let lineIndex = 0;
  350. let lineWidth = lineWidths[lineIndex];
  351. let widthOffset = calculateWidthOffset(
  352. lineWidth,
  353. horizontalOrigin,
  354. backgroundPadding
  355. );
  356. const lineSpacing =
  357. (defined(label._lineHeight)
  358. ? label._lineHeight
  359. : defaultLineSpacingPercent * label._fontSize) / label._relativeSize;
  360. const otherLinesHeight = lineSpacing * (numberOfLines - 1);
  361. let totalLineWidth = maxLineWidth;
  362. let totalLineHeight = maxLineHeight + otherLinesHeight;
  363. if (defined(backgroundBillboard)) {
  364. totalLineWidth += backgroundPadding.x * 2;
  365. totalLineHeight += backgroundPadding.y * 2;
  366. backgroundBillboard._labelHorizontalOrigin = horizontalOrigin;
  367. }
  368. glyphPixelOffset.x = widthOffset * scale;
  369. glyphPixelOffset.y = 0;
  370. let firstCharOfLine = true;
  371. let lineOffsetY = 0;
  372. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  373. if (text.charAt(glyphIndex) === "\n") {
  374. ++lineIndex;
  375. lineOffsetY += lineSpacing;
  376. lineWidth = lineWidths[lineIndex];
  377. widthOffset = calculateWidthOffset(
  378. lineWidth,
  379. horizontalOrigin,
  380. backgroundPadding
  381. );
  382. glyphPixelOffset.x = widthOffset * scale;
  383. firstCharOfLine = true;
  384. } else {
  385. glyph = glyphs[glyphIndex];
  386. dimensions = glyph.dimensions;
  387. if (verticalOrigin === VerticalOrigin.TOP) {
  388. glyphPixelOffset.y =
  389. dimensions.height - maxGlyphY - backgroundPadding.y;
  390. glyphPixelOffset.y += SDFSettings.PADDING;
  391. } else if (verticalOrigin === VerticalOrigin.CENTER) {
  392. glyphPixelOffset.y =
  393. (otherLinesHeight + dimensions.height - maxGlyphY) / 2;
  394. } else if (verticalOrigin === VerticalOrigin.BASELINE) {
  395. glyphPixelOffset.y = otherLinesHeight;
  396. glyphPixelOffset.y -= SDFSettings.PADDING;
  397. } else {
  398. // VerticalOrigin.BOTTOM
  399. glyphPixelOffset.y =
  400. otherLinesHeight + maxGlyphDescent + backgroundPadding.y;
  401. glyphPixelOffset.y -= SDFSettings.PADDING;
  402. }
  403. glyphPixelOffset.y =
  404. (glyphPixelOffset.y - dimensions.descent - lineOffsetY) * scale;
  405. // Handle any offsets for the first character of the line since the bounds might not be right on the bottom left pixel.
  406. if (firstCharOfLine) {
  407. glyphPixelOffset.x -= SDFSettings.PADDING * scale;
  408. firstCharOfLine = false;
  409. }
  410. if (defined(glyph.billboard)) {
  411. glyph.billboard._setTranslate(glyphPixelOffset);
  412. glyph.billboard._labelDimensions.x = totalLineWidth;
  413. glyph.billboard._labelDimensions.y = totalLineHeight;
  414. glyph.billboard._labelHorizontalOrigin = horizontalOrigin;
  415. }
  416. //Compute the next x offset taking into account the kerning performed
  417. //on both the current letter as well as the next letter to be drawn
  418. //as well as any applied scale.
  419. if (glyphIndex < glyphLength - 1) {
  420. const nextGlyph = glyphs[glyphIndex + 1];
  421. glyphPixelOffset.x +=
  422. (dimensions.width - dimensions.minx + nextGlyph.dimensions.minx) *
  423. scale;
  424. }
  425. }
  426. }
  427. if (defined(backgroundBillboard) && text.split("\n").join("").length > 0) {
  428. if (horizontalOrigin === HorizontalOrigin.CENTER) {
  429. widthOffset = -maxLineWidth / 2 - backgroundPadding.x;
  430. } else if (horizontalOrigin === HorizontalOrigin.RIGHT) {
  431. widthOffset = -(maxLineWidth + backgroundPadding.x * 2);
  432. } else {
  433. widthOffset = 0;
  434. }
  435. glyphPixelOffset.x = widthOffset * scale;
  436. if (verticalOrigin === VerticalOrigin.TOP) {
  437. glyphPixelOffset.y = maxLineHeight - maxGlyphY - maxGlyphDescent;
  438. } else if (verticalOrigin === VerticalOrigin.CENTER) {
  439. glyphPixelOffset.y = (maxLineHeight - maxGlyphY) / 2 - maxGlyphDescent;
  440. } else if (verticalOrigin === VerticalOrigin.BASELINE) {
  441. glyphPixelOffset.y = -backgroundPadding.y - maxGlyphDescent;
  442. } else {
  443. // VerticalOrigin.BOTTOM
  444. glyphPixelOffset.y = 0;
  445. }
  446. glyphPixelOffset.y = glyphPixelOffset.y * scale;
  447. backgroundBillboard.width = totalLineWidth;
  448. backgroundBillboard.height = totalLineHeight;
  449. backgroundBillboard._setTranslate(glyphPixelOffset);
  450. backgroundBillboard._labelTranslate = Cartesian2.clone(
  451. glyphPixelOffset,
  452. backgroundBillboard._labelTranslate
  453. );
  454. }
  455. if (label.heightReference === HeightReference.CLAMP_TO_GROUND) {
  456. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  457. glyph = glyphs[glyphIndex];
  458. const billboard = glyph.billboard;
  459. if (defined(billboard)) {
  460. billboard._labelTranslate = Cartesian2.clone(
  461. glyphPixelOffset,
  462. billboard._labelTranslate
  463. );
  464. }
  465. }
  466. }
  467. }
  468. function destroyLabel(labelCollection, label) {
  469. const glyphs = label._glyphs;
  470. for (let i = 0, len = glyphs.length; i < len; ++i) {
  471. unbindGlyph(labelCollection, glyphs[i]);
  472. }
  473. if (defined(label._backgroundBillboard)) {
  474. labelCollection._backgroundBillboardCollection.remove(
  475. label._backgroundBillboard
  476. );
  477. label._backgroundBillboard = undefined;
  478. }
  479. label._labelCollection = undefined;
  480. if (defined(label._removeCallbackFunc)) {
  481. label._removeCallbackFunc();
  482. }
  483. destroyObject(label);
  484. }
  485. /**
  486. * A renderable collection of labels. Labels are viewport-aligned text positioned in the 3D scene.
  487. * Each label can have a different font, color, scale, etc.
  488. * <br /><br />
  489. * <div align='center'>
  490. * <img src='Images/Label.png' width='400' height='300' /><br />
  491. * Example labels
  492. * </div>
  493. * <br /><br />
  494. * Labels are added and removed from the collection using {@link LabelCollection#add}
  495. * and {@link LabelCollection#remove}.
  496. *
  497. * @alias LabelCollection
  498. * @constructor
  499. *
  500. * @param {Object} [options] Object with the following properties:
  501. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each label from model to world coordinates.
  502. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
  503. * @param {Scene} [options.scene] Must be passed in for labels that use the height reference property or will be depth tested against the globe.
  504. * @param {BlendOption} [options.blendOption=BlendOption.OPAQUE_AND_TRANSLUCENT] The label blending option. The default
  505. * is used for rendering both opaque and translucent labels. However, if either all of the labels are completely opaque or all are completely translucent,
  506. * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve performance by up to 2x.
  507. * @param {Boolean} [options.show=true] Determines if the labels in the collection will be shown.
  508. *
  509. * @performance For best performance, prefer a few collections, each with many labels, to
  510. * many collections with only a few labels each. Avoid having collections where some
  511. * labels change every frame and others do not; instead, create one or more collections
  512. * for static labels, and one or more collections for dynamic labels.
  513. *
  514. * @see LabelCollection#add
  515. * @see LabelCollection#remove
  516. * @see Label
  517. * @see BillboardCollection
  518. *
  519. * @demo {@link https://sandcastle.cesium.com/index.html?src=Labels.html|Cesium Sandcastle Labels Demo}
  520. *
  521. * @example
  522. * // Create a label collection with two labels
  523. * const labels = scene.primitives.add(new Cesium.LabelCollection());
  524. * labels.add({
  525. * position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
  526. * text : 'A label'
  527. * });
  528. * labels.add({
  529. * position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
  530. * text : 'Another label'
  531. * });
  532. */
  533. function LabelCollection(options) {
  534. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  535. this._scene = options.scene;
  536. this._batchTable = options.batchTable;
  537. this._textureAtlas = undefined;
  538. this._backgroundTextureAtlas = undefined;
  539. this._whitePixelIndex = undefined;
  540. this._backgroundBillboardCollection = new BillboardCollection({
  541. scene: this._scene,
  542. });
  543. this._backgroundBillboardCollection.destroyTextureAtlas = false;
  544. this._billboardCollection = new BillboardCollection({
  545. scene: this._scene,
  546. batchTable: this._batchTable,
  547. });
  548. this._billboardCollection.destroyTextureAtlas = false;
  549. this._billboardCollection._sdf = true;
  550. this._spareBillboards = [];
  551. this._glyphTextureCache = {};
  552. this._labels = [];
  553. this._labelsToUpdate = [];
  554. this._totalGlyphCount = 0;
  555. this._highlightColor = Color.clone(Color.WHITE); // Only used by Vector3DTilePoints
  556. /**
  557. * Determines if labels in this collection will be shown.
  558. *
  559. * @type {Boolean}
  560. * @default true
  561. */
  562. this.show = defaultValue(options.show, true);
  563. /**
  564. * The 4x4 transformation matrix that transforms each label in this collection from model to world coordinates.
  565. * When this is the identity matrix, the labels are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  566. * Local reference frames can be used by providing a different transformation matrix, like that returned
  567. * by {@link Transforms.eastNorthUpToFixedFrame}.
  568. *
  569. * @type Matrix4
  570. * @default {@link Matrix4.IDENTITY}
  571. *
  572. * @example
  573. * const center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  574. * labels.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  575. * labels.add({
  576. * position : new Cesium.Cartesian3(0.0, 0.0, 0.0),
  577. * text : 'Center'
  578. * });
  579. * labels.add({
  580. * position : new Cesium.Cartesian3(1000000.0, 0.0, 0.0),
  581. * text : 'East'
  582. * });
  583. * labels.add({
  584. * position : new Cesium.Cartesian3(0.0, 1000000.0, 0.0),
  585. * text : 'North'
  586. * });
  587. * labels.add({
  588. * position : new Cesium.Cartesian3(0.0, 0.0, 1000000.0),
  589. * text : 'Up'
  590. * });
  591. */
  592. this.modelMatrix = Matrix4.clone(
  593. defaultValue(options.modelMatrix, Matrix4.IDENTITY)
  594. );
  595. /**
  596. * This property is for debugging only; it is not for production use nor is it optimized.
  597. * <p>
  598. * Draws the bounding sphere for each draw command in the primitive.
  599. * </p>
  600. *
  601. * @type {Boolean}
  602. *
  603. * @default false
  604. */
  605. this.debugShowBoundingVolume = defaultValue(
  606. options.debugShowBoundingVolume,
  607. false
  608. );
  609. /**
  610. * The label blending option. The default is used for rendering both opaque and translucent labels.
  611. * However, if either all of the labels are completely opaque or all are completely translucent,
  612. * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve
  613. * performance by up to 2x.
  614. * @type {BlendOption}
  615. * @default BlendOption.OPAQUE_AND_TRANSLUCENT
  616. */
  617. this.blendOption = defaultValue(
  618. options.blendOption,
  619. BlendOption.OPAQUE_AND_TRANSLUCENT
  620. );
  621. }
  622. Object.defineProperties(LabelCollection.prototype, {
  623. /**
  624. * Returns the number of labels in this collection. This is commonly used with
  625. * {@link LabelCollection#get} to iterate over all the labels
  626. * in the collection.
  627. * @memberof LabelCollection.prototype
  628. * @type {Number}
  629. */
  630. length: {
  631. get: function () {
  632. return this._labels.length;
  633. },
  634. },
  635. });
  636. /**
  637. * Creates and adds a label with the specified initial properties to the collection.
  638. * The added label is returned so it can be modified or removed from the collection later.
  639. *
  640. * @param {Object} [options] A template describing the label's properties as shown in Example 1.
  641. * @returns {Label} The label that was added to the collection.
  642. *
  643. * @performance Calling <code>add</code> is expected constant time. However, the collection's vertex buffer
  644. * is rewritten; this operations is <code>O(n)</code> and also incurs
  645. * CPU to GPU overhead. For best performance, add as many billboards as possible before
  646. * calling <code>update</code>.
  647. *
  648. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  649. *
  650. *
  651. * @example
  652. * // Example 1: Add a label, specifying all the default values.
  653. * const l = labels.add({
  654. * show : true,
  655. * position : Cesium.Cartesian3.ZERO,
  656. * text : '',
  657. * font : '30px sans-serif',
  658. * fillColor : Cesium.Color.WHITE,
  659. * outlineColor : Cesium.Color.BLACK,
  660. * outlineWidth : 1.0,
  661. * showBackground : false,
  662. * backgroundColor : new Cesium.Color(0.165, 0.165, 0.165, 0.8),
  663. * backgroundPadding : new Cesium.Cartesian2(7, 5),
  664. * style : Cesium.LabelStyle.FILL,
  665. * pixelOffset : Cesium.Cartesian2.ZERO,
  666. * eyeOffset : Cesium.Cartesian3.ZERO,
  667. * horizontalOrigin : Cesium.HorizontalOrigin.LEFT,
  668. * verticalOrigin : Cesium.VerticalOrigin.BASELINE,
  669. * scale : 1.0,
  670. * translucencyByDistance : undefined,
  671. * pixelOffsetScaleByDistance : undefined,
  672. * heightReference : HeightReference.NONE,
  673. * distanceDisplayCondition : undefined
  674. * });
  675. *
  676. * @example
  677. * // Example 2: Specify only the label's cartographic position,
  678. * // text, and font.
  679. * const l = labels.add({
  680. * position : Cesium.Cartesian3.fromRadians(longitude, latitude, height),
  681. * text : 'Hello World',
  682. * font : '24px Helvetica',
  683. * });
  684. *
  685. * @see LabelCollection#remove
  686. * @see LabelCollection#removeAll
  687. */
  688. LabelCollection.prototype.add = function (options) {
  689. const label = new Label(options, this);
  690. this._labels.push(label);
  691. this._labelsToUpdate.push(label);
  692. return label;
  693. };
  694. /**
  695. * Removes a label from the collection. Once removed, a label is no longer usable.
  696. *
  697. * @param {Label} label The label to remove.
  698. * @returns {Boolean} <code>true</code> if the label was removed; <code>false</code> if the label was not found in the collection.
  699. *
  700. * @performance Calling <code>remove</code> is expected constant time. However, the collection's vertex buffer
  701. * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead. For
  702. * best performance, remove as many labels as possible before calling <code>update</code>.
  703. * If you intend to temporarily hide a label, it is usually more efficient to call
  704. * {@link Label#show} instead of removing and re-adding the label.
  705. *
  706. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  707. *
  708. *
  709. * @example
  710. * const l = labels.add(...);
  711. * labels.remove(l); // Returns true
  712. *
  713. * @see LabelCollection#add
  714. * @see LabelCollection#removeAll
  715. * @see Label#show
  716. */
  717. LabelCollection.prototype.remove = function (label) {
  718. if (defined(label) && label._labelCollection === this) {
  719. const index = this._labels.indexOf(label);
  720. if (index !== -1) {
  721. this._labels.splice(index, 1);
  722. destroyLabel(this, label);
  723. return true;
  724. }
  725. }
  726. return false;
  727. };
  728. /**
  729. * Removes all labels from the collection.
  730. *
  731. * @performance <code>O(n)</code>. It is more efficient to remove all the labels
  732. * from a collection and then add new ones than to create a new collection entirely.
  733. *
  734. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  735. *
  736. *
  737. * @example
  738. * labels.add(...);
  739. * labels.add(...);
  740. * labels.removeAll();
  741. *
  742. * @see LabelCollection#add
  743. * @see LabelCollection#remove
  744. */
  745. LabelCollection.prototype.removeAll = function () {
  746. const labels = this._labels;
  747. for (let i = 0, len = labels.length; i < len; ++i) {
  748. destroyLabel(this, labels[i]);
  749. }
  750. labels.length = 0;
  751. };
  752. /**
  753. * Check whether this collection contains a given label.
  754. *
  755. * @param {Label} label The label to check for.
  756. * @returns {Boolean} true if this collection contains the label, false otherwise.
  757. *
  758. * @see LabelCollection#get
  759. *
  760. */
  761. LabelCollection.prototype.contains = function (label) {
  762. return defined(label) && label._labelCollection === this;
  763. };
  764. /**
  765. * Returns the label in the collection at the specified index. Indices are zero-based
  766. * and increase as labels are added. Removing a label shifts all labels after
  767. * it to the left, changing their indices. This function is commonly used with
  768. * {@link LabelCollection#length} to iterate over all the labels
  769. * in the collection.
  770. *
  771. * @param {Number} index The zero-based index of the billboard.
  772. *
  773. * @returns {Label} The label at the specified index.
  774. *
  775. * @performance Expected constant time. If labels were removed from the collection and
  776. * {@link Scene#render} was not called, an implicit <code>O(n)</code>
  777. * operation is performed.
  778. *
  779. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  780. *
  781. *
  782. * @example
  783. * // Toggle the show property of every label in the collection
  784. * const len = labels.length;
  785. * for (let i = 0; i < len; ++i) {
  786. * const l = billboards.get(i);
  787. * l.show = !l.show;
  788. * }
  789. *
  790. * @see LabelCollection#length
  791. */
  792. LabelCollection.prototype.get = function (index) {
  793. //>>includeStart('debug', pragmas.debug);
  794. if (!defined(index)) {
  795. throw new DeveloperError("index is required.");
  796. }
  797. //>>includeEnd('debug');
  798. return this._labels[index];
  799. };
  800. /**
  801. * @private
  802. *
  803. */
  804. LabelCollection.prototype.update = function (frameState) {
  805. if (!this.show) {
  806. return;
  807. }
  808. const billboardCollection = this._billboardCollection;
  809. const backgroundBillboardCollection = this._backgroundBillboardCollection;
  810. billboardCollection.modelMatrix = this.modelMatrix;
  811. billboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;
  812. backgroundBillboardCollection.modelMatrix = this.modelMatrix;
  813. backgroundBillboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;
  814. const context = frameState.context;
  815. if (!defined(this._textureAtlas)) {
  816. this._textureAtlas = new TextureAtlas({
  817. context: context,
  818. });
  819. billboardCollection.textureAtlas = this._textureAtlas;
  820. }
  821. if (!defined(this._backgroundTextureAtlas)) {
  822. this._backgroundTextureAtlas = new TextureAtlas({
  823. context: context,
  824. initialSize: whitePixelSize,
  825. });
  826. backgroundBillboardCollection.textureAtlas = this._backgroundTextureAtlas;
  827. addWhitePixelCanvas(this._backgroundTextureAtlas, this);
  828. }
  829. const len = this._labelsToUpdate.length;
  830. for (let i = 0; i < len; ++i) {
  831. const label = this._labelsToUpdate[i];
  832. if (label.isDestroyed()) {
  833. continue;
  834. }
  835. const preUpdateGlyphCount = label._glyphs.length;
  836. if (label._rebindAllGlyphs) {
  837. rebindAllGlyphs(this, label);
  838. label._rebindAllGlyphs = false;
  839. }
  840. if (label._repositionAllGlyphs) {
  841. repositionAllGlyphs(label);
  842. label._repositionAllGlyphs = false;
  843. }
  844. const glyphCountDifference = label._glyphs.length - preUpdateGlyphCount;
  845. this._totalGlyphCount += glyphCountDifference;
  846. }
  847. const blendOption =
  848. backgroundBillboardCollection.length > 0
  849. ? BlendOption.TRANSLUCENT
  850. : this.blendOption;
  851. billboardCollection.blendOption = blendOption;
  852. backgroundBillboardCollection.blendOption = blendOption;
  853. billboardCollection._highlightColor = this._highlightColor;
  854. backgroundBillboardCollection._highlightColor = this._highlightColor;
  855. this._labelsToUpdate.length = 0;
  856. backgroundBillboardCollection.update(frameState);
  857. billboardCollection.update(frameState);
  858. };
  859. /**
  860. * Returns true if this object was destroyed; otherwise, false.
  861. * <br /><br />
  862. * If this object was destroyed, it should not be used; calling any function other than
  863. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  864. *
  865. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  866. *
  867. * @see LabelCollection#destroy
  868. */
  869. LabelCollection.prototype.isDestroyed = function () {
  870. return false;
  871. };
  872. /**
  873. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  874. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  875. * <br /><br />
  876. * Once an object is destroyed, it should not be used; calling any function other than
  877. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  878. * assign the return value (<code>undefined</code>) to the object as done in the example.
  879. *
  880. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  881. *
  882. *
  883. * @example
  884. * labels = labels && labels.destroy();
  885. *
  886. * @see LabelCollection#isDestroyed
  887. */
  888. LabelCollection.prototype.destroy = function () {
  889. this.removeAll();
  890. this._billboardCollection = this._billboardCollection.destroy();
  891. this._textureAtlas = this._textureAtlas && this._textureAtlas.destroy();
  892. this._backgroundBillboardCollection = this._backgroundBillboardCollection.destroy();
  893. this._backgroundTextureAtlas =
  894. this._backgroundTextureAtlas && this._backgroundTextureAtlas.destroy();
  895. return destroyObject(this);
  896. };
  897. export default LabelCollection;