Drawable.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Graphics/Camera.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/File.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Material.h"
  29. #include "../Graphics/Octree.h"
  30. #include "../Graphics/Renderer.h"
  31. #include "../Graphics/VertexBuffer.h"
  32. #include "../Graphics/Zone.h"
  33. #include "../IO/Log.h"
  34. #include "../Scene/Scene.h"
  35. // ATOMIC BEGIN
  36. #include "../IO/Log.h"
  37. // ATOMIC END
  38. #include "../DebugNew.h"
  39. #ifdef _MSC_VER
  40. #pragma warning(disable:6293)
  41. #endif
  42. namespace Atomic
  43. {
  44. const char* GEOMETRY_CATEGORY = "Geometry";
  45. SourceBatch::SourceBatch() :
  46. distance_(0.0f),
  47. geometry_(0),
  48. worldTransform_(&Matrix3x4::IDENTITY),
  49. numWorldTransforms_(1),
  50. instancingData_((void*)0),
  51. geometryType_(GEOM_STATIC)
  52. {
  53. }
  54. SourceBatch::SourceBatch(const SourceBatch& batch)
  55. {
  56. *this = batch;
  57. }
  58. SourceBatch::~SourceBatch()
  59. {
  60. }
  61. SourceBatch& SourceBatch::operator =(const SourceBatch& rhs)
  62. {
  63. distance_ = rhs.distance_;
  64. geometry_ = rhs.geometry_;
  65. material_ = rhs.material_;
  66. worldTransform_ = rhs.worldTransform_;
  67. numWorldTransforms_ = rhs.numWorldTransforms_;
  68. instancingData_ = rhs.instancingData_;
  69. geometryType_ = rhs.geometryType_;
  70. return *this;
  71. }
  72. Drawable::Drawable(Context* context, unsigned char drawableFlags) :
  73. Component(context),
  74. boundingBox_(0.0f, 0.0f),
  75. drawableFlags_(drawableFlags),
  76. worldBoundingBoxDirty_(true),
  77. castShadows_(false),
  78. occluder_(false),
  79. occludee_(true),
  80. updateQueued_(false),
  81. zoneDirty_(false),
  82. octant_(0),
  83. zone_(0),
  84. viewMask_(DEFAULT_VIEWMASK),
  85. lightMask_(DEFAULT_LIGHTMASK),
  86. shadowMask_(DEFAULT_SHADOWMASK),
  87. zoneMask_(DEFAULT_ZONEMASK),
  88. viewFrameNumber_(0),
  89. distance_(0.0f),
  90. lodDistance_(0.0f),
  91. drawDistance_(0.0f),
  92. shadowDistance_(0.0f),
  93. sortValue_(0.0f),
  94. minZ_(0.0f),
  95. maxZ_(0.0f),
  96. lodBias_(1.0f),
  97. basePassFlags_(0),
  98. maxLights_(0),
  99. firstLight_(0)
  100. {
  101. // ATOMIC BEGIN
  102. if (drawableFlags == DRAWABLE_UNDEFINED || drawableFlags > DRAWABLE_ANY)
  103. {
  104. ATOMIC_LOGERROR("Drawable with undefined drawableFlags");
  105. }
  106. // ATOMIC END
  107. }
  108. Drawable::~Drawable()
  109. {
  110. RemoveFromOctree();
  111. }
  112. void Drawable::RegisterObject(Context* context)
  113. {
  114. ATOMIC_ATTRIBUTE("Max Lights", int, maxLights_, 0, AM_DEFAULT);
  115. ATOMIC_ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
  116. ATOMIC_ATTRIBUTE("Light Mask", int, lightMask_, DEFAULT_LIGHTMASK, AM_DEFAULT);
  117. ATOMIC_ATTRIBUTE("Shadow Mask", int, shadowMask_, DEFAULT_SHADOWMASK, AM_DEFAULT);
  118. ATOMIC_ACCESSOR_ATTRIBUTE("Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_ZONEMASK, AM_DEFAULT);
  119. }
  120. void Drawable::OnSetEnabled()
  121. {
  122. bool enabled = IsEnabledEffective();
  123. if (enabled && !octant_)
  124. AddToOctree();
  125. else if (!enabled && octant_)
  126. RemoveFromOctree();
  127. }
  128. void Drawable::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  129. {
  130. float distance = query.ray_.HitDistance(GetWorldBoundingBox());
  131. if (distance < query.maxDistance_)
  132. {
  133. RayQueryResult result;
  134. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  135. result.normal_ = -query.ray_.direction_;
  136. result.distance_ = distance;
  137. result.drawable_ = this;
  138. result.node_ = GetNode();
  139. result.subObject_ = M_MAX_UNSIGNED;
  140. results.Push(result);
  141. }
  142. }
  143. void Drawable::UpdateBatches(const FrameInfo& frame)
  144. {
  145. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  146. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  147. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  148. for (unsigned i = 0; i < batches_.Size(); ++i)
  149. {
  150. batches_[i].distance_ = distance_;
  151. batches_[i].worldTransform_ = &worldTransform;
  152. }
  153. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  154. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  155. if (newLodDistance != lodDistance_)
  156. lodDistance_ = newLodDistance;
  157. }
  158. Geometry* Drawable::GetLodGeometry(unsigned batchIndex, unsigned level)
  159. {
  160. // By default return the visible batch geometry
  161. if (batchIndex < batches_.Size())
  162. return batches_[batchIndex].geometry_;
  163. else
  164. return 0;
  165. }
  166. bool Drawable::DrawOcclusion(OcclusionBuffer* buffer)
  167. {
  168. return true;
  169. }
  170. void Drawable::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  171. {
  172. if (debug && IsEnabledEffective())
  173. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  174. }
  175. void Drawable::SetDrawDistance(float distance)
  176. {
  177. drawDistance_ = distance;
  178. MarkNetworkUpdate();
  179. }
  180. void Drawable::SetShadowDistance(float distance)
  181. {
  182. shadowDistance_ = distance;
  183. MarkNetworkUpdate();
  184. }
  185. void Drawable::SetLodBias(float bias)
  186. {
  187. lodBias_ = Max(bias, M_EPSILON);
  188. MarkNetworkUpdate();
  189. }
  190. void Drawable::SetViewMask(unsigned mask)
  191. {
  192. viewMask_ = mask;
  193. MarkNetworkUpdate();
  194. }
  195. void Drawable::SetLightMask(unsigned mask)
  196. {
  197. lightMask_ = mask;
  198. MarkNetworkUpdate();
  199. }
  200. void Drawable::SetShadowMask(unsigned mask)
  201. {
  202. shadowMask_ = mask;
  203. MarkNetworkUpdate();
  204. }
  205. void Drawable::SetZoneMask(unsigned mask)
  206. {
  207. zoneMask_ = mask;
  208. // Mark dirty to reset cached zone
  209. OnMarkedDirty(node_);
  210. MarkNetworkUpdate();
  211. }
  212. void Drawable::SetMaxLights(unsigned num)
  213. {
  214. maxLights_ = num;
  215. MarkNetworkUpdate();
  216. }
  217. void Drawable::SetCastShadows(bool enable)
  218. {
  219. castShadows_ = enable;
  220. MarkNetworkUpdate();
  221. }
  222. void Drawable::SetOccluder(bool enable)
  223. {
  224. occluder_ = enable;
  225. MarkNetworkUpdate();
  226. }
  227. void Drawable::SetOccludee(bool enable)
  228. {
  229. if (enable != occludee_)
  230. {
  231. occludee_ = enable;
  232. // Reinsert to octree to make sure octant occlusion does not erroneously hide this drawable
  233. if (octant_ && !updateQueued_)
  234. octant_->GetRoot()->QueueUpdate(this);
  235. MarkNetworkUpdate();
  236. }
  237. }
  238. void Drawable::MarkForUpdate()
  239. {
  240. if (!updateQueued_ && octant_)
  241. octant_->GetRoot()->QueueUpdate(this);
  242. }
  243. const BoundingBox& Drawable::GetWorldBoundingBox()
  244. {
  245. if (worldBoundingBoxDirty_)
  246. {
  247. OnWorldBoundingBoxUpdate();
  248. worldBoundingBoxDirty_ = false;
  249. }
  250. return worldBoundingBox_;
  251. }
  252. bool Drawable::IsInView() const
  253. {
  254. // Note: in headless mode there is no renderer subsystem and no view frustum tests are performed, so return
  255. // always false in that case
  256. Renderer* renderer = GetSubsystem<Renderer>();
  257. return renderer && viewFrameNumber_ == renderer->GetFrameInfo().frameNumber_ && !viewCameras_.Empty();
  258. }
  259. bool Drawable::IsInView(Camera* camera) const
  260. {
  261. Renderer* renderer = GetSubsystem<Renderer>();
  262. return renderer && viewFrameNumber_ == renderer->GetFrameInfo().frameNumber_ && (!camera || viewCameras_.Contains(camera));
  263. }
  264. bool Drawable::IsInView(const FrameInfo& frame, bool anyCamera) const
  265. {
  266. return viewFrameNumber_ == frame.frameNumber_ && (anyCamera || viewCameras_.Contains(frame.camera_));
  267. }
  268. void Drawable::SetZone(Zone* zone, bool temporary)
  269. {
  270. zone_ = zone;
  271. // If the zone assignment was temporary (inconclusive) set the dirty flag so that it will be re-evaluated on the next frame
  272. zoneDirty_ = temporary;
  273. }
  274. void Drawable::SetSortValue(float value)
  275. {
  276. sortValue_ = value;
  277. }
  278. void Drawable::MarkInView(const FrameInfo& frame)
  279. {
  280. if (frame.frameNumber_ != viewFrameNumber_)
  281. {
  282. viewFrameNumber_ = frame.frameNumber_;
  283. viewCameras_.Resize(1);
  284. viewCameras_[0] = frame.camera_;
  285. }
  286. else
  287. viewCameras_.Push(frame.camera_);
  288. basePassFlags_ = 0;
  289. firstLight_ = 0;
  290. lights_.Clear();
  291. vertexLights_.Clear();
  292. }
  293. void Drawable::MarkInView(unsigned frameNumber)
  294. {
  295. if (frameNumber != viewFrameNumber_)
  296. {
  297. viewFrameNumber_ = frameNumber;
  298. viewCameras_.Clear();
  299. }
  300. }
  301. void Drawable::LimitLights()
  302. {
  303. // Maximum lights value 0 means unlimited
  304. if (!maxLights_ || lights_.Size() <= maxLights_)
  305. return;
  306. // If more lights than allowed, move to vertex lights and cut the list
  307. const BoundingBox& box = GetWorldBoundingBox();
  308. for (unsigned i = 0; i < lights_.Size(); ++i)
  309. lights_[i]->SetIntensitySortValue(box);
  310. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  311. vertexLights_.Insert(vertexLights_.End(), lights_.Begin() + maxLights_, lights_.End());
  312. lights_.Resize(maxLights_);
  313. }
  314. void Drawable::LimitVertexLights(bool removeConvertedLights)
  315. {
  316. if (removeConvertedLights)
  317. {
  318. for (unsigned i = vertexLights_.Size() - 1; i < vertexLights_.Size(); --i)
  319. {
  320. if (!vertexLights_[i]->GetPerVertex())
  321. vertexLights_.Erase(i);
  322. }
  323. }
  324. if (vertexLights_.Size() <= MAX_VERTEX_LIGHTS)
  325. return;
  326. const BoundingBox& box = GetWorldBoundingBox();
  327. for (unsigned i = 0; i < vertexLights_.Size(); ++i)
  328. vertexLights_[i]->SetIntensitySortValue(box);
  329. Sort(vertexLights_.Begin(), vertexLights_.End(), CompareDrawables);
  330. vertexLights_.Resize(MAX_VERTEX_LIGHTS);
  331. }
  332. void Drawable::OnNodeSet(Node* node)
  333. {
  334. if (node)
  335. node->AddListener(this);
  336. }
  337. void Drawable::OnSceneSet(Scene* scene)
  338. {
  339. if (scene)
  340. AddToOctree();
  341. else
  342. RemoveFromOctree();
  343. }
  344. void Drawable::OnMarkedDirty(Node* node)
  345. {
  346. worldBoundingBoxDirty_ = true;
  347. if (!updateQueued_ && octant_)
  348. octant_->GetRoot()->QueueUpdate(this);
  349. // Mark zone assignment dirty when transform changes
  350. if (node == node_)
  351. zoneDirty_ = true;
  352. }
  353. void Drawable::AddToOctree()
  354. {
  355. // Do not add to octree when disabled
  356. if (!IsEnabledEffective())
  357. return;
  358. Scene* scene = GetScene();
  359. if (scene)
  360. {
  361. Octree* octree = scene->GetComponent<Octree>();
  362. if (octree)
  363. octree->InsertDrawable(this);
  364. else
  365. ATOMIC_LOGERROR("No Octree component in scene, drawable will not render");
  366. }
  367. else
  368. {
  369. // We have a mechanism for adding detached nodes to an octree manually, so do not log this error
  370. //ATOMIC_LOGERROR("Node is detached from scene, drawable will not render");
  371. }
  372. }
  373. void Drawable::RemoveFromOctree()
  374. {
  375. if (octant_)
  376. {
  377. Octree* octree = octant_->GetRoot();
  378. if (updateQueued_)
  379. octree->CancelUpdate(this);
  380. // Perform subclass specific deinitialization if necessary
  381. OnRemoveFromOctree();
  382. octant_->RemoveDrawable(this);
  383. }
  384. }
  385. bool WriteDrawablesToOBJ(PODVector<Drawable*> drawables, File* outputFile, bool asZUp, bool asRightHanded, bool writeLightmapUV)
  386. {
  387. // Must track indices independently to deal with potential mismatching of drawables vertex attributes (ie. one with UV, another without, then another with)
  388. unsigned currentPositionIndex = 1;
  389. unsigned currentUVIndex = 1;
  390. unsigned currentNormalIndex = 1;
  391. bool anythingWritten = false;
  392. // Write the common "I came from X" comment
  393. outputFile->WriteLine("# OBJ file exported from Atomic");
  394. for (unsigned i = 0; i < drawables.Size(); ++i)
  395. {
  396. Drawable* drawable = drawables[i];
  397. // Only write enabled drawables
  398. if (!drawable->IsEnabledEffective())
  399. continue;
  400. Node* node = drawable->GetNode();
  401. Matrix3x4 transMat = drawable->GetNode()->GetWorldTransform();
  402. Matrix3x4 n = transMat.Inverse();
  403. Matrix3 normalMat = Matrix3(n.m00_, n.m01_, n.m02_, n.m10_, n.m11_, n.m12_, n.m20_, n.m21_, n.m22_);
  404. normalMat = normalMat.Transpose();
  405. const Vector<SourceBatch>& batches = drawable->GetBatches();
  406. for (unsigned geoIndex = 0; geoIndex < batches.Size(); ++geoIndex)
  407. {
  408. Geometry* geo = drawable->GetLodGeometry(geoIndex, 0);
  409. if (geo == 0)
  410. continue;
  411. if (geo->GetPrimitiveType() != TRIANGLE_LIST)
  412. {
  413. ATOMIC_LOGERRORF("%s (%u) %s (%u) Geometry %u contains an unsupported geometry type %u", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex, (unsigned)geo->GetPrimitiveType());
  414. continue;
  415. }
  416. // If we've reached here than we're going to actually write something to the OBJ file
  417. anythingWritten = true;
  418. const unsigned char* vertexData;
  419. const unsigned char* indexData;
  420. unsigned elementSize, indexSize;
  421. const PODVector<VertexElement>* elements;
  422. geo->GetRawData(vertexData, elementSize, indexData, indexSize, elements);
  423. if (!vertexData || !elements)
  424. continue;
  425. bool hasPosition = VertexBuffer::HasElement(*elements, TYPE_VECTOR3, SEM_POSITION);
  426. if (!hasPosition)
  427. {
  428. ATOMIC_LOGERRORF("%s (%u) %s (%u) Geometry %u contains does not have Vector3 type positions in vertex data", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex);
  429. continue;
  430. }
  431. bool hasNormals = VertexBuffer::HasElement(*elements, TYPE_VECTOR3, SEM_NORMAL);
  432. bool hasUV = VertexBuffer::HasElement(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 0);
  433. bool hasLMUV = VertexBuffer::HasElement(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 1);
  434. if (elementSize > 0 && indexSize > 0)
  435. {
  436. unsigned vertexStart = geo->GetVertexStart();
  437. unsigned vertexCount = geo->GetVertexCount();
  438. unsigned indexStart = geo->GetIndexStart();
  439. unsigned indexCount = geo->GetIndexCount();
  440. // Name NodeID DrawableType DrawableID GeometryIndex ("Geo" is included for clarity as StaticModel_32_2 could easily be misinterpreted or even quickly misread as 322)
  441. // Generated object name example: Node_5_StaticModel_32_Geo_0 ... or ... Bob_5_StaticModel_32_Geo_0
  442. outputFile->WriteLine(String("o ").AppendWithFormat("%s_%u_%s_%u_Geo_%u", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex));
  443. // Write vertex position
  444. unsigned positionOffset = VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION);
  445. for (unsigned j = 0; j < vertexCount; ++j)
  446. {
  447. Vector3 vertexPosition = *((const Vector3*)(&vertexData[(vertexStart + j) * elementSize + positionOffset]));
  448. vertexPosition = transMat * vertexPosition;
  449. // Convert coordinates as requested
  450. if (asRightHanded)
  451. vertexPosition.x_ *= -1;
  452. if (asZUp)
  453. {
  454. float yVal = vertexPosition.y_;
  455. vertexPosition.y_ = vertexPosition.z_;
  456. vertexPosition.z_ = yVal;
  457. }
  458. outputFile->WriteLine("v " + String(vertexPosition));
  459. }
  460. if (hasNormals)
  461. {
  462. unsigned normalOffset = VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_NORMAL);
  463. for (unsigned j = 0; j < vertexCount; ++j)
  464. {
  465. Vector3 vertexNormal = *((const Vector3*)(&vertexData[(vertexStart + j) * elementSize + normalOffset]));
  466. vertexNormal = normalMat * vertexNormal;
  467. vertexNormal.Normalize();
  468. if (asRightHanded)
  469. vertexNormal.x_ *= -1;
  470. if (asZUp)
  471. {
  472. float yVal = vertexNormal.y_;
  473. vertexNormal.y_ = vertexNormal.z_;
  474. vertexNormal.z_ = yVal;
  475. }
  476. outputFile->WriteLine("vn " + String(vertexNormal));
  477. }
  478. }
  479. // Write TEXCOORD1 or TEXCOORD2 if it was chosen
  480. if (hasUV || (hasLMUV && writeLightmapUV))
  481. {
  482. // if writing Lightmap UV is chosen, only use it if TEXCOORD2 exists, otherwise use TEXCOORD1
  483. unsigned texCoordOffset = (writeLightmapUV && hasLMUV) ? VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 1) :
  484. VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 0);
  485. for (unsigned j = 0; j < vertexCount; ++j)
  486. {
  487. Vector2 uvCoords = *((const Vector2*)(&vertexData[(vertexStart + j) * elementSize + texCoordOffset]));
  488. outputFile->WriteLine("vt " + String(uvCoords));
  489. }
  490. }
  491. // If we don't have UV but have normals then must write a double-slash to indicate the absence of UV coords, otherwise use a single slash
  492. const String slashCharacter = hasNormals ? "//" : "/";
  493. // Amount by which to offset indices in the OBJ vs their values in the Urho3D geometry, basically the lowest index value
  494. // Compensates for the above vertex writing which doesn't write ALL vertices, just the used ones
  495. unsigned indexOffset = M_MAX_INT;
  496. for (unsigned indexIdx = indexStart; indexIdx < indexStart + indexCount; indexIdx++)
  497. {
  498. if (indexSize == 2)
  499. indexOffset = Min(indexOffset, (unsigned)*((unsigned short*)(indexData + indexIdx * indexSize)));
  500. else
  501. indexOffset = Min(indexOffset, *((unsigned*)(indexData + indexIdx * indexSize)));
  502. }
  503. for (unsigned indexIdx = indexStart; indexIdx < indexStart + indexCount; indexIdx += 3)
  504. {
  505. // Deal with 16 or 32 bit indices
  506. unsigned longIndices[3];
  507. if (indexSize == 2)
  508. {
  509. //16 bit indices
  510. unsigned short indices[3];
  511. memcpy(indices, indexData + (indexIdx * indexSize), indexSize * 3);
  512. longIndices[0] = indices[0] - indexOffset;
  513. longIndices[1] = indices[1] - indexOffset;
  514. longIndices[2] = indices[2] - indexOffset;
  515. }
  516. else
  517. {
  518. //32 bit indices
  519. unsigned indices[3];
  520. memcpy(indices, indexData + (indexIdx * indexSize), indexSize * 3);
  521. longIndices[0] = indices[0] - indexOffset;
  522. longIndices[1] = indices[1] - indexOffset;
  523. longIndices[2] = indices[2] - indexOffset;
  524. }
  525. String output = "f ";
  526. if (hasNormals)
  527. {
  528. output.AppendWithFormat("%l/%l/%l %l/%l/%l %l/%l/%l",
  529. currentPositionIndex + longIndices[0],
  530. currentUVIndex + longIndices[0],
  531. currentNormalIndex + longIndices[0],
  532. currentPositionIndex + longIndices[1],
  533. currentUVIndex + longIndices[1],
  534. currentNormalIndex + longIndices[1],
  535. currentPositionIndex + longIndices[2],
  536. currentUVIndex + longIndices[2],
  537. currentNormalIndex + longIndices[2]);
  538. }
  539. else if (hasNormals || hasUV)
  540. {
  541. unsigned secondTraitIndex = hasNormals ? currentNormalIndex : currentUVIndex;
  542. output.AppendWithFormat("%l%s%l %l%s%l %l%s%l",
  543. currentPositionIndex + longIndices[0],
  544. slashCharacter.CString(),
  545. secondTraitIndex + longIndices[0],
  546. currentPositionIndex + longIndices[1],
  547. slashCharacter.CString(),
  548. secondTraitIndex + longIndices[1],
  549. currentPositionIndex + longIndices[2],
  550. slashCharacter.CString(),
  551. secondTraitIndex + longIndices[2]);
  552. }
  553. else
  554. {
  555. output.AppendWithFormat("%l %l %l",
  556. currentPositionIndex + longIndices[0],
  557. currentPositionIndex + longIndices[1],
  558. currentPositionIndex + longIndices[2]);
  559. }
  560. outputFile->WriteLine(output);
  561. }
  562. // Increment our positions based on what vertex attributes we have
  563. currentPositionIndex += vertexCount;
  564. currentNormalIndex += hasNormals ? vertexCount : 0;
  565. // is it possible to have TEXCOORD2 but not have TEXCOORD1, assume anything
  566. currentUVIndex += (hasUV || hasLMUV) ? vertexCount : 0;
  567. }
  568. }
  569. }
  570. return anythingWritten;
  571. }
  572. }