ComputeUVMappingProcess.cpp 21 KB

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