tool.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #include <assert.h>
  2. #include <limits>
  3. #include <functional>
  4. #include "../../DFPSR/includeFramework.h"
  5. #include "sprite/spriteAPI.h"
  6. #include "sprite/importer.h"
  7. using namespace dsr;
  8. static constexpr float colorScale = 1.0f / 255.0f;
  9. static FVector4D pixelToVertexColor(const ColorRgbaI32& color) {
  10. return FVector4D(color.red * colorScale, color.green * colorScale, color.blue * colorScale, 1.0f);
  11. }
  12. static int createTriangle(Model& model, int part, int indexA, int indexB, int indexC, FVector4D colorA, FVector4D colorB, FVector4D colorC, bool flip = false) {
  13. if (flip) {
  14. int poly = model_addTriangle(model, part, indexB, indexA, indexC);
  15. model_setVertexColor(model, part, poly, 0, colorB);
  16. model_setVertexColor(model, part, poly, 1, colorA);
  17. model_setVertexColor(model, part, poly, 2, colorC);
  18. return poly;
  19. } else {
  20. int poly = model_addTriangle(model, part, indexA, indexB, indexC);
  21. model_setVertexColor(model, part, poly, 0, colorA);
  22. model_setVertexColor(model, part, poly, 1, colorB);
  23. model_setVertexColor(model, part, poly, 2, colorC);
  24. return poly;
  25. }
  26. }
  27. using TransformFunction = std::function<FVector3D(int pixelX, int pixelY, int displacement)>;
  28. // Returns the start point index for another side to weld against
  29. int createGridSide(Model& model, int part, const ImageU8& heightMap, const ImageRgbaU8& colorMap,
  30. const TransformFunction& transform, bool clipZero, bool mergeSides, bool flipDepth = false, bool flipFaces = false, int otherStartPointIndex = -1) {
  31. int startPointIndex = model_getNumberOfPoints(model);
  32. int mapWidth = image_getWidth(heightMap);
  33. int mapHeight = image_getHeight(heightMap);
  34. int flipScale = flipDepth ? -1 : 1;
  35. int columns = mergeSides ? mapWidth + 1 : mapWidth;
  36. // Create a part for the polygons
  37. for (int z = 0; z < mapHeight; z++) {
  38. for (int x = 0; x < columns; x++) {
  39. // Sample the height map and convert to world space
  40. int cx = x % mapWidth;
  41. int heightC = image_readPixel_border(heightMap, cx, z);
  42. // Add the point to the model
  43. if (x < mapWidth) {
  44. // Create a position from the 3D index
  45. model_addPoint(model, transform(x, z, heightC * flipScale));
  46. }
  47. if (x > 0 && z > 0) {
  48. // Create vertex data
  49. // A-B
  50. // |
  51. // D-C
  52. int px = x - 1;
  53. int cz = z;
  54. int pz = z - 1;
  55. // Sample previous heights
  56. int heightA = image_readPixel_border(heightMap, px, pz);
  57. int heightB = image_readPixel_border(heightMap, cx, pz);
  58. int heightD = image_readPixel_border(heightMap, px, cz);
  59. // Tell where to weld with another side's points
  60. bool weldA = otherStartPointIndex > -1 && heightA == 0;
  61. bool weldB = otherStartPointIndex > -1 && heightB == 0;
  62. bool weldC = otherStartPointIndex > -1 && heightC == 0;
  63. bool weldD = otherStartPointIndex > -1 && heightD == 0;
  64. // Get indices to points
  65. int indexA = (weldA ? otherStartPointIndex : startPointIndex) + px + pz * mapWidth;
  66. int indexB = (weldB ? otherStartPointIndex : startPointIndex) + cx + pz * mapWidth;
  67. int indexC = (weldC ? otherStartPointIndex : startPointIndex) + cx + cz * mapWidth;
  68. int indexD = (weldD ? otherStartPointIndex : startPointIndex) + px + cz * mapWidth;
  69. // Sample colors
  70. FVector4D colorA = pixelToVertexColor(image_readPixel_tile(colorMap, px, pz));
  71. FVector4D colorB = pixelToVertexColor(image_readPixel_tile(colorMap, cx, pz));
  72. FVector4D colorC = pixelToVertexColor(image_readPixel_tile(colorMap, cx, cz));
  73. FVector4D colorD = pixelToVertexColor(image_readPixel_tile(colorMap, px, cz));
  74. // Decide how to split triangles and which ones to display
  75. bool acSplit = false;
  76. bool skipFirst = false;
  77. bool skipSecond = false;
  78. if (heightA == 0 && heightC == 0) {
  79. // ABCD fan of ABC and ACD
  80. acSplit = true;
  81. if (heightB == 0) { skipFirst = true; }
  82. if (heightD == 0) { skipSecond = true; }
  83. } else if (heightB == 0 && heightD == 0) {
  84. // BCDA fan of ACD and BDA
  85. acSplit = false;
  86. if (heightC == 0) { skipFirst = true; }
  87. if (heightA == 0) { skipSecond = true; }
  88. } else {
  89. int cA = image_readPixel_tile(heightMap, cx - 2, cz - 2);
  90. int cB = image_readPixel_tile(heightMap, cx + 1, cz - 2);
  91. int cC = image_readPixel_tile(heightMap, cx + 1, cz + 1);
  92. int cD = image_readPixel_tile(heightMap, cx - 2, cz + 1);
  93. int diffAC = abs((cA + cC) - (heightA + heightC));
  94. int diffBD = abs((cB + cD) - (heightB + heightD));
  95. acSplit = diffBD > diffAC;
  96. }
  97. if (!clipZero) {
  98. skipFirst = false;
  99. skipSecond = false;
  100. }
  101. // Create a polygon
  102. if (!(skipFirst && skipSecond)) {
  103. if (acSplit) {
  104. if (!skipFirst) {
  105. createTriangle(model, part,
  106. indexA, indexB, indexC,
  107. colorA, colorB, colorC, flipFaces
  108. );
  109. }
  110. if (!skipSecond) {
  111. createTriangle(model, part,
  112. indexA, indexC, indexD,
  113. colorA, colorC, colorD, flipFaces
  114. );
  115. }
  116. } else {
  117. if (!skipFirst) {
  118. createTriangle(model, part,
  119. indexB, indexC, indexD,
  120. colorB, colorC, colorD, flipFaces
  121. );
  122. }
  123. if (!skipSecond) {
  124. createTriangle(model, part,
  125. indexB, indexD, indexA,
  126. colorB, colorD, colorA, flipFaces
  127. );
  128. }
  129. }
  130. }
  131. }
  132. }
  133. }
  134. return startPointIndex;
  135. }
  136. // clipZero:
  137. // Removing triangles from pixels with displacement zero.
  138. // Used for carving out non-square shapes using black height as the background.
  139. // mergeSides:
  140. // Connect vertices from the left side of the image with the right side using additional polygons.
  141. // Used for cylinder shapes to remove the seam where the sides meet.
  142. // mirror:
  143. // Create another instance of the height field with surfaces and displacement turned in the other direction.
  144. // weldNormals:
  145. // Merges normals between mirrored sides to let normals at displacement zero merge with the other side.
  146. // mirror must be active for this to have an effect, because there's no mirrored side to weld against otherwise.
  147. // clipZero must be active to hide polygons without a normal. (What is the average direction of two opposing planes?)
  148. void createGrid(Model& model, int part, const ImageU8& heightMap, const ImageRgbaU8& colorMap,
  149. const TransformFunction& transform, bool clipZero, bool mergeSides, bool mirror, bool weldNormals) {
  150. if (weldNormals && !mirror) {
  151. printText("\n Warning! Cannot weld normals without a mirrored side. The \"weldNormals\" will be ignored because \"mirror\" was not active.\n\n");
  152. weldNormals = false;
  153. }
  154. if (weldNormals && !clipZero) {
  155. printText("\n Warning! Cannot weld normals without clipping zero displacement. The \"weldNormals\" will be ignored because \"clipZero\" was not active.\n\n");
  156. weldNormals = false;
  157. }
  158. // Generate primary side
  159. int otherStartPointIndex = createGridSide(model, part, heightMap, colorMap, transform, clipZero, mergeSides);
  160. // Generate additional mirrored side
  161. if (mirror) {
  162. createGridSide(model, part, heightMap, colorMap, transform, clipZero, mergeSides, true, true, weldNormals ? otherStartPointIndex : -1);
  163. }
  164. }
  165. // The part of ParserState that resets when creating a new part but is kept after generating geometry
  166. struct PartSettings {
  167. Transform3D location;
  168. float displacement = 1.0f, patchWidth = 1.0f, patchHeight = 1.0f, radius = 0.0f;
  169. int clipZero = 0; // 1 will cut away displacements from height zero, 0 will try to display all polygons
  170. int mirror = 0; // 1 will let height fields generate polygons on both sides to create solid shapes
  171. PartSettings() {}
  172. };
  173. struct ParserState {
  174. String sourcePath;
  175. int angles = 4;
  176. Model model, shadow;
  177. int part = -1; // Current part index for model (No index used for shadows)
  178. PartSettings partSettings;
  179. explicit ParserState(const String& sourcePath) : sourcePath(sourcePath), model(model_create()), shadow(model_create()) {
  180. model_addEmptyPart(this->shadow, U"shadow");
  181. }
  182. };
  183. static void parse_scope(ParserState& state, const ReadableString& key) {
  184. // End the previous scope
  185. state.partSettings = PartSettings();
  186. state.part = -1;
  187. if (string_caseInsensitiveMatch(key, U"PART")) {
  188. // Enter a new part's scope
  189. printText(" New part begins\n");
  190. state.part = model_addEmptyPart(state.model, U"part");
  191. } else {
  192. printText(" Unrecognized scope ", key, " within <>.\n");
  193. }
  194. }
  195. #define MATCH_ASSIGN_GLOBAL(NAME,ACCESS,PARSER,DESCRIPTION) \
  196. if (string_caseInsensitiveMatch(key, NAME)) { \
  197. ACCESS = PARSER(value); \
  198. printText(" ", #DESCRIPTION, " = ", ACCESS, "\n"); \
  199. }
  200. #define MATCH_ASSIGN(BLOCK,NAME,ACCESS,PARSER,DESCRIPTION) \
  201. if (string_caseInsensitiveMatch(key, NAME)) { \
  202. if (state.BLOCK == -1) { \
  203. printText(" Cannot assign ", DESCRIPTION, " without a ", #BLOCK, ".\n"); \
  204. } else { \
  205. ACCESS = PARSER(value); \
  206. printText(" ", #DESCRIPTION, " = ", ACCESS, "\n"); \
  207. } \
  208. }
  209. static void parse_assignment(ParserState& state, const ReadableString& key, const ReadableString& value) {
  210. MATCH_ASSIGN_GLOBAL(U"Angles", state.angles, string_toInteger, "camera angle count")
  211. else MATCH_ASSIGN(part, U"Origin", state.partSettings.location.position, parseFVector3D, "origin")
  212. else MATCH_ASSIGN(part, U"XAxis", state.partSettings.location.transform.xAxis, parseFVector3D, "X-Axis")
  213. else MATCH_ASSIGN(part, U"YAxis", state.partSettings.location.transform.yAxis, parseFVector3D, "Y-Axis")
  214. else MATCH_ASSIGN(part, U"ZAxis", state.partSettings.location.transform.zAxis, parseFVector3D, "Z-Axis")
  215. else MATCH_ASSIGN(part, U"Displacement", state.partSettings.displacement, string_toDouble, "displacement")
  216. else MATCH_ASSIGN(part, U"ClipZero", state.partSettings.clipZero, string_toInteger, "zero clipping")
  217. else MATCH_ASSIGN(part, U"Mirror", state.partSettings.mirror, string_toInteger, "mirror flag")
  218. else MATCH_ASSIGN(part, U"PatchWidth", state.partSettings.patchWidth, string_toDouble, "patch width")
  219. else MATCH_ASSIGN(part, U"PatchHeight", state.partSettings.patchHeight, string_toDouble, "patch height")
  220. else MATCH_ASSIGN(part, U"Radius", state.partSettings.radius, string_toDouble, "radius")
  221. else {
  222. printText(" Tried to assign ", value, " to unrecognized key ", key, ".\n");
  223. }
  224. }
  225. enum class Shape {
  226. None, Plane, Box, Cylinder, LeftHandedModel, RightHandedModel
  227. };
  228. static Shape ShapeFromName(const ReadableString& name) {
  229. if (string_caseInsensitiveMatch(name, U"PLANE")) {
  230. return Shape::Plane;
  231. } else if (string_caseInsensitiveMatch(name, U"BOX")) {
  232. return Shape::Box;
  233. } else if (string_caseInsensitiveMatch(name, U"CYLINDER")) {
  234. return Shape::Cylinder;
  235. } else if (string_caseInsensitiveMatch(name, U"LEFTHANDEDMODEL")) {
  236. return Shape::LeftHandedModel;
  237. } else if (string_caseInsensitiveMatch(name, U"RIGHTHANDEDMODEL")) {
  238. return Shape::RightHandedModel;
  239. } else {
  240. throwError("Unhandled shape \"", name, "\"!\n");
  241. return Shape::None;
  242. }
  243. }
  244. static String nameOfShape(Shape shape) {
  245. if (shape == Shape::None) {
  246. return U"None";
  247. } else if (shape == Shape::Plane) {
  248. return U"Plane";
  249. } else if (shape == Shape::Box) {
  250. return U"Box";
  251. } else if (shape == Shape::Cylinder) {
  252. return U"Cylinder";
  253. } else if (shape == Shape::LeftHandedModel) {
  254. return U"LeftHandedModel";
  255. } else if (shape == Shape::RightHandedModel) {
  256. return U"RightHandedModel";
  257. } else {
  258. return U"?";
  259. }
  260. }
  261. // TODO: Arguments for repeating the input images so that pillars can reuse textures for multiple sides when only one camera angle will be saved
  262. static void generateField(ParserState& state, Shape shape, const ImageU8& heightMap, const ImageRgbaU8& colorMap, bool shadow) {
  263. Transform3D system = state.partSettings.location;
  264. bool clipZero = state.partSettings.clipZero;
  265. float offsetPerUnit = state.partSettings.displacement / 255.0f;
  266. bool mirror = state.partSettings.mirror != 0;
  267. bool mergeSides = shape == Shape::Cylinder;
  268. bool weldNormals = mirror && clipZero;
  269. // Create a transform function based on the shape
  270. TransformFunction transform;
  271. if (shape == Shape::Plane) {
  272. // PatchWidth along local X
  273. // PatchHeight along local Z
  274. // Displacement along local Y
  275. float widthScale = state.partSettings.patchWidth / (image_getWidth(heightMap) - 1);
  276. float heightScale = state.partSettings.patchHeight / -(image_getHeight(heightMap) - 1);
  277. FVector3D localScaling = FVector3D(widthScale, offsetPerUnit, heightScale);
  278. FVector3D localOrigin = FVector3D(state.partSettings.patchWidth * -0.5f, 0.0f, state.partSettings.patchHeight * 0.5f);
  279. transform = [system, localOrigin, localScaling](int pixelX, int pixelY, int displacement){
  280. return system.transformPoint(localOrigin + (FVector3D(pixelX, displacement, pixelY) * localScaling));
  281. };
  282. } else if (shape == Shape::Cylinder) {
  283. // Radius + Displacement along local X, Z
  284. // PatchHeight along local Y
  285. float radius = state.partSettings.radius;
  286. float angleScale = 6.283185307f / image_getWidth(heightMap);
  287. float angleOffset = angleScale * 0.5f; // Start and end half a pixel from the seam
  288. float heightScale = state.partSettings.patchHeight / -(image_getHeight(heightMap) - 1);
  289. float heightOffset = state.partSettings.patchHeight * 0.5f;
  290. int lastRow = image_getHeight(heightMap) - 1;
  291. bool fillHoles = !mirror && !clipZero; // Automatically fill the holes to close the shape when not mirroring nor clipping the sides
  292. transform = [system, angleOffset, angleScale, heightOffset, heightScale, radius, offsetPerUnit, fillHoles, lastRow](int pixelX, int pixelY, int displacement){
  293. float angle = ((float)pixelX * angleScale) + angleOffset;
  294. float offset = ((float)displacement * offsetPerUnit) + radius;
  295. float height = ((float)pixelY * heightScale) + heightOffset;
  296. if (fillHoles && (pixelY == 0 || pixelY == lastRow)) {
  297. offset = 0.0f;
  298. }
  299. return system.transformPoint(FVector3D(-sin(angle) * offset, height, cos(angle) * offset));
  300. };
  301. } else {
  302. printText("Field generation is not implemented for ", nameOfShape(shape), "!\n");
  303. return;
  304. }
  305. if (shadow) {
  306. createGrid(state.shadow, 0, heightMap, colorMap, transform, clipZero, mergeSides, mirror, weldNormals);
  307. } else {
  308. createGrid(state.model, state.part, heightMap, colorMap, transform, clipZero, mergeSides, mirror, weldNormals);
  309. }
  310. }
  311. static void generateBasicShape(ParserState& state, Shape shape, const ReadableString& arg1, const ReadableString& arg2, const ReadableString& arg3, bool shadow) {
  312. Transform3D system = state.partSettings.location;
  313. Model model = shadow ? state.shadow : state.model;
  314. int part = shadow ? 0 : state.part;
  315. // All shapes are centered around the axis system's origin from -0.5 to +0.5 of any given size
  316. if (shape == Shape::Box) {
  317. // Parse arguments
  318. float width = string_toDouble(arg1);
  319. float height = string_toDouble(arg2);
  320. float depth = string_toDouble(arg3);
  321. // Create a bound
  322. FVector3D upper = FVector3D(width, height, depth) * 0.5f;
  323. FVector3D lower = -upper;
  324. // Positions
  325. int first = model_getNumberOfPoints(model);
  326. model_addPoint(model, system.transformPoint(FVector3D(lower.x, lower.y, lower.z))); // first + 0: Left-down-near
  327. model_addPoint(model, system.transformPoint(FVector3D(lower.x, lower.y, upper.z))); // first + 1: Left-down-far
  328. model_addPoint(model, system.transformPoint(FVector3D(lower.x, upper.y, lower.z))); // first + 2: Left-up-near
  329. model_addPoint(model, system.transformPoint(FVector3D(lower.x, upper.y, upper.z))); // first + 3: Left-up-far
  330. model_addPoint(model, system.transformPoint(FVector3D(upper.x, lower.y, lower.z))); // first + 4: Right-down-near
  331. model_addPoint(model, system.transformPoint(FVector3D(upper.x, lower.y, upper.z))); // first + 5: Right-down-far
  332. model_addPoint(model, system.transformPoint(FVector3D(upper.x, upper.y, lower.z))); // first + 6: Right-up-near
  333. model_addPoint(model, system.transformPoint(FVector3D(upper.x, upper.y, upper.z))); // first + 7: Right-up-far
  334. // Polygons
  335. model_addQuad(model, part, first + 3, first + 2, first + 0, first + 1); // Left quad
  336. model_addQuad(model, part, first + 6, first + 7, first + 5, first + 4); // Right quad
  337. model_addQuad(model, part, first + 2, first + 6, first + 4, first + 0); // Front quad
  338. model_addQuad(model, part, first + 7, first + 3, first + 1, first + 5); // Back quad
  339. model_addQuad(model, part, first + 3, first + 7, first + 6, first + 2); // Top quad
  340. model_addQuad(model, part, first + 0, first + 4, first + 5, first + 1); // Bottom quad
  341. } else if (shape == Shape::Cylinder) {
  342. // Parse arguments
  343. float radius = string_toDouble(arg1);
  344. float height = string_toDouble(arg2);
  345. int sideCount = string_toDouble(arg3);
  346. // Create a bound
  347. float topHeight = height * 0.5f;
  348. float bottomHeight = height * -0.5f;
  349. // Positions
  350. float angleScale = 6.283185307 / (float)sideCount;
  351. int centerTop = model_addPoint(model, system.transformPoint(FVector3D(0.0f, topHeight, 0.0f)));
  352. int firstTopSide = model_getNumberOfPoints(model);
  353. for (int p = 0; p < sideCount; p++) {
  354. float radians = p * angleScale;
  355. model_addPoint(model, system.transformPoint(FVector3D(sin(radians) * radius, topHeight, cos(radians) * radius)));
  356. }
  357. int centerBottom = model_addPoint(model, system.transformPoint(FVector3D(0.0f, bottomHeight, 0.0f)));
  358. int firstBottomSide = model_getNumberOfPoints(model);
  359. for (int p = 0; p < sideCount; p++) {
  360. float radians = p * angleScale;
  361. model_addPoint(model, system.transformPoint(FVector3D(sin(radians) * radius, bottomHeight, cos(radians) * radius)));
  362. }
  363. for (int p = 0; p < sideCount; p++) {
  364. int q = (p + 1) % sideCount;
  365. // Top fan
  366. model_addTriangle(model, part, centerTop, firstTopSide + p, firstTopSide + q);
  367. // Bottom fan
  368. model_addTriangle(model, part, centerBottom, firstBottomSide + q, firstBottomSide + p);
  369. // Side
  370. model_addQuad(model, part, firstTopSide + q, firstTopSide + p, firstBottomSide + p, firstBottomSide + q);
  371. }
  372. } else {
  373. printText("Basic shape generation is not implemented for ", nameOfShape(shape), "!\n");
  374. return;
  375. }
  376. }
  377. // Used when displaying shadow models for debugging
  378. static ImageRgbaU8 createDebugTexture() {
  379. ImageRgbaU8 result = image_create_RgbaU8(2, 2);
  380. image_writePixel(result, 0, 0, ColorRgbaI32(255, 0, 0, 255));
  381. image_writePixel(result, 1, 0, ColorRgbaI32(0, 255, 0, 255));
  382. image_writePixel(result, 0, 1, ColorRgbaI32(0, 0, 255, 255));
  383. image_writePixel(result, 1, 1, ColorRgbaI32(255, 255, 0, 255));
  384. return result;
  385. }
  386. ImageRgbaU8 debugTexture = createDebugTexture();
  387. static void parse_shape(ParserState& state, List<String>& args, bool shadow) {
  388. if (state.part == -1) {
  389. printText(" Cannot generate a ", args[0], " without a part.\n");
  390. }
  391. Shape shape = ShapeFromName(args[0]);
  392. if (shape == Shape::LeftHandedModel || shape == Shape::RightHandedModel) {
  393. if (args.length() > 2) {
  394. printText(" Too many arguments when trying to load a model. Just give one file name without spaces.\n");
  395. } else if (args.length() < 2) {
  396. printText(" Loading a model requires a filename.\n");
  397. } else {
  398. bool flipX = (shape == Shape::RightHandedModel);
  399. Model targetModel = shadow ? state.shadow : state.model;
  400. int targetPart = shadow ? 0 : state.part;
  401. importer_loadModel(targetModel, targetPart, string_combine(state.sourcePath, args[1]), flipX, state.partSettings.location);
  402. }
  403. } else if (args.length() == 2) {
  404. // Shape, HeightMap
  405. ImageU8 heightMap = image_get_red(image_load_RgbaU8(state.sourcePath + args[1]));
  406. generateField(state, shape, heightMap, debugTexture, shadow);
  407. } else if (args.length() == 3) {
  408. // Shape, HeightMap, ColorMap
  409. ImageU8 heightMap = image_get_red(image_load_RgbaU8(state.sourcePath + args[1]));
  410. ImageRgbaU8 colorMap = image_load_RgbaU8(state.sourcePath + args[2]);
  411. generateField(state, shape, heightMap, colorMap, shadow);
  412. } else if (args.length() == 4) {
  413. // Shape, Width, Height, Depth
  414. generateBasicShape(state, shape, args[1], args[2], args[3], shadow);
  415. } else {
  416. printText(" The ", args[0], " shape needs at least a height map to know the number of vertices to generate. A color map can also be given.\n");
  417. }
  418. }
  419. static void parse_dsm(ParserState& state, const ReadableString& content) {
  420. List<String> lines = string_split(content, U'\n');
  421. for (int l = 0; l < lines.length(); l++) {
  422. // Get the current line
  423. ReadableString line = lines[l];
  424. // Skip comments
  425. int commentIndex = string_findFirst(line, U';');
  426. if (commentIndex > -1) {
  427. line = string_removeOuterWhiteSpace(string_before(line, commentIndex));
  428. }
  429. if (string_length(line) > 0) {
  430. // Find assignments
  431. int assignmentIndex = string_findFirst(line, U'=');
  432. int colonIndex = string_findFirst(line, U':');
  433. int blockStartIndex = string_findFirst(line, U'<');
  434. int blockEndIndex = string_findFirst(line, U'>');
  435. if (assignmentIndex > -1) {
  436. ReadableString key = string_removeOuterWhiteSpace(string_before(line, assignmentIndex));
  437. ReadableString value = string_removeOuterWhiteSpace(string_after(line, assignmentIndex));
  438. parse_assignment(state, key, value);
  439. } else if (colonIndex > -1) {
  440. ReadableString command = string_removeOuterWhiteSpace(string_before(line, colonIndex));
  441. ReadableString argContent = string_after(line, colonIndex);
  442. List<String> args = string_split(argContent, U',');
  443. for (int a = 0; a < args.length(); a++) {
  444. args[a] = string_removeOuterWhiteSpace(args[a]);
  445. }
  446. if (string_caseInsensitiveMatch(command, U"Visible")) {
  447. parse_shape(state, args, false);
  448. } else if (string_caseInsensitiveMatch(command, U"Shadow")) {
  449. parse_shape(state, args, true);
  450. } else {
  451. printText(" Unrecognized command ", command, ".\n");
  452. }
  453. } else if (blockStartIndex > -1 && blockEndIndex > -1) {
  454. String block = string_removeOuterWhiteSpace(string_inclusiveRange(line, blockStartIndex + 1, blockEndIndex - 1));
  455. parse_scope(state, block);
  456. } else {
  457. printText("Unrecognized content \"", line, "\" on line ", l + 1, ".\n");
  458. }
  459. }
  460. }
  461. }
  462. void processScript(const String& sourcePath, const String& targetPath, OrthoSystem ortho, const String& scriptName) {
  463. // Initialize a parser state containing an empty model
  464. ParserState state = ParserState(sourcePath);
  465. // Parse the script to fill the state with a model and additional render settings
  466. String scriptPath = string_combine(state.sourcePath, scriptName, U".dsm");
  467. printText("Generating ", scriptPath, "\n");
  468. parse_dsm(state, string_load(scriptPath));
  469. // Render the model
  470. sprite_generateFromModel(state.model, state.shadow, ortho, targetPath + scriptName, state.angles, false);
  471. }
  472. // The first argument is the source folder in which the model scripts are stored.
  473. // The second argument is the target folder in which the results are saved.
  474. // The third argument is the ortho configuration file path.
  475. // The following arguments are plain names of the scripts to process without any path nor extension.
  476. void tool_main(int argn, char **argv) {
  477. if (argn < 5) {
  478. printText("Nothing to process. Terminating sprite generation tool.\n");
  479. } else {
  480. String sourcePath = string_combine(argv[1], file_separator());
  481. String targetPath = string_combine(argv[2], file_separator());
  482. OrthoSystem ortho = OrthoSystem(string_load(String(argv[3])));
  483. for (int a = 4; a < argn; a++) {
  484. processScript(sourcePath, targetPath, ortho, String(argv[a]));
  485. }
  486. }
  487. }