summaryrefslogtreecommitdiff
path: root/src/video_core/swrasterizer/rasterizer.cpp
diff options
context:
space:
mode:
authorGravatar Yuri Kunde Schlesner2017-01-28 15:59:36 -0800
committerGravatar Yuri Kunde Schlesner2017-02-12 18:08:11 -0800
commite24717bca04a51fe185e5dbbb4918e31c923e8fa (patch)
tree2895fb88f190a7cc49ef19835cff6aa3d85fc3ff /src/video_core/swrasterizer/rasterizer.cpp
parentvideo_core/shader: Document sanitized MUL operation (diff)
downloadyuzu-e24717bca04a51fe185e5dbbb4918e31c923e8fa.tar.gz
yuzu-e24717bca04a51fe185e5dbbb4918e31c923e8fa.tar.xz
yuzu-e24717bca04a51fe185e5dbbb4918e31c923e8fa.zip
VideoCore: Move software rasterizer files to sub-directory
Diffstat (limited to 'src/video_core/swrasterizer/rasterizer.cpp')
-rw-r--r--src/video_core/swrasterizer/rasterizer.cpp1299
1 files changed, 1299 insertions, 0 deletions
diff --git a/src/video_core/swrasterizer/rasterizer.cpp b/src/video_core/swrasterizer/rasterizer.cpp
new file mode 100644
index 000000000..17ba59144
--- /dev/null
+++ b/src/video_core/swrasterizer/rasterizer.cpp
@@ -0,0 +1,1299 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <array>
7#include <cmath>
8#include "common/assert.h"
9#include "common/bit_field.h"
10#include "common/color.h"
11#include "common/common_types.h"
12#include "common/logging/log.h"
13#include "common/math_util.h"
14#include "common/microprofile.h"
15#include "common/vector_math.h"
16#include "core/hw/gpu.h"
17#include "core/memory.h"
18#include "video_core/debug_utils/debug_utils.h"
19#include "video_core/pica_state.h"
20#include "video_core/pica_types.h"
21#include "video_core/regs_framebuffer.h"
22#include "video_core/regs_rasterizer.h"
23#include "video_core/regs_texturing.h"
24#include "video_core/shader/shader.h"
25#include "video_core/swrasterizer/rasterizer.h"
26#include "video_core/texture/texture_decode.h"
27#include "video_core/utils.h"
28
29namespace Pica {
30
31namespace Rasterizer {
32
33static void DrawPixel(int x, int y, const Math::Vec4<u8>& color) {
34 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
35 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
36
37 // Similarly to textures, the render framebuffer is laid out from bottom to top, too.
38 // NOTE: The framebuffer height register contains the actual FB height minus one.
39 y = framebuffer.height - y;
40
41 const u32 coarse_y = y & ~7;
42 u32 bytes_per_pixel =
43 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
44 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
45 coarse_y * framebuffer.width * bytes_per_pixel;
46 u8* dst_pixel = Memory::GetPhysicalPointer(addr) + dst_offset;
47
48 switch (framebuffer.color_format) {
49 case FramebufferRegs::ColorFormat::RGBA8:
50 Color::EncodeRGBA8(color, dst_pixel);
51 break;
52
53 case FramebufferRegs::ColorFormat::RGB8:
54 Color::EncodeRGB8(color, dst_pixel);
55 break;
56
57 case FramebufferRegs::ColorFormat::RGB5A1:
58 Color::EncodeRGB5A1(color, dst_pixel);
59 break;
60
61 case FramebufferRegs::ColorFormat::RGB565:
62 Color::EncodeRGB565(color, dst_pixel);
63 break;
64
65 case FramebufferRegs::ColorFormat::RGBA4:
66 Color::EncodeRGBA4(color, dst_pixel);
67 break;
68
69 default:
70 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
71 framebuffer.color_format.Value());
72 UNIMPLEMENTED();
73 }
74}
75
76static const Math::Vec4<u8> GetPixel(int x, int y) {
77 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
78 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
79
80 y = framebuffer.height - y;
81
82 const u32 coarse_y = y & ~7;
83 u32 bytes_per_pixel =
84 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
85 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
86 coarse_y * framebuffer.width * bytes_per_pixel;
87 u8* src_pixel = Memory::GetPhysicalPointer(addr) + src_offset;
88
89 switch (framebuffer.color_format) {
90 case FramebufferRegs::ColorFormat::RGBA8:
91 return Color::DecodeRGBA8(src_pixel);
92
93 case FramebufferRegs::ColorFormat::RGB8:
94 return Color::DecodeRGB8(src_pixel);
95
96 case FramebufferRegs::ColorFormat::RGB5A1:
97 return Color::DecodeRGB5A1(src_pixel);
98
99 case FramebufferRegs::ColorFormat::RGB565:
100 return Color::DecodeRGB565(src_pixel);
101
102 case FramebufferRegs::ColorFormat::RGBA4:
103 return Color::DecodeRGBA4(src_pixel);
104
105 default:
106 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
107 framebuffer.color_format.Value());
108 UNIMPLEMENTED();
109 }
110
111 return {0, 0, 0, 0};
112}
113
114static u32 GetDepth(int x, int y) {
115 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
116 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
117 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
118
119 y = framebuffer.height - y;
120
121 const u32 coarse_y = y & ~7;
122 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
123 u32 stride = framebuffer.width * bytes_per_pixel;
124
125 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
126 u8* src_pixel = depth_buffer + src_offset;
127
128 switch (framebuffer.depth_format) {
129 case FramebufferRegs::DepthFormat::D16:
130 return Color::DecodeD16(src_pixel);
131 case FramebufferRegs::DepthFormat::D24:
132 return Color::DecodeD24(src_pixel);
133 case FramebufferRegs::DepthFormat::D24S8:
134 return Color::DecodeD24S8(src_pixel).x;
135 default:
136 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
137 UNIMPLEMENTED();
138 return 0;
139 }
140}
141
142static u8 GetStencil(int x, int y) {
143 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
144 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
145 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
146
147 y = framebuffer.height - y;
148
149 const u32 coarse_y = y & ~7;
150 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
151 u32 stride = framebuffer.width * bytes_per_pixel;
152
153 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
154 u8* src_pixel = depth_buffer + src_offset;
155
156 switch (framebuffer.depth_format) {
157 case FramebufferRegs::DepthFormat::D24S8:
158 return Color::DecodeD24S8(src_pixel).y;
159
160 default:
161 LOG_WARNING(
162 HW_GPU,
163 "GetStencil called for function which doesn't have a stencil component (format %u)",
164 framebuffer.depth_format);
165 return 0;
166 }
167}
168
169static void SetDepth(int x, int y, u32 value) {
170 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
171 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
172 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
173
174 y = framebuffer.height - y;
175
176 const u32 coarse_y = y & ~7;
177 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
178 u32 stride = framebuffer.width * bytes_per_pixel;
179
180 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
181 u8* dst_pixel = depth_buffer + dst_offset;
182
183 switch (framebuffer.depth_format) {
184 case FramebufferRegs::DepthFormat::D16:
185 Color::EncodeD16(value, dst_pixel);
186 break;
187
188 case FramebufferRegs::DepthFormat::D24:
189 Color::EncodeD24(value, dst_pixel);
190 break;
191
192 case FramebufferRegs::DepthFormat::D24S8:
193 Color::EncodeD24X8(value, dst_pixel);
194 break;
195
196 default:
197 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
198 UNIMPLEMENTED();
199 break;
200 }
201}
202
203static void SetStencil(int x, int y, u8 value) {
204 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
205 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
206 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
207
208 y = framebuffer.height - y;
209
210 const u32 coarse_y = y & ~7;
211 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
212 u32 stride = framebuffer.width * bytes_per_pixel;
213
214 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
215 u8* dst_pixel = depth_buffer + dst_offset;
216
217 switch (framebuffer.depth_format) {
218 case Pica::FramebufferRegs::DepthFormat::D16:
219 case Pica::FramebufferRegs::DepthFormat::D24:
220 // Nothing to do
221 break;
222
223 case Pica::FramebufferRegs::DepthFormat::D24S8:
224 Color::EncodeX24S8(value, dst_pixel);
225 break;
226
227 default:
228 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
229 UNIMPLEMENTED();
230 break;
231 }
232}
233
234static u8 PerformStencilAction(FramebufferRegs::StencilAction action, u8 old_stencil, u8 ref) {
235 switch (action) {
236 case FramebufferRegs::StencilAction::Keep:
237 return old_stencil;
238
239 case FramebufferRegs::StencilAction::Zero:
240 return 0;
241
242 case FramebufferRegs::StencilAction::Replace:
243 return ref;
244
245 case FramebufferRegs::StencilAction::Increment:
246 // Saturated increment
247 return std::min<u8>(old_stencil, 254) + 1;
248
249 case FramebufferRegs::StencilAction::Decrement:
250 // Saturated decrement
251 return std::max<u8>(old_stencil, 1) - 1;
252
253 case FramebufferRegs::StencilAction::Invert:
254 return ~old_stencil;
255
256 case FramebufferRegs::StencilAction::IncrementWrap:
257 return old_stencil + 1;
258
259 case FramebufferRegs::StencilAction::DecrementWrap:
260 return old_stencil - 1;
261
262 default:
263 LOG_CRITICAL(HW_GPU, "Unknown stencil action %x", (int)action);
264 UNIMPLEMENTED();
265 return 0;
266 }
267}
268
269// NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
270struct Fix12P4 {
271 Fix12P4() {}
272 Fix12P4(u16 val) : val(val) {}
273
274 static u16 FracMask() {
275 return 0xF;
276 }
277 static u16 IntMask() {
278 return (u16)~0xF;
279 }
280
281 operator u16() const {
282 return val;
283 }
284
285 bool operator<(const Fix12P4& oth) const {
286 return (u16) * this < (u16)oth;
287 }
288
289private:
290 u16 val;
291};
292
293/**
294 * Calculate signed area of the triangle spanned by the three argument vertices.
295 * The sign denotes an orientation.
296 *
297 * @todo define orientation concretely.
298 */
299static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
300 const Math::Vec2<Fix12P4>& vtx3) {
301 const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
302 const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
303 // TODO: There is a very small chance this will overflow for sizeof(int) == 4
304 return Math::Cross(vec1, vec2).z;
305};
306
307MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
308
309/**
310 * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
311 * culling via recursion.
312 */
313static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
314 bool reversed = false) {
315 const auto& regs = g_state.regs;
316 MICROPROFILE_SCOPE(GPU_Rasterization);
317
318 // vertex positions in rasterizer coordinates
319 static auto FloatToFix = [](float24 flt) {
320 // TODO: Rounding here is necessary to prevent garbage pixels at
321 // triangle borders. Is it that the correct solution, though?
322 return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
323 };
324 static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
325 return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
326 };
327
328 Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
329 ScreenToRasterizerCoordinates(v1.screenpos),
330 ScreenToRasterizerCoordinates(v2.screenpos)};
331
332 if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
333 // Make sure we always end up with a triangle wound counter-clockwise
334 if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
335 ProcessTriangleInternal(v0, v2, v1, true);
336 return;
337 }
338 } else {
339 if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
340 // Reverse vertex order and use the CCW code path.
341 ProcessTriangleInternal(v0, v2, v1, true);
342 return;
343 }
344
345 // Cull away triangles which are wound clockwise.
346 if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
347 return;
348 }
349
350 u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
351 u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
352 u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
353 u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
354
355 // Convert the scissor box coordinates to 12.4 fixed point
356 u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
357 u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
358 // x2,y2 have +1 added to cover the entire sub-pixel area
359 u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
360 u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
361
362 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
363 // Calculate the new bounds
364 min_x = std::max(min_x, scissor_x1);
365 min_y = std::max(min_y, scissor_y1);
366 max_x = std::min(max_x, scissor_x2);
367 max_y = std::min(max_y, scissor_y2);
368 }
369
370 min_x &= Fix12P4::IntMask();
371 min_y &= Fix12P4::IntMask();
372 max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
373 max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
374
375 // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
376 // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
377 // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
378 // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
379 auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
380 const Math::Vec2<Fix12P4>& line1,
381 const Math::Vec2<Fix12P4>& line2) {
382 if (line1.y == line2.y) {
383 // just check if vertex is above us => bottom line parallel to x-axis
384 return vtx.y < line1.y;
385 } else {
386 // check if vertex is on our left => right side
387 // TODO: Not sure how likely this is to overflow
388 return (int)vtx.x < (int)line1.x +
389 ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
390 ((int)line2.y - (int)line1.y);
391 }
392 };
393 int bias0 =
394 IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
395 int bias1 =
396 IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
397 int bias2 =
398 IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
399
400 auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
401
402 auto textures = regs.texturing.GetTextures();
403 auto tev_stages = regs.texturing.GetTevStages();
404
405 bool stencil_action_enable =
406 g_state.regs.framebuffer.output_merger.stencil_test.enable &&
407 g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
408 const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
409
410 // Enter rasterization loop, starting at the center of the topleft bounding box corner.
411 // TODO: Not sure if looping through x first might be faster
412 for (u16 y = min_y + 8; y < max_y; y += 0x10) {
413 for (u16 x = min_x + 8; x < max_x; x += 0x10) {
414
415 // Do not process the pixel if it's inside the scissor box and the scissor mode is set
416 // to Exclude
417 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
418 if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
419 continue;
420 }
421
422 // Calculate the barycentric coordinates w0, w1 and w2
423 int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
424 int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
425 int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
426 int wsum = w0 + w1 + w2;
427
428 // If current pixel is not covered by the current primitive
429 if (w0 < 0 || w1 < 0 || w2 < 0)
430 continue;
431
432 auto baricentric_coordinates =
433 Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
434 float24::FromFloat32(static_cast<float>(w1)),
435 float24::FromFloat32(static_cast<float>(w2)));
436 float24 interpolated_w_inverse =
437 float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
438
439 // interpolated_z = z / w
440 float interpolated_z_over_w =
441 (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
442 v2.screenpos[2].ToFloat32() * w2) /
443 wsum;
444
445 // Not fully accurate. About 3 bits in precision are missing.
446 // Z-Buffer (z / w * scale + offset)
447 float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
448 float depth_offset =
449 float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
450 float depth = interpolated_z_over_w * depth_scale + depth_offset;
451
452 // Potentially switch to W-Buffer
453 if (regs.rasterizer.depthmap_enable ==
454 Pica::RasterizerRegs::DepthBuffering::WBuffering) {
455 // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
456 depth *= interpolated_w_inverse.ToFloat32() * wsum;
457 }
458
459 // Clamp the result
460 depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
461
462 // Perspective correct attribute interpolation:
463 // Attribute values cannot be calculated by simple linear interpolation since
464 // they are not linear in screen space. For example, when interpolating a
465 // texture coordinate across two vertices, something simple like
466 // u = (u0*w0 + u1*w1)/(w0+w1)
467 // will not work. However, the attribute value divided by the
468 // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
469 // in screenspace. Hence, we can linearly interpolate these two independently and
470 // calculate the interpolated attribute by dividing the results.
471 // I.e.
472 // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
473 // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
474 // u = u_over_w / one_over_w
475 //
476 // The generalization to three vertices is straightforward in baricentric coordinates.
477 auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
478 auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
479 float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
480 return interpolated_attr_over_w * interpolated_w_inverse;
481 };
482
483 Math::Vec4<u8> primary_color{
484 (u8)(
485 GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
486 255),
487 (u8)(
488 GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
489 255),
490 (u8)(
491 GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
492 255),
493 (u8)(
494 GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
495 255),
496 };
497
498 Math::Vec2<float24> uv[3];
499 uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
500 uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
501 uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
502 uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
503 uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
504 uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
505
506 Math::Vec4<u8> texture_color[3]{};
507 for (int i = 0; i < 3; ++i) {
508 const auto& texture = textures[i];
509 if (!texture.enabled)
510 continue;
511
512 DEBUG_ASSERT(0 != texture.config.address);
513
514 float24 u = uv[i].u();
515 float24 v = uv[i].v();
516
517 // Only unit 0 respects the texturing type (according to 3DBrew)
518 // TODO: Refactor so cubemaps and shadowmaps can be handled
519 if (i == 0) {
520 switch (texture.config.type) {
521 case TexturingRegs::TextureConfig::Texture2D:
522 break;
523 case TexturingRegs::TextureConfig::Projection2D: {
524 auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
525 u /= tc0_w;
526 v /= tc0_w;
527 break;
528 }
529 default:
530 // TODO: Change to LOG_ERROR when more types are handled.
531 LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
532 UNIMPLEMENTED();
533 break;
534 }
535 }
536
537 int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
538 .ToFloat32();
539 int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
540 .ToFloat32();
541
542 static auto GetWrappedTexCoord = [](TexturingRegs::TextureConfig::WrapMode mode,
543 int val, unsigned size) {
544 switch (mode) {
545 case TexturingRegs::TextureConfig::ClampToEdge:
546 val = std::max(val, 0);
547 val = std::min(val, (int)size - 1);
548 return val;
549
550 case TexturingRegs::TextureConfig::ClampToBorder:
551 return val;
552
553 case TexturingRegs::TextureConfig::Repeat:
554 return (int)((unsigned)val % size);
555
556 case TexturingRegs::TextureConfig::MirroredRepeat: {
557 unsigned int coord = ((unsigned)val % (2 * size));
558 if (coord >= size)
559 coord = 2 * size - 1 - coord;
560 return (int)coord;
561 }
562
563 default:
564 LOG_ERROR(HW_GPU, "Unknown texture coordinate wrapping mode %x", (int)mode);
565 UNIMPLEMENTED();
566 return 0;
567 }
568 };
569
570 if ((texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder &&
571 (s < 0 || static_cast<u32>(s) >= texture.config.width)) ||
572 (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder &&
573 (t < 0 || static_cast<u32>(t) >= texture.config.height))) {
574 auto border_color = texture.config.border_color;
575 texture_color[i] = {border_color.r, border_color.g, border_color.b,
576 border_color.a};
577 } else {
578 // Textures are laid out from bottom to top, hence we invert the t coordinate.
579 // NOTE: This may not be the right place for the inversion.
580 // TODO: Check if this applies to ETC textures, too.
581 s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
582 t = texture.config.height - 1 -
583 GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
584
585 u8* texture_data =
586 Memory::GetPhysicalPointer(texture.config.GetPhysicalAddress());
587 auto info =
588 Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
589
590 // TODO: Apply the min and mag filters to the texture
591 texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
592#if PICA_DUMP_TEXTURES
593 DebugUtils::DumpTexture(texture.config, texture_data);
594#endif
595 }
596 }
597
598 // Texture environment - consists of 6 stages of color and alpha combining.
599 //
600 // Color combiners take three input color values from some source (e.g. interpolated
601 // vertex color, texture color, previous stage, etc), perform some very simple
602 // operations on each of them (e.g. inversion) and then calculate the output color
603 // with some basic arithmetic. Alpha combiners can be configured separately but work
604 // analogously.
605 Math::Vec4<u8> combiner_output;
606 Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
607 Math::Vec4<u8> next_combiner_buffer = {
608 regs.texturing.tev_combiner_buffer_color.r,
609 regs.texturing.tev_combiner_buffer_color.g,
610 regs.texturing.tev_combiner_buffer_color.b,
611 regs.texturing.tev_combiner_buffer_color.a,
612 };
613
614 for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
615 ++tev_stage_index) {
616 const auto& tev_stage = tev_stages[tev_stage_index];
617 using Source = TexturingRegs::TevStageConfig::Source;
618 using ColorModifier = TexturingRegs::TevStageConfig::ColorModifier;
619 using AlphaModifier = TexturingRegs::TevStageConfig::AlphaModifier;
620 using Operation = TexturingRegs::TevStageConfig::Operation;
621
622 auto GetSource = [&](Source source) -> Math::Vec4<u8> {
623 switch (source) {
624 case Source::PrimaryColor:
625
626 // HACK: Until we implement fragment lighting, use primary_color
627 case Source::PrimaryFragmentColor:
628 return primary_color;
629
630 // HACK: Until we implement fragment lighting, use zero
631 case Source::SecondaryFragmentColor:
632 return {0, 0, 0, 0};
633
634 case Source::Texture0:
635 return texture_color[0];
636
637 case Source::Texture1:
638 return texture_color[1];
639
640 case Source::Texture2:
641 return texture_color[2];
642
643 case Source::PreviousBuffer:
644 return combiner_buffer;
645
646 case Source::Constant:
647 return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
648 tev_stage.const_a};
649
650 case Source::Previous:
651 return combiner_output;
652
653 default:
654 LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
655 UNIMPLEMENTED();
656 return {0, 0, 0, 0};
657 }
658 };
659
660 static auto GetColorModifier = [](ColorModifier factor,
661 const Math::Vec4<u8>& values) -> Math::Vec3<u8> {
662 switch (factor) {
663 case ColorModifier::SourceColor:
664 return values.rgb();
665
666 case ColorModifier::OneMinusSourceColor:
667 return (Math::Vec3<u8>(255, 255, 255) - values.rgb()).Cast<u8>();
668
669 case ColorModifier::SourceAlpha:
670 return values.aaa();
671
672 case ColorModifier::OneMinusSourceAlpha:
673 return (Math::Vec3<u8>(255, 255, 255) - values.aaa()).Cast<u8>();
674
675 case ColorModifier::SourceRed:
676 return values.rrr();
677
678 case ColorModifier::OneMinusSourceRed:
679 return (Math::Vec3<u8>(255, 255, 255) - values.rrr()).Cast<u8>();
680
681 case ColorModifier::SourceGreen:
682 return values.ggg();
683
684 case ColorModifier::OneMinusSourceGreen:
685 return (Math::Vec3<u8>(255, 255, 255) - values.ggg()).Cast<u8>();
686
687 case ColorModifier::SourceBlue:
688 return values.bbb();
689
690 case ColorModifier::OneMinusSourceBlue:
691 return (Math::Vec3<u8>(255, 255, 255) - values.bbb()).Cast<u8>();
692 }
693 };
694
695 static auto GetAlphaModifier = [](AlphaModifier factor,
696 const Math::Vec4<u8>& values) -> u8 {
697 switch (factor) {
698 case AlphaModifier::SourceAlpha:
699 return values.a();
700
701 case AlphaModifier::OneMinusSourceAlpha:
702 return 255 - values.a();
703
704 case AlphaModifier::SourceRed:
705 return values.r();
706
707 case AlphaModifier::OneMinusSourceRed:
708 return 255 - values.r();
709
710 case AlphaModifier::SourceGreen:
711 return values.g();
712
713 case AlphaModifier::OneMinusSourceGreen:
714 return 255 - values.g();
715
716 case AlphaModifier::SourceBlue:
717 return values.b();
718
719 case AlphaModifier::OneMinusSourceBlue:
720 return 255 - values.b();
721 }
722 };
723
724 static auto ColorCombine = [](Operation op,
725 const Math::Vec3<u8> input[3]) -> Math::Vec3<u8> {
726 switch (op) {
727 case Operation::Replace:
728 return input[0];
729
730 case Operation::Modulate:
731 return ((input[0] * input[1]) / 255).Cast<u8>();
732
733 case Operation::Add: {
734 auto result = input[0] + input[1];
735 result.r() = std::min(255, result.r());
736 result.g() = std::min(255, result.g());
737 result.b() = std::min(255, result.b());
738 return result.Cast<u8>();
739 }
740
741 case Operation::AddSigned: {
742 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to
743 // (byte) 128 is correct
744 auto result = input[0].Cast<int>() + input[1].Cast<int>() -
745 Math::MakeVec<int>(128, 128, 128);
746 result.r() = MathUtil::Clamp<int>(result.r(), 0, 255);
747 result.g() = MathUtil::Clamp<int>(result.g(), 0, 255);
748 result.b() = MathUtil::Clamp<int>(result.b(), 0, 255);
749 return result.Cast<u8>();
750 }
751
752 case Operation::Lerp:
753 return ((input[0] * input[2] +
754 input[1] *
755 (Math::MakeVec<u8>(255, 255, 255) - input[2]).Cast<u8>()) /
756 255)
757 .Cast<u8>();
758
759 case Operation::Subtract: {
760 auto result = input[0].Cast<int>() - input[1].Cast<int>();
761 result.r() = std::max(0, result.r());
762 result.g() = std::max(0, result.g());
763 result.b() = std::max(0, result.b());
764 return result.Cast<u8>();
765 }
766
767 case Operation::MultiplyThenAdd: {
768 auto result = (input[0] * input[1] + 255 * input[2].Cast<int>()) / 255;
769 result.r() = std::min(255, result.r());
770 result.g() = std::min(255, result.g());
771 result.b() = std::min(255, result.b());
772 return result.Cast<u8>();
773 }
774
775 case Operation::AddThenMultiply: {
776 auto result = input[0] + input[1];
777 result.r() = std::min(255, result.r());
778 result.g() = std::min(255, result.g());
779 result.b() = std::min(255, result.b());
780 result = (result * input[2].Cast<int>()) / 255;
781 return result.Cast<u8>();
782 }
783 case Operation::Dot3_RGB: {
784 // Not fully accurate.
785 // Worst case scenario seems to yield a +/-3 error
786 // Some HW results indicate that the per-component computation can't have a
787 // higher precision than 1/256,
788 // while dot3_rgb( (0x80,g0,b0),(0x7F,g1,b1) ) and dot3_rgb(
789 // (0x80,g0,b0),(0x80,g1,b1) ) give different results
790 int result =
791 ((input[0].r() * 2 - 255) * (input[1].r() * 2 - 255) + 128) / 256 +
792 ((input[0].g() * 2 - 255) * (input[1].g() * 2 - 255) + 128) / 256 +
793 ((input[0].b() * 2 - 255) * (input[1].b() * 2 - 255) + 128) / 256;
794 result = std::max(0, std::min(255, result));
795 return {(u8)result, (u8)result, (u8)result};
796 }
797 default:
798 LOG_ERROR(HW_GPU, "Unknown color combiner operation %d", (int)op);
799 UNIMPLEMENTED();
800 return {0, 0, 0};
801 }
802 };
803
804 static auto AlphaCombine = [](Operation op, const std::array<u8, 3>& input) -> u8 {
805 switch (op) {
806 case Operation::Replace:
807 return input[0];
808
809 case Operation::Modulate:
810 return input[0] * input[1] / 255;
811
812 case Operation::Add:
813 return std::min(255, input[0] + input[1]);
814
815 case Operation::AddSigned: {
816 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to
817 // (byte) 128 is correct
818 auto result = static_cast<int>(input[0]) + static_cast<int>(input[1]) - 128;
819 return static_cast<u8>(MathUtil::Clamp<int>(result, 0, 255));
820 }
821
822 case Operation::Lerp:
823 return (input[0] * input[2] + input[1] * (255 - input[2])) / 255;
824
825 case Operation::Subtract:
826 return std::max(0, (int)input[0] - (int)input[1]);
827
828 case Operation::MultiplyThenAdd:
829 return std::min(255, (input[0] * input[1] + 255 * input[2]) / 255);
830
831 case Operation::AddThenMultiply:
832 return (std::min(255, (input[0] + input[1])) * input[2]) / 255;
833
834 default:
835 LOG_ERROR(HW_GPU, "Unknown alpha combiner operation %d", (int)op);
836 UNIMPLEMENTED();
837 return 0;
838 }
839 };
840
841 // color combiner
842 // NOTE: Not sure if the alpha combiner might use the color output of the previous
843 // stage as input. Hence, we currently don't directly write the result to
844 // combiner_output.rgb(), but instead store it in a temporary variable until
845 // alpha combining has been done.
846 Math::Vec3<u8> color_result[3] = {
847 GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
848 GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
849 GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
850 };
851 auto color_output = ColorCombine(tev_stage.color_op, color_result);
852
853 // alpha combiner
854 std::array<u8, 3> alpha_result = {{
855 GetAlphaModifier(tev_stage.alpha_modifier1, GetSource(tev_stage.alpha_source1)),
856 GetAlphaModifier(tev_stage.alpha_modifier2, GetSource(tev_stage.alpha_source2)),
857 GetAlphaModifier(tev_stage.alpha_modifier3, GetSource(tev_stage.alpha_source3)),
858 }};
859 auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
860
861 combiner_output[0] =
862 std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
863 combiner_output[1] =
864 std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
865 combiner_output[2] =
866 std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
867 combiner_output[3] =
868 std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
869
870 combiner_buffer = next_combiner_buffer;
871
872 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
873 tev_stage_index)) {
874 next_combiner_buffer.r() = combiner_output.r();
875 next_combiner_buffer.g() = combiner_output.g();
876 next_combiner_buffer.b() = combiner_output.b();
877 }
878
879 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
880 tev_stage_index)) {
881 next_combiner_buffer.a() = combiner_output.a();
882 }
883 }
884
885 const auto& output_merger = regs.framebuffer.output_merger;
886 // TODO: Does alpha testing happen before or after stencil?
887 if (output_merger.alpha_test.enable) {
888 bool pass = false;
889
890 switch (output_merger.alpha_test.func) {
891 case FramebufferRegs::CompareFunc::Never:
892 pass = false;
893 break;
894
895 case FramebufferRegs::CompareFunc::Always:
896 pass = true;
897 break;
898
899 case FramebufferRegs::CompareFunc::Equal:
900 pass = combiner_output.a() == output_merger.alpha_test.ref;
901 break;
902
903 case FramebufferRegs::CompareFunc::NotEqual:
904 pass = combiner_output.a() != output_merger.alpha_test.ref;
905 break;
906
907 case FramebufferRegs::CompareFunc::LessThan:
908 pass = combiner_output.a() < output_merger.alpha_test.ref;
909 break;
910
911 case FramebufferRegs::CompareFunc::LessThanOrEqual:
912 pass = combiner_output.a() <= output_merger.alpha_test.ref;
913 break;
914
915 case FramebufferRegs::CompareFunc::GreaterThan:
916 pass = combiner_output.a() > output_merger.alpha_test.ref;
917 break;
918
919 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
920 pass = combiner_output.a() >= output_merger.alpha_test.ref;
921 break;
922 }
923
924 if (!pass)
925 continue;
926 }
927
928 // Apply fog combiner
929 // Not fully accurate. We'd have to know what data type is used to
930 // store the depth etc. Using float for now until we know more
931 // about Pica datatypes
932 if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
933 const Math::Vec3<u8> fog_color = {
934 static_cast<u8>(regs.texturing.fog_color.r.Value()),
935 static_cast<u8>(regs.texturing.fog_color.g.Value()),
936 static_cast<u8>(regs.texturing.fog_color.b.Value()),
937 };
938
939 // Get index into fog LUT
940 float fog_index;
941 if (g_state.regs.texturing.fog_flip) {
942 fog_index = (1.0f - depth) * 128.0f;
943 } else {
944 fog_index = depth * 128.0f;
945 }
946
947 // Generate clamped fog factor from LUT for given fog index
948 float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
949 float fog_f = fog_index - fog_i;
950 const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
951 float fog_factor = (fog_lut_entry.value + fog_lut_entry.difference * fog_f) /
952 2047.0f; // This is signed fixed point 1.11
953 fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
954
955 // Blend the fog
956 for (unsigned i = 0; i < 3; i++) {
957 combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
958 (1.0f - fog_factor) * fog_color[i]);
959 }
960 }
961
962 u8 old_stencil = 0;
963
964 auto UpdateStencil = [stencil_test, x, y,
965 &old_stencil](Pica::FramebufferRegs::StencilAction action) {
966 u8 new_stencil =
967 PerformStencilAction(action, old_stencil, stencil_test.reference_value);
968 if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
969 SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
970 (old_stencil & ~stencil_test.write_mask));
971 };
972
973 if (stencil_action_enable) {
974 old_stencil = GetStencil(x >> 4, y >> 4);
975 u8 dest = old_stencil & stencil_test.input_mask;
976 u8 ref = stencil_test.reference_value & stencil_test.input_mask;
977
978 bool pass = false;
979 switch (stencil_test.func) {
980 case FramebufferRegs::CompareFunc::Never:
981 pass = false;
982 break;
983
984 case FramebufferRegs::CompareFunc::Always:
985 pass = true;
986 break;
987
988 case FramebufferRegs::CompareFunc::Equal:
989 pass = (ref == dest);
990 break;
991
992 case FramebufferRegs::CompareFunc::NotEqual:
993 pass = (ref != dest);
994 break;
995
996 case FramebufferRegs::CompareFunc::LessThan:
997 pass = (ref < dest);
998 break;
999
1000 case FramebufferRegs::CompareFunc::LessThanOrEqual:
1001 pass = (ref <= dest);
1002 break;
1003
1004 case FramebufferRegs::CompareFunc::GreaterThan:
1005 pass = (ref > dest);
1006 break;
1007
1008 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
1009 pass = (ref >= dest);
1010 break;
1011 }
1012
1013 if (!pass) {
1014 UpdateStencil(stencil_test.action_stencil_fail);
1015 continue;
1016 }
1017 }
1018
1019 // Convert float to integer
1020 unsigned num_bits =
1021 FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
1022 u32 z = (u32)(depth * ((1 << num_bits) - 1));
1023
1024 if (output_merger.depth_test_enable) {
1025 u32 ref_z = GetDepth(x >> 4, y >> 4);
1026
1027 bool pass = false;
1028
1029 switch (output_merger.depth_test_func) {
1030 case FramebufferRegs::CompareFunc::Never:
1031 pass = false;
1032 break;
1033
1034 case FramebufferRegs::CompareFunc::Always:
1035 pass = true;
1036 break;
1037
1038 case FramebufferRegs::CompareFunc::Equal:
1039 pass = z == ref_z;
1040 break;
1041
1042 case FramebufferRegs::CompareFunc::NotEqual:
1043 pass = z != ref_z;
1044 break;
1045
1046 case FramebufferRegs::CompareFunc::LessThan:
1047 pass = z < ref_z;
1048 break;
1049
1050 case FramebufferRegs::CompareFunc::LessThanOrEqual:
1051 pass = z <= ref_z;
1052 break;
1053
1054 case FramebufferRegs::CompareFunc::GreaterThan:
1055 pass = z > ref_z;
1056 break;
1057
1058 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
1059 pass = z >= ref_z;
1060 break;
1061 }
1062
1063 if (!pass) {
1064 if (stencil_action_enable)
1065 UpdateStencil(stencil_test.action_depth_fail);
1066 continue;
1067 }
1068 }
1069
1070 if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
1071 output_merger.depth_write_enable) {
1072
1073 SetDepth(x >> 4, y >> 4, z);
1074 }
1075
1076 // The stencil depth_pass action is executed even if depth testing is disabled
1077 if (stencil_action_enable)
1078 UpdateStencil(stencil_test.action_depth_pass);
1079
1080 auto dest = GetPixel(x >> 4, y >> 4);
1081 Math::Vec4<u8> blend_output = combiner_output;
1082
1083 if (output_merger.alphablend_enable) {
1084 auto params = output_merger.alpha_blending;
1085
1086 auto LookupFactor = [&](unsigned channel,
1087 FramebufferRegs::BlendFactor factor) -> u8 {
1088 DEBUG_ASSERT(channel < 4);
1089
1090 const Math::Vec4<u8> blend_const = {
1091 static_cast<u8>(output_merger.blend_const.r),
1092 static_cast<u8>(output_merger.blend_const.g),
1093 static_cast<u8>(output_merger.blend_const.b),
1094 static_cast<u8>(output_merger.blend_const.a),
1095 };
1096
1097 switch (factor) {
1098 case FramebufferRegs::BlendFactor::Zero:
1099 return 0;
1100
1101 case FramebufferRegs::BlendFactor::One:
1102 return 255;
1103
1104 case FramebufferRegs::BlendFactor::SourceColor:
1105 return combiner_output[channel];
1106
1107 case FramebufferRegs::BlendFactor::OneMinusSourceColor:
1108 return 255 - combiner_output[channel];
1109
1110 case FramebufferRegs::BlendFactor::DestColor:
1111 return dest[channel];
1112
1113 case FramebufferRegs::BlendFactor::OneMinusDestColor:
1114 return 255 - dest[channel];
1115
1116 case FramebufferRegs::BlendFactor::SourceAlpha:
1117 return combiner_output.a();
1118
1119 case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
1120 return 255 - combiner_output.a();
1121
1122 case FramebufferRegs::BlendFactor::DestAlpha:
1123 return dest.a();
1124
1125 case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
1126 return 255 - dest.a();
1127
1128 case FramebufferRegs::BlendFactor::ConstantColor:
1129 return blend_const[channel];
1130
1131 case FramebufferRegs::BlendFactor::OneMinusConstantColor:
1132 return 255 - blend_const[channel];
1133
1134 case FramebufferRegs::BlendFactor::ConstantAlpha:
1135 return blend_const.a();
1136
1137 case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
1138 return 255 - blend_const.a();
1139
1140 case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
1141 // Returns 1.0 for the alpha channel
1142 if (channel == 3)
1143 return 255;
1144 return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
1145
1146 default:
1147 LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
1148 UNIMPLEMENTED();
1149 break;
1150 }
1151
1152 return combiner_output[channel];
1153 };
1154
1155 static auto EvaluateBlendEquation = [](
1156 const Math::Vec4<u8>& src, const Math::Vec4<u8>& srcfactor,
1157 const Math::Vec4<u8>& dest, const Math::Vec4<u8>& destfactor,
1158 FramebufferRegs::BlendEquation equation) {
1159
1160 Math::Vec4<int> result;
1161
1162 auto src_result = (src * srcfactor).Cast<int>();
1163 auto dst_result = (dest * destfactor).Cast<int>();
1164
1165 switch (equation) {
1166 case FramebufferRegs::BlendEquation::Add:
1167 result = (src_result + dst_result) / 255;
1168 break;
1169
1170 case FramebufferRegs::BlendEquation::Subtract:
1171 result = (src_result - dst_result) / 255;
1172 break;
1173
1174 case FramebufferRegs::BlendEquation::ReverseSubtract:
1175 result = (dst_result - src_result) / 255;
1176 break;
1177
1178 // TODO: How do these two actually work?
1179 // OpenGL doesn't include the blend factors in the min/max computations,
1180 // but is this what the 3DS actually does?
1181 case FramebufferRegs::BlendEquation::Min:
1182 result.r() = std::min(src.r(), dest.r());
1183 result.g() = std::min(src.g(), dest.g());
1184 result.b() = std::min(src.b(), dest.b());
1185 result.a() = std::min(src.a(), dest.a());
1186 break;
1187
1188 case FramebufferRegs::BlendEquation::Max:
1189 result.r() = std::max(src.r(), dest.r());
1190 result.g() = std::max(src.g(), dest.g());
1191 result.b() = std::max(src.b(), dest.b());
1192 result.a() = std::max(src.a(), dest.a());
1193 break;
1194
1195 default:
1196 LOG_CRITICAL(HW_GPU, "Unknown RGB blend equation %x", equation);
1197 UNIMPLEMENTED();
1198 }
1199
1200 return Math::Vec4<u8>(
1201 MathUtil::Clamp(result.r(), 0, 255), MathUtil::Clamp(result.g(), 0, 255),
1202 MathUtil::Clamp(result.b(), 0, 255), MathUtil::Clamp(result.a(), 0, 255));
1203 };
1204
1205 auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
1206 LookupFactor(1, params.factor_source_rgb),
1207 LookupFactor(2, params.factor_source_rgb),
1208 LookupFactor(3, params.factor_source_a));
1209
1210 auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
1211 LookupFactor(1, params.factor_dest_rgb),
1212 LookupFactor(2, params.factor_dest_rgb),
1213 LookupFactor(3, params.factor_dest_a));
1214
1215 blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
1216 params.blend_equation_rgb);
1217 blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
1218 dstfactor, params.blend_equation_a)
1219 .a();
1220 } else {
1221 static auto LogicOp = [](u8 src, u8 dest, FramebufferRegs::LogicOp op) -> u8 {
1222 switch (op) {
1223 case FramebufferRegs::LogicOp::Clear:
1224 return 0;
1225
1226 case FramebufferRegs::LogicOp::And:
1227 return src & dest;
1228
1229 case FramebufferRegs::LogicOp::AndReverse:
1230 return src & ~dest;
1231
1232 case FramebufferRegs::LogicOp::Copy:
1233 return src;
1234
1235 case FramebufferRegs::LogicOp::Set:
1236 return 255;
1237
1238 case FramebufferRegs::LogicOp::CopyInverted:
1239 return ~src;
1240
1241 case FramebufferRegs::LogicOp::NoOp:
1242 return dest;
1243
1244 case FramebufferRegs::LogicOp::Invert:
1245 return ~dest;
1246
1247 case FramebufferRegs::LogicOp::Nand:
1248 return ~(src & dest);
1249
1250 case FramebufferRegs::LogicOp::Or:
1251 return src | dest;
1252
1253 case FramebufferRegs::LogicOp::Nor:
1254 return ~(src | dest);
1255
1256 case FramebufferRegs::LogicOp::Xor:
1257 return src ^ dest;
1258
1259 case FramebufferRegs::LogicOp::Equiv:
1260 return ~(src ^ dest);
1261
1262 case FramebufferRegs::LogicOp::AndInverted:
1263 return ~src & dest;
1264
1265 case FramebufferRegs::LogicOp::OrReverse:
1266 return src | ~dest;
1267
1268 case FramebufferRegs::LogicOp::OrInverted:
1269 return ~src | dest;
1270 }
1271 };
1272
1273 blend_output =
1274 Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
1275 LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
1276 LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
1277 LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
1278 }
1279
1280 const Math::Vec4<u8> result = {
1281 output_merger.red_enable ? blend_output.r() : dest.r(),
1282 output_merger.green_enable ? blend_output.g() : dest.g(),
1283 output_merger.blue_enable ? blend_output.b() : dest.b(),
1284 output_merger.alpha_enable ? blend_output.a() : dest.a(),
1285 };
1286
1287 if (regs.framebuffer.framebuffer.allow_color_write != 0)
1288 DrawPixel(x >> 4, y >> 4, result);
1289 }
1290 }
1291}
1292
1293void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
1294 ProcessTriangleInternal(v0, v1, v2);
1295}
1296
1297} // namespace Rasterizer
1298
1299} // namespace Pica