importer.cpp 13 KB

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