Geometry.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import Cartesian2 from "./Cartesian2.js";
  2. import Cartesian3 from "./Cartesian3.js";
  3. import Cartographic from "./Cartographic.js";
  4. import Check from "./Check.js";
  5. import defaultValue from "./defaultValue.js";
  6. import defined from "./defined.js";
  7. import DeveloperError from "./DeveloperError.js";
  8. import GeometryType from "./GeometryType.js";
  9. import Matrix2 from "./Matrix2.js";
  10. import Matrix3 from "./Matrix3.js";
  11. import Matrix4 from "./Matrix4.js";
  12. import PrimitiveType from "./PrimitiveType.js";
  13. import Quaternion from "./Quaternion.js";
  14. import Rectangle from "./Rectangle.js";
  15. import Transforms from "./Transforms.js";
  16. /**
  17. * A geometry representation with attributes forming vertices and optional index data
  18. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  19. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  20. * be created from many heterogeneous - in many cases - geometries for performance.
  21. * <p>
  22. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  23. * </p>
  24. *
  25. * @alias Geometry
  26. * @constructor
  27. *
  28. * @param {Object} options Object with the following properties:
  29. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  30. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  31. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  32. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  33. *
  34. * @see PolygonGeometry
  35. * @see RectangleGeometry
  36. * @see EllipseGeometry
  37. * @see CircleGeometry
  38. * @see WallGeometry
  39. * @see SimplePolylineGeometry
  40. * @see BoxGeometry
  41. * @see EllipsoidGeometry
  42. *
  43. * @demo {@link https://sandcastle.cesium.com/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  44. *
  45. * @example
  46. * // Create geometry with a position attribute and indexed lines.
  47. * const positions = new Float64Array([
  48. * 0.0, 0.0, 0.0,
  49. * 7500000.0, 0.0, 0.0,
  50. * 0.0, 7500000.0, 0.0
  51. * ]);
  52. *
  53. * const geometry = new Cesium.Geometry({
  54. * attributes : {
  55. * position : new Cesium.GeometryAttribute({
  56. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  57. * componentsPerAttribute : 3,
  58. * values : positions
  59. * })
  60. * },
  61. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  62. * primitiveType : Cesium.PrimitiveType.LINES,
  63. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  64. * });
  65. */
  66. function Geometry(options) {
  67. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  68. //>>includeStart('debug', pragmas.debug);
  69. Check.typeOf.object("options.attributes", options.attributes);
  70. //>>includeEnd('debug');
  71. /**
  72. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  73. * {@link GeometryAttribute} containing the attribute's data.
  74. * <p>
  75. * Attributes are always stored non-interleaved in a Geometry.
  76. * </p>
  77. * <p>
  78. * There are reserved attribute names with well-known semantics. The following attributes
  79. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  80. * <ul>
  81. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  82. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  83. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  84. * <li><code>bitangent</code> - Bitangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#bitangent}.</li>
  85. * <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
  86. * </ul>
  87. * </p>
  88. * <p>
  89. * The following attribute names are generally not created by a Geometry, but are added
  90. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  91. * the geometry for rendering.
  92. * <ul>
  93. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  94. * <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  95. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  96. * <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  97. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  98. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  99. * </ul>
  100. * </p>
  101. *
  102. * @type GeometryAttributes
  103. *
  104. * @default undefined
  105. *
  106. *
  107. * @example
  108. * geometry.attributes.position = new Cesium.GeometryAttribute({
  109. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  110. * componentsPerAttribute : 3,
  111. * values : new Float32Array(0)
  112. * });
  113. *
  114. * @see GeometryAttribute
  115. * @see VertexFormat
  116. */
  117. this.attributes = options.attributes;
  118. /**
  119. * Optional index data that - along with {@link Geometry#primitiveType} -
  120. * determines the primitives in the geometry.
  121. *
  122. * @type Array
  123. *
  124. * @default undefined
  125. */
  126. this.indices = options.indices;
  127. /**
  128. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  129. * but can varying based on the specific geometry.
  130. *
  131. * @type PrimitiveType
  132. *
  133. * @default undefined
  134. */
  135. this.primitiveType = defaultValue(
  136. options.primitiveType,
  137. PrimitiveType.TRIANGLES
  138. );
  139. /**
  140. * An optional bounding sphere that fully encloses the geometry. This is
  141. * commonly used for culling.
  142. *
  143. * @type BoundingSphere
  144. *
  145. * @default undefined
  146. */
  147. this.boundingSphere = options.boundingSphere;
  148. /**
  149. * @private
  150. */
  151. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  152. /**
  153. * @private
  154. */
  155. this.boundingSphereCV = options.boundingSphereCV;
  156. /**
  157. * Used for computing the bounding sphere for geometry using the applyOffset vertex attribute
  158. * @private
  159. */
  160. this.offsetAttribute = options.offsetAttribute;
  161. }
  162. /**
  163. * Computes the number of vertices in a geometry. The runtime is linear with
  164. * respect to the number of attributes in a vertex, not the number of vertices.
  165. *
  166. * @param {Geometry} geometry The geometry.
  167. * @returns {Number} The number of vertices in the geometry.
  168. *
  169. * @example
  170. * const numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  171. */
  172. Geometry.computeNumberOfVertices = function (geometry) {
  173. //>>includeStart('debug', pragmas.debug);
  174. Check.typeOf.object("geometry", geometry);
  175. //>>includeEnd('debug');
  176. let numberOfVertices = -1;
  177. for (const property in geometry.attributes) {
  178. if (
  179. geometry.attributes.hasOwnProperty(property) &&
  180. defined(geometry.attributes[property]) &&
  181. defined(geometry.attributes[property].values)
  182. ) {
  183. const attribute = geometry.attributes[property];
  184. const num = attribute.values.length / attribute.componentsPerAttribute;
  185. //>>includeStart('debug', pragmas.debug);
  186. if (numberOfVertices !== num && numberOfVertices !== -1) {
  187. throw new DeveloperError(
  188. "All attribute lists must have the same number of attributes."
  189. );
  190. }
  191. //>>includeEnd('debug');
  192. numberOfVertices = num;
  193. }
  194. }
  195. return numberOfVertices;
  196. };
  197. const rectangleCenterScratch = new Cartographic();
  198. const enuCenterScratch = new Cartesian3();
  199. const fixedFrameToEnuScratch = new Matrix4();
  200. const boundingRectanglePointsCartographicScratch = [
  201. new Cartographic(),
  202. new Cartographic(),
  203. new Cartographic(),
  204. ];
  205. const boundingRectanglePointsEnuScratch = [
  206. new Cartesian2(),
  207. new Cartesian2(),
  208. new Cartesian2(),
  209. ];
  210. const points2DScratch = [new Cartesian2(), new Cartesian2(), new Cartesian2()];
  211. const pointEnuScratch = new Cartesian3();
  212. const enuRotationScratch = new Quaternion();
  213. const enuRotationMatrixScratch = new Matrix4();
  214. const rotation2DScratch = new Matrix2();
  215. /**
  216. * For remapping texture coordinates when rendering GroundPrimitives with materials.
  217. * GroundPrimitive texture coordinates are computed to align with the cartographic coordinate system on the globe.
  218. * However, EllipseGeometry, RectangleGeometry, and PolygonGeometry all bake rotations to per-vertex texture coordinates
  219. * using different strategies.
  220. *
  221. * This method is used by EllipseGeometry and PolygonGeometry to approximate the same visual effect.
  222. * We encapsulate rotation and scale by computing a "transformed" texture coordinate system and computing
  223. * a set of reference points from which "cartographic" texture coordinates can be remapped to the "transformed"
  224. * system using distances to lines in 2D.
  225. *
  226. * This approximation becomes less accurate as the covered area increases, especially for GroundPrimitives near the poles,
  227. * but is generally reasonable for polygons and ellipses around the size of USA states.
  228. *
  229. * RectangleGeometry has its own version of this method that computes remapping coordinates using cartographic space
  230. * as an intermediary instead of local ENU, which is more accurate for large-area rectangles.
  231. *
  232. * @param {Cartesian3[]} positions Array of positions outlining the geometry
  233. * @param {Number} stRotation Texture coordinate rotation.
  234. * @param {Ellipsoid} ellipsoid Ellipsoid for projecting and generating local vectors.
  235. * @param {Rectangle} boundingRectangle Bounding rectangle around the positions.
  236. * @returns {Number[]} An array of 6 numbers specifying [minimum point, u extent, v extent] as points in the "cartographic" system.
  237. * @private
  238. */
  239. Geometry._textureCoordinateRotationPoints = function (
  240. positions,
  241. stRotation,
  242. ellipsoid,
  243. boundingRectangle
  244. ) {
  245. let i;
  246. // Create a local east-north-up coordinate system centered on the polygon's bounding rectangle.
  247. // Project the southwest, northwest, and southeast corners of the bounding rectangle into the plane of ENU as 2D points.
  248. // These are the equivalents of (0,0), (0,1), and (1,0) in the texture coordiante system computed in ShadowVolumeAppearanceFS,
  249. // aka "ENU texture space."
  250. const rectangleCenter = Rectangle.center(
  251. boundingRectangle,
  252. rectangleCenterScratch
  253. );
  254. const enuCenter = Cartographic.toCartesian(
  255. rectangleCenter,
  256. ellipsoid,
  257. enuCenterScratch
  258. );
  259. const enuToFixedFrame = Transforms.eastNorthUpToFixedFrame(
  260. enuCenter,
  261. ellipsoid,
  262. fixedFrameToEnuScratch
  263. );
  264. const fixedFrameToEnu = Matrix4.inverse(
  265. enuToFixedFrame,
  266. fixedFrameToEnuScratch
  267. );
  268. const boundingPointsEnu = boundingRectanglePointsEnuScratch;
  269. const boundingPointsCarto = boundingRectanglePointsCartographicScratch;
  270. boundingPointsCarto[0].longitude = boundingRectangle.west;
  271. boundingPointsCarto[0].latitude = boundingRectangle.south;
  272. boundingPointsCarto[1].longitude = boundingRectangle.west;
  273. boundingPointsCarto[1].latitude = boundingRectangle.north;
  274. boundingPointsCarto[2].longitude = boundingRectangle.east;
  275. boundingPointsCarto[2].latitude = boundingRectangle.south;
  276. let posEnu = pointEnuScratch;
  277. for (i = 0; i < 3; i++) {
  278. Cartographic.toCartesian(boundingPointsCarto[i], ellipsoid, posEnu);
  279. posEnu = Matrix4.multiplyByPointAsVector(fixedFrameToEnu, posEnu, posEnu);
  280. boundingPointsEnu[i].x = posEnu.x;
  281. boundingPointsEnu[i].y = posEnu.y;
  282. }
  283. // Rotate each point in the polygon around the up vector in the ENU by -stRotation and project into ENU as 2D.
  284. // Compute the bounding box of these rotated points in the 2D ENU plane.
  285. // Rotate the corners back by stRotation, then compute their equivalents in the ENU texture space using the corners computed earlier.
  286. const rotation = Quaternion.fromAxisAngle(
  287. Cartesian3.UNIT_Z,
  288. -stRotation,
  289. enuRotationScratch
  290. );
  291. const textureMatrix = Matrix3.fromQuaternion(
  292. rotation,
  293. enuRotationMatrixScratch
  294. );
  295. const positionsLength = positions.length;
  296. let enuMinX = Number.POSITIVE_INFINITY;
  297. let enuMinY = Number.POSITIVE_INFINITY;
  298. let enuMaxX = Number.NEGATIVE_INFINITY;
  299. let enuMaxY = Number.NEGATIVE_INFINITY;
  300. for (i = 0; i < positionsLength; i++) {
  301. posEnu = Matrix4.multiplyByPointAsVector(
  302. fixedFrameToEnu,
  303. positions[i],
  304. posEnu
  305. );
  306. posEnu = Matrix3.multiplyByVector(textureMatrix, posEnu, posEnu);
  307. enuMinX = Math.min(enuMinX, posEnu.x);
  308. enuMinY = Math.min(enuMinY, posEnu.y);
  309. enuMaxX = Math.max(enuMaxX, posEnu.x);
  310. enuMaxY = Math.max(enuMaxY, posEnu.y);
  311. }
  312. const toDesiredInComputed = Matrix2.fromRotation(
  313. stRotation,
  314. rotation2DScratch
  315. );
  316. const points2D = points2DScratch;
  317. points2D[0].x = enuMinX;
  318. points2D[0].y = enuMinY;
  319. points2D[1].x = enuMinX;
  320. points2D[1].y = enuMaxY;
  321. points2D[2].x = enuMaxX;
  322. points2D[2].y = enuMinY;
  323. const boundingEnuMin = boundingPointsEnu[0];
  324. const boundingPointsWidth = boundingPointsEnu[2].x - boundingEnuMin.x;
  325. const boundingPointsHeight = boundingPointsEnu[1].y - boundingEnuMin.y;
  326. for (i = 0; i < 3; i++) {
  327. const point2D = points2D[i];
  328. // rotate back
  329. Matrix2.multiplyByVector(toDesiredInComputed, point2D, point2D);
  330. // Convert point into east-north texture coordinate space
  331. point2D.x = (point2D.x - boundingEnuMin.x) / boundingPointsWidth;
  332. point2D.y = (point2D.y - boundingEnuMin.y) / boundingPointsHeight;
  333. }
  334. const minXYCorner = points2D[0];
  335. const maxYCorner = points2D[1];
  336. const maxXCorner = points2D[2];
  337. const result = new Array(6);
  338. Cartesian2.pack(minXYCorner, result);
  339. Cartesian2.pack(maxYCorner, result, 2);
  340. Cartesian2.pack(maxXCorner, result, 4);
  341. return result;
  342. };
  343. export default Geometry;