Heightmap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #include "Heightmap.h"
  2. #include "GPBFile.h"
  3. #include "Thread.h"
  4. namespace gameplay
  5. {
  6. // Number of threads to spawn for the heightmap generator
  7. #define THREAD_COUNT 8
  8. // Thread data structure
  9. struct HeightmapThreadData
  10. {
  11. float rayHeight; // [in]
  12. const Vector3* rayDirection; // [in]
  13. const std::vector<Mesh*>* meshes; // [in]
  14. const BoundingVolume* bounds; // [in]
  15. int minX; // [in]
  16. int maxX; // [in]
  17. int minZ; // [in]
  18. int maxZ; // [in]
  19. float minHeight; // [out]
  20. float maxHeight; // [out]
  21. float* heights; // [in][out]
  22. int heightIndex; // [in]
  23. };
  24. // Globals used by thread
  25. int __processedHeightmapScanLines = 0;
  26. int __totalHeightmapScanlines = 0;
  27. int __failedRayCasts = 0;
  28. // Forward declarations
  29. int generateHeightmapChunk(void* threadData);
  30. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const Vector3& boxMin, const Vector3& boxMax, float* distance = NULL);
  31. int intersect_triangle(const float orig[3], const float dir[3], const float vert0[3], const float vert1[3], const float vert2[3], float *t, float *u, float *v);
  32. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const std::vector<Vertex>& vertices, const std::vector<MeshPart*>& parts, Vector3* point);
  33. void Heightmap::generate(const std::vector<std::string>& nodeIds, const char* filename, bool highP)
  34. {
  35. LOG(1, "Generating heightmap: %s...\n", filename);
  36. // Initialize state variables
  37. __processedHeightmapScanLines = 0;
  38. __totalHeightmapScanlines = 0;
  39. __failedRayCasts = 0;
  40. GPBFile* gpbFile = GPBFile::getInstance();
  41. // Lookup nodes in GPB file and compute a single bounding volume that encapsulates all meshes
  42. // to be included in the heightmap generation.
  43. BoundingVolume bounds;
  44. bounds.min.set(FLT_MAX, FLT_MAX, FLT_MAX);
  45. bounds.max.set(-FLT_MAX, -FLT_MAX, -FLT_MAX);
  46. std::vector<Mesh*> meshes;
  47. for (unsigned int j = 0, ncount = nodeIds.size(); j < ncount; ++j)
  48. {
  49. Node* node = gpbFile->getNode(nodeIds[j].c_str());
  50. if (node)
  51. {
  52. Mesh* mesh = node->getModel() ? node->getModel()->getMesh() : NULL;
  53. if (mesh)
  54. {
  55. // Add this mesh and update our bounding volume
  56. if (meshes.size() == 0)
  57. bounds = mesh->bounds;
  58. else
  59. bounds.merge(mesh->bounds);
  60. meshes.push_back(mesh);
  61. }
  62. else
  63. {
  64. LOG(1, "WARNING: Node passed to heightmap argument does not have a mesh: %s\n", nodeIds[j].c_str());
  65. }
  66. }
  67. else
  68. {
  69. LOG(1, "WARNING: Failed to locate node for heightmap argument: %s\n", nodeIds[j].c_str());
  70. }
  71. }
  72. if (meshes.size() == 0)
  73. {
  74. LOG(1, "WARNING: Skipping generation of heightmap '%s'. No nodes found.\n", filename);
  75. return;
  76. }
  77. // Shoot rays down from a point just above the max Y position of the mesh.
  78. // Compute ray-triangle intersection tests against the ray and this mesh to
  79. // generate heightmap data.
  80. Vector3 rayOrigin(0, bounds.max.y + 10, 0);
  81. Vector3 rayDirection(0, -1, 0);
  82. int minX = (int)ceil(bounds.min.x);
  83. int maxX = (int)floor(bounds.max.x);
  84. int minZ = (int)ceil(bounds.min.z);
  85. int maxZ = (int)floor(bounds.max.z);
  86. int width = maxX - minX + 1;
  87. int height = maxZ - minZ + 1;
  88. int size = width * height;
  89. float* heights = new float[size];
  90. float minHeight = FLT_MAX;
  91. float maxHeight = -FLT_MAX;
  92. __totalHeightmapScanlines = height;
  93. // Split the work into separate threads to make max use of available cpu cores and speed up computation.
  94. HeightmapThreadData threadData[THREAD_COUNT];
  95. THREAD_HANDLE threads[THREAD_COUNT];
  96. int stepSize = height / THREAD_COUNT;
  97. for (int i = 0; i < THREAD_COUNT; ++i)
  98. {
  99. HeightmapThreadData& data = threadData[i];
  100. data.rayHeight = rayOrigin.y;
  101. data.rayDirection = &rayDirection;
  102. data.bounds = &bounds;
  103. data.meshes = &meshes;
  104. data.minX = minX;
  105. data.maxX = maxX;
  106. data.minZ = minZ + (stepSize * i);
  107. data.maxZ = data.minZ + stepSize - 1;
  108. if (i == THREAD_COUNT - 1)
  109. data.maxZ = maxZ;
  110. data.heights = heights;
  111. data.heightIndex = width * (stepSize * i);
  112. // Start the processing thread
  113. if (!createThread(&threads[i], &generateHeightmapChunk, &data))
  114. {
  115. LOG(1, "ERROR: Failed to spawn worker thread for generation of heightmap: %s\n", filename);
  116. return;
  117. }
  118. }
  119. // Wait for all threads to terminate
  120. waitForThreads(THREAD_COUNT, threads);
  121. // Close all thread handles and free memory allocations.
  122. for (int i = 0; i < THREAD_COUNT; ++i)
  123. closeThread(threads[i]);
  124. // Update min/max height from all completed threads
  125. for (int i = 0; i < THREAD_COUNT; ++i)
  126. {
  127. if (threadData[i].minHeight < minHeight)
  128. minHeight = threadData[i].minHeight;
  129. if (threadData[i].maxHeight > maxHeight)
  130. maxHeight = threadData[i].maxHeight;
  131. }
  132. LOG(1, "\r\tDone.\n");
  133. if (__failedRayCasts)
  134. {
  135. LOG(1, "Warning: %d triangle intersections failed for heightmap: %s\n", __failedRayCasts, filename);
  136. // Go through and clamp any height values that are set to -FLT_MAX to the min recorded height value
  137. // (otherwise the range of height values will be far too large).
  138. for (int i = 0; i < size; ++i)
  139. {
  140. if (heights[i] == -FLT_MAX)
  141. heights[i] = minHeight;
  142. }
  143. }
  144. // Normalize the max height value
  145. maxHeight = maxHeight - minHeight;
  146. png_structp png_ptr = NULL;
  147. png_infop info_ptr = NULL;
  148. png_bytep row = NULL;
  149. FILE* fp = fopen(filename, "wb");
  150. if (fp == NULL)
  151. {
  152. LOG(1, "Error: Failed to open file for writing: %s\n", filename);
  153. goto error;
  154. }
  155. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  156. if (png_ptr == NULL)
  157. {
  158. LOG(1, "Error: Write struct creation failed: %s\n", filename);
  159. goto error;
  160. }
  161. info_ptr = png_create_info_struct(png_ptr);
  162. if (info_ptr == NULL)
  163. {
  164. LOG(1, "Error: Info struct creation failed: %s\n", filename);
  165. goto error;
  166. }
  167. png_init_io(png_ptr, fp);
  168. png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  169. png_write_info(png_ptr, info_ptr);
  170. // Allocate memory for a single row of image data
  171. row = (png_bytep)malloc(3 * width * sizeof(png_byte));
  172. for (int y = 0; y < height; y++)
  173. {
  174. for (int x = 0; x < width; x++)
  175. {
  176. // Write height value normalized between 0-255 (between min and max height)
  177. float h = heights[y*width + x];
  178. float nh = (h - minHeight) / maxHeight;
  179. int pos = x*3;
  180. if (highP)
  181. {
  182. // high precision packed 24-bit (RGB)
  183. int bits = (int)(nh * 16777215.0f); // 2^24-1
  184. row[pos+2] = (png_byte)(bits & 0xff);
  185. bits >>= 8;
  186. row[pos+1] = (png_byte)(bits & 0xff);
  187. bits >>= 8;
  188. row[pos] = (png_byte)(bits & 0xff);
  189. }
  190. else
  191. {
  192. // standard precision 8-bit (grayscale)
  193. png_byte b = (png_byte)(nh * 255.0f);
  194. row[pos] = row[pos+1] = row[pos+2] = b;
  195. }
  196. }
  197. png_write_row(png_ptr, row);
  198. }
  199. png_write_end(png_ptr, NULL);
  200. LOG(1, "Saved heightmap: %s\n", filename);
  201. error:
  202. if (heights)
  203. delete[] heights;
  204. if (fp)
  205. fclose(fp);
  206. if (row)
  207. free(row);
  208. if (info_ptr)
  209. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  210. if (png_ptr)
  211. png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  212. }
  213. int generateHeightmapChunk(void* threadData)
  214. {
  215. HeightmapThreadData* data = (HeightmapThreadData*)threadData;
  216. Vector3 rayOrigin(0, data->rayHeight, 0);
  217. const Vector3& rayDirection = *data->rayDirection;
  218. int minX = data->minX;
  219. int maxX = data->maxX;
  220. int minZ = data->minZ;
  221. int maxZ = data->maxZ;
  222. const std::vector<Mesh*>& meshes = *data->meshes;
  223. float* heights = data->heights;
  224. Vector3 intersectionPoint;
  225. float minHeight = FLT_MAX;
  226. float maxHeight = -FLT_MAX;
  227. int index = data->heightIndex;
  228. for (int z = minZ; z <= maxZ; ++z)
  229. {
  230. LOG(1, "\r\t%d%%", (int)(((float)__processedHeightmapScanLines / __totalHeightmapScanlines) * 100.0f));
  231. rayOrigin.z = (float)z;
  232. for (int x = minX; x <= maxX; ++x)
  233. {
  234. float h = -FLT_MAX;
  235. rayOrigin.x = (float)x;
  236. for (unsigned int i = 0, count = meshes.size(); i < count; ++i)
  237. {
  238. // Pick the highest intersecting Y value of all meshes
  239. Mesh* mesh = meshes[i];
  240. // Perform a quick ray/bounding box test to quick-out
  241. if (!intersect(rayOrigin, rayDirection, mesh->bounds.min, mesh->bounds.max))
  242. continue;
  243. // Computer intersection point of ray with mesh
  244. if (intersect(rayOrigin, rayDirection, mesh->vertices, mesh->parts, &intersectionPoint))
  245. {
  246. if (intersectionPoint.y > h)
  247. {
  248. h = intersectionPoint.y;
  249. // Update min/max height values
  250. if (h < minHeight)
  251. minHeight = h;
  252. if (h > maxHeight)
  253. maxHeight = h;
  254. }
  255. }
  256. }
  257. // Update the glboal height array
  258. heights[index++] = h;
  259. if (h == -FLT_MAX)
  260. ++__failedRayCasts;
  261. }
  262. ++__processedHeightmapScanLines;
  263. }
  264. // Update min/max height for this thread data
  265. data->minHeight = minHeight;
  266. data->maxHeight = maxHeight;
  267. return 0;
  268. }
  269. /////////////////////////////////////////////////////////////
  270. //
  271. // Fast, Minimum Storage Ray-Triangle Intersection
  272. //
  273. // Authors: Tomas Möller, Ben Trumbore
  274. // http://jgt.akpeters.com/papers/MollerTrumbore97
  275. //
  276. // Implementation of algorithm from Real-Time Rendering (vol 1), pg. 305.
  277. //
  278. // Adapted slightly for use here.
  279. //
  280. #ifndef EPSILON
  281. #define EPSILON 0.000001
  282. #endif
  283. #define CROSS(dest,v1,v2) \
  284. dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; \
  285. dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; \
  286. dest[2]=v1[0]*v2[1]-v1[1]*v2[0];
  287. #define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
  288. #define SUB(dest,v1,v2) \
  289. dest[0]=v1[0]-v2[0]; \
  290. dest[1]=v1[1]-v2[1]; \
  291. dest[2]=v1[2]-v2[2];
  292. int intersect_triangle(const float orig[3], const float dir[3], const float vert0[3], const float vert1[3], const float vert2[3], float *t, float *u, float *v)
  293. {
  294. float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
  295. float det,inv_det;
  296. /* find vectors for two edges sharing vert0 */
  297. SUB(edge1, vert1, vert0);
  298. SUB(edge2, vert2, vert0);
  299. /* begin calculating determinant - also used to calculate U parameter */
  300. CROSS(pvec, dir, edge2);
  301. /* if determinant is near zero, ray lies in plane of triangle */
  302. det = DOT(edge1, pvec);
  303. if (det > -EPSILON && det < EPSILON)
  304. return 0;
  305. inv_det = 1.0f / det;
  306. /* calculate distance from vert0 to ray origin */
  307. SUB(tvec, orig, vert0);
  308. /* calculate U parameter and test bounds */
  309. *u = DOT(tvec, pvec) * inv_det;
  310. if (*u < 0.0 || *u > 1.0)
  311. return 0;
  312. /* prepare to test V parameter */
  313. CROSS(qvec, tvec, edge1);
  314. /* calculate V parameter and test bounds */
  315. *v = DOT(dir, qvec) * inv_det;
  316. if (*v < 0.0 || *u + *v > 1.0)
  317. return 0;
  318. /* calculate t, ray intersects triangle */
  319. *t = DOT(edge2, qvec) * inv_det;
  320. return 1;
  321. }
  322. // Performs an intersection test between a ray and the given mesh part and stores the result in "point".
  323. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const std::vector<Vertex>& vertices, const std::vector<MeshPart*>& parts, Vector3* point)
  324. {
  325. const float* orig = &rayOrigin.x;
  326. const float* dir = &rayDirection.x;
  327. float minT = FLT_MAX;
  328. for (unsigned int i = 0, partCount = parts.size(); i < partCount; ++i)
  329. {
  330. MeshPart* part = parts[i];
  331. for (unsigned int j = 0, indexCount = part->getIndicesCount(); j < indexCount; j += 3)
  332. {
  333. const float* v0 = &vertices[part->getIndex( j )].position.x;
  334. const float* v1 = &vertices[part->getIndex(j+1)].position.x;
  335. const float* v2 = &vertices[part->getIndex(j+2)].position.x;
  336. // Perform a quick check (in 2D) to determine if the point is definitely NOT in the triangle
  337. float xmin, xmax, zmin, zmax;
  338. xmin = v0[0] < v1[0] ? v0[0] : v1[0]; xmin = xmin < v2[0] ? xmin : v2[0];
  339. xmax = v0[0] > v1[0] ? v0[0] : v1[0]; xmax = xmax > v2[0] ? xmax : v2[0];
  340. zmin = v0[2] < v1[2] ? v0[2] : v1[2]; zmin = zmin < v2[2] ? zmin : v2[2];
  341. zmax = v0[2] > v1[2] ? v0[2] : v1[2]; zmax = zmax > v2[2] ? zmax : v2[2];
  342. if (orig[0] < xmin || orig[0] > xmax || orig[2] < zmin || orig[2] > zmax)
  343. continue;
  344. // Perform a full ray/traingle intersection test in 3D to get the intersection point
  345. float t, u, v;
  346. if (intersect_triangle(orig, dir, v0, v1, v2, &t, &u, &v))
  347. {
  348. // Found an intersection!
  349. if (t < minT)
  350. {
  351. minT = t;
  352. if (point)
  353. {
  354. Vector3 rd(rayDirection);
  355. rd.scale(t);
  356. Vector3::add(rayOrigin, rd, point);
  357. }
  358. }
  359. //return true;
  360. }
  361. }
  362. }
  363. return (minT != FLT_MAX);//false;
  364. }
  365. // Ray/Box intersection test.
  366. bool intersect(const Vector3& rayOrigin, const Vector3& rayDirection, const Vector3& boxMin, const Vector3& boxMax, float* distance)
  367. {
  368. const Vector3& origin = rayOrigin;
  369. const Vector3& direction = rayDirection;
  370. const Vector3& min = boxMin;
  371. const Vector3& max = boxMax;
  372. // Intermediate calculation variables.
  373. float dnear = 0.0f;
  374. float dfar = 0.0f;
  375. float tmin = 0.0f;
  376. float tmax = 0.0f;
  377. // X direction.
  378. float div = 1.0f / direction.x;
  379. if (div >= 0.0f)
  380. {
  381. tmin = (min.x - origin.x) * div;
  382. tmax = (max.x - origin.x) * div;
  383. }
  384. else
  385. {
  386. tmin = (max.x - origin.x) * div;
  387. tmax = (min.x - origin.x) * div;
  388. }
  389. dnear = tmin;
  390. dfar = tmax;
  391. // Check if the ray misses the box.
  392. if (dnear > dfar || dfar < 0.0f)
  393. {
  394. return false;
  395. }
  396. // Y direction.
  397. div = 1.0f / direction.y;
  398. if (div >= 0.0f)
  399. {
  400. tmin = (min.y - origin.y) * div;
  401. tmax = (max.y - origin.y) * div;
  402. }
  403. else
  404. {
  405. tmin = (max.y - origin.y) * div;
  406. tmax = (min.y - origin.y) * div;
  407. }
  408. // Update the near and far intersection distances.
  409. if (tmin > dnear)
  410. {
  411. dnear = tmin;
  412. }
  413. if (tmax < dfar)
  414. {
  415. dfar = tmax;
  416. }
  417. // Check if the ray misses the box.
  418. if (dnear > dfar || dfar < 0.0f)
  419. {
  420. return false;
  421. }
  422. // Z direction.
  423. div = 1.0f / direction.z;
  424. if (div >= 0.0f)
  425. {
  426. tmin = (min.z - origin.z) * div;
  427. tmax = (max.z - origin.z) * div;
  428. }
  429. else
  430. {
  431. tmin = (max.z - origin.z) * div;
  432. tmax = (min.z - origin.z) * div;
  433. }
  434. // Update the near and far intersection distances.
  435. if (tmin > dnear)
  436. {
  437. dnear = tmin;
  438. }
  439. if (tmax < dfar)
  440. {
  441. dfar = tmax;
  442. }
  443. // Check if the ray misses the box.
  444. if (dnear > dfar || dfar < 0.0f)
  445. {
  446. return false;
  447. }
  448. // The ray intersects the box
  449. if (distance)
  450. *distance = dnear;
  451. return true;
  452. }
  453. }