importer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #include "importer.h"
  2. namespace dsr {
  3. struct PlyProperty {
  4. String name;
  5. bool list;
  6. int scale = 1; // 1 for normalized input, 255 for uchar
  7. // Single property
  8. PlyProperty(String name, ReadableString typeName) : name(name), list(false) {
  9. if (string_caseInsensitiveMatch(typeName, U"UCHAR")) {
  10. this->scale = 255;
  11. } else {
  12. this->scale = 1;
  13. }
  14. }
  15. // List of properties
  16. PlyProperty(String name, ReadableString typeName, ReadableString lengthTypeName) : name(name), list(true) {
  17. if (string_caseInsensitiveMatch(typeName, U"UCHAR")) {
  18. this->scale = 255;
  19. } else {
  20. this->scale = 1;
  21. }
  22. if (string_caseInsensitiveMatch(lengthTypeName, U"FLOAT")) {
  23. printText("loadPlyModel: Using floating-point numbers to describe the length of a list is nonsense!\n");
  24. }
  25. }
  26. };
  27. struct PlyElement {
  28. String name; // Name of the collection
  29. int count; // Size of the collection
  30. List<PlyProperty> properties; // Properties on each line (list properties consume additional tokens)
  31. PlyElement(const String &name, int count) : name(name), count(count) {}
  32. };
  33. enum class PlyDataInput {
  34. Ignore, Vertex, Face
  35. };
  36. static PlyDataInput PlyDataInputFromName(const ReadableString& name) {
  37. if (string_caseInsensitiveMatch(name, U"VERTEX")) {
  38. return PlyDataInput::Vertex;
  39. } else if (string_caseInsensitiveMatch(name, U"FACE")) {
  40. return PlyDataInput::Face;
  41. } else {
  42. return PlyDataInput::Ignore;
  43. }
  44. }
  45. struct PlyVertex {
  46. FVector3D position = FVector3D(0.0f, 0.0f, 0.0f);
  47. FVector4D color = FVector4D(1.0f, 1.0f, 1.0f, 1.0f);
  48. };
  49. // When exporting PLY to this tool:
  50. // +X is right
  51. // +Y is up
  52. // +Z is forward
  53. // This coordinate system is left handed, which makes more sense when working with depth buffers.
  54. // If exporting from a right-handed editor, setting Y as up and Z as forward might flip the X axis to the left side.
  55. // In that case, flip the X axis when calling this function.
  56. static void loadPlyModel(Model& targetModel, int targetPart, const ReadableString& content, bool flipX, Transform3D axisConversion) {
  57. //printText("loadPlyModel:\n", content, "\n");
  58. // Find the target model
  59. int startPointIndex = model_getNumberOfPoints(targetModel);
  60. // Split lines
  61. List<String> lines = string_split(content, U'\n', true);
  62. List<PlyElement> elements;
  63. bool readingContent = false; // True after passing end_header
  64. int elementIndex = -1; // current member of elements
  65. int memberIndex = 0; // current data line within the content of the current element
  66. PlyDataInput inputMode = PlyDataInput::Ignore;
  67. // Temporary geometry
  68. List<PlyVertex> vertices;
  69. if (lines.length() < 2) {
  70. printText("loadPlyModel: Failed to identify line-breaks in the PLY file!\n");
  71. return;
  72. } else if (!string_caseInsensitiveMatch(string_removeOuterWhiteSpace(lines[0]), U"PLY")) {
  73. printText("loadPlyModel: Failed to identify the file as PLY!\n");
  74. return;
  75. } else if (!string_caseInsensitiveMatch(string_removeOuterWhiteSpace(lines[1]), U"FORMAT ASCII 1.0")) {
  76. printText("loadPlyModel: Only supporting the ascii 1.0 format!\n");
  77. return;
  78. }
  79. for (int l = 0; l < lines.length(); l++) {
  80. // Tokenize the current line
  81. List<String> tokens = string_split(lines[l], U' ');
  82. if (tokens.length() > 0 && !string_caseInsensitiveMatch(tokens[0], U"COMMENT")) {
  83. if (readingContent) {
  84. // Parse geometry
  85. if (inputMode == PlyDataInput::Vertex || inputMode == PlyDataInput::Face) {
  86. // Create new vertex with default properties
  87. if (inputMode == PlyDataInput::Vertex) {
  88. vertices.push(PlyVertex());
  89. }
  90. PlyElement *currentElement = &(elements[elementIndex]);
  91. int tokenIndex = 0;
  92. for (int propertyIndex = 0; propertyIndex < currentElement->properties.length(); propertyIndex++) {
  93. if (tokenIndex >= tokens.length()) {
  94. printText("loadPlyModel: Undeclared properties given to ", currentElement->name, " in the data!\n");
  95. break;
  96. }
  97. PlyProperty *currentProperty = &(currentElement->properties[propertyIndex]);
  98. if (currentProperty->list) {
  99. int listLength = string_toInteger(tokens[tokenIndex]);
  100. tokenIndex++;
  101. // Detect polygons
  102. if (inputMode == PlyDataInput::Face && string_caseInsensitiveMatch(currentProperty->name, U"VERTEX_INDICES")) {
  103. if (vertices.length() == 0) {
  104. printText("loadPlyModel: This ply importer does not support feeding polygons before vertices! Using vertices before defining them would require an additional intermediate representation.\n");
  105. }
  106. bool flipSides = flipX;
  107. if (listLength == 4) {
  108. // Use a quad to save memory
  109. int indexA = string_toInteger(tokens[tokenIndex]);
  110. int indexB = string_toInteger(tokens[tokenIndex + 1]);
  111. int indexC = string_toInteger(tokens[tokenIndex + 2]);
  112. int indexD = string_toInteger(tokens[tokenIndex + 3]);
  113. FVector4D colorA = vertices[indexA].color;
  114. FVector4D colorB = vertices[indexB].color;
  115. FVector4D colorC = vertices[indexC].color;
  116. FVector4D colorD = vertices[indexD].color;
  117. if (flipSides) {
  118. int polygon = model_addQuad(targetModel, targetPart,
  119. startPointIndex + indexD,
  120. startPointIndex + indexC,
  121. startPointIndex + indexB,
  122. startPointIndex + indexA
  123. );
  124. model_setVertexColor(targetModel, targetPart, polygon, 0, colorD);
  125. model_setVertexColor(targetModel, targetPart, polygon, 1, colorC);
  126. model_setVertexColor(targetModel, targetPart, polygon, 2, colorB);
  127. model_setVertexColor(targetModel, targetPart, polygon, 3, colorA);
  128. } else {
  129. int polygon = model_addQuad(targetModel, targetPart,
  130. startPointIndex + indexA,
  131. startPointIndex + indexB,
  132. startPointIndex + indexC,
  133. startPointIndex + indexD
  134. );
  135. model_setVertexColor(targetModel, targetPart, polygon, 0, colorA);
  136. model_setVertexColor(targetModel, targetPart, polygon, 1, colorB);
  137. model_setVertexColor(targetModel, targetPart, polygon, 2, colorC);
  138. model_setVertexColor(targetModel, targetPart, polygon, 3, colorD);
  139. }
  140. } else {
  141. // Polygon generating a triangle fan
  142. int indexA = string_toInteger(tokens[tokenIndex]);
  143. int indexB = string_toInteger(tokens[tokenIndex + 1]);
  144. FVector4D colorA = vertices[indexA].color;
  145. FVector4D colorB = vertices[indexB].color;
  146. for (int i = 2; i < listLength; i++) {
  147. int indexC = string_toInteger(tokens[tokenIndex + i]);
  148. FVector4D colorC = vertices[indexC].color;
  149. // Create a triangle
  150. if (flipSides) {
  151. int polygon = model_addTriangle(targetModel, targetPart,
  152. startPointIndex + indexC,
  153. startPointIndex + indexB,
  154. startPointIndex + indexA
  155. );
  156. model_setVertexColor(targetModel, targetPart, polygon, 0, colorC);
  157. model_setVertexColor(targetModel, targetPart, polygon, 1, colorB);
  158. model_setVertexColor(targetModel, targetPart, polygon, 2, colorA);
  159. } else {
  160. int polygon = model_addTriangle(targetModel, targetPart,
  161. startPointIndex + indexA,
  162. startPointIndex + indexB,
  163. startPointIndex + indexC
  164. );
  165. model_setVertexColor(targetModel, targetPart, polygon, 0, colorA);
  166. model_setVertexColor(targetModel, targetPart, polygon, 1, colorB);
  167. model_setVertexColor(targetModel, targetPart, polygon, 2, colorC);
  168. }
  169. // Iterate the triangle fan
  170. indexB = indexC;
  171. colorB = colorC;
  172. }
  173. }
  174. }
  175. tokenIndex += listLength;
  176. } else {
  177. // Detect vertex data
  178. if (inputMode == PlyDataInput::Vertex) {
  179. float value = string_toDouble(tokens[tokenIndex]) / (double)currentProperty->scale;
  180. // Swap X, Y and Z to convert from PLY coordinates
  181. if (string_caseInsensitiveMatch(currentProperty->name, U"X")) {
  182. if (flipX) {
  183. value = -value; // Right-handed to left-handed conversion
  184. }
  185. vertices[vertices.length() - 1].position.x = value;
  186. } else if (string_caseInsensitiveMatch(currentProperty->name, U"Y")) {
  187. vertices[vertices.length() - 1].position.y = value;
  188. } else if (string_caseInsensitiveMatch(currentProperty->name, U"Z")) {
  189. vertices[vertices.length() - 1].position.z = value;
  190. } else if (string_caseInsensitiveMatch(currentProperty->name, U"RED")) {
  191. vertices[vertices.length() - 1].color.x = value;
  192. } else if (string_caseInsensitiveMatch(currentProperty->name, U"GREEN")) {
  193. vertices[vertices.length() - 1].color.y = value;
  194. } else if (string_caseInsensitiveMatch(currentProperty->name, U"BLUE")) {
  195. vertices[vertices.length() - 1].color.z = value;
  196. } else if (string_caseInsensitiveMatch(currentProperty->name, U"ALPHA")) {
  197. vertices[vertices.length() - 1].color.w = value;
  198. }
  199. }
  200. }
  201. // Count one for a list size or single property
  202. tokenIndex++;
  203. }
  204. // Complete the vertex
  205. if (inputMode == PlyDataInput::Vertex) {
  206. FVector3D localPosition = vertices[vertices.length() - 1].position;
  207. model_addPoint(targetModel, axisConversion.transformPoint(localPosition));
  208. }
  209. }
  210. memberIndex++;
  211. if (memberIndex >= elements[elementIndex].count) {
  212. // Done with the element
  213. elementIndex++;
  214. memberIndex = 0;
  215. if (elementIndex >= elements.length()) {
  216. // Done with the file
  217. if (l < lines.length() - 1) {
  218. // Remaining lines will be ignored with a warning
  219. printText("loadPlyModel: Ignored ", (lines.length() - 1) - l, " undeclared lines at file end!\n");
  220. }
  221. return;
  222. } else {
  223. // Identify the next element by name
  224. inputMode = PlyDataInputFromName(elements[elementIndex].name);
  225. }
  226. }
  227. } else {
  228. if (tokens.length() == 1) {
  229. if (string_caseInsensitiveMatch(tokens[0], U"END_HEADER")) {
  230. readingContent = true;
  231. elementIndex = 0;
  232. memberIndex = 0;
  233. if (elements.length() < 2) {
  234. printText("loadPlyModel: Need at least two elements to defined faces and vertices in the model!\n");
  235. return;
  236. }
  237. // Identify the first element by name
  238. inputMode = PlyDataInputFromName(elements[elementIndex].name);
  239. }
  240. } else if (tokens.length() >= 3) {
  241. if (string_caseInsensitiveMatch(tokens[0], U"ELEMENT")) {
  242. elements.push(PlyElement(tokens[1], string_toInteger(tokens[2])));
  243. elementIndex = elements.length() - 1;
  244. } else if (string_caseInsensitiveMatch(tokens[0], U"PROPERTY")) {
  245. if (elementIndex < 0) {
  246. printText("loadPlyModel: Cannot declare a property without an element!\n");
  247. } else if (readingContent) {
  248. printText("loadPlyModel: Cannot declare a property outside of the header!\n");
  249. } else {
  250. if (tokens.length() == 3) {
  251. // Single property
  252. elements[elementIndex].properties.push(PlyProperty(tokens[2], tokens[1]));
  253. } else if (tokens.length() == 5 && string_caseInsensitiveMatch(tokens[1], U"LIST")) {
  254. // Integer followed by that number of properties as a list
  255. elements[elementIndex].properties.push(PlyProperty(tokens[4], tokens[3], tokens[2]));
  256. } else {
  257. printText("loadPlyModel: Unable to parse property!\n");
  258. return;
  259. }
  260. }
  261. }
  262. }
  263. }
  264. }
  265. }
  266. }
  267. void importer_loadModel(Model& targetModel, int part, const ReadableString& filename, bool flipX, Transform3D axisConversion) {
  268. int lastDotIndex = string_findLast(filename, U'.');
  269. if (lastDotIndex == -1) {
  270. printText("The model's filename ", filename, " does not have an extension!\n");
  271. } else {
  272. ReadableString extension = string_after(filename, lastDotIndex);
  273. if (string_caseInsensitiveMatch(extension, U"PLY")) {
  274. // Store the whole model file in a string for fast reading
  275. String content = string_load(filename);
  276. // Parse the file from the string
  277. loadPlyModel(targetModel, part, content, flipX, axisConversion);
  278. } else {
  279. printText("The extension ", extension, " in ", filename, " is not yet supported! You can implement an importer and call it from the loadModel function in tool.cpp.\n");
  280. }
  281. }
  282. }
  283. Model importer_loadModel(const ReadableString& filename, bool flipX, Transform3D axisConversion) {
  284. Model result = model_create();
  285. model_addEmptyPart(result, U"Imported");
  286. importer_loadModel(result, 0, filename, flipX, axisConversion);
  287. return result;
  288. }
  289. }