OcclusionBuffer.cpp 30 KB

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