PolylineGeometry.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import ArcType from "./ArcType.js";
  2. import arrayRemoveDuplicates from "./arrayRemoveDuplicates.js";
  3. import BoundingSphere from "./BoundingSphere.js";
  4. import Cartesian3 from "./Cartesian3.js";
  5. import Color from "./Color.js";
  6. import ComponentDatatype from "./ComponentDatatype.js";
  7. import defaultValue from "./defaultValue.js";
  8. import defined from "./defined.js";
  9. import DeveloperError from "./DeveloperError.js";
  10. import Ellipsoid from "./Ellipsoid.js";
  11. import Geometry from "./Geometry.js";
  12. import GeometryAttribute from "./GeometryAttribute.js";
  13. import GeometryAttributes from "./GeometryAttributes.js";
  14. import GeometryType from "./GeometryType.js";
  15. import IndexDatatype from "./IndexDatatype.js";
  16. import CesiumMath from "./Math.js";
  17. import PolylinePipeline from "./PolylinePipeline.js";
  18. import PrimitiveType from "./PrimitiveType.js";
  19. import VertexFormat from "./VertexFormat.js";
  20. const scratchInterpolateColorsArray = [];
  21. function interpolateColors(p0, p1, color0, color1, numPoints) {
  22. const colors = scratchInterpolateColorsArray;
  23. colors.length = numPoints;
  24. let i;
  25. const r0 = color0.red;
  26. const g0 = color0.green;
  27. const b0 = color0.blue;
  28. const a0 = color0.alpha;
  29. const r1 = color1.red;
  30. const g1 = color1.green;
  31. const b1 = color1.blue;
  32. const a1 = color1.alpha;
  33. if (Color.equals(color0, color1)) {
  34. for (i = 0; i < numPoints; i++) {
  35. colors[i] = Color.clone(color0);
  36. }
  37. return colors;
  38. }
  39. const redPerVertex = (r1 - r0) / numPoints;
  40. const greenPerVertex = (g1 - g0) / numPoints;
  41. const bluePerVertex = (b1 - b0) / numPoints;
  42. const alphaPerVertex = (a1 - a0) / numPoints;
  43. for (i = 0; i < numPoints; i++) {
  44. colors[i] = new Color(
  45. r0 + i * redPerVertex,
  46. g0 + i * greenPerVertex,
  47. b0 + i * bluePerVertex,
  48. a0 + i * alphaPerVertex
  49. );
  50. }
  51. return colors;
  52. }
  53. /**
  54. * A description of a polyline modeled as a line strip; the first two positions define a line segment,
  55. * and each additional position defines a line segment from the previous position. The polyline is capable of
  56. * displaying with a material.
  57. *
  58. * @alias PolylineGeometry
  59. * @constructor
  60. *
  61. * @param {Object} options Object with the following properties:
  62. * @param {Cartesian3[]} options.positions An array of {@link Cartesian3} defining the positions in the polyline as a line strip.
  63. * @param {Number} [options.width=1.0] The width in pixels.
  64. * @param {Color[]} [options.colors] An Array of {@link Color} defining the per vertex or per segment colors.
  65. * @param {Boolean} [options.colorsPerVertex=false] A boolean that determines whether the colors will be flat across each segment of the line or interpolated across the vertices.
  66. * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polyline segments must follow.
  67. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude if options.arcType is not ArcType.NONE. Determines the number of positions in the buffer.
  68. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  69. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  70. *
  71. * @exception {DeveloperError} At least two positions are required.
  72. * @exception {DeveloperError} width must be greater than or equal to one.
  73. * @exception {DeveloperError} colors has an invalid length.
  74. *
  75. * @see PolylineGeometry#createGeometry
  76. *
  77. * @demo {@link https://sandcastle.cesium.com/index.html?src=Polyline.html|Cesium Sandcastle Polyline Demo}
  78. *
  79. * @example
  80. * // A polyline with two connected line segments
  81. * const polyline = new Cesium.PolylineGeometry({
  82. * positions : Cesium.Cartesian3.fromDegreesArray([
  83. * 0.0, 0.0,
  84. * 5.0, 0.0,
  85. * 5.0, 5.0
  86. * ]),
  87. * width : 10.0
  88. * });
  89. * const geometry = Cesium.PolylineGeometry.createGeometry(polyline);
  90. */
  91. function PolylineGeometry(options) {
  92. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  93. const positions = options.positions;
  94. const colors = options.colors;
  95. const width = defaultValue(options.width, 1.0);
  96. const colorsPerVertex = defaultValue(options.colorsPerVertex, false);
  97. //>>includeStart('debug', pragmas.debug);
  98. if (!defined(positions) || positions.length < 2) {
  99. throw new DeveloperError("At least two positions are required.");
  100. }
  101. if (typeof width !== "number") {
  102. throw new DeveloperError("width must be a number");
  103. }
  104. if (
  105. defined(colors) &&
  106. ((colorsPerVertex && colors.length < positions.length) ||
  107. (!colorsPerVertex && colors.length < positions.length - 1))
  108. ) {
  109. throw new DeveloperError("colors has an invalid length.");
  110. }
  111. //>>includeEnd('debug');
  112. this._positions = positions;
  113. this._colors = colors;
  114. this._width = width;
  115. this._colorsPerVertex = colorsPerVertex;
  116. this._vertexFormat = VertexFormat.clone(
  117. defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
  118. );
  119. this._arcType = defaultValue(options.arcType, ArcType.GEODESIC);
  120. this._granularity = defaultValue(
  121. options.granularity,
  122. CesiumMath.RADIANS_PER_DEGREE
  123. );
  124. this._ellipsoid = Ellipsoid.clone(
  125. defaultValue(options.ellipsoid, Ellipsoid.WGS84)
  126. );
  127. this._workerName = "createPolylineGeometry";
  128. let numComponents = 1 + positions.length * Cartesian3.packedLength;
  129. numComponents += defined(colors) ? 1 + colors.length * Color.packedLength : 1;
  130. /**
  131. * The number of elements used to pack the object into an array.
  132. * @type {Number}
  133. */
  134. this.packedLength =
  135. numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 4;
  136. }
  137. /**
  138. * Stores the provided instance into the provided array.
  139. *
  140. * @param {PolylineGeometry} value The value to pack.
  141. * @param {Number[]} array The array to pack into.
  142. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  143. *
  144. * @returns {Number[]} The array that was packed into
  145. */
  146. PolylineGeometry.pack = function (value, array, startingIndex) {
  147. //>>includeStart('debug', pragmas.debug);
  148. if (!defined(value)) {
  149. throw new DeveloperError("value is required");
  150. }
  151. if (!defined(array)) {
  152. throw new DeveloperError("array is required");
  153. }
  154. //>>includeEnd('debug');
  155. startingIndex = defaultValue(startingIndex, 0);
  156. let i;
  157. const positions = value._positions;
  158. let length = positions.length;
  159. array[startingIndex++] = length;
  160. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  161. Cartesian3.pack(positions[i], array, startingIndex);
  162. }
  163. const colors = value._colors;
  164. length = defined(colors) ? colors.length : 0.0;
  165. array[startingIndex++] = length;
  166. for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
  167. Color.pack(colors[i], array, startingIndex);
  168. }
  169. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  170. startingIndex += Ellipsoid.packedLength;
  171. VertexFormat.pack(value._vertexFormat, array, startingIndex);
  172. startingIndex += VertexFormat.packedLength;
  173. array[startingIndex++] = value._width;
  174. array[startingIndex++] = value._colorsPerVertex ? 1.0 : 0.0;
  175. array[startingIndex++] = value._arcType;
  176. array[startingIndex] = value._granularity;
  177. return array;
  178. };
  179. const scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  180. const scratchVertexFormat = new VertexFormat();
  181. const scratchOptions = {
  182. positions: undefined,
  183. colors: undefined,
  184. ellipsoid: scratchEllipsoid,
  185. vertexFormat: scratchVertexFormat,
  186. width: undefined,
  187. colorsPerVertex: undefined,
  188. arcType: undefined,
  189. granularity: undefined,
  190. };
  191. /**
  192. * Retrieves an instance from a packed array.
  193. *
  194. * @param {Number[]} array The packed array.
  195. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  196. * @param {PolylineGeometry} [result] The object into which to store the result.
  197. * @returns {PolylineGeometry} The modified result parameter or a new PolylineGeometry instance if one was not provided.
  198. */
  199. PolylineGeometry.unpack = function (array, startingIndex, result) {
  200. //>>includeStart('debug', pragmas.debug);
  201. if (!defined(array)) {
  202. throw new DeveloperError("array is required");
  203. }
  204. //>>includeEnd('debug');
  205. startingIndex = defaultValue(startingIndex, 0);
  206. let i;
  207. let length = array[startingIndex++];
  208. const positions = new Array(length);
  209. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  210. positions[i] = Cartesian3.unpack(array, startingIndex);
  211. }
  212. length = array[startingIndex++];
  213. const colors = length > 0 ? new Array(length) : undefined;
  214. for (i = 0; i < length; ++i, startingIndex += Color.packedLength) {
  215. colors[i] = Color.unpack(array, startingIndex);
  216. }
  217. const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  218. startingIndex += Ellipsoid.packedLength;
  219. const vertexFormat = VertexFormat.unpack(
  220. array,
  221. startingIndex,
  222. scratchVertexFormat
  223. );
  224. startingIndex += VertexFormat.packedLength;
  225. const width = array[startingIndex++];
  226. const colorsPerVertex = array[startingIndex++] === 1.0;
  227. const arcType = array[startingIndex++];
  228. const granularity = array[startingIndex];
  229. if (!defined(result)) {
  230. scratchOptions.positions = positions;
  231. scratchOptions.colors = colors;
  232. scratchOptions.width = width;
  233. scratchOptions.colorsPerVertex = colorsPerVertex;
  234. scratchOptions.arcType = arcType;
  235. scratchOptions.granularity = granularity;
  236. return new PolylineGeometry(scratchOptions);
  237. }
  238. result._positions = positions;
  239. result._colors = colors;
  240. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  241. result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
  242. result._width = width;
  243. result._colorsPerVertex = colorsPerVertex;
  244. result._arcType = arcType;
  245. result._granularity = granularity;
  246. return result;
  247. };
  248. const scratchCartesian3 = new Cartesian3();
  249. const scratchPosition = new Cartesian3();
  250. const scratchPrevPosition = new Cartesian3();
  251. const scratchNextPosition = new Cartesian3();
  252. /**
  253. * Computes the geometric representation of a polyline, including its vertices, indices, and a bounding sphere.
  254. *
  255. * @param {PolylineGeometry} polylineGeometry A description of the polyline.
  256. * @returns {Geometry|undefined} The computed vertices and indices.
  257. */
  258. PolylineGeometry.createGeometry = function (polylineGeometry) {
  259. const width = polylineGeometry._width;
  260. const vertexFormat = polylineGeometry._vertexFormat;
  261. let colors = polylineGeometry._colors;
  262. const colorsPerVertex = polylineGeometry._colorsPerVertex;
  263. const arcType = polylineGeometry._arcType;
  264. const granularity = polylineGeometry._granularity;
  265. const ellipsoid = polylineGeometry._ellipsoid;
  266. let i;
  267. let j;
  268. let k;
  269. const removedIndices = [];
  270. let positions = arrayRemoveDuplicates(
  271. polylineGeometry._positions,
  272. Cartesian3.equalsEpsilon,
  273. false,
  274. removedIndices
  275. );
  276. if (defined(colors) && removedIndices.length > 0) {
  277. let removedArrayIndex = 0;
  278. let nextRemovedIndex = removedIndices[0];
  279. colors = colors.filter(function (color, index) {
  280. let remove = false;
  281. if (colorsPerVertex) {
  282. remove =
  283. index === nextRemovedIndex || (index === 0 && nextRemovedIndex === 1);
  284. } else {
  285. remove = index + 1 === nextRemovedIndex;
  286. }
  287. if (remove) {
  288. removedArrayIndex++;
  289. nextRemovedIndex = removedIndices[removedArrayIndex];
  290. return false;
  291. }
  292. return true;
  293. });
  294. }
  295. let positionsLength = positions.length;
  296. // A width of a pixel or less is not a valid geometry, but in order to support external data
  297. // that may have errors we treat this as an empty geometry.
  298. if (positionsLength < 2 || width <= 0.0) {
  299. return undefined;
  300. }
  301. if (arcType === ArcType.GEODESIC || arcType === ArcType.RHUMB) {
  302. let subdivisionSize;
  303. let numberOfPointsFunction;
  304. if (arcType === ArcType.GEODESIC) {
  305. subdivisionSize = CesiumMath.chordLength(
  306. granularity,
  307. ellipsoid.maximumRadius
  308. );
  309. numberOfPointsFunction = PolylinePipeline.numberOfPoints;
  310. } else {
  311. subdivisionSize = granularity;
  312. numberOfPointsFunction = PolylinePipeline.numberOfPointsRhumbLine;
  313. }
  314. const heights = PolylinePipeline.extractHeights(positions, ellipsoid);
  315. if (defined(colors)) {
  316. let colorLength = 1;
  317. for (i = 0; i < positionsLength - 1; ++i) {
  318. colorLength += numberOfPointsFunction(
  319. positions[i],
  320. positions[i + 1],
  321. subdivisionSize
  322. );
  323. }
  324. const newColors = new Array(colorLength);
  325. let newColorIndex = 0;
  326. for (i = 0; i < positionsLength - 1; ++i) {
  327. const p0 = positions[i];
  328. const p1 = positions[i + 1];
  329. const c0 = colors[i];
  330. const numColors = numberOfPointsFunction(p0, p1, subdivisionSize);
  331. if (colorsPerVertex && i < colorLength) {
  332. const c1 = colors[i + 1];
  333. const interpolatedColors = interpolateColors(
  334. p0,
  335. p1,
  336. c0,
  337. c1,
  338. numColors
  339. );
  340. const interpolatedColorsLength = interpolatedColors.length;
  341. for (j = 0; j < interpolatedColorsLength; ++j) {
  342. newColors[newColorIndex++] = interpolatedColors[j];
  343. }
  344. } else {
  345. for (j = 0; j < numColors; ++j) {
  346. newColors[newColorIndex++] = Color.clone(c0);
  347. }
  348. }
  349. }
  350. newColors[newColorIndex] = Color.clone(colors[colors.length - 1]);
  351. colors = newColors;
  352. scratchInterpolateColorsArray.length = 0;
  353. }
  354. if (arcType === ArcType.GEODESIC) {
  355. positions = PolylinePipeline.generateCartesianArc({
  356. positions: positions,
  357. minDistance: subdivisionSize,
  358. ellipsoid: ellipsoid,
  359. height: heights,
  360. });
  361. } else {
  362. positions = PolylinePipeline.generateCartesianRhumbArc({
  363. positions: positions,
  364. granularity: subdivisionSize,
  365. ellipsoid: ellipsoid,
  366. height: heights,
  367. });
  368. }
  369. }
  370. positionsLength = positions.length;
  371. const size = positionsLength * 4.0 - 4.0;
  372. const finalPositions = new Float64Array(size * 3);
  373. const prevPositions = new Float64Array(size * 3);
  374. const nextPositions = new Float64Array(size * 3);
  375. const expandAndWidth = new Float32Array(size * 2);
  376. const st = vertexFormat.st ? new Float32Array(size * 2) : undefined;
  377. const finalColors = defined(colors) ? new Uint8Array(size * 4) : undefined;
  378. let positionIndex = 0;
  379. let expandAndWidthIndex = 0;
  380. let stIndex = 0;
  381. let colorIndex = 0;
  382. let position;
  383. for (j = 0; j < positionsLength; ++j) {
  384. if (j === 0) {
  385. position = scratchCartesian3;
  386. Cartesian3.subtract(positions[0], positions[1], position);
  387. Cartesian3.add(positions[0], position, position);
  388. } else {
  389. position = positions[j - 1];
  390. }
  391. Cartesian3.clone(position, scratchPrevPosition);
  392. Cartesian3.clone(positions[j], scratchPosition);
  393. if (j === positionsLength - 1) {
  394. position = scratchCartesian3;
  395. Cartesian3.subtract(
  396. positions[positionsLength - 1],
  397. positions[positionsLength - 2],
  398. position
  399. );
  400. Cartesian3.add(positions[positionsLength - 1], position, position);
  401. } else {
  402. position = positions[j + 1];
  403. }
  404. Cartesian3.clone(position, scratchNextPosition);
  405. let color0, color1;
  406. if (defined(finalColors)) {
  407. if (j !== 0 && !colorsPerVertex) {
  408. color0 = colors[j - 1];
  409. } else {
  410. color0 = colors[j];
  411. }
  412. if (j !== positionsLength - 1) {
  413. color1 = colors[j];
  414. }
  415. }
  416. const startK = j === 0 ? 2 : 0;
  417. const endK = j === positionsLength - 1 ? 2 : 4;
  418. for (k = startK; k < endK; ++k) {
  419. Cartesian3.pack(scratchPosition, finalPositions, positionIndex);
  420. Cartesian3.pack(scratchPrevPosition, prevPositions, positionIndex);
  421. Cartesian3.pack(scratchNextPosition, nextPositions, positionIndex);
  422. positionIndex += 3;
  423. const direction = k - 2 < 0 ? -1.0 : 1.0;
  424. expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1; // expand direction
  425. expandAndWidth[expandAndWidthIndex++] = direction * width;
  426. if (vertexFormat.st) {
  427. st[stIndex++] = j / (positionsLength - 1);
  428. st[stIndex++] = Math.max(expandAndWidth[expandAndWidthIndex - 2], 0.0);
  429. }
  430. if (defined(finalColors)) {
  431. const color = k < 2 ? color0 : color1;
  432. finalColors[colorIndex++] = Color.floatToByte(color.red);
  433. finalColors[colorIndex++] = Color.floatToByte(color.green);
  434. finalColors[colorIndex++] = Color.floatToByte(color.blue);
  435. finalColors[colorIndex++] = Color.floatToByte(color.alpha);
  436. }
  437. }
  438. }
  439. const attributes = new GeometryAttributes();
  440. attributes.position = new GeometryAttribute({
  441. componentDatatype: ComponentDatatype.DOUBLE,
  442. componentsPerAttribute: 3,
  443. values: finalPositions,
  444. });
  445. attributes.prevPosition = new GeometryAttribute({
  446. componentDatatype: ComponentDatatype.DOUBLE,
  447. componentsPerAttribute: 3,
  448. values: prevPositions,
  449. });
  450. attributes.nextPosition = new GeometryAttribute({
  451. componentDatatype: ComponentDatatype.DOUBLE,
  452. componentsPerAttribute: 3,
  453. values: nextPositions,
  454. });
  455. attributes.expandAndWidth = new GeometryAttribute({
  456. componentDatatype: ComponentDatatype.FLOAT,
  457. componentsPerAttribute: 2,
  458. values: expandAndWidth,
  459. });
  460. if (vertexFormat.st) {
  461. attributes.st = new GeometryAttribute({
  462. componentDatatype: ComponentDatatype.FLOAT,
  463. componentsPerAttribute: 2,
  464. values: st,
  465. });
  466. }
  467. if (defined(finalColors)) {
  468. attributes.color = new GeometryAttribute({
  469. componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
  470. componentsPerAttribute: 4,
  471. values: finalColors,
  472. normalize: true,
  473. });
  474. }
  475. const indices = IndexDatatype.createTypedArray(size, positionsLength * 6 - 6);
  476. let index = 0;
  477. let indicesIndex = 0;
  478. const length = positionsLength - 1.0;
  479. for (j = 0; j < length; ++j) {
  480. indices[indicesIndex++] = index;
  481. indices[indicesIndex++] = index + 2;
  482. indices[indicesIndex++] = index + 1;
  483. indices[indicesIndex++] = index + 1;
  484. indices[indicesIndex++] = index + 2;
  485. indices[indicesIndex++] = index + 3;
  486. index += 4;
  487. }
  488. return new Geometry({
  489. attributes: attributes,
  490. indices: indices,
  491. primitiveType: PrimitiveType.TRIANGLES,
  492. boundingSphere: BoundingSphere.fromPoints(positions),
  493. geometryType: GeometryType.POLYLINES,
  494. });
  495. };
  496. export default PolylineGeometry;