ComputeUVMappingProcess.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2008, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file GenUVCoords step */
  34. #include "AssimpPCH.h"
  35. #include "ComputeUVMappingProcess.h"
  36. #include "ProcessHelper.h"
  37. using namespace Assimp;
  38. // ------------------------------------------------------------------------------------------------
  39. // Constructor to be privately used by Importer
  40. ComputeUVMappingProcess::ComputeUVMappingProcess()
  41. {
  42. // nothing to do here
  43. }
  44. // ------------------------------------------------------------------------------------------------
  45. // Destructor, private as well
  46. ComputeUVMappingProcess::~ComputeUVMappingProcess()
  47. {
  48. // nothing to do here
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Returns whether the processing step is present in the given flag field.
  52. bool ComputeUVMappingProcess::IsActive( unsigned int pFlags) const
  53. {
  54. return (pFlags & aiProcess_GenUVCoords) != 0;
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Compute the AABB of a mesh
  58. inline void FindAABB (aiMesh* mesh, aiVector3D& min, aiVector3D& max)
  59. {
  60. min = aiVector3D (10e10f, 10e10f, 10e10f);
  61. max = aiVector3D (-10e10f,-10e10f,-10e10f);
  62. for (unsigned int i = 0;i < mesh->mNumVertices;++i)
  63. {
  64. const aiVector3D& v = mesh->mVertices[i];
  65. min.x = ::std::min(v.x,min.x);
  66. min.y = ::std::min(v.y,min.y);
  67. min.z = ::std::min(v.z,min.z);
  68. max.x = ::std::max(v.x,max.x);
  69. max.y = ::std::max(v.y,max.y);
  70. max.z = ::std::max(v.z,max.z);
  71. }
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Helper function to determine the 'real' center of a mesh
  75. inline void FindMeshCenter (aiMesh* mesh, aiVector3D& out, aiVector3D& min, aiVector3D& max)
  76. {
  77. FindAABB(mesh,min,max);
  78. out = min + (max-min)*0.5f;
  79. }
  80. // ------------------------------------------------------------------------------------------------
  81. // Helper function to determine the 'real' center of a mesh
  82. inline void FindMeshCenter (aiMesh* mesh, aiVector3D& out)
  83. {
  84. aiVector3D min,max;
  85. FindMeshCenter(mesh,out,min,max);
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Check whether a ray intersects a plane and find the intersection point
  89. inline bool PlaneIntersect(const aiRay& ray, const aiVector3D& planePos,
  90. const aiVector3D& planeNormal, aiVector3D& pos)
  91. {
  92. const float b = planeNormal * (planePos - ray.pos);
  93. float h = ray.dir * planeNormal;
  94. if (h < 10e-5f && h > -10e-5f || (h = b/h) < 0)
  95. return false;
  96. pos = ray.pos + (ray.dir * h);
  97. return true;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Find the first empty UV channel in a mesh
  101. inline unsigned int FindEmptyUVChannel (aiMesh* mesh)
  102. {
  103. for (unsigned int m = 0; m < AI_MAX_NUMBER_OF_TEXTURECOORDS;++m)
  104. if (!mesh->mTextureCoords[m])return m;
  105. DefaultLogger::get()->error("Unable to compute UV coordinates, no free UV slot found");
  106. return 0xffffffff;
  107. }
  108. // ------------------------------------------------------------------------------------------------
  109. // Try to remove UV seams
  110. void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
  111. {
  112. // TODO: just a very rough algorithm. I think it could be done
  113. // much easier, but I don't know how and am currently too tired to
  114. // to think about a better solution.
  115. const static float LOWER_LIMIT = 0.1f;
  116. const static float UPPER_LIMIT = 0.9f;
  117. const static float LOWER_EPSILON = 1e-3f;
  118. const static float UPPER_EPSILON = 1.f-1e-3f;
  119. for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx)
  120. {
  121. const aiFace& face = mesh->mFaces[fidx];
  122. if (face.mNumIndices < 3) continue; // triangles and polygons only, please
  123. unsigned int small = face.mNumIndices, large = small;
  124. bool zero = false, one = false, round_to_zero = false;
  125. // Check whether this face lies on a UV seam. We can just guess,
  126. // but the assumption that a face with at least one very small
  127. // on the one side and one very large U coord on the other side
  128. // lies on a UV seam should work for most cases.
  129. for (unsigned int n = 0; n < face.mNumIndices;++n)
  130. {
  131. if (out[face.mIndices[n]].x < LOWER_LIMIT)
  132. {
  133. small = n;
  134. // If we have a U value very close to 0 we can't
  135. // round the others to 0, too.
  136. if (out[face.mIndices[n]].x <= LOWER_EPSILON)
  137. zero = true;
  138. else round_to_zero = true;
  139. }
  140. if (out[face.mIndices[n]].x > UPPER_LIMIT)
  141. {
  142. large = n;
  143. // If we have a U value very close to 1 we can't
  144. // round the others to 1, too.
  145. if (out[face.mIndices[n]].x >= UPPER_EPSILON)
  146. one = true;
  147. }
  148. }
  149. if (small != face.mNumIndices && large != face.mNumIndices)
  150. {
  151. for (unsigned int n = 0; n < face.mNumIndices;++n)
  152. {
  153. // If the u value is over the upper limit and no other u
  154. // value of that face is 0, round it to 0
  155. if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero)
  156. out[face.mIndices[n]].x = 0.f;
  157. // If the u value is below the lower limit and no other u
  158. // value of that face is 1, round it to 1
  159. else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one)
  160. out[face.mIndices[n]].x = 1.f;
  161. // The face contains both 0 and 1 as UV coords. This can occur
  162. // for faces which have an edge that lies directly on the seam.
  163. // Due to numerical inaccuracies one U coord becomes 0, the
  164. // other 1. But we do still have a third UV coord to determine
  165. // to which side we must round to.
  166. else if (one && zero)
  167. {
  168. if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON)
  169. out[face.mIndices[n]].x = 0.f;
  170. else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON)
  171. out[face.mIndices[n]].x = 1.f;
  172. }
  173. }
  174. }
  175. }
  176. }
  177. // ------------------------------------------------------------------------------------------------
  178. void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,aiAxis axis, aiVector3D* out)
  179. {
  180. aiVector3D center;
  181. FindMeshCenter (mesh, center);
  182. // For each point get a normalized projection vector in the sphere,
  183. // get its longitude and latitude and map them to their respective
  184. // UV axes. Problems occur around the poles ... unsolvable.
  185. //
  186. // The spherical coordinate system looks like this:
  187. // x = cos(lon)*cos(lat)
  188. // y = sin(lon)*cos(lat)
  189. // z = sin(lat)
  190. //
  191. // Thus we can derive:
  192. // lat = arcsin (z)
  193. // lon = arctan (y/x)
  194. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt)
  195. {
  196. const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
  197. float lat, lon;
  198. switch (axis)
  199. {
  200. case aiAxis_X:
  201. lat = asin (diff.x);
  202. lon = atan2 (diff.z, diff.y);
  203. break;
  204. case aiAxis_Y:
  205. lat = asin (diff.y);
  206. lon = atan2 (diff.x, diff.z);
  207. break;
  208. case aiAxis_Z:
  209. lat = asin (diff.z);
  210. lon = atan2 (diff.y, diff.x);
  211. break;
  212. }
  213. out[pnt] = aiVector3D((lon + (float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI,
  214. (lat + (float)AI_MATH_HALF_PI) / (float)AI_MATH_PI, 0.f);
  215. }
  216. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  217. // close to zero on the one side, and a tcoord close to one on the
  218. // other side.
  219. RemoveUVSeams(mesh,out);
  220. }
  221. // ------------------------------------------------------------------------------------------------
  222. void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,aiAxis axis, aiVector3D* out)
  223. {
  224. aiVector3D center, min, max;
  225. FindMeshCenter(mesh, center, min, max);
  226. ai_assert(0 == aiAxis_X);
  227. const float diff = max[axis] - min[axis];
  228. if (!diff)
  229. {
  230. DefaultLogger::get()->error("Can't compute cylindrical mapping, the mesh is "
  231. "flat in the requested axis");
  232. return;
  233. }
  234. // If the main axis is 'z', the z coordinate of a point 'p' is mapped
  235. // directly to the texture V axis. The other axis is derived from
  236. // the angle between ( p.x - c.x, p.y - c.y ) and (1,0), where
  237. // 'c' is the center point of the mesh.
  238. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt)
  239. {
  240. const aiVector3D& pos = mesh->mVertices[pnt];
  241. aiVector3D& uv = out[pnt];
  242. switch (axis)
  243. {
  244. case aiAxis_X:
  245. uv.y = (pos.x - min.x) / diff;
  246. uv.x = atan2 ( pos.z - center.z, pos.y - center.y);
  247. break;
  248. case aiAxis_Y:
  249. uv.y = (pos.y - min.y) / diff;
  250. uv.x = atan2 ( pos.x - center.x, pos.z - center.z);
  251. break;
  252. case aiAxis_Z:
  253. uv.y = (pos.z - min.z) / diff;
  254. uv.x = atan2 ( pos.y - center.y, pos.x - center.x);
  255. break;
  256. }
  257. uv.x = (uv.x +(float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI;
  258. uv.z = 0.f;
  259. }
  260. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  261. // close to zero on the one side, and a tcoord close to one on the
  262. // other side.
  263. RemoveUVSeams(mesh,out);
  264. }
  265. // ------------------------------------------------------------------------------------------------
  266. void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,aiAxis axis, aiVector3D* out)
  267. {
  268. aiVector3D center, min, max;
  269. FindMeshCenter(mesh, center, min, max);
  270. float diffu,diffv;
  271. switch (axis)
  272. {
  273. case aiAxis_X:
  274. diffu = max.z - min.z;
  275. diffv = max.y - min.y;
  276. break;
  277. case aiAxis_Y:
  278. diffu = max.x - min.x;
  279. diffv = max.z - min.z;
  280. break;
  281. case aiAxis_Z:
  282. diffu = max.y - min.y;
  283. diffv = max.z - min.z;
  284. break;
  285. }
  286. if (!diffu || !diffv)
  287. {
  288. DefaultLogger::get()->error("Can't compute plane mapping, the mesh is "
  289. "flat in the requested axis");
  290. return;
  291. }
  292. // That's rather simple. We just project the vertices onto a plane
  293. // that lies on the two coordinate aces orthogonal to the main axis
  294. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt)
  295. {
  296. const aiVector3D& pos = mesh->mVertices[pnt];
  297. aiVector3D& uv = out[pnt];
  298. switch (axis)
  299. {
  300. case aiAxis_X:
  301. uv.x = (pos.z - min.z) / diffu;
  302. uv.y = (pos.y - min.y) / diffv;
  303. break;
  304. case aiAxis_Y:
  305. uv.x = (pos.x - min.x) / diffu;
  306. uv.y = (pos.z - min.z) / diffv;
  307. break;
  308. case aiAxis_Z:
  309. uv.x = (pos.y - min.y) / diffu;
  310. uv.y = (pos.x - min.x) / diffv;
  311. break;
  312. }
  313. uv.z = 0.f;
  314. }
  315. }
  316. // ------------------------------------------------------------------------------------------------
  317. void ComputeUVMappingProcess::ComputeBoxMapping(aiMesh* mesh, aiVector3D* out)
  318. {
  319. DefaultLogger::get()->error("Mapping type currently not implemented");
  320. }
  321. // ------------------------------------------------------------------------------------------------
  322. void ComputeUVMappingProcess::Execute( aiScene* pScene)
  323. {
  324. DefaultLogger::get()->debug("GenUVCoordsProcess begin");
  325. char buffer[1024];
  326. if (pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT)
  327. throw new ImportErrorException("Post-processing order mismatch: expecting pseudo-indexed (\"verbose\") vertices here");
  328. std::list<MappingInfo> mappingStack;
  329. /* Iterate through all materials and search for non-UV mapped textures
  330. */
  331. for (unsigned int i = 0; i < pScene->mNumMaterials;++i)
  332. {
  333. mappingStack.clear();
  334. aiMaterial* mat = pScene->mMaterials[i];
  335. for (unsigned int a = 0; a < mat->mNumProperties;++a)
  336. {
  337. aiMaterialProperty* prop = mat->mProperties[a];
  338. if (!::strcmp( prop->mKey.data, "$tex.mapping"))
  339. {
  340. aiTextureMapping& mapping = *((aiTextureMapping*)prop->mData);
  341. if (aiTextureMapping_UV != mapping)
  342. {
  343. if (!DefaultLogger::isNullLogger())
  344. {
  345. sprintf(buffer, "Found non-UV mapped texture (%s,%i). Mapping type: %s",
  346. TextureTypeToString((aiTextureType)prop->mSemantic),prop->mIndex,
  347. MappingTypeToString(mapping));
  348. DefaultLogger::get()->info(buffer);
  349. }
  350. if (aiTextureMapping_OTHER == mapping)
  351. continue;
  352. MappingInfo info (mapping);
  353. // Get further properties - currently only the major axis
  354. for (unsigned int a2 = 0; a2 < mat->mNumProperties;++a2)
  355. {
  356. aiMaterialProperty* prop2 = mat->mProperties[a2];
  357. if (prop2->mSemantic != prop->mSemantic || prop2->mIndex != prop->mIndex)
  358. continue;
  359. if ( !::strcmp( prop2->mKey.data, "$tex.mapaxis"))
  360. {
  361. info.axis = *((aiAxis*)prop2->mData);
  362. break;
  363. }
  364. }
  365. unsigned int idx;
  366. // Check whether we have this mapping mode already
  367. std::list<MappingInfo>::iterator it = std::find (mappingStack.begin(),mappingStack.end(), info);
  368. if (mappingStack.end() != it)
  369. {
  370. idx = (*it).uv;
  371. }
  372. else
  373. {
  374. /* We have found a non-UV mapped texture. Now
  375. * we need to find all meshes using this material
  376. * that we can compute UV channels for them.
  377. */
  378. for (unsigned int m = 0; m < pScene->mNumMeshes;++m)
  379. {
  380. aiMesh* mesh = pScene->mMeshes[m];
  381. unsigned int outIdx;
  382. if ( mesh->mMaterialIndex != i || ( outIdx = FindEmptyUVChannel(mesh) ) == 0xffffffff ||
  383. !mesh->mNumVertices)
  384. {
  385. continue;
  386. }
  387. // Allocate output storage
  388. aiVector3D* p = mesh->mTextureCoords[outIdx] = new aiVector3D[mesh->mNumVertices];
  389. switch (mapping)
  390. {
  391. case aiTextureMapping_SPHERE:
  392. ComputeSphereMapping(mesh,info.axis,p);
  393. break;
  394. case aiTextureMapping_CYLINDER:
  395. ComputeCylinderMapping(mesh,info.axis,p);
  396. break;
  397. case aiTextureMapping_PLANE:
  398. ComputePlaneMapping(mesh,info.axis,p);
  399. break;
  400. case aiTextureMapping_BOX:
  401. ComputeBoxMapping(mesh,p);
  402. break;
  403. default:
  404. ai_assert(false);
  405. }
  406. if (m && idx != outIdx)
  407. {
  408. DefaultLogger::get()->warn("UV index mismatch. Not all meshes assigned to "
  409. "this material have equal numbers of UV channels. The UV index stored in "
  410. "the material structure does therefore not apply for all meshes. ");
  411. }
  412. idx = outIdx;
  413. }
  414. info.uv = idx;
  415. mappingStack.push_back(info);
  416. }
  417. // Update the material property list
  418. mapping = aiTextureMapping_UV;
  419. ((MaterialHelper*)mat)->AddProperty(&idx,1,AI_MATKEY_UVWSRC(prop->mSemantic,prop->mIndex));
  420. }
  421. }
  422. }
  423. }
  424. DefaultLogger::get()->debug("GenUVCoordsProcess finished");
  425. }