The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

372 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #include <map>
  18. //==============================================================================
  19. /**
  20. This is a quick-and-dirty parser for the 3D OBJ file format.
  21. Just call load() and if there aren't any errors, the 'shapes' array should
  22. be filled with all the shape objects that were loaded from the file.
  23. */
  24. class WavefrontObjFile
  25. {
  26. public:
  27. WavefrontObjFile() {}
  28. Result load (const String& objFileContent)
  29. {
  30. shapes.clear();
  31. return parseObjFile (StringArray::fromLines (objFileContent));
  32. }
  33. Result load (const File& file)
  34. {
  35. sourceFile = file;
  36. return load (file.loadFileAsString());
  37. }
  38. //==============================================================================
  39. typedef juce::uint32 Index;
  40. struct Vertex { float x, y, z; };
  41. struct TextureCoord { float x, y; };
  42. struct Mesh
  43. {
  44. Array<Vertex> vertices, normals;
  45. Array<TextureCoord> textureCoords;
  46. Array<Index> indices;
  47. };
  48. struct Material
  49. {
  50. Material() noexcept : shininess (1.0f), refractiveIndex (0.0f)
  51. {
  52. zerostruct (ambient);
  53. zerostruct (diffuse);
  54. zerostruct (specular);
  55. zerostruct (transmittance);
  56. zerostruct (emission);
  57. }
  58. String name;
  59. Vertex ambient, diffuse, specular, transmittance, emission;
  60. float shininess, refractiveIndex;
  61. String ambientTextureName, diffuseTextureName,
  62. specularTextureName, normalTextureName;
  63. StringPairArray parameters;
  64. };
  65. struct Shape
  66. {
  67. String name;
  68. Mesh mesh;
  69. Material material;
  70. };
  71. OwnedArray<Shape> shapes;
  72. private:
  73. //==============================================================================
  74. File sourceFile;
  75. struct TripleIndex
  76. {
  77. TripleIndex() noexcept : vertexIndex (-1), textureIndex (-1), normalIndex (-1) {}
  78. bool operator< (const TripleIndex& other) const noexcept
  79. {
  80. if (this == &other)
  81. return false;
  82. if (vertexIndex != other.vertexIndex)
  83. return vertexIndex < other.vertexIndex;
  84. if (textureIndex != other.textureIndex)
  85. return textureIndex < other.textureIndex;
  86. return normalIndex < other.normalIndex;
  87. }
  88. int vertexIndex, textureIndex, normalIndex;
  89. };
  90. struct IndexMap
  91. {
  92. std::map<TripleIndex, Index> map;
  93. Index getIndexFor (TripleIndex i, Mesh& newMesh, const Mesh& srcMesh)
  94. {
  95. const std::map<TripleIndex, Index>::iterator it (map.find (i));
  96. if (it != map.end())
  97. return it->second;
  98. const Index index = (Index) newMesh.vertices.size();
  99. if (isPositiveAndBelow (i.vertexIndex, srcMesh.vertices.size()))
  100. newMesh.vertices.add (srcMesh.vertices.getReference (i.vertexIndex));
  101. if (isPositiveAndBelow (i.normalIndex, srcMesh.normals.size()))
  102. newMesh.normals.add (srcMesh.normals.getReference (i.normalIndex));
  103. if (isPositiveAndBelow (i.textureIndex, srcMesh.textureCoords.size()))
  104. newMesh.textureCoords.add (srcMesh.textureCoords.getReference (i.textureIndex));
  105. map[i] = index;
  106. return index;
  107. }
  108. };
  109. static float parseFloat (String::CharPointerType& t)
  110. {
  111. t = t.findEndOfWhitespace();
  112. return (float) CharacterFunctions::readDoubleValue (t);
  113. }
  114. static Vertex parseVertex (String::CharPointerType t)
  115. {
  116. Vertex v;
  117. v.x = parseFloat (t);
  118. v.y = parseFloat (t);
  119. v.z = parseFloat (t);
  120. return v;
  121. }
  122. static TextureCoord parseTextureCoord (String::CharPointerType t)
  123. {
  124. TextureCoord tc;
  125. tc.x = parseFloat (t);
  126. tc.y = parseFloat (t);
  127. return tc;
  128. }
  129. static bool matchToken (String::CharPointerType& t, const char* token)
  130. {
  131. const int len = (int) strlen (token);
  132. if (CharacterFunctions::compareUpTo (CharPointer_ASCII (token), t, len) == 0)
  133. {
  134. String::CharPointerType end = t + len;
  135. if (end.isEmpty() || end.isWhitespace())
  136. {
  137. t = end.findEndOfWhitespace();
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. struct Face
  144. {
  145. Face (String::CharPointerType t)
  146. {
  147. while (! t.isEmpty())
  148. triples.add (parseTriple (t));
  149. }
  150. Array<TripleIndex> triples;
  151. void addIndices (Mesh& newMesh, const Mesh& srcMesh, IndexMap& indexMap)
  152. {
  153. TripleIndex i0 (triples[0]), i1, i2 (triples[1]);
  154. for (int i = 2; i < triples.size(); ++i)
  155. {
  156. i1 = i2;
  157. i2 = triples.getReference (i);
  158. newMesh.indices.add (indexMap.getIndexFor (i0, newMesh, srcMesh));
  159. newMesh.indices.add (indexMap.getIndexFor (i1, newMesh, srcMesh));
  160. newMesh.indices.add (indexMap.getIndexFor (i2, newMesh, srcMesh));
  161. }
  162. }
  163. static TripleIndex parseTriple (String::CharPointerType& t)
  164. {
  165. TripleIndex i;
  166. t = t.findEndOfWhitespace();
  167. i.vertexIndex = t.getIntValue32() - 1;
  168. t = findEndOfFaceToken (t);
  169. if (t.isEmpty() || t.getAndAdvance() != '/')
  170. return i;
  171. if (*t == '/')
  172. {
  173. ++t;
  174. }
  175. else
  176. {
  177. i.textureIndex = t.getIntValue32() - 1;
  178. t = findEndOfFaceToken (t);
  179. if (t.isEmpty() || t.getAndAdvance() != '/')
  180. return i;
  181. }
  182. i.normalIndex = t.getIntValue32() - 1;
  183. t = findEndOfFaceToken (t);
  184. return i;
  185. }
  186. static String::CharPointerType findEndOfFaceToken (String::CharPointerType t) noexcept
  187. {
  188. return CharacterFunctions::findEndOfToken (t, CharPointer_ASCII ("/ \t"), String().getCharPointer());
  189. }
  190. };
  191. static Shape* parseFaceGroup (const Mesh& srcMesh,
  192. const Array<Face>& faceGroup,
  193. const Material& material,
  194. const String& name)
  195. {
  196. if (faceGroup.size() == 0)
  197. return nullptr;
  198. ScopedPointer<Shape> shape (new Shape());
  199. shape->name = name;
  200. shape->material = material;
  201. IndexMap indexMap;
  202. for (int i = 0; i < faceGroup.size(); ++i)
  203. faceGroup.getReference(i).addIndices (shape->mesh, srcMesh, indexMap);
  204. return shape.release();
  205. }
  206. Result parseObjFile (const StringArray& lines)
  207. {
  208. Mesh mesh;
  209. Array<Face> faceGroup;
  210. Array<Material> knownMaterials;
  211. Material lastMaterial;
  212. String lastName;
  213. for (int lineNum = 0; lineNum < lines.size(); ++lineNum)
  214. {
  215. String::CharPointerType l = lines[lineNum].getCharPointer().findEndOfWhitespace();
  216. if (matchToken (l, "v")) { mesh.vertices.add (parseVertex (l)); continue; }
  217. if (matchToken (l, "vn")) { mesh.normals.add (parseVertex (l)); continue; }
  218. if (matchToken (l, "vt")) { mesh.textureCoords.add (parseTextureCoord (l)); continue; }
  219. if (matchToken (l, "f")) { faceGroup.add (Face (l)); continue; }
  220. if (matchToken (l, "usemtl"))
  221. {
  222. const String name (String (l).trim());
  223. for (int i = knownMaterials.size(); --i >= 0;)
  224. {
  225. if (knownMaterials.getReference(i).name == name)
  226. {
  227. lastMaterial = knownMaterials.getReference(i);
  228. break;
  229. }
  230. }
  231. continue;
  232. }
  233. if (matchToken (l, "mtllib"))
  234. {
  235. Result r = parseMaterial (knownMaterials, String (l).trim());
  236. continue;
  237. }
  238. if (matchToken (l, "g") || matchToken (l, "o"))
  239. {
  240. if (Shape* shape = parseFaceGroup (mesh, faceGroup, lastMaterial, lastName))
  241. shapes.add (shape);
  242. faceGroup.clear();
  243. lastName = StringArray::fromTokens (l, " \t", "")[0];
  244. continue;
  245. }
  246. }
  247. if (Shape* shape = parseFaceGroup (mesh, faceGroup, lastMaterial, lastName))
  248. shapes.add (shape);
  249. return Result::ok();
  250. }
  251. Result parseMaterial (Array<Material>& materials, const String& filename)
  252. {
  253. jassert (sourceFile.exists());
  254. File f (sourceFile.getSiblingFile (filename));
  255. if (! f.exists())
  256. return Result::fail ("Cannot open file: " + filename);
  257. StringArray lines;
  258. lines.addLines (f.loadFileAsString());
  259. materials.clear();
  260. Material material;
  261. for (int i = 0; i < lines.size(); ++i)
  262. {
  263. String::CharPointerType l (lines[i].getCharPointer().findEndOfWhitespace());
  264. if (matchToken (l, "newmtl")) { materials.add (material); material.name = String (l).trim(); continue; }
  265. if (matchToken (l, "Ka")) { material.ambient = parseVertex (l); continue; }
  266. if (matchToken (l, "Kd")) { material.diffuse = parseVertex (l); continue; }
  267. if (matchToken (l, "Ks")) { material.specular = parseVertex (l); continue; }
  268. if (matchToken (l, "Kt")) { material.transmittance = parseVertex (l); continue; }
  269. if (matchToken (l, "Ke")) { material.emission = parseVertex (l); continue; }
  270. if (matchToken (l, "Ni")) { material.refractiveIndex = parseFloat (l); continue; }
  271. if (matchToken (l, "Ns")) { material.shininess = parseFloat (l); continue; }
  272. if (matchToken (l, "map_Ka")) { material.ambientTextureName = String (l).trim(); continue; }
  273. if (matchToken (l, "map_Kd")) { material.diffuseTextureName = String (l).trim(); continue; }
  274. if (matchToken (l, "map_Ks")) { material.specularTextureName = String (l).trim(); continue; }
  275. if (matchToken (l, "map_Ns")) { material.normalTextureName = String (l).trim(); continue; }
  276. StringArray tokens;
  277. tokens.addTokens (l, " \t", "");
  278. if (tokens.size() >= 2)
  279. material.parameters.set (tokens[0].trim(), tokens[1].trim());
  280. }
  281. materials.add (material);
  282. return Result::ok();
  283. }
  284. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavefrontObjFile)
  285. };