Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

505 řádky
18 KiB

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