1 /**
2 Copyright: Copyright (c) 2016-2017 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module voxelman.model.utils;
7 
8 import voxelman.container.buffer : Buffer;
9 import voxelman.model.mesh : Face3, Faces;
10 
11 T[] allocate(T)(size_t size) {
12 	import std.experimental.allocator.gc_allocator;
13 	alias allocator = GCAllocator.instance;
14 	return cast(T[])allocator.allocate(T.sizeof * size);
15 }
16 
17 V[] unrollFaces(V)(V[] vertices, Face3[] faces)
18 {
19 	int[] indexes = cast(int[])faces;
20 	V[] result = allocate!(V)(indexes.length);
21 
22 	foreach(i, index; indexes)
23 	{
24 		result[i] = vertices[index];
25 	}
26 
27 	return result;
28 }
29 
30 V[] unrollFaces(V)(V[] vertices, Faces faces)
31 {
32 	if (faces.isTriangulated)
33 	{
34 		V[] result = allocate!(V)(faces.numFaces * 3);
35 
36 		size_t i;
37 		foreach(face; faces[])
38 		{
39 			result[i  ] = vertices[face[i  ]];
40 			result[i+1] = vertices[face[i+1]];
41 			result[i+2] = vertices[face[i+2]];
42 			i += 3;
43 		}
44 
45 		return result;
46 	}
47 	else
48 	{
49 		return unrollFaces(vertices, triangulateFaces(faces));
50 	}
51 }
52 
53 Face3[] triangulateFaces(Faces faces)
54 {
55 	Buffer!int triFaces;
56 	foreach(faceVertices; faces[])
57 	{
58 		triFaces.put(faceVertices[0], faceVertices[1], faceVertices[2]);
59 		for(size_t i = 3; i < faceVertices.length; ++i)
60 		{
61 			triFaces.put(faceVertices[0], faceVertices[i-1], faceVertices[i]);
62 		}
63 	}
64 	return cast(Face3[])triFaces.data;
65 }