ComputeUVMappingProcess.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, assimp 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 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 "ComputeUVMappingProcess.h"
  35. #include "Geometry/GeometryUtils.h"
  36. #include "ProcessHelper.h"
  37. #include <assimp/Exceptional.h>
  38. using namespace Assimp;
  39. namespace {
  40. const static aiVector3D base_axis_y(0.0, 1.0, 0.0);
  41. const static aiVector3D base_axis_x(1.0, 0.0, 0.0);
  42. const static aiVector3D base_axis_z(0.0, 0.0, 1.0);
  43. const static ai_real angle_epsilon = ai_real(0.95);
  44. } // namespace
  45. // ------------------------------------------------------------------------------------------------
  46. // Returns whether the processing step is present in the given flag field.
  47. bool ComputeUVMappingProcess::IsActive(unsigned int pFlags) const {
  48. return (pFlags & aiProcess_GenUVCoords) != 0;
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Find the first empty UV channel in a mesh
  52. inline unsigned int FindEmptyUVChannel(aiMesh *mesh) {
  53. for (unsigned int m = 0; m < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++m)
  54. if (!mesh->mTextureCoords[m]) {
  55. return m;
  56. }
  57. ASSIMP_LOG_ERROR("Unable to compute UV coordinates, no free UV slot found");
  58. return UINT_MAX;
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. // Try to remove UV seams
  62. void RemoveUVSeams(aiMesh *mesh, aiVector3D *out) {
  63. // TODO: just a very rough algorithm. I think it could be done
  64. // much easier, but I don't know how and am currently too tired to
  65. // to think about a better solution.
  66. const static ai_real LOWER_LIMIT = ai_real(0.1);
  67. const static ai_real UPPER_LIMIT = ai_real(0.9);
  68. const static ai_real LOWER_EPSILON = ai_real(10e-3);
  69. const static ai_real UPPER_EPSILON = ai_real(1.0 - 10e-3);
  70. for (unsigned int fidx = 0; fidx < mesh->mNumFaces; ++fidx) {
  71. const aiFace &face = mesh->mFaces[fidx];
  72. if (face.mNumIndices < 3) {
  73. continue; // triangles and polygons only, please
  74. }
  75. unsigned int smallV = face.mNumIndices, large = smallV;
  76. bool zero = false, one = false, round_to_zero = false;
  77. // Check whether this face lies on a UV seam. We can just guess,
  78. // but the assumption that a face with at least one very small
  79. // on the one side and one very large U coord on the other side
  80. // lies on a UV seam should work for most cases.
  81. for (unsigned int n = 0; n < face.mNumIndices; ++n) {
  82. if (out[face.mIndices[n]].x < LOWER_LIMIT) {
  83. smallV = n;
  84. // If we have a U value very close to 0 we can't
  85. // round the others to 0, too.
  86. if (out[face.mIndices[n]].x <= LOWER_EPSILON)
  87. zero = true;
  88. else
  89. round_to_zero = true;
  90. }
  91. if (out[face.mIndices[n]].x > UPPER_LIMIT) {
  92. large = n;
  93. // If we have a U value very close to 1 we can't
  94. // round the others to 1, too.
  95. if (out[face.mIndices[n]].x >= UPPER_EPSILON)
  96. one = true;
  97. }
  98. }
  99. if (smallV != face.mNumIndices && large != face.mNumIndices) {
  100. for (unsigned int n = 0; n < face.mNumIndices; ++n) {
  101. // If the u value is over the upper limit and no other u
  102. // value of that face is 0, round it to 0
  103. if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero)
  104. out[face.mIndices[n]].x = 0.0;
  105. // If the u value is below the lower limit and no other u
  106. // value of that face is 1, round it to 1
  107. else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one)
  108. out[face.mIndices[n]].x = 1.0;
  109. // The face contains both 0 and 1 as UV coords. This can occur
  110. // for faces which have an edge that lies directly on the seam.
  111. // Due to numerical inaccuracies one U coord becomes 0, the
  112. // other 1. But we do still have a third UV coord to determine
  113. // to which side we must round to.
  114. else if (one && zero) {
  115. if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON)
  116. out[face.mIndices[n]].x = 0.0;
  117. else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON)
  118. out[face.mIndices[n]].x = 1.0;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh *mesh, const aiVector3D &axis, aiVector3D *out) {
  126. aiVector3D center, min, max;
  127. FindMeshCenter(mesh, center, min, max);
  128. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  129. // currently the mapping axis will always be one of x,y,z, except if the
  130. // PretransformVertices step is used (it transforms the meshes into worldspace,
  131. // thus changing the mapping axis)
  132. if (axis * base_axis_x >= angle_epsilon) {
  133. // For each point get a normalized projection vector in the sphere,
  134. // get its longitude and latitude and map them to their respective
  135. // UV axes. Problems occur around the poles ... unsolvable.
  136. //
  137. // The spherical coordinate system looks like this:
  138. // x = cos(lon)*cos(lat)
  139. // y = sin(lon)*cos(lat)
  140. // z = sin(lat)
  141. //
  142. // Thus we can derive:
  143. // lat = arcsin (z)
  144. // lon = arctan (y/x)
  145. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  146. const aiVector3D diff = (mesh->mVertices[pnt] - center).Normalize();
  147. out[pnt] = aiVector3D((std::atan2(diff.z, diff.y) + AI_MATH_PI_F) / AI_MATH_TWO_PI_F,
  148. (std::asin(diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  149. }
  150. } else if (axis * base_axis_y >= angle_epsilon) {
  151. // ... just the same again
  152. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  153. const aiVector3D diff = (mesh->mVertices[pnt] - center).Normalize();
  154. out[pnt] = aiVector3D((std::atan2(diff.x, diff.z) + AI_MATH_PI_F) / AI_MATH_TWO_PI_F,
  155. (std::asin(diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  156. }
  157. } else if (axis * base_axis_z >= angle_epsilon) {
  158. // ... just the same again
  159. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  160. const aiVector3D diff = (mesh->mVertices[pnt] - center).Normalize();
  161. out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F) / AI_MATH_TWO_PI_F,
  162. (std::asin(diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  163. }
  164. }
  165. // slower code path in case the mapping axis is not one of the coordinate system axes
  166. else {
  167. aiMatrix4x4 mTrafo;
  168. aiMatrix4x4::FromToMatrix(axis, base_axis_y, mTrafo);
  169. // again the same, except we're applying a transformation now
  170. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  171. const aiVector3D diff = ((mTrafo * mesh->mVertices[pnt]) - center).Normalize();
  172. out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F) / AI_MATH_TWO_PI_F,
  173. (std::asin(diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  174. }
  175. }
  176. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  177. // close to zero on the one side, and a tcoord close to one on the
  178. // other side.
  179. RemoveUVSeams(mesh, out);
  180. }
  181. // ------------------------------------------------------------------------------------------------
  182. void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh *mesh, const aiVector3D &axis, aiVector3D *out) {
  183. aiVector3D center, min, max;
  184. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  185. // currently the mapping axis will always be one of x,y,z, except if the
  186. // PretransformVertices step is used (it transforms the meshes into worldspace,
  187. // thus changing the mapping axis)
  188. if (axis * base_axis_x >= angle_epsilon) {
  189. FindMeshCenter(mesh, center, min, max);
  190. const ai_real diff = max.x - min.x;
  191. // If the main axis is 'z', the z coordinate of a point 'p' is mapped
  192. // directly to the texture V axis. The other axis is derived from
  193. // the angle between ( p.x - c.x, p.y - c.y ) and (1,0), where
  194. // 'c' is the center point of the mesh.
  195. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  196. const aiVector3D &pos = mesh->mVertices[pnt];
  197. aiVector3D &uv = out[pnt];
  198. uv.y = (pos.x - min.x) / diff;
  199. uv.x = (std::atan2(pos.z - center.z, pos.y - center.y) + (ai_real)AI_MATH_PI) / (ai_real)AI_MATH_TWO_PI;
  200. }
  201. } else if (axis * base_axis_y >= angle_epsilon) {
  202. FindMeshCenter(mesh, center, min, max);
  203. const ai_real diff = max.y - min.y;
  204. // just the same ...
  205. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  206. const aiVector3D &pos = mesh->mVertices[pnt];
  207. aiVector3D &uv = out[pnt];
  208. uv.y = (pos.y - min.y) / diff;
  209. uv.x = (std::atan2(pos.x - center.x, pos.z - center.z) + (ai_real)AI_MATH_PI) / (ai_real)AI_MATH_TWO_PI;
  210. }
  211. } else if (axis * base_axis_z >= angle_epsilon) {
  212. FindMeshCenter(mesh, center, min, max);
  213. const ai_real diff = max.z - min.z;
  214. // just the same ...
  215. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  216. const aiVector3D &pos = mesh->mVertices[pnt];
  217. aiVector3D &uv = out[pnt];
  218. uv.y = (pos.z - min.z) / diff;
  219. uv.x = (std::atan2(pos.y - center.y, pos.x - center.x) + (ai_real)AI_MATH_PI) / (ai_real)AI_MATH_TWO_PI;
  220. }
  221. }
  222. // slower code path in case the mapping axis is not one of the coordinate system axes
  223. else {
  224. aiMatrix4x4 mTrafo;
  225. aiMatrix4x4::FromToMatrix(axis, base_axis_y, mTrafo);
  226. FindMeshCenterTransformed(mesh, center, min, max, mTrafo);
  227. const ai_real diff = max.y - min.y;
  228. // again the same, except we're applying a transformation now
  229. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  230. const aiVector3D pos = mTrafo * mesh->mVertices[pnt];
  231. aiVector3D &uv = out[pnt];
  232. uv.y = (pos.y - min.y) / diff;
  233. uv.x = (std::atan2(pos.x - center.x, pos.z - center.z) + (ai_real)AI_MATH_PI) / (ai_real)AI_MATH_TWO_PI;
  234. }
  235. }
  236. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  237. // close to zero on the one side, and a tcoord close to one on the
  238. // other side.
  239. RemoveUVSeams(mesh, out);
  240. }
  241. // ------------------------------------------------------------------------------------------------
  242. void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh *mesh, const aiVector3D &axis, aiVector3D *out) {
  243. ai_real diffu, diffv;
  244. aiVector3D center, min, max;
  245. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  246. // currently the mapping axis will always be one of x,y,z, except if the
  247. // PretransformVertices step is used (it transforms the meshes into worldspace,
  248. // thus changing the mapping axis)
  249. if (axis * base_axis_x >= angle_epsilon) {
  250. FindMeshCenter(mesh, center, min, max);
  251. diffu = max.z - min.z;
  252. diffv = max.y - min.y;
  253. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  254. const aiVector3D &pos = mesh->mVertices[pnt];
  255. out[pnt].Set((pos.z - min.z) / diffu, (pos.y - min.y) / diffv, 0.0);
  256. }
  257. } else if (axis * base_axis_y >= angle_epsilon) {
  258. FindMeshCenter(mesh, center, min, max);
  259. diffu = max.x - min.x;
  260. diffv = max.z - min.z;
  261. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  262. const aiVector3D &pos = mesh->mVertices[pnt];
  263. out[pnt].Set((pos.x - min.x) / diffu, (pos.z - min.z) / diffv, 0.0);
  264. }
  265. } else if (axis * base_axis_z >= angle_epsilon) {
  266. FindMeshCenter(mesh, center, min, max);
  267. diffu = max.x - min.x;
  268. diffv = max.y - min.y;
  269. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  270. const aiVector3D &pos = mesh->mVertices[pnt];
  271. out[pnt].Set((pos.x - min.x) / diffu, (pos.y - min.y) / diffv, 0.0);
  272. }
  273. }
  274. // slower code path in case the mapping axis is not one of the coordinate system axes
  275. else {
  276. aiMatrix4x4 mTrafo;
  277. aiMatrix4x4::FromToMatrix(axis, base_axis_y, mTrafo);
  278. FindMeshCenterTransformed(mesh, center, min, max, mTrafo);
  279. diffu = max.x - min.x;
  280. diffv = max.z - min.z;
  281. // again the same, except we're applying a transformation now
  282. for (unsigned int pnt = 0; pnt < mesh->mNumVertices; ++pnt) {
  283. const aiVector3D pos = mTrafo * mesh->mVertices[pnt];
  284. out[pnt].Set((pos.x - min.x) / diffu, (pos.z - min.z) / diffv, 0.0);
  285. }
  286. }
  287. // shouldn't be necessary to remove UV seams ...
  288. }
  289. // ------------------------------------------------------------------------------------------------
  290. void ComputeUVMappingProcess::ComputeBoxMapping(aiMesh *, aiVector3D *) {
  291. ASSIMP_LOG_ERROR("Mapping type currently not implemented");
  292. }
  293. // ------------------------------------------------------------------------------------------------
  294. void ComputeUVMappingProcess::Execute(aiScene *pScene) {
  295. ASSIMP_LOG_DEBUG("GenUVCoordsProcess begin");
  296. char buffer[1024];
  297. if (pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT)
  298. throw DeadlyImportError("Post-processing order mismatch: expecting pseudo-indexed (\"verbose\") vertices here");
  299. std::list<MappingInfo> mappingStack;
  300. /* Iterate through all materials and search for non-UV mapped textures
  301. */
  302. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  303. mappingStack.clear();
  304. aiMaterial *mat = pScene->mMaterials[i];
  305. for (unsigned int a = 0; a < mat->mNumProperties; ++a) {
  306. aiMaterialProperty *prop = mat->mProperties[a];
  307. if (!::strcmp(prop->mKey.data, "$tex.mapping")) {
  308. aiTextureMapping &mapping = *((aiTextureMapping *)prop->mData);
  309. if (aiTextureMapping_UV != mapping) {
  310. if (!DefaultLogger::isNullLogger()) {
  311. ai_snprintf(buffer, 1024, "Found non-UV mapped texture (%s,%u). Mapping type: %s",
  312. aiTextureTypeToString((aiTextureType)prop->mSemantic), prop->mIndex,
  313. MappingTypeToString(mapping));
  314. ASSIMP_LOG_INFO(buffer);
  315. }
  316. if (aiTextureMapping_OTHER == mapping)
  317. continue;
  318. MappingInfo info(mapping);
  319. // Get further properties - currently only the major axis
  320. for (unsigned int a2 = 0; a2 < mat->mNumProperties; ++a2) {
  321. aiMaterialProperty *prop2 = mat->mProperties[a2];
  322. if (prop2->mSemantic != prop->mSemantic || prop2->mIndex != prop->mIndex)
  323. continue;
  324. if (!::strcmp(prop2->mKey.data, "$tex.mapaxis")) {
  325. info.axis = *((aiVector3D *)prop2->mData);
  326. break;
  327. }
  328. }
  329. unsigned int idx(99999999);
  330. // Check whether we have this mapping mode already
  331. std::list<MappingInfo>::iterator it = std::find(mappingStack.begin(), mappingStack.end(), info);
  332. if (mappingStack.end() != it) {
  333. idx = (*it).uv;
  334. } else {
  335. /* We have found a non-UV mapped texture. Now
  336. * we need to find all meshes using this material
  337. * that we can compute UV channels for them.
  338. */
  339. for (unsigned int m = 0; m < pScene->mNumMeshes; ++m) {
  340. aiMesh *mesh = pScene->mMeshes[m];
  341. unsigned int outIdx = 0;
  342. if (mesh->mMaterialIndex != i || (outIdx = FindEmptyUVChannel(mesh)) == UINT_MAX ||
  343. !mesh->mNumVertices) {
  344. continue;
  345. }
  346. // Allocate output storage
  347. aiVector3D *p = mesh->mTextureCoords[outIdx] = new aiVector3D[mesh->mNumVertices];
  348. switch (mapping) {
  349. case aiTextureMapping_SPHERE:
  350. ComputeSphereMapping(mesh, info.axis, p);
  351. break;
  352. case aiTextureMapping_CYLINDER:
  353. ComputeCylinderMapping(mesh, info.axis, p);
  354. break;
  355. case aiTextureMapping_PLANE:
  356. ComputePlaneMapping(mesh, info.axis, p);
  357. break;
  358. case aiTextureMapping_BOX:
  359. ComputeBoxMapping(mesh, p);
  360. break;
  361. default:
  362. ai_assert(false);
  363. }
  364. if (m && idx != outIdx) {
  365. ASSIMP_LOG_WARN("UV index mismatch. Not all meshes assigned to "
  366. "this material have equal numbers of UV channels. The UV index stored in "
  367. "the material structure does therefore not apply for all meshes. ");
  368. }
  369. idx = outIdx;
  370. }
  371. info.uv = idx;
  372. mappingStack.push_back(info);
  373. }
  374. // Update the material property list
  375. mapping = aiTextureMapping_UV;
  376. ((aiMaterial *)mat)->AddProperty(&idx, 1, AI_MATKEY_UVWSRC(prop->mSemantic, prop->mIndex));
  377. }
  378. }
  379. }
  380. }
  381. ASSIMP_LOG_DEBUG("GenUVCoordsProcess finished");
  382. }