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.

366 lines
12KB

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