|
| 1 | +import 'dart:typed_data'; |
| 2 | + |
| 3 | +import 'basic_types.dart'; |
| 4 | + |
| 5 | +/// A description of vertex points for drawing triangles. |
| 6 | +class Vertices { |
| 7 | + const Vertices(this.vertexPoints); |
| 8 | + |
| 9 | + factory Vertices.fromFloat32List(Float32List vertices) { |
| 10 | + if (vertices.length.isOdd) { |
| 11 | + throw ArgumentError( |
| 12 | + 'must be an even number of vertex points', |
| 13 | + 'vertices', |
| 14 | + ); |
| 15 | + } |
| 16 | + final List<Point> vertexPoints = []; |
| 17 | + for (int index = 0; index < vertices.length; index += 2) { |
| 18 | + vertexPoints.add(Point(vertices[index], vertices[index + 1])); |
| 19 | + } |
| 20 | + return Vertices(vertexPoints); |
| 21 | + } |
| 22 | + |
| 23 | + /// A list of vertex points descibing this triangular mesh. |
| 24 | + /// |
| 25 | + /// The vertex points are assumed to be in VertexMode.triangle. |
| 26 | + final List<Point> vertexPoints; |
| 27 | + |
| 28 | + /// Creates an optimized version of [vertexPoints] where the points are |
| 29 | + /// deduplicated via an index buffer. |
| 30 | + IndexedVertices createIndex() { |
| 31 | + final pointMap = <Point, int>{}; |
| 32 | + int index = 0; |
| 33 | + final List<int> indices = []; |
| 34 | + for (final point in vertexPoints) { |
| 35 | + indices.add(pointMap.putIfAbsent(point, () => index++)); |
| 36 | + } |
| 37 | + |
| 38 | + Float32List pointsToFloat32List(List<Point> points) { |
| 39 | + final Float32List vertices = Float32List(points.length * 2); |
| 40 | + int vertexIndex = 0; |
| 41 | + for (final point in points) { |
| 42 | + vertices[vertexIndex++] = point.x; |
| 43 | + vertices[vertexIndex++] = point.y; |
| 44 | + } |
| 45 | + return vertices; |
| 46 | + } |
| 47 | + |
| 48 | + final List<Point> compressedPoints = pointMap.keys.toList(); |
| 49 | + if (compressedPoints.length * 2 + indices.length > |
| 50 | + vertexPoints.length * 2) { |
| 51 | + return IndexedVertices(pointsToFloat32List(vertexPoints), null); |
| 52 | + } |
| 53 | + |
| 54 | + return IndexedVertices( |
| 55 | + pointsToFloat32List(compressedPoints), |
| 56 | + Uint16List.fromList(indices), |
| 57 | + ); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/// An optimized version of [Vertices] that uses an index buffer to specify |
| 62 | +/// reused vertex points. |
| 63 | +class IndexedVertices { |
| 64 | + const IndexedVertices(this.vertices, this.indices); |
| 65 | + |
| 66 | + /// The raw vertex points. |
| 67 | + final Float32List vertices; |
| 68 | + |
| 69 | + /// The order to use vertices from [vertuces]. |
| 70 | + /// |
| 71 | + /// May be null if [vertices] was not compressable. |
| 72 | + final Uint16List? indices; |
| 73 | +} |
0 commit comments