Clipper.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. // Copyright 2009 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. /*
  4. Portions of this file are based off work by Markus Trenkwalder.
  5. Copyright (c) 2007, 2008 Markus Trenkwalder
  6. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without
  8. modification, are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright notice,
  10. this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright notice,
  12. this list of conditions and the following disclaimer in the documentation
  13. and/or other materials provided with the distribution.
  14. * Neither the name of the library's copyright owner nor the names of its
  15. contributors may be used to endorse or promote products derived from this
  16. software without specific prior written permission.
  17. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  21. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  22. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  23. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  24. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  25. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  26. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include "VideoBackends/Software/Clipper.h"
  30. #include "Common/Assert.h"
  31. #include "VideoBackends/Software/NativeVertexFormat.h"
  32. #include "VideoBackends/Software/Rasterizer.h"
  33. #include "VideoCommon/BPMemory.h"
  34. #include "VideoCommon/Statistics.h"
  35. #include "VideoCommon/XFMemory.h"
  36. namespace Clipper
  37. {
  38. enum
  39. {
  40. NUM_CLIPPED_VERTICES = 33,
  41. NUM_INDICES = NUM_CLIPPED_VERTICES + 3
  42. };
  43. static OutputVertexData ClippedVertices[NUM_CLIPPED_VERTICES];
  44. static OutputVertexData* Vertices[NUM_INDICES];
  45. void Init()
  46. {
  47. for (int i = 0; i < NUM_CLIPPED_VERTICES; ++i)
  48. Vertices[i + 3] = &ClippedVertices[i];
  49. }
  50. enum
  51. {
  52. SKIP_FLAG = -1,
  53. CLIP_POS_X_BIT = 0x01,
  54. CLIP_NEG_X_BIT = 0x02,
  55. CLIP_POS_Y_BIT = 0x04,
  56. CLIP_NEG_Y_BIT = 0x08,
  57. CLIP_POS_Z_BIT = 0x10,
  58. CLIP_NEG_Z_BIT = 0x20
  59. };
  60. static inline int CalcClipMask(const OutputVertexData* v)
  61. {
  62. int cmask = 0;
  63. Vec4 pos = v->projectedPosition;
  64. if (pos.w - pos.x < 0)
  65. cmask |= CLIP_POS_X_BIT;
  66. if (pos.x + pos.w < 0)
  67. cmask |= CLIP_NEG_X_BIT;
  68. if (pos.w - pos.y < 0)
  69. cmask |= CLIP_POS_Y_BIT;
  70. if (pos.y + pos.w < 0)
  71. cmask |= CLIP_NEG_Y_BIT;
  72. if (pos.w * pos.z > 0)
  73. cmask |= CLIP_POS_Z_BIT;
  74. if (pos.z + pos.w < 0)
  75. cmask |= CLIP_NEG_Z_BIT;
  76. return cmask;
  77. }
  78. static inline void AddInterpolatedVertex(float t, int out, int in, int* numVertices)
  79. {
  80. Vertices[(*numVertices)++]->Lerp(t, Vertices[out], Vertices[in]);
  81. }
  82. #define DIFFERENT_SIGNS(x, y) ((x <= 0 && y > 0) || (x > 0 && y <= 0))
  83. #define CLIP_DOTPROD(I, A, B, C, D) \
  84. (Vertices[I]->projectedPosition.x * A + Vertices[I]->projectedPosition.y * B + \
  85. Vertices[I]->projectedPosition.z * C + Vertices[I]->projectedPosition.w * D)
  86. #define POLY_CLIP(PLANE_BIT, A, B, C, D) \
  87. { \
  88. if (mask & PLANE_BIT) \
  89. { \
  90. int idxPrev = inlist[0]; \
  91. float dpPrev = CLIP_DOTPROD(idxPrev, A, B, C, D); \
  92. int outcount = 0; \
  93. \
  94. inlist[n] = inlist[0]; \
  95. for (int j = 1; j <= n; j++) \
  96. { \
  97. int idx = inlist[j]; \
  98. float dp = CLIP_DOTPROD(idx, A, B, C, D); \
  99. if (dpPrev >= 0) \
  100. { \
  101. outlist[outcount++] = idxPrev; \
  102. } \
  103. \
  104. if (DIFFERENT_SIGNS(dp, dpPrev)) \
  105. { \
  106. if (dp < 0) \
  107. { \
  108. float t = dp / (dp - dpPrev); \
  109. AddInterpolatedVertex(t, idx, idxPrev, &numVertices); \
  110. } \
  111. else \
  112. { \
  113. float t = dpPrev / (dpPrev - dp); \
  114. AddInterpolatedVertex(t, idxPrev, idx, &numVertices); \
  115. } \
  116. outlist[outcount++] = numVertices - 1; \
  117. } \
  118. \
  119. idxPrev = idx; \
  120. dpPrev = dp; \
  121. } \
  122. \
  123. if (outcount < 3) \
  124. continue; \
  125. \
  126. { \
  127. int* tmp = inlist; \
  128. inlist = outlist; \
  129. outlist = tmp; \
  130. n = outcount; \
  131. } \
  132. } \
  133. }
  134. #define LINE_CLIP(PLANE_BIT, A, B, C, D) \
  135. { \
  136. if (mask & PLANE_BIT) \
  137. { \
  138. const float dp0 = CLIP_DOTPROD(0, A, B, C, D); \
  139. const float dp1 = CLIP_DOTPROD(1, A, B, C, D); \
  140. const bool neg_dp0 = dp0 < 0; \
  141. const bool neg_dp1 = dp1 < 0; \
  142. \
  143. if (neg_dp0 && neg_dp1) \
  144. return; \
  145. \
  146. if (neg_dp1) \
  147. { \
  148. float t = dp1 / (dp1 - dp0); \
  149. if (t > t1) \
  150. t1 = t; \
  151. } \
  152. else if (neg_dp0) \
  153. { \
  154. float t = dp0 / (dp0 - dp1); \
  155. if (t > t0) \
  156. t0 = t; \
  157. } \
  158. } \
  159. }
  160. static void ClipTriangle(int* indices, int* numIndices)
  161. {
  162. int mask = 0;
  163. mask |= CalcClipMask(Vertices[0]);
  164. mask |= CalcClipMask(Vertices[1]);
  165. mask |= CalcClipMask(Vertices[2]);
  166. if (mask != 0)
  167. {
  168. for (int i = 0; i < 3; i += 3)
  169. {
  170. int vlist[2][2 * 6 + 1];
  171. int *inlist = vlist[0], *outlist = vlist[1];
  172. int n = 3;
  173. int numVertices = 3;
  174. inlist[0] = 0;
  175. inlist[1] = 1;
  176. inlist[2] = 2;
  177. // mark this triangle as unused in case it should be completely
  178. // clipped
  179. indices[0] = SKIP_FLAG;
  180. indices[1] = SKIP_FLAG;
  181. indices[2] = SKIP_FLAG;
  182. POLY_CLIP(CLIP_POS_X_BIT, -1, 0, 0, 1);
  183. POLY_CLIP(CLIP_NEG_X_BIT, 1, 0, 0, 1);
  184. POLY_CLIP(CLIP_POS_Y_BIT, 0, -1, 0, 1);
  185. POLY_CLIP(CLIP_NEG_Y_BIT, 0, 1, 0, 1);
  186. POLY_CLIP(CLIP_POS_Z_BIT, 0, 0, 0, 1);
  187. POLY_CLIP(CLIP_NEG_Z_BIT, 0, 0, 1, 1);
  188. INCSTAT(g_stats.this_frame.num_triangles_clipped);
  189. // transform the poly in inlist into triangles
  190. indices[0] = inlist[0];
  191. indices[1] = inlist[1];
  192. indices[2] = inlist[2];
  193. for (int j = 3; j < n; ++j)
  194. {
  195. indices[(*numIndices)++] = inlist[0];
  196. indices[(*numIndices)++] = inlist[j - 1];
  197. indices[(*numIndices)++] = inlist[j];
  198. }
  199. }
  200. }
  201. }
  202. static void ClipLine(int* indices)
  203. {
  204. int mask = 0;
  205. int clip_mask[2] = {0, 0};
  206. for (int i = 0; i < 2; ++i)
  207. {
  208. clip_mask[i] = CalcClipMask(Vertices[i]);
  209. mask |= clip_mask[i];
  210. }
  211. if (mask == 0)
  212. return;
  213. float t0 = 0;
  214. float t1 = 0;
  215. // Mark unused in case of early termination
  216. // of the macros below. (When fully clipped)
  217. indices[0] = SKIP_FLAG;
  218. indices[1] = SKIP_FLAG;
  219. LINE_CLIP(CLIP_POS_X_BIT, -1, 0, 0, 1);
  220. LINE_CLIP(CLIP_NEG_X_BIT, 1, 0, 0, 1);
  221. LINE_CLIP(CLIP_POS_Y_BIT, 0, -1, 0, 1);
  222. LINE_CLIP(CLIP_NEG_Y_BIT, 0, 1, 0, 1);
  223. LINE_CLIP(CLIP_POS_Z_BIT, 0, 0, -1, 1);
  224. LINE_CLIP(CLIP_NEG_Z_BIT, 0, 0, 1, 1);
  225. // Restore the old values as this line
  226. // was not fully clipped.
  227. indices[0] = 0;
  228. indices[1] = 1;
  229. int numVertices = 2;
  230. if (clip_mask[0])
  231. {
  232. indices[0] = numVertices;
  233. AddInterpolatedVertex(t0, 0, 1, &numVertices);
  234. }
  235. if (clip_mask[1])
  236. {
  237. indices[1] = numVertices;
  238. AddInterpolatedVertex(t1, 1, 0, &numVertices);
  239. }
  240. }
  241. void ProcessTriangle(OutputVertexData* v0, OutputVertexData* v1, OutputVertexData* v2)
  242. {
  243. INCSTAT(g_stats.this_frame.num_triangles_in);
  244. if (IsTriviallyRejected(v0, v1, v2))
  245. {
  246. INCSTAT(g_stats.this_frame.num_triangles_rejected);
  247. // NOTE: The slope used by zfreeze shouldn't be updated if the triangle is
  248. // trivially rejected during clipping
  249. return;
  250. }
  251. bool backface = IsBackface(v0, v1, v2);
  252. if (!backface)
  253. {
  254. if (bpmem.genMode.cullmode == CullMode::Back || bpmem.genMode.cullmode == CullMode::All)
  255. {
  256. // cull frontfacing - we still need to update the slope for zfreeze
  257. PerspectiveDivide(v0);
  258. PerspectiveDivide(v1);
  259. PerspectiveDivide(v2);
  260. Rasterizer::UpdateZSlope(v0, v1, v2, bpmem.scissorOffset.x * 2, bpmem.scissorOffset.y * 2);
  261. INCSTAT(g_stats.this_frame.num_triangles_culled);
  262. return;
  263. }
  264. }
  265. else
  266. {
  267. if (bpmem.genMode.cullmode == CullMode::Front || bpmem.genMode.cullmode == CullMode::All)
  268. {
  269. // cull backfacing - we still need to update the slope for zfreeze
  270. PerspectiveDivide(v0);
  271. PerspectiveDivide(v2);
  272. PerspectiveDivide(v1);
  273. Rasterizer::UpdateZSlope(v0, v2, v1, bpmem.scissorOffset.x * 2, bpmem.scissorOffset.y * 2);
  274. INCSTAT(g_stats.this_frame.num_triangles_culled);
  275. return;
  276. }
  277. }
  278. int indices[NUM_INDICES] = {0, 1, 2, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG,
  279. SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG,
  280. SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG, SKIP_FLAG,
  281. SKIP_FLAG, SKIP_FLAG, SKIP_FLAG};
  282. int numIndices = 3;
  283. if (backface)
  284. {
  285. Vertices[0] = v0;
  286. Vertices[1] = v2;
  287. Vertices[2] = v1;
  288. }
  289. else
  290. {
  291. Vertices[0] = v0;
  292. Vertices[1] = v1;
  293. Vertices[2] = v2;
  294. }
  295. // TODO: behavior when disable_clipping_detection is set doesn't quite match actual hardware;
  296. // there does still seem to be a maximum size after which things are clipped. Also, currently
  297. // when clipping is enabled triangles are clipped to exactly the viewport, but on hardware there
  298. // is a guardband (and with certain scissor configurations, things can show up in it)
  299. // Mario Party 8 in widescreen breaks without this: https://bugs.dolphin-emu.org/issues/12769
  300. bool skip_clipping = false;
  301. if (xfmem.clipDisable.disable_clipping_detection)
  302. {
  303. // If any w coordinate is negative, then the perspective divide will flip coordinates, breaking
  304. // various assumptions (including backface). So, we still need to do clipping in that case.
  305. // This isn't the actual condition hardware uses.
  306. if (Vertices[0]->projectedPosition.w >= 0 && Vertices[1]->projectedPosition.w >= 0 &&
  307. Vertices[2]->projectedPosition.w >= 0)
  308. skip_clipping = true;
  309. }
  310. if (!skip_clipping)
  311. ClipTriangle(indices, &numIndices);
  312. for (int i = 0; i + 3 <= numIndices; i += 3)
  313. {
  314. ASSERT(i < NUM_INDICES);
  315. if (indices[i] != SKIP_FLAG)
  316. {
  317. PerspectiveDivide(Vertices[indices[i]]);
  318. PerspectiveDivide(Vertices[indices[i + 1]]);
  319. PerspectiveDivide(Vertices[indices[i + 2]]);
  320. Rasterizer::DrawTriangleFrontFace(Vertices[indices[i]], Vertices[indices[i + 1]],
  321. Vertices[indices[i + 2]]);
  322. }
  323. }
  324. }
  325. constexpr std::array<float, 8> LINE_PT_TEX_OFFSETS = {
  326. 0, 1 / 16.f, 1 / 8.f, 1 / 4.f, 1 / 2.f, 1, 1, 1,
  327. };
  328. static void CopyLineVertex(OutputVertexData* dst, const OutputVertexData* src, int px, int py,
  329. bool apply_line_offset)
  330. {
  331. const float line_half_width = bpmem.lineptwidth.linesize / 12.0f;
  332. dst->projectedPosition = src->projectedPosition;
  333. dst->screenPosition.x = src->screenPosition.x + px * line_half_width;
  334. dst->screenPosition.y = src->screenPosition.y + py * line_half_width;
  335. dst->screenPosition.z = src->screenPosition.z;
  336. dst->normal = src->normal;
  337. dst->color = src->color;
  338. dst->texCoords = src->texCoords;
  339. if (apply_line_offset && LINE_PT_TEX_OFFSETS[bpmem.lineptwidth.lineoff] != 0)
  340. {
  341. for (u32 coord_num = 0; coord_num < xfmem.numTexGen.numTexGens; coord_num++)
  342. {
  343. if (bpmem.texcoords[coord_num].s.line_offset)
  344. {
  345. dst->texCoords[coord_num].x += (bpmem.texcoords[coord_num].s.scale_minus_1 + 1) *
  346. LINE_PT_TEX_OFFSETS[bpmem.lineptwidth.lineoff];
  347. }
  348. }
  349. }
  350. }
  351. void ProcessLine(OutputVertexData* lineV0, OutputVertexData* lineV1)
  352. {
  353. int indices[4] = {0, 1, SKIP_FLAG, SKIP_FLAG};
  354. Vertices[0] = lineV0;
  355. Vertices[1] = lineV1;
  356. // point to a valid vertex to store to when clipping
  357. Vertices[2] = &ClippedVertices[17];
  358. ClipLine(indices);
  359. if (indices[0] != SKIP_FLAG)
  360. {
  361. OutputVertexData* v0 = Vertices[indices[0]];
  362. OutputVertexData* v1 = Vertices[indices[1]];
  363. PerspectiveDivide(v0);
  364. PerspectiveDivide(v1);
  365. const float dx = v1->screenPosition.x - v0->screenPosition.x;
  366. const float dy = v1->screenPosition.y - v0->screenPosition.y;
  367. int px = 0;
  368. int py = 0;
  369. // GameCube/Wii's line drawing algorithm is a little quirky. It does not
  370. // use the correct line caps. Instead, the line caps are vertical or
  371. // horizontal depending the slope of the line.
  372. // FIXME: What does real hardware do when line is at a 45-degree angle?
  373. // Note that py or px are set positive or negative to ensure that the triangles are drawn ccw.
  374. if (fabsf(dx) > fabsf(dy))
  375. py = (dx > 0) ? -1 : 1;
  376. else
  377. px = (dy > 0) ? 1 : -1;
  378. OutputVertexData triangle[3];
  379. CopyLineVertex(&triangle[0], v0, px, py, false);
  380. CopyLineVertex(&triangle[1], v1, px, py, false);
  381. CopyLineVertex(&triangle[2], v1, -px, -py, true);
  382. // ccw winding
  383. Rasterizer::DrawTriangleFrontFace(&triangle[2], &triangle[1], &triangle[0]);
  384. CopyLineVertex(&triangle[1], v0, -px, -py, true);
  385. Rasterizer::DrawTriangleFrontFace(&triangle[0], &triangle[1], &triangle[2]);
  386. }
  387. }
  388. static void CopyPointVertex(OutputVertexData* dst, const OutputVertexData* src, bool px, bool py)
  389. {
  390. const float point_radius = bpmem.lineptwidth.pointsize / 12.0f;
  391. dst->projectedPosition = src->projectedPosition;
  392. dst->screenPosition.x = src->screenPosition.x + (px ? 1 : -1) * point_radius;
  393. dst->screenPosition.y = src->screenPosition.y + (py ? 1 : -1) * point_radius;
  394. dst->screenPosition.z = src->screenPosition.z;
  395. dst->normal = src->normal;
  396. dst->color = src->color;
  397. dst->texCoords = src->texCoords;
  398. const float point_offset = LINE_PT_TEX_OFFSETS[bpmem.lineptwidth.pointoff];
  399. if (point_offset != 0)
  400. {
  401. for (u32 coord_num = 0; coord_num < xfmem.numTexGen.numTexGens; coord_num++)
  402. {
  403. const auto coord_info = bpmem.texcoords[coord_num];
  404. if (coord_info.s.point_offset)
  405. {
  406. if (px)
  407. dst->texCoords[coord_num].x += (coord_info.s.scale_minus_1 + 1) * point_offset;
  408. if (py)
  409. dst->texCoords[coord_num].y += (coord_info.t.scale_minus_1 + 1) * point_offset;
  410. }
  411. }
  412. }
  413. }
  414. void ProcessPoint(OutputVertexData* center)
  415. {
  416. // TODO: This isn't actually doing any clipping
  417. PerspectiveDivide(center);
  418. OutputVertexData ll, lr, ul, ur;
  419. CopyPointVertex(&ll, center, false, false);
  420. CopyPointVertex(&lr, center, true, false);
  421. CopyPointVertex(&ur, center, true, true);
  422. CopyPointVertex(&ul, center, false, true);
  423. Rasterizer::DrawTriangleFrontFace(&ll, &ul, &lr);
  424. Rasterizer::DrawTriangleFrontFace(&ur, &lr, &ul);
  425. }
  426. bool IsTriviallyRejected(const OutputVertexData* v0, const OutputVertexData* v1,
  427. const OutputVertexData* v2)
  428. {
  429. int mask = CalcClipMask(v0);
  430. mask &= CalcClipMask(v1);
  431. mask &= CalcClipMask(v2);
  432. return mask != 0;
  433. }
  434. bool IsBackface(const OutputVertexData* v0, const OutputVertexData* v1, const OutputVertexData* v2)
  435. {
  436. float x0 = v0->projectedPosition.x;
  437. float x1 = v1->projectedPosition.x;
  438. float x2 = v2->projectedPosition.x;
  439. float y1 = v1->projectedPosition.y;
  440. float y0 = v0->projectedPosition.y;
  441. float y2 = v2->projectedPosition.y;
  442. float w0 = v0->projectedPosition.w;
  443. float w1 = v1->projectedPosition.w;
  444. float w2 = v2->projectedPosition.w;
  445. float normalZDir = (x0 * w2 - x2 * w0) * y1 + (x2 * y0 - x0 * y2) * w1 + (y2 * w0 - y0 * w2) * x1;
  446. bool backface = normalZDir <= 0.0f;
  447. // Jimmie Johnson's Anything with an Engine has a positive viewport, while other games have a
  448. // negative viewport. The positive viewport does not require vertices to be vertically mirrored,
  449. // but the backface test does need to be inverted for things to be drawn.
  450. if (xfmem.viewport.ht > 0)
  451. backface = !backface;
  452. return backface;
  453. }
  454. void PerspectiveDivide(OutputVertexData* vertex)
  455. {
  456. Vec4& projected = vertex->projectedPosition;
  457. Vec3& screen = vertex->screenPosition;
  458. float wInverse = 1.0f / projected.w;
  459. screen.x = projected.x * wInverse * xfmem.viewport.wd + xfmem.viewport.xOrig;
  460. screen.y = projected.y * wInverse * xfmem.viewport.ht + xfmem.viewport.yOrig;
  461. screen.z = projected.z * wInverse * xfmem.viewport.zRange + xfmem.viewport.farZ;
  462. }
  463. } // namespace Clipper