OcclusionBuffer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "Log.h"
  26. #include "OcclusionBuffer.h"
  27. #include <cstring>
  28. #include "DebugNew.h"
  29. static const unsigned CLIPMASK_X_POS = 0x1;
  30. static const unsigned CLIPMASK_X_NEG = 0x2;
  31. static const unsigned CLIPMASK_Y_POS = 0x4;
  32. static const unsigned CLIPMASK_Y_NEG = 0x8;
  33. static const unsigned CLIPMASK_Z_POS = 0x10;
  34. static const unsigned CLIPMASK_Z_NEG = 0x20;
  35. OBJECTTYPESTATIC(OcclusionBuffer);
  36. OcclusionBuffer::OcclusionBuffer(Context* context) :
  37. Object(context),
  38. buffer_(0),
  39. width_(0),
  40. height_(0),
  41. numTriangles_(0),
  42. maxTriangles_(OCCLUSION_DEFAULT_MAX_TRIANGLES),
  43. cullMode_(CULL_CCW),
  44. depthHierarchyDirty_(true),
  45. nearClip_(0.0f),
  46. farClip_(0.0f)
  47. {
  48. }
  49. OcclusionBuffer::~OcclusionBuffer()
  50. {
  51. }
  52. bool OcclusionBuffer::SetSize(int width, int height)
  53. {
  54. if (width == width_ && height == height_)
  55. return true;
  56. if (width <= 0 || height <= 0)
  57. return false;
  58. if (!IsPowerOfTwo(width))
  59. {
  60. LOGERROR("Width is not a power of two");
  61. return false;
  62. }
  63. // Force the height to an even amount of pixels for better mip generation
  64. if (height & 1)
  65. ++height;
  66. width_ = width;
  67. height_ = height;
  68. // Reserve extra memory in case 3D clipping is not exact
  69. fullBuffer_ = new int[width * (height + 2) + 2];
  70. buffer_ = fullBuffer_.Get() + width + 1;
  71. mipBuffers_.Clear();
  72. // Build buffers for mip levels
  73. for (;;)
  74. {
  75. width = (width + 1) / 2;
  76. height = (height + 1) / 2;
  77. mipBuffers_.Push(SharedArrayPtr<DepthValue>(new DepthValue[width * height]));
  78. if (width <= OCCLUSION_MIN_SIZE && height <= OCCLUSION_MIN_SIZE)
  79. break;
  80. }
  81. LOGDEBUG("Set occlusion buffer size " + String(width_) + "x" + String(height_) + " with " +
  82. String(mipBuffers_.Size()) + " mip levels");
  83. CalculateViewport();
  84. return true;
  85. }
  86. void OcclusionBuffer::SetView(Camera* camera)
  87. {
  88. if (!camera)
  89. return;
  90. view_ = camera->GetInverseWorldTransform();
  91. projection_ = camera->GetProjection();
  92. viewProj_ = projection_ * view_;
  93. nearClip_ = camera->GetNearClip();
  94. farClip_ = camera->GetFarClip();
  95. CalculateViewport();
  96. }
  97. void OcclusionBuffer::SetMaxTriangles(unsigned triangles)
  98. {
  99. maxTriangles_ = triangles;
  100. }
  101. void OcclusionBuffer::SetCullMode(CullMode mode)
  102. {
  103. cullMode_ = mode;
  104. }
  105. void OcclusionBuffer::Reset()
  106. {
  107. numTriangles_ = 0;
  108. }
  109. void OcclusionBuffer::Clear()
  110. {
  111. if (!buffer_)
  112. return;
  113. Reset();
  114. int* dest = buffer_;
  115. int count = width_ * height_;
  116. while (count)
  117. {
  118. *dest++ = 0x7fffffff;
  119. --count;
  120. }
  121. depthHierarchyDirty_ = true;
  122. }
  123. bool OcclusionBuffer::Draw(const Matrix3x4& model, const void* vertexData, unsigned vertexSize, const void* indexData,
  124. unsigned indexSize, unsigned indexStart, unsigned indexCount)
  125. {
  126. const unsigned char* vertexDataChar = (const unsigned char*)vertexData;
  127. Matrix4 modelViewProj = viewProj_ * model;
  128. depthHierarchyDirty_ = true;
  129. // Theoretical max. amount of vertices if each of the 6 clipping planes doubles the triangle count
  130. Vector4 vertices[64 * 3];
  131. // 16-bit indices
  132. if (indexSize == sizeof(unsigned short))
  133. {
  134. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  135. const unsigned short* indicesEnd = indices + indexCount;
  136. while (indices < indicesEnd)
  137. {
  138. if (numTriangles_ >= maxTriangles_)
  139. return false;
  140. const Vector3& v0 = *((const Vector3*)(&vertexDataChar[indices[0] * vertexSize]));
  141. const Vector3& v1 = *((const Vector3*)(&vertexDataChar[indices[1] * vertexSize]));
  142. const Vector3& v2 = *((const Vector3*)(&vertexDataChar[indices[2] * vertexSize]));
  143. vertices[0] = ModelTransform(modelViewProj, v0);
  144. vertices[1] = ModelTransform(modelViewProj, v1);
  145. vertices[2] = ModelTransform(modelViewProj, v2);
  146. DrawTriangle(vertices);
  147. indices += 3;
  148. }
  149. }
  150. else
  151. {
  152. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  153. const unsigned* indicesEnd = indices + indexCount;
  154. while (indices < indicesEnd)
  155. {
  156. if (numTriangles_ >= maxTriangles_)
  157. return false;
  158. const Vector3& v0 = *((const Vector3*)(&vertexDataChar[indices[0] * vertexSize]));
  159. const Vector3& v1 = *((const Vector3*)(&vertexDataChar[indices[1] * vertexSize]));
  160. const Vector3& v2 = *((const Vector3*)(&vertexDataChar[indices[2] * vertexSize]));
  161. vertices[0] = ModelTransform(modelViewProj, v0);
  162. vertices[1] = ModelTransform(modelViewProj, v1);
  163. vertices[2] = ModelTransform(modelViewProj, v2);
  164. DrawTriangle(vertices);
  165. indices += 3;
  166. }
  167. }
  168. return true;
  169. }
  170. void OcclusionBuffer::BuildDepthHierarchy()
  171. {
  172. if (!buffer_)
  173. return;
  174. // Build the first mip level from the pixel-level data
  175. int width = (width_ + 1) / 2;
  176. int height = (height_ + 1) / 2;
  177. if (mipBuffers_.Size())
  178. {
  179. for (int y = 0; y < height; ++y)
  180. {
  181. int* src = buffer_ + (y * 2) * width_;
  182. DepthValue* dest = mipBuffers_[0].Get() + y * width;
  183. DepthValue* end = dest + width;
  184. if (y * 2 + 1 < height_)
  185. {
  186. int* src2 = src + width_;
  187. while (dest < end)
  188. {
  189. int minUpper = Min(src[0], src[1]);
  190. int minLower = Min(src2[0], src2[1]);
  191. dest->min_ = Min(minUpper, minLower);
  192. int maxUpper = Max(src[0], src[1]);
  193. int maxLower = Max(src2[0], src2[1]);
  194. dest->max_ = Max(maxUpper, maxLower);
  195. src += 2;
  196. src2 += 2;
  197. ++dest;
  198. }
  199. }
  200. else
  201. {
  202. while (dest < end)
  203. {
  204. dest->min_ = Min(src[0], src[1]);
  205. dest->max_ = Max(src[0], src[1]);
  206. src += 2;
  207. ++dest;
  208. }
  209. }
  210. }
  211. }
  212. // Build the rest of the mip levels
  213. for (unsigned i = 1; i < mipBuffers_.Size(); ++i)
  214. {
  215. int prevWidth = width;
  216. int prevHeight = height;
  217. width = (width + 1) / 2;
  218. height = (height + 1) / 2;
  219. for (int y = 0; y < height; ++y)
  220. {
  221. DepthValue* src = mipBuffers_[i - 1].Get() + (y * 2) * prevWidth;
  222. DepthValue* dest = mipBuffers_[i].Get() + y * width;
  223. DepthValue* end = dest + width;
  224. if (y * 2 + 1 < prevHeight)
  225. {
  226. DepthValue* src2 = src + prevWidth;
  227. while (dest < end)
  228. {
  229. int minUpper = Min(src[0].min_, src[1].min_);
  230. int minLower = Min(src2[0].min_, src2[1].min_);
  231. dest->min_ = Min(minUpper, minLower);
  232. int maxUpper = Max(src[0].max_, src[1].max_);
  233. int maxLower = Max(src2[0].max_, src2[1].max_);
  234. dest->max_ = Max(maxUpper, maxLower);
  235. src += 2;
  236. src2 += 2;
  237. ++dest;
  238. }
  239. }
  240. else
  241. {
  242. while (dest < end)
  243. {
  244. dest->min_ = Min(src[0].min_, src[1].min_);
  245. dest->max_ = Max(src[0].max_, src[1].max_);
  246. src += 2;
  247. ++dest;
  248. }
  249. }
  250. }
  251. }
  252. depthHierarchyDirty_ = false;
  253. }
  254. void OcclusionBuffer::ResetUseTimer()
  255. {
  256. useTimer_.Reset();
  257. }
  258. bool OcclusionBuffer::IsVisible(const BoundingBox& worldSpaceBox) const
  259. {
  260. if (!buffer_)
  261. return true;
  262. // Transform corners to projection space
  263. Vector4 vertices[8];
  264. vertices[0] = ModelTransform(viewProj_, worldSpaceBox.min_);
  265. vertices[1] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.min_.y_, worldSpaceBox.min_.z_));
  266. vertices[2] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.max_.y_, worldSpaceBox.min_.z_));
  267. vertices[3] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.max_.y_, worldSpaceBox.min_.z_));
  268. vertices[4] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.min_.y_, worldSpaceBox.max_.z_));
  269. vertices[5] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.min_.y_, worldSpaceBox.max_.z_));
  270. vertices[6] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.max_.y_, worldSpaceBox.max_.z_));
  271. vertices[7] = ModelTransform(viewProj_, worldSpaceBox.max_);
  272. // Apply a far clip relative bias
  273. for (unsigned i = 0; i < 8; ++i)
  274. vertices[i].z_ -= OCCLUSION_RELATIVE_BIAS;
  275. // Transform to screen space. If any of the corners cross the near plane, assume visible
  276. float minX, maxX, minY, maxY, minZ;
  277. if (vertices[0].z_ <= 0.0f)
  278. return true;
  279. Vector3 projected = ViewportTransform(vertices[0]);
  280. minX = maxX = projected.x_;
  281. minY = maxY = projected.y_;
  282. minZ = projected.z_;
  283. // Project the rest
  284. for (unsigned i = 1; i < 8; ++i)
  285. {
  286. if (vertices[i].z_ <= 0.0f)
  287. return true;
  288. projected = ViewportTransform(vertices[i]);
  289. if (projected.x_ < minX) minX = projected.x_;
  290. if (projected.x_ > maxX) maxX = projected.x_;
  291. if (projected.y_ < minY) minY = projected.y_;
  292. if (projected.y_ > maxY) maxY = projected.y_;
  293. if (projected.z_ < minZ) minZ = projected.z_;
  294. }
  295. // Expand the bounding box 1 pixel in each direction to be conservative and correct rasterization offset
  296. IntRect rect(
  297. (int)(minX - 1.5f), (int)(minY - 1.5f),
  298. (int)(maxX + 0.5f), (int)(maxY + 0.5f)
  299. );
  300. // If the rect is outside, let frustum culling handle
  301. if (rect.right_ < 0 || rect.bottom_ < 0)
  302. return true;
  303. if (rect.left_ >= width_ || rect.top_ >= height_)
  304. return true;
  305. // Clipping of rect
  306. if (rect.left_ < 0)
  307. rect.left_ = 0;
  308. if (rect.top_ < 0)
  309. rect.top_ = 0;
  310. if (rect.right_ >= width_)
  311. rect.right_ = width_ - 1;
  312. if (rect.bottom_ >= height_)
  313. rect.bottom_ = height_ - 1;
  314. int z = (int)(minZ + 0.5f) - OCCLUSION_FIXED_BIAS;
  315. if (!depthHierarchyDirty_)
  316. {
  317. // Start from lowest mip level and check if a conclusive result can be found
  318. for (int i = mipBuffers_.Size() - 1; i >= 0; --i)
  319. {
  320. int shift = i + 1;
  321. int width = width_ >> shift;
  322. int left = rect.left_ >> shift;
  323. int right = rect.right_ >> shift;
  324. DepthValue* buffer = mipBuffers_[i].Get();
  325. DepthValue* row = buffer + (rect.top_ >> shift) * width;
  326. DepthValue* endRow = buffer + (rect.bottom_ >> shift) * width;
  327. bool allOccluded = true;
  328. while (row <= endRow)
  329. {
  330. DepthValue* src = row + left;
  331. DepthValue* end = row + right;
  332. while (src <= end)
  333. {
  334. if (z <= src->min_)
  335. return true;
  336. if (z <= src->max_)
  337. allOccluded = false;
  338. ++src;
  339. }
  340. row += width;
  341. }
  342. if (allOccluded)
  343. return false;
  344. }
  345. }
  346. // If no conclusive result, finally check the pixel-level data
  347. int* row = buffer_ + rect.top_ * width_;
  348. int* endRow = buffer_ + rect.bottom_ * width_;
  349. while (row <= endRow)
  350. {
  351. int* src = row + rect.left_;
  352. int* end = row + rect.right_;
  353. while (src <= end)
  354. {
  355. if (z <= *src)
  356. return true;
  357. ++src;
  358. }
  359. row += width_;
  360. }
  361. return false;
  362. }
  363. unsigned OcclusionBuffer::GetUseTimer()
  364. {
  365. return useTimer_.GetMSec(false);
  366. }
  367. inline Vector4 OcclusionBuffer::ModelTransform(const Matrix4& transform, const Vector3& vertex) const
  368. {
  369. return Vector4(
  370. transform.m00_ * vertex.x_ + transform.m01_ * vertex.y_ + transform.m02_ * vertex.z_ + transform.m03_,
  371. transform.m10_ * vertex.x_ + transform.m11_ * vertex.y_ + transform.m12_ * vertex.z_ + transform.m13_,
  372. transform.m20_ * vertex.x_ + transform.m21_ * vertex.y_ + transform.m22_ * vertex.z_ + transform.m23_,
  373. transform.m30_ * vertex.x_ + transform.m31_ * vertex.y_ + transform.m32_ * vertex.z_ + transform.m33_
  374. );
  375. }
  376. inline Vector3 OcclusionBuffer::ViewportTransform(const Vector4& vertex) const
  377. {
  378. float invW = 1.0f / vertex.w_;
  379. return Vector3(
  380. invW * vertex.x_ * scaleX_ + offsetX_,
  381. invW * vertex.y_ * scaleY_ + offsetY_,
  382. invW * vertex.z_ * OCCLUSION_Z_SCALE
  383. );
  384. }
  385. inline Vector4 OcclusionBuffer::ClipEdge(const Vector4& v0, const Vector4& v1, float d0, float d1) const
  386. {
  387. float t = d0 / (d0 - d1);
  388. return v0 + t * (v1 - v0);
  389. }
  390. inline bool OcclusionBuffer::CheckFacing(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  391. {
  392. if (cullMode_ == CULL_NONE)
  393. return true;
  394. float aX = v0.x_ - v1.x_;
  395. float aY = v0.y_ - v1.y_;
  396. float bX = v2.x_ - v1.x_;
  397. float bY = v2.y_ - v1.y_;
  398. float signedArea = aX * bY - aY * bX;
  399. if (cullMode_ == CULL_CCW)
  400. return signedArea < 0.0f;
  401. else
  402. return signedArea > 0.0f;
  403. }
  404. void OcclusionBuffer::CalculateViewport()
  405. {
  406. // Add half pixel offset due to 3D frustum culling
  407. scaleX_ = 0.5f * width_;
  408. scaleY_ = -0.5f * height_;
  409. offsetX_ = 0.5f * width_ + 0.5f;
  410. offsetY_ = 0.5f * height_ + 0.5f;
  411. projOffsetScaleX_ = projection_.m00_ * scaleX_;
  412. projOffsetScaleY_ = projection_.m11_ * scaleY_;
  413. }
  414. void OcclusionBuffer::DrawTriangle(Vector4* vertices)
  415. {
  416. unsigned clipMask = 0;
  417. unsigned andClipMask = 0;
  418. Vector3 projected[3];
  419. // Build the clip plane mask for the triangle
  420. for (unsigned i = 0; i < 3; ++i)
  421. {
  422. unsigned vertexClipMask = 0;
  423. if (vertices[i].x_ > vertices[i].w_)
  424. vertexClipMask |= CLIPMASK_X_POS;
  425. if (vertices[i].x_ < -vertices[i].w_)
  426. vertexClipMask |= CLIPMASK_X_NEG;
  427. if (vertices[i].y_ > vertices[i].w_)
  428. vertexClipMask |= CLIPMASK_Y_POS;
  429. if (vertices[i].y_ < -vertices[i].w_)
  430. vertexClipMask |= CLIPMASK_Y_NEG;
  431. if (vertices[i].z_ > vertices[i].w_)
  432. vertexClipMask |= CLIPMASK_Z_POS;
  433. if (vertices[i].z_ < 0.0f)
  434. vertexClipMask |= CLIPMASK_Z_NEG;
  435. clipMask |= vertexClipMask;
  436. if (!i)
  437. andClipMask = vertexClipMask;
  438. else
  439. andClipMask &= vertexClipMask;
  440. }
  441. // If triangle is fully behind any clip plane, can reject quickly
  442. if (andClipMask)
  443. return;
  444. // Check if triangle is fully inside
  445. if (!clipMask)
  446. {
  447. projected[0] = ViewportTransform(vertices[0]);
  448. projected[1] = ViewportTransform(vertices[1]);
  449. projected[2] = ViewportTransform(vertices[2]);
  450. if (CheckFacing(projected[0], projected[1], projected[2]))
  451. DrawTriangle2D(projected);
  452. }
  453. else
  454. {
  455. bool triangles[64];
  456. // Initial triangle
  457. triangles[0] = true;
  458. unsigned numTriangles = 1;
  459. if (clipMask & CLIPMASK_X_POS)
  460. ClipVertices(Vector4(-1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  461. if (clipMask & CLIPMASK_X_NEG)
  462. ClipVertices(Vector4(1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  463. if (clipMask & CLIPMASK_Y_POS)
  464. ClipVertices(Vector4(0.0f, -1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  465. if (clipMask & CLIPMASK_Y_NEG)
  466. ClipVertices(Vector4(0.0f, 1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  467. if (clipMask & CLIPMASK_Z_POS)
  468. ClipVertices(Vector4(0.0f, 0.0f, -1.0f, 1.0f), vertices, triangles, numTriangles);
  469. if (clipMask & CLIPMASK_Z_NEG)
  470. ClipVertices(Vector4(0.0f, 0.0f, 1.0f, 0.0f), vertices, triangles, numTriangles);
  471. // Draw each accepted triangle
  472. for (unsigned i = 0; i < numTriangles; ++i)
  473. {
  474. if (triangles[i])
  475. {
  476. unsigned index = i * 3;
  477. projected[0] = ViewportTransform(vertices[index]);
  478. projected[1] = ViewportTransform(vertices[index + 1]);
  479. projected[2] = ViewportTransform(vertices[index + 2]);
  480. if (CheckFacing(projected[0], projected[1], projected[2]))
  481. DrawTriangle2D(projected);
  482. }
  483. }
  484. }
  485. }
  486. void OcclusionBuffer::ClipVertices(const Vector4& plane, Vector4* vertices, bool* triangles, unsigned& numTriangles)
  487. {
  488. unsigned num = numTriangles;
  489. for (unsigned i = 0; i < num; ++i)
  490. {
  491. if (triangles[i])
  492. {
  493. unsigned index = i * 3;
  494. float d0 = plane.DotProduct(vertices[index]);
  495. float d1 = plane.DotProduct(vertices[index + 1]);
  496. float d2 = plane.DotProduct(vertices[index + 2]);
  497. // If all vertices behind the plane, reject triangle
  498. if (d0 < 0.0f && d1 < 0.0f && d2 < 0.0f)
  499. {
  500. triangles[i] = false;
  501. continue;
  502. }
  503. // If 2 vertices behind the plane, create a new triangle in-place
  504. else if (d0 < 0.0f && d1 < 0.0f)
  505. {
  506. vertices[index] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  507. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  508. }
  509. else if (d0 < 0.0f && d2 < 0.0f)
  510. {
  511. vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  512. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  513. }
  514. else if (d1 < 0.0f && d2 < 0.0f)
  515. {
  516. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  517. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  518. }
  519. // 1 vertex behind the plane: create one new triangle, and modify one in-place
  520. else if (d0 < 0.0f)
  521. {
  522. unsigned newIdx = numTriangles * 3;
  523. triangles[numTriangles] = true;
  524. ++numTriangles;
  525. vertices[newIdx] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  526. vertices[newIdx + 1] = vertices[index + 1];
  527. vertices[newIdx + 2] = vertices[index] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  528. }
  529. else if (d1 < 0.0f)
  530. {
  531. unsigned newIdx = numTriangles * 3;
  532. triangles[numTriangles] = true;
  533. ++numTriangles;
  534. vertices[newIdx + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  535. vertices[newIdx + 2] = vertices[index + 2];
  536. vertices[newIdx] = vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  537. }
  538. else if (d2 < 0.0f)
  539. {
  540. unsigned newIdx = numTriangles * 3;
  541. triangles[numTriangles] = true;
  542. ++numTriangles;
  543. vertices[newIdx + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  544. vertices[newIdx] = vertices[index];
  545. vertices[newIdx + 1] = vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  546. }
  547. }
  548. }
  549. }
  550. // Code based on Chris Hecker's Perspective Texture Mapping series in the Game Developer magazine
  551. // Also available online at http://chrishecker.com/Miscellaneous_Technical_Articles
  552. /// %Gradients of a software rasterized triangle.
  553. struct Gradients
  554. {
  555. /// Construct from vertices.
  556. Gradients(const Vector3* vertices)
  557. {
  558. float invdX = 1.0f / (((vertices[1].x_ - vertices[2].x_) *
  559. (vertices[0].y_ - vertices[2].y_)) -
  560. ((vertices[0].x_ - vertices[2].x_) *
  561. (vertices[1].y_ - vertices[2].y_)));
  562. float invdY = -invdX;
  563. dInvZdX_ = invdX * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].y_ - vertices[2].y_)) -
  564. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].y_ - vertices[2].y_)));
  565. dInvZdY_ = invdY * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].x_ - vertices[2].x_)) -
  566. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].x_ - vertices[2].x_)));
  567. dInvZdXInt_ = (int)dInvZdX_;
  568. }
  569. /// Integer horizontal gradient.
  570. int dInvZdXInt_;
  571. /// Horizontal gradient.
  572. float dInvZdX_;
  573. /// Vertical gradient.
  574. float dInvZdY_;
  575. };
  576. /// %Edge of a software rasterized triangle.
  577. struct Edge
  578. {
  579. /// Construct from gradients and top & bottom vertices.
  580. Edge(const Gradients& gradients, const Vector3& top, const Vector3& bottom, int topY)
  581. {
  582. float slope = (bottom.x_ - top.x_) / (bottom.y_ - top.y_);
  583. float yPreStep = (float)(topY + 1) - top.y_;
  584. float xPreStep = slope * yPreStep;
  585. x_ = (int)((xPreStep + top.x_) * OCCLUSION_X_SCALE + 0.5f);
  586. xStep_ = (int)(slope * OCCLUSION_X_SCALE + 0.5f);
  587. invZ_ = (int)(top.z_ + xPreStep * gradients.dInvZdX_ + yPreStep * gradients.dInvZdY_ + 0.5f);
  588. invZStep_ = (int)(slope * gradients.dInvZdX_ + gradients.dInvZdY_ + 0.5f);
  589. }
  590. /// X coordinate.
  591. int x_;
  592. /// X coordinate step.
  593. int xStep_;
  594. /// Inverse Z.
  595. int invZ_;
  596. /// Inverse Z step.
  597. int invZStep_;
  598. };
  599. void OcclusionBuffer::DrawTriangle2D(const Vector3* vertices)
  600. {
  601. int top, middle, bottom;
  602. bool middleIsRight;
  603. numTriangles_++;
  604. // Sort vertices in Y-direction
  605. if (vertices[0].y_ < vertices[1].y_)
  606. {
  607. if (vertices[2].y_ < vertices[0].y_)
  608. {
  609. top = 2; middle = 0; bottom = 1;
  610. middleIsRight = true;
  611. }
  612. else
  613. {
  614. top = 0;
  615. if (vertices[1].y_ < vertices[2].y_)
  616. {
  617. middle = 1; bottom = 2;
  618. middleIsRight = true;
  619. }
  620. else
  621. {
  622. middle = 2; bottom = 1;
  623. middleIsRight = false;
  624. }
  625. }
  626. }
  627. else
  628. {
  629. if (vertices[2].y_ < vertices[1].y_)
  630. {
  631. top = 2; middle = 1; bottom = 0;
  632. middleIsRight = false;
  633. }
  634. else
  635. {
  636. top = 1;
  637. if (vertices[0].y_ < vertices[2].y_)
  638. {
  639. middle = 0; bottom = 2;
  640. middleIsRight = false;
  641. }
  642. else
  643. {
  644. middle = 2; bottom = 0;
  645. middleIsRight = true;
  646. }
  647. }
  648. }
  649. int topY = (int)vertices[top].y_;
  650. int middleY = (int)vertices[middle].y_;
  651. int bottomY = (int)vertices[bottom].y_;
  652. // Check for degenerate triangle
  653. if (topY == bottomY)
  654. return;
  655. Gradients gradients(vertices);
  656. Edge topToMiddle(gradients, vertices[top], vertices[middle], topY);
  657. Edge topToBottom(gradients, vertices[top], vertices[bottom], topY);
  658. Edge middleToBottom(gradients, vertices[middle], vertices[bottom], middleY);
  659. // The triangle is clockwise, so if bottom > middle then middle is right
  660. if (middleIsRight)
  661. {
  662. // Top half
  663. int* row = buffer_ + topY * width_;
  664. int* endRow = buffer_ + middleY * width_;
  665. while (row < endRow)
  666. {
  667. int invZ = topToBottom.invZ_;
  668. int* dest = row + (topToBottom.x_ >> 16);
  669. int* end = row + (topToMiddle.x_ >> 16);
  670. while (dest < end)
  671. {
  672. if (invZ < *dest)
  673. *dest = invZ;
  674. invZ += gradients.dInvZdXInt_;
  675. ++dest;
  676. }
  677. topToBottom.x_ += topToBottom.xStep_;
  678. topToBottom.invZ_ += topToBottom.invZStep_;
  679. topToMiddle.x_ += topToMiddle.xStep_;
  680. row += width_;
  681. }
  682. // Bottom half
  683. row = buffer_ + middleY * width_;
  684. endRow = buffer_ + bottomY * width_;
  685. while (row < endRow)
  686. {
  687. int invZ = topToBottom.invZ_;
  688. int* dest = row + (topToBottom.x_ >> 16);
  689. int* end = row + (middleToBottom.x_ >> 16);
  690. while (dest < end)
  691. {
  692. if (invZ < *dest)
  693. *dest = invZ;
  694. invZ += gradients.dInvZdXInt_;
  695. ++dest;
  696. }
  697. topToBottom.x_ += topToBottom.xStep_;
  698. topToBottom.invZ_ += topToBottom.invZStep_;
  699. middleToBottom.x_ += middleToBottom.xStep_;
  700. row += width_;
  701. }
  702. }
  703. else
  704. {
  705. // Top half
  706. int* row = buffer_ + topY * width_;
  707. int* endRow = buffer_ + middleY * width_;
  708. while (row < endRow)
  709. {
  710. int invZ = topToMiddle.invZ_;
  711. int* dest = row + (topToMiddle.x_ >> 16);
  712. int* end = row + (topToBottom.x_ >> 16);
  713. while (dest < end)
  714. {
  715. if (invZ < *dest)
  716. *dest = invZ;
  717. invZ += gradients.dInvZdXInt_;
  718. ++dest;
  719. }
  720. topToMiddle.x_ += topToMiddle.xStep_;
  721. topToMiddle.invZ_ += topToMiddle.invZStep_;
  722. topToBottom.x_ += topToBottom.xStep_;
  723. row += width_;
  724. }
  725. // Bottom half
  726. row = buffer_ + middleY * width_;
  727. endRow = buffer_ + bottomY * width_;
  728. while (row < endRow)
  729. {
  730. int invZ = middleToBottom.invZ_;
  731. int* dest = row + (middleToBottom.x_ >> 16);
  732. int* end = row + (topToBottom.x_ >> 16);
  733. while (dest < end)
  734. {
  735. if (invZ < *dest)
  736. *dest = invZ;
  737. invZ += gradients.dInvZdXInt_;
  738. ++dest;
  739. }
  740. middleToBottom.x_ += middleToBottom.xStep_;
  741. middleToBottom.invZ_ += middleToBottom.invZStep_;
  742. topToBottom.x_ += topToBottom.xStep_;
  743. row += width_;
  744. }
  745. }
  746. }