summaryrefslogtreecommitdiff
path: root/src/video_core/swrasterizer
diff options
context:
space:
mode:
authorGravatar Yuri Kunde Schlesner2017-02-13 12:04:17 -0800
committerGravatar GitHub2017-02-13 12:04:17 -0800
commit1bf449d752f8e68c41321be68b3add7abc7f698f (patch)
tree5fbe02315127869eabd13c25b59c03f70e5759b8 /src/video_core/swrasterizer
parentCore: add cryptopp library (#2412) (diff)
parentSWRasterizer: Move more framebuffer functions to file (diff)
downloadyuzu-1bf449d752f8e68c41321be68b3add7abc7f698f.tar.gz
yuzu-1bf449d752f8e68c41321be68b3add7abc7f698f.tar.xz
yuzu-1bf449d752f8e68c41321be68b3add7abc7f698f.zip
Merge pull request #2562 from yuriks/pica-refactor3
Re-organize software rasterizer code
Diffstat (limited to 'src/video_core/swrasterizer')
-rw-r--r--src/video_core/swrasterizer/clipper.cpp178
-rw-r--r--src/video_core/swrasterizer/clipper.h21
-rw-r--r--src/video_core/swrasterizer/framebuffer.cpp358
-rw-r--r--src/video_core/swrasterizer/framebuffer.h29
-rw-r--r--src/video_core/swrasterizer/rasterizer.cpp750
-rw-r--r--src/video_core/swrasterizer/rasterizer.h48
-rw-r--r--src/video_core/swrasterizer/swrasterizer.cpp15
-rw-r--r--src/video_core/swrasterizer/swrasterizer.h27
-rw-r--r--src/video_core/swrasterizer/texturing.cpp228
-rw-r--r--src/video_core/swrasterizer/texturing.h28
10 files changed, 1682 insertions, 0 deletions
diff --git a/src/video_core/swrasterizer/clipper.cpp b/src/video_core/swrasterizer/clipper.cpp
new file mode 100644
index 000000000..2d80822d9
--- /dev/null
+++ b/src/video_core/swrasterizer/clipper.cpp
@@ -0,0 +1,178 @@
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 <cstddef>
8#include <boost/container/static_vector.hpp>
9#include <boost/container/vector.hpp>
10#include "common/bit_field.h"
11#include "common/common_types.h"
12#include "common/logging/log.h"
13#include "common/vector_math.h"
14#include "video_core/pica_state.h"
15#include "video_core/pica_types.h"
16#include "video_core/shader/shader.h"
17#include "video_core/swrasterizer/clipper.h"
18#include "video_core/swrasterizer/rasterizer.h"
19
20using Pica::Rasterizer::Vertex;
21
22namespace Pica {
23
24namespace Clipper {
25
26struct ClippingEdge {
27public:
28 ClippingEdge(Math::Vec4<float24> coeffs, Math::Vec4<float24> bias = Math::Vec4<float24>(
29 float24::FromFloat32(0), float24::FromFloat32(0),
30 float24::FromFloat32(0), float24::FromFloat32(0)))
31 : coeffs(coeffs), bias(bias) {}
32
33 bool IsInside(const Vertex& vertex) const {
34 return Math::Dot(vertex.pos + bias, coeffs) <= float24::FromFloat32(0);
35 }
36
37 bool IsOutSide(const Vertex& vertex) const {
38 return !IsInside(vertex);
39 }
40
41 Vertex GetIntersection(const Vertex& v0, const Vertex& v1) const {
42 float24 dp = Math::Dot(v0.pos + bias, coeffs);
43 float24 dp_prev = Math::Dot(v1.pos + bias, coeffs);
44 float24 factor = dp_prev / (dp_prev - dp);
45
46 return Vertex::Lerp(factor, v0, v1);
47 }
48
49private:
50 float24 pos;
51 Math::Vec4<float24> coeffs;
52 Math::Vec4<float24> bias;
53};
54
55static void InitScreenCoordinates(Vertex& vtx) {
56 struct {
57 float24 halfsize_x;
58 float24 offset_x;
59 float24 halfsize_y;
60 float24 offset_y;
61 float24 zscale;
62 float24 offset_z;
63 } viewport;
64
65 const auto& regs = g_state.regs;
66 viewport.halfsize_x = float24::FromRaw(regs.rasterizer.viewport_size_x);
67 viewport.halfsize_y = float24::FromRaw(regs.rasterizer.viewport_size_y);
68 viewport.offset_x = float24::FromFloat32(static_cast<float>(regs.rasterizer.viewport_corner.x));
69 viewport.offset_y = float24::FromFloat32(static_cast<float>(regs.rasterizer.viewport_corner.y));
70
71 float24 inv_w = float24::FromFloat32(1.f) / vtx.pos.w;
72 vtx.color *= inv_w;
73 vtx.view *= inv_w;
74 vtx.quat *= inv_w;
75 vtx.tc0 *= inv_w;
76 vtx.tc1 *= inv_w;
77 vtx.tc2 *= inv_w;
78 vtx.pos.w = inv_w;
79
80 vtx.screenpos[0] =
81 (vtx.pos.x * inv_w + float24::FromFloat32(1.0)) * viewport.halfsize_x + viewport.offset_x;
82 vtx.screenpos[1] =
83 (vtx.pos.y * inv_w + float24::FromFloat32(1.0)) * viewport.halfsize_y + viewport.offset_y;
84 vtx.screenpos[2] = vtx.pos.z * inv_w;
85}
86
87void ProcessTriangle(const OutputVertex& v0, const OutputVertex& v1, const OutputVertex& v2) {
88 using boost::container::static_vector;
89
90 // Clipping a planar n-gon against a plane will remove at least 1 vertex and introduces 2 at
91 // the new edge (or less in degenerate cases). As such, we can say that each clipping plane
92 // introduces at most 1 new vertex to the polygon. Since we start with a triangle and have a
93 // fixed 6 clipping planes, the maximum number of vertices of the clipped polygon is 3 + 6 = 9.
94 static const size_t MAX_VERTICES = 9;
95 static_vector<Vertex, MAX_VERTICES> buffer_a = {v0, v1, v2};
96 static_vector<Vertex, MAX_VERTICES> buffer_b;
97 auto* output_list = &buffer_a;
98 auto* input_list = &buffer_b;
99
100 // NOTE: We clip against a w=epsilon plane to guarantee that the output has a positive w value.
101 // TODO: Not sure if this is a valid approach. Also should probably instead use the smallest
102 // epsilon possible within float24 accuracy.
103 static const float24 EPSILON = float24::FromFloat32(0.00001f);
104 static const float24 f0 = float24::FromFloat32(0.0);
105 static const float24 f1 = float24::FromFloat32(1.0);
106 static const std::array<ClippingEdge, 7> clipping_edges = {{
107 {Math::MakeVec(f1, f0, f0, -f1)}, // x = +w
108 {Math::MakeVec(-f1, f0, f0, -f1)}, // x = -w
109 {Math::MakeVec(f0, f1, f0, -f1)}, // y = +w
110 {Math::MakeVec(f0, -f1, f0, -f1)}, // y = -w
111 {Math::MakeVec(f0, f0, f1, f0)}, // z = 0
112 {Math::MakeVec(f0, f0, -f1, -f1)}, // z = -w
113 {Math::MakeVec(f0, f0, f0, -f1), Math::Vec4<float24>(f0, f0, f0, EPSILON)}, // w = EPSILON
114 }};
115
116 // TODO: If one vertex lies outside one of the depth clipping planes, some platforms (e.g. Wii)
117 // drop the whole primitive instead of clipping the primitive properly. We should test if
118 // this happens on the 3DS, too.
119
120 // Simple implementation of the Sutherland-Hodgman clipping algorithm.
121 // TODO: Make this less inefficient (currently lots of useless buffering overhead happens here)
122 for (auto edge : clipping_edges) {
123
124 std::swap(input_list, output_list);
125 output_list->clear();
126
127 const Vertex* reference_vertex = &input_list->back();
128
129 for (const auto& vertex : *input_list) {
130 // NOTE: This algorithm changes vertex order in some cases!
131 if (edge.IsInside(vertex)) {
132 if (edge.IsOutSide(*reference_vertex)) {
133 output_list->push_back(edge.GetIntersection(vertex, *reference_vertex));
134 }
135
136 output_list->push_back(vertex);
137 } else if (edge.IsInside(*reference_vertex)) {
138 output_list->push_back(edge.GetIntersection(vertex, *reference_vertex));
139 }
140 reference_vertex = &vertex;
141 }
142
143 // Need to have at least a full triangle to continue...
144 if (output_list->size() < 3)
145 return;
146 }
147
148 InitScreenCoordinates((*output_list)[0]);
149 InitScreenCoordinates((*output_list)[1]);
150
151 for (size_t i = 0; i < output_list->size() - 2; i++) {
152 Vertex& vtx0 = (*output_list)[0];
153 Vertex& vtx1 = (*output_list)[i + 1];
154 Vertex& vtx2 = (*output_list)[i + 2];
155
156 InitScreenCoordinates(vtx2);
157
158 LOG_TRACE(Render_Software,
159 "Triangle %lu/%lu at position (%.3f, %.3f, %.3f, %.3f), "
160 "(%.3f, %.3f, %.3f, %.3f), (%.3f, %.3f, %.3f, %.3f) and "
161 "screen position (%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f)",
162 i + 1, output_list->size() - 2, vtx0.pos.x.ToFloat32(), vtx0.pos.y.ToFloat32(),
163 vtx0.pos.z.ToFloat32(), vtx0.pos.w.ToFloat32(), vtx1.pos.x.ToFloat32(),
164 vtx1.pos.y.ToFloat32(), vtx1.pos.z.ToFloat32(), vtx1.pos.w.ToFloat32(),
165 vtx2.pos.x.ToFloat32(), vtx2.pos.y.ToFloat32(), vtx2.pos.z.ToFloat32(),
166 vtx2.pos.w.ToFloat32(), vtx0.screenpos.x.ToFloat32(),
167 vtx0.screenpos.y.ToFloat32(), vtx0.screenpos.z.ToFloat32(),
168 vtx1.screenpos.x.ToFloat32(), vtx1.screenpos.y.ToFloat32(),
169 vtx1.screenpos.z.ToFloat32(), vtx2.screenpos.x.ToFloat32(),
170 vtx2.screenpos.y.ToFloat32(), vtx2.screenpos.z.ToFloat32());
171
172 Rasterizer::ProcessTriangle(vtx0, vtx1, vtx2);
173 }
174}
175
176} // namespace
177
178} // namespace
diff --git a/src/video_core/swrasterizer/clipper.h b/src/video_core/swrasterizer/clipper.h
new file mode 100644
index 000000000..b51af0af9
--- /dev/null
+++ b/src/video_core/swrasterizer/clipper.h
@@ -0,0 +1,21 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7namespace Pica {
8
9namespace Shader {
10struct OutputVertex;
11}
12
13namespace Clipper {
14
15using Shader::OutputVertex;
16
17void ProcessTriangle(const OutputVertex& v0, const OutputVertex& v1, const OutputVertex& v2);
18
19} // namespace
20
21} // namespace
diff --git a/src/video_core/swrasterizer/framebuffer.cpp b/src/video_core/swrasterizer/framebuffer.cpp
new file mode 100644
index 000000000..7de3aac75
--- /dev/null
+++ b/src/video_core/swrasterizer/framebuffer.cpp
@@ -0,0 +1,358 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6
7#include "common/assert.h"
8#include "common/color.h"
9#include "common/common_types.h"
10#include "common/logging/log.h"
11#include "common/math_util.h"
12#include "common/vector_math.h"
13#include "core/hw/gpu.h"
14#include "core/memory.h"
15#include "video_core/pica_state.h"
16#include "video_core/regs_framebuffer.h"
17#include "video_core/swrasterizer/framebuffer.h"
18#include "video_core/utils.h"
19
20namespace Pica {
21namespace Rasterizer {
22
23void DrawPixel(int x, int y, const Math::Vec4<u8>& color) {
24 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
25 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
26
27 // Similarly to textures, the render framebuffer is laid out from bottom to top, too.
28 // NOTE: The framebuffer height register contains the actual FB height minus one.
29 y = framebuffer.height - y;
30
31 const u32 coarse_y = y & ~7;
32 u32 bytes_per_pixel =
33 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
34 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
35 coarse_y * framebuffer.width * bytes_per_pixel;
36 u8* dst_pixel = Memory::GetPhysicalPointer(addr) + dst_offset;
37
38 switch (framebuffer.color_format) {
39 case FramebufferRegs::ColorFormat::RGBA8:
40 Color::EncodeRGBA8(color, dst_pixel);
41 break;
42
43 case FramebufferRegs::ColorFormat::RGB8:
44 Color::EncodeRGB8(color, dst_pixel);
45 break;
46
47 case FramebufferRegs::ColorFormat::RGB5A1:
48 Color::EncodeRGB5A1(color, dst_pixel);
49 break;
50
51 case FramebufferRegs::ColorFormat::RGB565:
52 Color::EncodeRGB565(color, dst_pixel);
53 break;
54
55 case FramebufferRegs::ColorFormat::RGBA4:
56 Color::EncodeRGBA4(color, dst_pixel);
57 break;
58
59 default:
60 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
61 framebuffer.color_format.Value());
62 UNIMPLEMENTED();
63 }
64}
65
66const Math::Vec4<u8> GetPixel(int x, int y) {
67 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
68 const PAddr addr = framebuffer.GetColorBufferPhysicalAddress();
69
70 y = framebuffer.height - y;
71
72 const u32 coarse_y = y & ~7;
73 u32 bytes_per_pixel =
74 GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
75 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
76 coarse_y * framebuffer.width * bytes_per_pixel;
77 u8* src_pixel = Memory::GetPhysicalPointer(addr) + src_offset;
78
79 switch (framebuffer.color_format) {
80 case FramebufferRegs::ColorFormat::RGBA8:
81 return Color::DecodeRGBA8(src_pixel);
82
83 case FramebufferRegs::ColorFormat::RGB8:
84 return Color::DecodeRGB8(src_pixel);
85
86 case FramebufferRegs::ColorFormat::RGB5A1:
87 return Color::DecodeRGB5A1(src_pixel);
88
89 case FramebufferRegs::ColorFormat::RGB565:
90 return Color::DecodeRGB565(src_pixel);
91
92 case FramebufferRegs::ColorFormat::RGBA4:
93 return Color::DecodeRGBA4(src_pixel);
94
95 default:
96 LOG_CRITICAL(Render_Software, "Unknown framebuffer color format %x",
97 framebuffer.color_format.Value());
98 UNIMPLEMENTED();
99 }
100
101 return {0, 0, 0, 0};
102}
103
104u32 GetDepth(int x, int y) {
105 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
106 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
107 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
108
109 y = framebuffer.height - y;
110
111 const u32 coarse_y = y & ~7;
112 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
113 u32 stride = framebuffer.width * bytes_per_pixel;
114
115 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
116 u8* src_pixel = depth_buffer + src_offset;
117
118 switch (framebuffer.depth_format) {
119 case FramebufferRegs::DepthFormat::D16:
120 return Color::DecodeD16(src_pixel);
121 case FramebufferRegs::DepthFormat::D24:
122 return Color::DecodeD24(src_pixel);
123 case FramebufferRegs::DepthFormat::D24S8:
124 return Color::DecodeD24S8(src_pixel).x;
125 default:
126 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
127 UNIMPLEMENTED();
128 return 0;
129 }
130}
131
132u8 GetStencil(int x, int y) {
133 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
134 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
135 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
136
137 y = framebuffer.height - y;
138
139 const u32 coarse_y = y & ~7;
140 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
141 u32 stride = framebuffer.width * bytes_per_pixel;
142
143 u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
144 u8* src_pixel = depth_buffer + src_offset;
145
146 switch (framebuffer.depth_format) {
147 case FramebufferRegs::DepthFormat::D24S8:
148 return Color::DecodeD24S8(src_pixel).y;
149
150 default:
151 LOG_WARNING(
152 HW_GPU,
153 "GetStencil called for function which doesn't have a stencil component (format %u)",
154 framebuffer.depth_format);
155 return 0;
156 }
157}
158
159void SetDepth(int x, int y, u32 value) {
160 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
161 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
162 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
163
164 y = framebuffer.height - y;
165
166 const u32 coarse_y = y & ~7;
167 u32 bytes_per_pixel = FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
168 u32 stride = framebuffer.width * bytes_per_pixel;
169
170 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
171 u8* dst_pixel = depth_buffer + dst_offset;
172
173 switch (framebuffer.depth_format) {
174 case FramebufferRegs::DepthFormat::D16:
175 Color::EncodeD16(value, dst_pixel);
176 break;
177
178 case FramebufferRegs::DepthFormat::D24:
179 Color::EncodeD24(value, dst_pixel);
180 break;
181
182 case FramebufferRegs::DepthFormat::D24S8:
183 Color::EncodeD24X8(value, dst_pixel);
184 break;
185
186 default:
187 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
188 UNIMPLEMENTED();
189 break;
190 }
191}
192
193void SetStencil(int x, int y, u8 value) {
194 const auto& framebuffer = g_state.regs.framebuffer.framebuffer;
195 const PAddr addr = framebuffer.GetDepthBufferPhysicalAddress();
196 u8* depth_buffer = Memory::GetPhysicalPointer(addr);
197
198 y = framebuffer.height - y;
199
200 const u32 coarse_y = y & ~7;
201 u32 bytes_per_pixel = Pica::FramebufferRegs::BytesPerDepthPixel(framebuffer.depth_format);
202 u32 stride = framebuffer.width * bytes_per_pixel;
203
204 u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * stride;
205 u8* dst_pixel = depth_buffer + dst_offset;
206
207 switch (framebuffer.depth_format) {
208 case Pica::FramebufferRegs::DepthFormat::D16:
209 case Pica::FramebufferRegs::DepthFormat::D24:
210 // Nothing to do
211 break;
212
213 case Pica::FramebufferRegs::DepthFormat::D24S8:
214 Color::EncodeX24S8(value, dst_pixel);
215 break;
216
217 default:
218 LOG_CRITICAL(HW_GPU, "Unimplemented depth format %u", framebuffer.depth_format);
219 UNIMPLEMENTED();
220 break;
221 }
222}
223
224u8 PerformStencilAction(FramebufferRegs::StencilAction action, u8 old_stencil, u8 ref) {
225 switch (action) {
226 case FramebufferRegs::StencilAction::Keep:
227 return old_stencil;
228
229 case FramebufferRegs::StencilAction::Zero:
230 return 0;
231
232 case FramebufferRegs::StencilAction::Replace:
233 return ref;
234
235 case FramebufferRegs::StencilAction::Increment:
236 // Saturated increment
237 return std::min<u8>(old_stencil, 254) + 1;
238
239 case FramebufferRegs::StencilAction::Decrement:
240 // Saturated decrement
241 return std::max<u8>(old_stencil, 1) - 1;
242
243 case FramebufferRegs::StencilAction::Invert:
244 return ~old_stencil;
245
246 case FramebufferRegs::StencilAction::IncrementWrap:
247 return old_stencil + 1;
248
249 case FramebufferRegs::StencilAction::DecrementWrap:
250 return old_stencil - 1;
251
252 default:
253 LOG_CRITICAL(HW_GPU, "Unknown stencil action %x", (int)action);
254 UNIMPLEMENTED();
255 return 0;
256 }
257}
258
259Math::Vec4<u8> EvaluateBlendEquation(const Math::Vec4<u8>& src, const Math::Vec4<u8>& srcfactor,
260 const Math::Vec4<u8>& dest, const Math::Vec4<u8>& destfactor,
261 FramebufferRegs::BlendEquation equation) {
262 Math::Vec4<int> result;
263
264 auto src_result = (src * srcfactor).Cast<int>();
265 auto dst_result = (dest * destfactor).Cast<int>();
266
267 switch (equation) {
268 case FramebufferRegs::BlendEquation::Add:
269 result = (src_result + dst_result) / 255;
270 break;
271
272 case FramebufferRegs::BlendEquation::Subtract:
273 result = (src_result - dst_result) / 255;
274 break;
275
276 case FramebufferRegs::BlendEquation::ReverseSubtract:
277 result = (dst_result - src_result) / 255;
278 break;
279
280 // TODO: How do these two actually work? OpenGL doesn't include the blend factors in the
281 // min/max computations, but is this what the 3DS actually does?
282 case FramebufferRegs::BlendEquation::Min:
283 result.r() = std::min(src.r(), dest.r());
284 result.g() = std::min(src.g(), dest.g());
285 result.b() = std::min(src.b(), dest.b());
286 result.a() = std::min(src.a(), dest.a());
287 break;
288
289 case FramebufferRegs::BlendEquation::Max:
290 result.r() = std::max(src.r(), dest.r());
291 result.g() = std::max(src.g(), dest.g());
292 result.b() = std::max(src.b(), dest.b());
293 result.a() = std::max(src.a(), dest.a());
294 break;
295
296 default:
297 LOG_CRITICAL(HW_GPU, "Unknown RGB blend equation %x", equation);
298 UNIMPLEMENTED();
299 }
300
301 return Math::Vec4<u8>(MathUtil::Clamp(result.r(), 0, 255), MathUtil::Clamp(result.g(), 0, 255),
302 MathUtil::Clamp(result.b(), 0, 255), MathUtil::Clamp(result.a(), 0, 255));
303};
304
305u8 LogicOp(u8 src, u8 dest, FramebufferRegs::LogicOp op) {
306 switch (op) {
307 case FramebufferRegs::LogicOp::Clear:
308 return 0;
309
310 case FramebufferRegs::LogicOp::And:
311 return src & dest;
312
313 case FramebufferRegs::LogicOp::AndReverse:
314 return src & ~dest;
315
316 case FramebufferRegs::LogicOp::Copy:
317 return src;
318
319 case FramebufferRegs::LogicOp::Set:
320 return 255;
321
322 case FramebufferRegs::LogicOp::CopyInverted:
323 return ~src;
324
325 case FramebufferRegs::LogicOp::NoOp:
326 return dest;
327
328 case FramebufferRegs::LogicOp::Invert:
329 return ~dest;
330
331 case FramebufferRegs::LogicOp::Nand:
332 return ~(src & dest);
333
334 case FramebufferRegs::LogicOp::Or:
335 return src | dest;
336
337 case FramebufferRegs::LogicOp::Nor:
338 return ~(src | dest);
339
340 case FramebufferRegs::LogicOp::Xor:
341 return src ^ dest;
342
343 case FramebufferRegs::LogicOp::Equiv:
344 return ~(src ^ dest);
345
346 case FramebufferRegs::LogicOp::AndInverted:
347 return ~src & dest;
348
349 case FramebufferRegs::LogicOp::OrReverse:
350 return src | ~dest;
351
352 case FramebufferRegs::LogicOp::OrInverted:
353 return ~src | dest;
354 }
355};
356
357} // namespace Rasterizer
358} // namespace Pica
diff --git a/src/video_core/swrasterizer/framebuffer.h b/src/video_core/swrasterizer/framebuffer.h
new file mode 100644
index 000000000..4a32a4979
--- /dev/null
+++ b/src/video_core/swrasterizer/framebuffer.h
@@ -0,0 +1,29 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "common/vector_math.h"
9#include "video_core/regs_framebuffer.h"
10
11namespace Pica {
12namespace Rasterizer {
13
14void DrawPixel(int x, int y, const Math::Vec4<u8>& color);
15const Math::Vec4<u8> GetPixel(int x, int y);
16u32 GetDepth(int x, int y);
17u8 GetStencil(int x, int y);
18void SetDepth(int x, int y, u32 value);
19void SetStencil(int x, int y, u8 value);
20u8 PerformStencilAction(FramebufferRegs::StencilAction action, u8 old_stencil, u8 ref);
21
22Math::Vec4<u8> EvaluateBlendEquation(const Math::Vec4<u8>& src, const Math::Vec4<u8>& srcfactor,
23 const Math::Vec4<u8>& dest, const Math::Vec4<u8>& destfactor,
24 FramebufferRegs::BlendEquation equation);
25
26u8 LogicOp(u8 src, u8 dest, FramebufferRegs::LogicOp op);
27
28} // namespace Rasterizer
29} // namespace Pica
diff --git a/src/video_core/swrasterizer/rasterizer.cpp b/src/video_core/swrasterizer/rasterizer.cpp
new file mode 100644
index 000000000..7557fcb89
--- /dev/null
+++ b/src/video_core/swrasterizer/rasterizer.cpp
@@ -0,0 +1,750 @@
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/framebuffer.h"
26#include "video_core/swrasterizer/rasterizer.h"
27#include "video_core/swrasterizer/texturing.h"
28#include "video_core/texture/texture_decode.h"
29#include "video_core/utils.h"
30
31namespace Pica {
32namespace Rasterizer {
33
34// NOTE: Assuming that rasterizer coordinates are 12.4 fixed-point values
35struct Fix12P4 {
36 Fix12P4() {}
37 Fix12P4(u16 val) : val(val) {}
38
39 static u16 FracMask() {
40 return 0xF;
41 }
42 static u16 IntMask() {
43 return (u16)~0xF;
44 }
45
46 operator u16() const {
47 return val;
48 }
49
50 bool operator<(const Fix12P4& oth) const {
51 return (u16) * this < (u16)oth;
52 }
53
54private:
55 u16 val;
56};
57
58/**
59 * Calculate signed area of the triangle spanned by the three argument vertices.
60 * The sign denotes an orientation.
61 *
62 * @todo define orientation concretely.
63 */
64static int SignedArea(const Math::Vec2<Fix12P4>& vtx1, const Math::Vec2<Fix12P4>& vtx2,
65 const Math::Vec2<Fix12P4>& vtx3) {
66 const auto vec1 = Math::MakeVec(vtx2 - vtx1, 0);
67 const auto vec2 = Math::MakeVec(vtx3 - vtx1, 0);
68 // TODO: There is a very small chance this will overflow for sizeof(int) == 4
69 return Math::Cross(vec1, vec2).z;
70};
71
72MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240));
73
74/**
75 * Helper function for ProcessTriangle with the "reversed" flag to allow for implementing
76 * culling via recursion.
77 */
78static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Vertex& v2,
79 bool reversed = false) {
80 const auto& regs = g_state.regs;
81 MICROPROFILE_SCOPE(GPU_Rasterization);
82
83 // vertex positions in rasterizer coordinates
84 static auto FloatToFix = [](float24 flt) {
85 // TODO: Rounding here is necessary to prevent garbage pixels at
86 // triangle borders. Is it that the correct solution, though?
87 return Fix12P4(static_cast<unsigned short>(round(flt.ToFloat32() * 16.0f)));
88 };
89 static auto ScreenToRasterizerCoordinates = [](const Math::Vec3<float24>& vec) {
90 return Math::Vec3<Fix12P4>{FloatToFix(vec.x), FloatToFix(vec.y), FloatToFix(vec.z)};
91 };
92
93 Math::Vec3<Fix12P4> vtxpos[3]{ScreenToRasterizerCoordinates(v0.screenpos),
94 ScreenToRasterizerCoordinates(v1.screenpos),
95 ScreenToRasterizerCoordinates(v2.screenpos)};
96
97 if (regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepAll) {
98 // Make sure we always end up with a triangle wound counter-clockwise
99 if (!reversed && SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0) {
100 ProcessTriangleInternal(v0, v2, v1, true);
101 return;
102 }
103 } else {
104 if (!reversed && regs.rasterizer.cull_mode == RasterizerRegs::CullMode::KeepClockWise) {
105 // Reverse vertex order and use the CCW code path.
106 ProcessTriangleInternal(v0, v2, v1, true);
107 return;
108 }
109
110 // Cull away triangles which are wound clockwise.
111 if (SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) <= 0)
112 return;
113 }
114
115 u16 min_x = std::min({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
116 u16 min_y = std::min({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
117 u16 max_x = std::max({vtxpos[0].x, vtxpos[1].x, vtxpos[2].x});
118 u16 max_y = std::max({vtxpos[0].y, vtxpos[1].y, vtxpos[2].y});
119
120 // Convert the scissor box coordinates to 12.4 fixed point
121 u16 scissor_x1 = (u16)(regs.rasterizer.scissor_test.x1 << 4);
122 u16 scissor_y1 = (u16)(regs.rasterizer.scissor_test.y1 << 4);
123 // x2,y2 have +1 added to cover the entire sub-pixel area
124 u16 scissor_x2 = (u16)((regs.rasterizer.scissor_test.x2 + 1) << 4);
125 u16 scissor_y2 = (u16)((regs.rasterizer.scissor_test.y2 + 1) << 4);
126
127 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Include) {
128 // Calculate the new bounds
129 min_x = std::max(min_x, scissor_x1);
130 min_y = std::max(min_y, scissor_y1);
131 max_x = std::min(max_x, scissor_x2);
132 max_y = std::min(max_y, scissor_y2);
133 }
134
135 min_x &= Fix12P4::IntMask();
136 min_y &= Fix12P4::IntMask();
137 max_x = ((max_x + Fix12P4::FracMask()) & Fix12P4::IntMask());
138 max_y = ((max_y + Fix12P4::FracMask()) & Fix12P4::IntMask());
139
140 // Triangle filling rules: Pixels on the right-sided edge or on flat bottom edges are not
141 // drawn. Pixels on any other triangle border are drawn. This is implemented with three bias
142 // values which are added to the barycentric coordinates w0, w1 and w2, respectively.
143 // NOTE: These are the PSP filling rules. Not sure if the 3DS uses the same ones...
144 auto IsRightSideOrFlatBottomEdge = [](const Math::Vec2<Fix12P4>& vtx,
145 const Math::Vec2<Fix12P4>& line1,
146 const Math::Vec2<Fix12P4>& line2) {
147 if (line1.y == line2.y) {
148 // just check if vertex is above us => bottom line parallel to x-axis
149 return vtx.y < line1.y;
150 } else {
151 // check if vertex is on our left => right side
152 // TODO: Not sure how likely this is to overflow
153 return (int)vtx.x < (int)line1.x +
154 ((int)line2.x - (int)line1.x) * ((int)vtx.y - (int)line1.y) /
155 ((int)line2.y - (int)line1.y);
156 }
157 };
158 int bias0 =
159 IsRightSideOrFlatBottomEdge(vtxpos[0].xy(), vtxpos[1].xy(), vtxpos[2].xy()) ? -1 : 0;
160 int bias1 =
161 IsRightSideOrFlatBottomEdge(vtxpos[1].xy(), vtxpos[2].xy(), vtxpos[0].xy()) ? -1 : 0;
162 int bias2 =
163 IsRightSideOrFlatBottomEdge(vtxpos[2].xy(), vtxpos[0].xy(), vtxpos[1].xy()) ? -1 : 0;
164
165 auto w_inverse = Math::MakeVec(v0.pos.w, v1.pos.w, v2.pos.w);
166
167 auto textures = regs.texturing.GetTextures();
168 auto tev_stages = regs.texturing.GetTevStages();
169
170 bool stencil_action_enable =
171 g_state.regs.framebuffer.output_merger.stencil_test.enable &&
172 g_state.regs.framebuffer.framebuffer.depth_format == FramebufferRegs::DepthFormat::D24S8;
173 const auto stencil_test = g_state.regs.framebuffer.output_merger.stencil_test;
174
175 // Enter rasterization loop, starting at the center of the topleft bounding box corner.
176 // TODO: Not sure if looping through x first might be faster
177 for (u16 y = min_y + 8; y < max_y; y += 0x10) {
178 for (u16 x = min_x + 8; x < max_x; x += 0x10) {
179
180 // Do not process the pixel if it's inside the scissor box and the scissor mode is set
181 // to Exclude
182 if (regs.rasterizer.scissor_test.mode == RasterizerRegs::ScissorMode::Exclude) {
183 if (x >= scissor_x1 && x < scissor_x2 && y >= scissor_y1 && y < scissor_y2)
184 continue;
185 }
186
187 // Calculate the barycentric coordinates w0, w1 and w2
188 int w0 = bias0 + SignedArea(vtxpos[1].xy(), vtxpos[2].xy(), {x, y});
189 int w1 = bias1 + SignedArea(vtxpos[2].xy(), vtxpos[0].xy(), {x, y});
190 int w2 = bias2 + SignedArea(vtxpos[0].xy(), vtxpos[1].xy(), {x, y});
191 int wsum = w0 + w1 + w2;
192
193 // If current pixel is not covered by the current primitive
194 if (w0 < 0 || w1 < 0 || w2 < 0)
195 continue;
196
197 auto baricentric_coordinates =
198 Math::MakeVec(float24::FromFloat32(static_cast<float>(w0)),
199 float24::FromFloat32(static_cast<float>(w1)),
200 float24::FromFloat32(static_cast<float>(w2)));
201 float24 interpolated_w_inverse =
202 float24::FromFloat32(1.0f) / Math::Dot(w_inverse, baricentric_coordinates);
203
204 // interpolated_z = z / w
205 float interpolated_z_over_w =
206 (v0.screenpos[2].ToFloat32() * w0 + v1.screenpos[2].ToFloat32() * w1 +
207 v2.screenpos[2].ToFloat32() * w2) /
208 wsum;
209
210 // Not fully accurate. About 3 bits in precision are missing.
211 // Z-Buffer (z / w * scale + offset)
212 float depth_scale = float24::FromRaw(regs.rasterizer.viewport_depth_range).ToFloat32();
213 float depth_offset =
214 float24::FromRaw(regs.rasterizer.viewport_depth_near_plane).ToFloat32();
215 float depth = interpolated_z_over_w * depth_scale + depth_offset;
216
217 // Potentially switch to W-Buffer
218 if (regs.rasterizer.depthmap_enable ==
219 Pica::RasterizerRegs::DepthBuffering::WBuffering) {
220 // W-Buffer (z * scale + w * offset = (z / w * scale + offset) * w)
221 depth *= interpolated_w_inverse.ToFloat32() * wsum;
222 }
223
224 // Clamp the result
225 depth = MathUtil::Clamp(depth, 0.0f, 1.0f);
226
227 // Perspective correct attribute interpolation:
228 // Attribute values cannot be calculated by simple linear interpolation since
229 // they are not linear in screen space. For example, when interpolating a
230 // texture coordinate across two vertices, something simple like
231 // u = (u0*w0 + u1*w1)/(w0+w1)
232 // will not work. However, the attribute value divided by the
233 // clipspace w-coordinate (u/w) and and the inverse w-coordinate (1/w) are linear
234 // in screenspace. Hence, we can linearly interpolate these two independently and
235 // calculate the interpolated attribute by dividing the results.
236 // I.e.
237 // u_over_w = ((u0/v0.pos.w)*w0 + (u1/v1.pos.w)*w1)/(w0+w1)
238 // one_over_w = (( 1/v0.pos.w)*w0 + ( 1/v1.pos.w)*w1)/(w0+w1)
239 // u = u_over_w / one_over_w
240 //
241 // The generalization to three vertices is straightforward in baricentric coordinates.
242 auto GetInterpolatedAttribute = [&](float24 attr0, float24 attr1, float24 attr2) {
243 auto attr_over_w = Math::MakeVec(attr0, attr1, attr2);
244 float24 interpolated_attr_over_w = Math::Dot(attr_over_w, baricentric_coordinates);
245 return interpolated_attr_over_w * interpolated_w_inverse;
246 };
247
248 Math::Vec4<u8> primary_color{
249 (u8)(
250 GetInterpolatedAttribute(v0.color.r(), v1.color.r(), v2.color.r()).ToFloat32() *
251 255),
252 (u8)(
253 GetInterpolatedAttribute(v0.color.g(), v1.color.g(), v2.color.g()).ToFloat32() *
254 255),
255 (u8)(
256 GetInterpolatedAttribute(v0.color.b(), v1.color.b(), v2.color.b()).ToFloat32() *
257 255),
258 (u8)(
259 GetInterpolatedAttribute(v0.color.a(), v1.color.a(), v2.color.a()).ToFloat32() *
260 255),
261 };
262
263 Math::Vec2<float24> uv[3];
264 uv[0].u() = GetInterpolatedAttribute(v0.tc0.u(), v1.tc0.u(), v2.tc0.u());
265 uv[0].v() = GetInterpolatedAttribute(v0.tc0.v(), v1.tc0.v(), v2.tc0.v());
266 uv[1].u() = GetInterpolatedAttribute(v0.tc1.u(), v1.tc1.u(), v2.tc1.u());
267 uv[1].v() = GetInterpolatedAttribute(v0.tc1.v(), v1.tc1.v(), v2.tc1.v());
268 uv[2].u() = GetInterpolatedAttribute(v0.tc2.u(), v1.tc2.u(), v2.tc2.u());
269 uv[2].v() = GetInterpolatedAttribute(v0.tc2.v(), v1.tc2.v(), v2.tc2.v());
270
271 Math::Vec4<u8> texture_color[3]{};
272 for (int i = 0; i < 3; ++i) {
273 const auto& texture = textures[i];
274 if (!texture.enabled)
275 continue;
276
277 DEBUG_ASSERT(0 != texture.config.address);
278
279 float24 u = uv[i].u();
280 float24 v = uv[i].v();
281
282 // Only unit 0 respects the texturing type (according to 3DBrew)
283 // TODO: Refactor so cubemaps and shadowmaps can be handled
284 if (i == 0) {
285 switch (texture.config.type) {
286 case TexturingRegs::TextureConfig::Texture2D:
287 break;
288 case TexturingRegs::TextureConfig::Projection2D: {
289 auto tc0_w = GetInterpolatedAttribute(v0.tc0_w, v1.tc0_w, v2.tc0_w);
290 u /= tc0_w;
291 v /= tc0_w;
292 break;
293 }
294 default:
295 // TODO: Change to LOG_ERROR when more types are handled.
296 LOG_DEBUG(HW_GPU, "Unhandled texture type %x", (int)texture.config.type);
297 UNIMPLEMENTED();
298 break;
299 }
300 }
301
302 int s = (int)(u * float24::FromFloat32(static_cast<float>(texture.config.width)))
303 .ToFloat32();
304 int t = (int)(v * float24::FromFloat32(static_cast<float>(texture.config.height)))
305 .ToFloat32();
306
307 if ((texture.config.wrap_s == TexturingRegs::TextureConfig::ClampToBorder &&
308 (s < 0 || static_cast<u32>(s) >= texture.config.width)) ||
309 (texture.config.wrap_t == TexturingRegs::TextureConfig::ClampToBorder &&
310 (t < 0 || static_cast<u32>(t) >= texture.config.height))) {
311 auto border_color = texture.config.border_color;
312 texture_color[i] = {border_color.r, border_color.g, border_color.b,
313 border_color.a};
314 } else {
315 // Textures are laid out from bottom to top, hence we invert the t coordinate.
316 // NOTE: This may not be the right place for the inversion.
317 // TODO: Check if this applies to ETC textures, too.
318 s = GetWrappedTexCoord(texture.config.wrap_s, s, texture.config.width);
319 t = texture.config.height - 1 -
320 GetWrappedTexCoord(texture.config.wrap_t, t, texture.config.height);
321
322 u8* texture_data =
323 Memory::GetPhysicalPointer(texture.config.GetPhysicalAddress());
324 auto info =
325 Texture::TextureInfo::FromPicaRegister(texture.config, texture.format);
326
327 // TODO: Apply the min and mag filters to the texture
328 texture_color[i] = Texture::LookupTexture(texture_data, s, t, info);
329#if PICA_DUMP_TEXTURES
330 DebugUtils::DumpTexture(texture.config, texture_data);
331#endif
332 }
333 }
334
335 // Texture environment - consists of 6 stages of color and alpha combining.
336 //
337 // Color combiners take three input color values from some source (e.g. interpolated
338 // vertex color, texture color, previous stage, etc), perform some very simple
339 // operations on each of them (e.g. inversion) and then calculate the output color
340 // with some basic arithmetic. Alpha combiners can be configured separately but work
341 // analogously.
342 Math::Vec4<u8> combiner_output;
343 Math::Vec4<u8> combiner_buffer = {0, 0, 0, 0};
344 Math::Vec4<u8> next_combiner_buffer = {
345 regs.texturing.tev_combiner_buffer_color.r,
346 regs.texturing.tev_combiner_buffer_color.g,
347 regs.texturing.tev_combiner_buffer_color.b,
348 regs.texturing.tev_combiner_buffer_color.a,
349 };
350
351 for (unsigned tev_stage_index = 0; tev_stage_index < tev_stages.size();
352 ++tev_stage_index) {
353 const auto& tev_stage = tev_stages[tev_stage_index];
354 using Source = TexturingRegs::TevStageConfig::Source;
355
356 auto GetSource = [&](Source source) -> Math::Vec4<u8> {
357 switch (source) {
358 case Source::PrimaryColor:
359
360 // HACK: Until we implement fragment lighting, use primary_color
361 case Source::PrimaryFragmentColor:
362 return primary_color;
363
364 // HACK: Until we implement fragment lighting, use zero
365 case Source::SecondaryFragmentColor:
366 return {0, 0, 0, 0};
367
368 case Source::Texture0:
369 return texture_color[0];
370
371 case Source::Texture1:
372 return texture_color[1];
373
374 case Source::Texture2:
375 return texture_color[2];
376
377 case Source::PreviousBuffer:
378 return combiner_buffer;
379
380 case Source::Constant:
381 return {tev_stage.const_r, tev_stage.const_g, tev_stage.const_b,
382 tev_stage.const_a};
383
384 case Source::Previous:
385 return combiner_output;
386
387 default:
388 LOG_ERROR(HW_GPU, "Unknown color combiner source %d", (int)source);
389 UNIMPLEMENTED();
390 return {0, 0, 0, 0};
391 }
392 };
393
394 // color combiner
395 // NOTE: Not sure if the alpha combiner might use the color output of the previous
396 // stage as input. Hence, we currently don't directly write the result to
397 // combiner_output.rgb(), but instead store it in a temporary variable until
398 // alpha combining has been done.
399 Math::Vec3<u8> color_result[3] = {
400 GetColorModifier(tev_stage.color_modifier1, GetSource(tev_stage.color_source1)),
401 GetColorModifier(tev_stage.color_modifier2, GetSource(tev_stage.color_source2)),
402 GetColorModifier(tev_stage.color_modifier3, GetSource(tev_stage.color_source3)),
403 };
404 auto color_output = ColorCombine(tev_stage.color_op, color_result);
405
406 // alpha combiner
407 std::array<u8, 3> alpha_result = {{
408 GetAlphaModifier(tev_stage.alpha_modifier1, GetSource(tev_stage.alpha_source1)),
409 GetAlphaModifier(tev_stage.alpha_modifier2, GetSource(tev_stage.alpha_source2)),
410 GetAlphaModifier(tev_stage.alpha_modifier3, GetSource(tev_stage.alpha_source3)),
411 }};
412 auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result);
413
414 combiner_output[0] =
415 std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier());
416 combiner_output[1] =
417 std::min((unsigned)255, color_output.g() * tev_stage.GetColorMultiplier());
418 combiner_output[2] =
419 std::min((unsigned)255, color_output.b() * tev_stage.GetColorMultiplier());
420 combiner_output[3] =
421 std::min((unsigned)255, alpha_output * tev_stage.GetAlphaMultiplier());
422
423 combiner_buffer = next_combiner_buffer;
424
425 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferColor(
426 tev_stage_index)) {
427 next_combiner_buffer.r() = combiner_output.r();
428 next_combiner_buffer.g() = combiner_output.g();
429 next_combiner_buffer.b() = combiner_output.b();
430 }
431
432 if (regs.texturing.tev_combiner_buffer_input.TevStageUpdatesCombinerBufferAlpha(
433 tev_stage_index)) {
434 next_combiner_buffer.a() = combiner_output.a();
435 }
436 }
437
438 const auto& output_merger = regs.framebuffer.output_merger;
439 // TODO: Does alpha testing happen before or after stencil?
440 if (output_merger.alpha_test.enable) {
441 bool pass = false;
442
443 switch (output_merger.alpha_test.func) {
444 case FramebufferRegs::CompareFunc::Never:
445 pass = false;
446 break;
447
448 case FramebufferRegs::CompareFunc::Always:
449 pass = true;
450 break;
451
452 case FramebufferRegs::CompareFunc::Equal:
453 pass = combiner_output.a() == output_merger.alpha_test.ref;
454 break;
455
456 case FramebufferRegs::CompareFunc::NotEqual:
457 pass = combiner_output.a() != output_merger.alpha_test.ref;
458 break;
459
460 case FramebufferRegs::CompareFunc::LessThan:
461 pass = combiner_output.a() < output_merger.alpha_test.ref;
462 break;
463
464 case FramebufferRegs::CompareFunc::LessThanOrEqual:
465 pass = combiner_output.a() <= output_merger.alpha_test.ref;
466 break;
467
468 case FramebufferRegs::CompareFunc::GreaterThan:
469 pass = combiner_output.a() > output_merger.alpha_test.ref;
470 break;
471
472 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
473 pass = combiner_output.a() >= output_merger.alpha_test.ref;
474 break;
475 }
476
477 if (!pass)
478 continue;
479 }
480
481 // Apply fog combiner
482 // Not fully accurate. We'd have to know what data type is used to
483 // store the depth etc. Using float for now until we know more
484 // about Pica datatypes
485 if (regs.texturing.fog_mode == TexturingRegs::FogMode::Fog) {
486 const Math::Vec3<u8> fog_color = {
487 static_cast<u8>(regs.texturing.fog_color.r.Value()),
488 static_cast<u8>(regs.texturing.fog_color.g.Value()),
489 static_cast<u8>(regs.texturing.fog_color.b.Value()),
490 };
491
492 // Get index into fog LUT
493 float fog_index;
494 if (g_state.regs.texturing.fog_flip) {
495 fog_index = (1.0f - depth) * 128.0f;
496 } else {
497 fog_index = depth * 128.0f;
498 }
499
500 // Generate clamped fog factor from LUT for given fog index
501 float fog_i = MathUtil::Clamp(floorf(fog_index), 0.0f, 127.0f);
502 float fog_f = fog_index - fog_i;
503 const auto& fog_lut_entry = g_state.fog.lut[static_cast<unsigned int>(fog_i)];
504 float fog_factor = (fog_lut_entry.value + fog_lut_entry.difference * fog_f) /
505 2047.0f; // This is signed fixed point 1.11
506 fog_factor = MathUtil::Clamp(fog_factor, 0.0f, 1.0f);
507
508 // Blend the fog
509 for (unsigned i = 0; i < 3; i++) {
510 combiner_output[i] = static_cast<u8>(fog_factor * combiner_output[i] +
511 (1.0f - fog_factor) * fog_color[i]);
512 }
513 }
514
515 u8 old_stencil = 0;
516
517 auto UpdateStencil = [stencil_test, x, y,
518 &old_stencil](Pica::FramebufferRegs::StencilAction action) {
519 u8 new_stencil =
520 PerformStencilAction(action, old_stencil, stencil_test.reference_value);
521 if (g_state.regs.framebuffer.framebuffer.allow_depth_stencil_write != 0)
522 SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) |
523 (old_stencil & ~stencil_test.write_mask));
524 };
525
526 if (stencil_action_enable) {
527 old_stencil = GetStencil(x >> 4, y >> 4);
528 u8 dest = old_stencil & stencil_test.input_mask;
529 u8 ref = stencil_test.reference_value & stencil_test.input_mask;
530
531 bool pass = false;
532 switch (stencil_test.func) {
533 case FramebufferRegs::CompareFunc::Never:
534 pass = false;
535 break;
536
537 case FramebufferRegs::CompareFunc::Always:
538 pass = true;
539 break;
540
541 case FramebufferRegs::CompareFunc::Equal:
542 pass = (ref == dest);
543 break;
544
545 case FramebufferRegs::CompareFunc::NotEqual:
546 pass = (ref != dest);
547 break;
548
549 case FramebufferRegs::CompareFunc::LessThan:
550 pass = (ref < dest);
551 break;
552
553 case FramebufferRegs::CompareFunc::LessThanOrEqual:
554 pass = (ref <= dest);
555 break;
556
557 case FramebufferRegs::CompareFunc::GreaterThan:
558 pass = (ref > dest);
559 break;
560
561 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
562 pass = (ref >= dest);
563 break;
564 }
565
566 if (!pass) {
567 UpdateStencil(stencil_test.action_stencil_fail);
568 continue;
569 }
570 }
571
572 // Convert float to integer
573 unsigned num_bits =
574 FramebufferRegs::DepthBitsPerPixel(regs.framebuffer.framebuffer.depth_format);
575 u32 z = (u32)(depth * ((1 << num_bits) - 1));
576
577 if (output_merger.depth_test_enable) {
578 u32 ref_z = GetDepth(x >> 4, y >> 4);
579
580 bool pass = false;
581
582 switch (output_merger.depth_test_func) {
583 case FramebufferRegs::CompareFunc::Never:
584 pass = false;
585 break;
586
587 case FramebufferRegs::CompareFunc::Always:
588 pass = true;
589 break;
590
591 case FramebufferRegs::CompareFunc::Equal:
592 pass = z == ref_z;
593 break;
594
595 case FramebufferRegs::CompareFunc::NotEqual:
596 pass = z != ref_z;
597 break;
598
599 case FramebufferRegs::CompareFunc::LessThan:
600 pass = z < ref_z;
601 break;
602
603 case FramebufferRegs::CompareFunc::LessThanOrEqual:
604 pass = z <= ref_z;
605 break;
606
607 case FramebufferRegs::CompareFunc::GreaterThan:
608 pass = z > ref_z;
609 break;
610
611 case FramebufferRegs::CompareFunc::GreaterThanOrEqual:
612 pass = z >= ref_z;
613 break;
614 }
615
616 if (!pass) {
617 if (stencil_action_enable)
618 UpdateStencil(stencil_test.action_depth_fail);
619 continue;
620 }
621 }
622
623 if (regs.framebuffer.framebuffer.allow_depth_stencil_write != 0 &&
624 output_merger.depth_write_enable) {
625
626 SetDepth(x >> 4, y >> 4, z);
627 }
628
629 // The stencil depth_pass action is executed even if depth testing is disabled
630 if (stencil_action_enable)
631 UpdateStencil(stencil_test.action_depth_pass);
632
633 auto dest = GetPixel(x >> 4, y >> 4);
634 Math::Vec4<u8> blend_output = combiner_output;
635
636 if (output_merger.alphablend_enable) {
637 auto params = output_merger.alpha_blending;
638
639 auto LookupFactor = [&](unsigned channel,
640 FramebufferRegs::BlendFactor factor) -> u8 {
641 DEBUG_ASSERT(channel < 4);
642
643 const Math::Vec4<u8> blend_const = {
644 static_cast<u8>(output_merger.blend_const.r),
645 static_cast<u8>(output_merger.blend_const.g),
646 static_cast<u8>(output_merger.blend_const.b),
647 static_cast<u8>(output_merger.blend_const.a),
648 };
649
650 switch (factor) {
651 case FramebufferRegs::BlendFactor::Zero:
652 return 0;
653
654 case FramebufferRegs::BlendFactor::One:
655 return 255;
656
657 case FramebufferRegs::BlendFactor::SourceColor:
658 return combiner_output[channel];
659
660 case FramebufferRegs::BlendFactor::OneMinusSourceColor:
661 return 255 - combiner_output[channel];
662
663 case FramebufferRegs::BlendFactor::DestColor:
664 return dest[channel];
665
666 case FramebufferRegs::BlendFactor::OneMinusDestColor:
667 return 255 - dest[channel];
668
669 case FramebufferRegs::BlendFactor::SourceAlpha:
670 return combiner_output.a();
671
672 case FramebufferRegs::BlendFactor::OneMinusSourceAlpha:
673 return 255 - combiner_output.a();
674
675 case FramebufferRegs::BlendFactor::DestAlpha:
676 return dest.a();
677
678 case FramebufferRegs::BlendFactor::OneMinusDestAlpha:
679 return 255 - dest.a();
680
681 case FramebufferRegs::BlendFactor::ConstantColor:
682 return blend_const[channel];
683
684 case FramebufferRegs::BlendFactor::OneMinusConstantColor:
685 return 255 - blend_const[channel];
686
687 case FramebufferRegs::BlendFactor::ConstantAlpha:
688 return blend_const.a();
689
690 case FramebufferRegs::BlendFactor::OneMinusConstantAlpha:
691 return 255 - blend_const.a();
692
693 case FramebufferRegs::BlendFactor::SourceAlphaSaturate:
694 // Returns 1.0 for the alpha channel
695 if (channel == 3)
696 return 255;
697 return std::min(combiner_output.a(), static_cast<u8>(255 - dest.a()));
698
699 default:
700 LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor);
701 UNIMPLEMENTED();
702 break;
703 }
704
705 return combiner_output[channel];
706 };
707
708 auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb),
709 LookupFactor(1, params.factor_source_rgb),
710 LookupFactor(2, params.factor_source_rgb),
711 LookupFactor(3, params.factor_source_a));
712
713 auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb),
714 LookupFactor(1, params.factor_dest_rgb),
715 LookupFactor(2, params.factor_dest_rgb),
716 LookupFactor(3, params.factor_dest_a));
717
718 blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor,
719 params.blend_equation_rgb);
720 blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest,
721 dstfactor, params.blend_equation_a)
722 .a();
723 } else {
724 blend_output =
725 Math::MakeVec(LogicOp(combiner_output.r(), dest.r(), output_merger.logic_op),
726 LogicOp(combiner_output.g(), dest.g(), output_merger.logic_op),
727 LogicOp(combiner_output.b(), dest.b(), output_merger.logic_op),
728 LogicOp(combiner_output.a(), dest.a(), output_merger.logic_op));
729 }
730
731 const Math::Vec4<u8> result = {
732 output_merger.red_enable ? blend_output.r() : dest.r(),
733 output_merger.green_enable ? blend_output.g() : dest.g(),
734 output_merger.blue_enable ? blend_output.b() : dest.b(),
735 output_merger.alpha_enable ? blend_output.a() : dest.a(),
736 };
737
738 if (regs.framebuffer.framebuffer.allow_color_write != 0)
739 DrawPixel(x >> 4, y >> 4, result);
740 }
741 }
742}
743
744void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2) {
745 ProcessTriangleInternal(v0, v1, v2);
746}
747
748} // namespace Rasterizer
749
750} // namespace Pica
diff --git a/src/video_core/swrasterizer/rasterizer.h b/src/video_core/swrasterizer/rasterizer.h
new file mode 100644
index 000000000..3a72ac343
--- /dev/null
+++ b/src/video_core/swrasterizer/rasterizer.h
@@ -0,0 +1,48 @@
1// Copyright 2014 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "video_core/shader/shader.h"
8
9namespace Pica {
10
11namespace Rasterizer {
12
13struct Vertex : Shader::OutputVertex {
14 Vertex(const OutputVertex& v) : OutputVertex(v) {}
15
16 // Attributes used to store intermediate results
17 // position after perspective divide
18 Math::Vec3<float24> screenpos;
19
20 // Linear interpolation
21 // factor: 0=this, 1=vtx
22 void Lerp(float24 factor, const Vertex& vtx) {
23 pos = pos * factor + vtx.pos * (float24::FromFloat32(1) - factor);
24
25 // TODO: Should perform perspective correct interpolation here...
26 tc0 = tc0 * factor + vtx.tc0 * (float24::FromFloat32(1) - factor);
27 tc1 = tc1 * factor + vtx.tc1 * (float24::FromFloat32(1) - factor);
28 tc2 = tc2 * factor + vtx.tc2 * (float24::FromFloat32(1) - factor);
29
30 screenpos = screenpos * factor + vtx.screenpos * (float24::FromFloat32(1) - factor);
31
32 color = color * factor + vtx.color * (float24::FromFloat32(1) - factor);
33 }
34
35 // Linear interpolation
36 // factor: 0=v0, 1=v1
37 static Vertex Lerp(float24 factor, const Vertex& v0, const Vertex& v1) {
38 Vertex ret = v0;
39 ret.Lerp(factor, v1);
40 return ret;
41 }
42};
43
44void ProcessTriangle(const Vertex& v0, const Vertex& v1, const Vertex& v2);
45
46} // namespace Rasterizer
47
48} // namespace Pica
diff --git a/src/video_core/swrasterizer/swrasterizer.cpp b/src/video_core/swrasterizer/swrasterizer.cpp
new file mode 100644
index 000000000..402b705dd
--- /dev/null
+++ b/src/video_core/swrasterizer/swrasterizer.cpp
@@ -0,0 +1,15 @@
1// Copyright 2015 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "video_core/swrasterizer/clipper.h"
6#include "video_core/swrasterizer/swrasterizer.h"
7
8namespace VideoCore {
9
10void SWRasterizer::AddTriangle(const Pica::Shader::OutputVertex& v0,
11 const Pica::Shader::OutputVertex& v1,
12 const Pica::Shader::OutputVertex& v2) {
13 Pica::Clipper::ProcessTriangle(v0, v1, v2);
14}
15}
diff --git a/src/video_core/swrasterizer/swrasterizer.h b/src/video_core/swrasterizer/swrasterizer.h
new file mode 100644
index 000000000..6d42d7409
--- /dev/null
+++ b/src/video_core/swrasterizer/swrasterizer.h
@@ -0,0 +1,27 @@
1// Copyright 2015 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "video_core/rasterizer_interface.h"
9
10namespace Pica {
11namespace Shader {
12struct OutputVertex;
13}
14}
15
16namespace VideoCore {
17
18class SWRasterizer : public RasterizerInterface {
19 void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1,
20 const Pica::Shader::OutputVertex& v2) override;
21 void DrawTriangles() override {}
22 void NotifyPicaRegisterChanged(u32 id) override {}
23 void FlushAll() override {}
24 void FlushRegion(PAddr addr, u32 size) override {}
25 void FlushAndInvalidateRegion(PAddr addr, u32 size) override {}
26};
27}
diff --git a/src/video_core/swrasterizer/texturing.cpp b/src/video_core/swrasterizer/texturing.cpp
new file mode 100644
index 000000000..eb18e4ba4
--- /dev/null
+++ b/src/video_core/swrasterizer/texturing.cpp
@@ -0,0 +1,228 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6
7#include "common/assert.h"
8#include "common/common_types.h"
9#include "common/math_util.h"
10#include "common/vector_math.h"
11#include "video_core/regs_texturing.h"
12#include "video_core/swrasterizer/texturing.h"
13
14namespace Pica {
15namespace Rasterizer {
16
17using TevStageConfig = TexturingRegs::TevStageConfig;
18
19int GetWrappedTexCoord(TexturingRegs::TextureConfig::WrapMode mode, int val, unsigned size) {
20 switch (mode) {
21 case TexturingRegs::TextureConfig::ClampToEdge:
22 val = std::max(val, 0);
23 val = std::min(val, (int)size - 1);
24 return val;
25
26 case TexturingRegs::TextureConfig::ClampToBorder:
27 return val;
28
29 case TexturingRegs::TextureConfig::Repeat:
30 return (int)((unsigned)val % size);
31
32 case TexturingRegs::TextureConfig::MirroredRepeat: {
33 unsigned int coord = ((unsigned)val % (2 * size));
34 if (coord >= size)
35 coord = 2 * size - 1 - coord;
36 return (int)coord;
37 }
38
39 default:
40 LOG_ERROR(HW_GPU, "Unknown texture coordinate wrapping mode %x", (int)mode);
41 UNIMPLEMENTED();
42 return 0;
43 }
44};
45
46Math::Vec3<u8> GetColorModifier(TevStageConfig::ColorModifier factor,
47 const Math::Vec4<u8>& values) {
48 using ColorModifier = TevStageConfig::ColorModifier;
49
50 switch (factor) {
51 case ColorModifier::SourceColor:
52 return values.rgb();
53
54 case ColorModifier::OneMinusSourceColor:
55 return (Math::Vec3<u8>(255, 255, 255) - values.rgb()).Cast<u8>();
56
57 case ColorModifier::SourceAlpha:
58 return values.aaa();
59
60 case ColorModifier::OneMinusSourceAlpha:
61 return (Math::Vec3<u8>(255, 255, 255) - values.aaa()).Cast<u8>();
62
63 case ColorModifier::SourceRed:
64 return values.rrr();
65
66 case ColorModifier::OneMinusSourceRed:
67 return (Math::Vec3<u8>(255, 255, 255) - values.rrr()).Cast<u8>();
68
69 case ColorModifier::SourceGreen:
70 return values.ggg();
71
72 case ColorModifier::OneMinusSourceGreen:
73 return (Math::Vec3<u8>(255, 255, 255) - values.ggg()).Cast<u8>();
74
75 case ColorModifier::SourceBlue:
76 return values.bbb();
77
78 case ColorModifier::OneMinusSourceBlue:
79 return (Math::Vec3<u8>(255, 255, 255) - values.bbb()).Cast<u8>();
80 }
81};
82
83u8 GetAlphaModifier(TevStageConfig::AlphaModifier factor, const Math::Vec4<u8>& values) {
84 using AlphaModifier = TevStageConfig::AlphaModifier;
85
86 switch (factor) {
87 case AlphaModifier::SourceAlpha:
88 return values.a();
89
90 case AlphaModifier::OneMinusSourceAlpha:
91 return 255 - values.a();
92
93 case AlphaModifier::SourceRed:
94 return values.r();
95
96 case AlphaModifier::OneMinusSourceRed:
97 return 255 - values.r();
98
99 case AlphaModifier::SourceGreen:
100 return values.g();
101
102 case AlphaModifier::OneMinusSourceGreen:
103 return 255 - values.g();
104
105 case AlphaModifier::SourceBlue:
106 return values.b();
107
108 case AlphaModifier::OneMinusSourceBlue:
109 return 255 - values.b();
110 }
111};
112
113Math::Vec3<u8> ColorCombine(TevStageConfig::Operation op, const Math::Vec3<u8> input[3]) {
114 using Operation = TevStageConfig::Operation;
115
116 switch (op) {
117 case Operation::Replace:
118 return input[0];
119
120 case Operation::Modulate:
121 return ((input[0] * input[1]) / 255).Cast<u8>();
122
123 case Operation::Add: {
124 auto result = input[0] + input[1];
125 result.r() = std::min(255, result.r());
126 result.g() = std::min(255, result.g());
127 result.b() = std::min(255, result.b());
128 return result.Cast<u8>();
129 }
130
131 case Operation::AddSigned: {
132 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to
133 // (byte) 128 is correct
134 auto result =
135 input[0].Cast<int>() + input[1].Cast<int>() - Math::MakeVec<int>(128, 128, 128);
136 result.r() = MathUtil::Clamp<int>(result.r(), 0, 255);
137 result.g() = MathUtil::Clamp<int>(result.g(), 0, 255);
138 result.b() = MathUtil::Clamp<int>(result.b(), 0, 255);
139 return result.Cast<u8>();
140 }
141
142 case Operation::Lerp:
143 return ((input[0] * input[2] +
144 input[1] * (Math::MakeVec<u8>(255, 255, 255) - input[2]).Cast<u8>()) /
145 255)
146 .Cast<u8>();
147
148 case Operation::Subtract: {
149 auto result = input[0].Cast<int>() - input[1].Cast<int>();
150 result.r() = std::max(0, result.r());
151 result.g() = std::max(0, result.g());
152 result.b() = std::max(0, result.b());
153 return result.Cast<u8>();
154 }
155
156 case Operation::MultiplyThenAdd: {
157 auto result = (input[0] * input[1] + 255 * input[2].Cast<int>()) / 255;
158 result.r() = std::min(255, result.r());
159 result.g() = std::min(255, result.g());
160 result.b() = std::min(255, result.b());
161 return result.Cast<u8>();
162 }
163
164 case Operation::AddThenMultiply: {
165 auto result = input[0] + input[1];
166 result.r() = std::min(255, result.r());
167 result.g() = std::min(255, result.g());
168 result.b() = std::min(255, result.b());
169 result = (result * input[2].Cast<int>()) / 255;
170 return result.Cast<u8>();
171 }
172 case Operation::Dot3_RGB: {
173 // Not fully accurate. Worst case scenario seems to yield a +/-3 error. Some HW results
174 // indicate that the per-component computation can't have a higher precision than 1/256,
175 // while dot3_rgb((0x80,g0,b0), (0x7F,g1,b1)) and dot3_rgb((0x80,g0,b0), (0x80,g1,b1)) give
176 // different results.
177 int result = ((input[0].r() * 2 - 255) * (input[1].r() * 2 - 255) + 128) / 256 +
178 ((input[0].g() * 2 - 255) * (input[1].g() * 2 - 255) + 128) / 256 +
179 ((input[0].b() * 2 - 255) * (input[1].b() * 2 - 255) + 128) / 256;
180 result = std::max(0, std::min(255, result));
181 return {(u8)result, (u8)result, (u8)result};
182 }
183 default:
184 LOG_ERROR(HW_GPU, "Unknown color combiner operation %d", (int)op);
185 UNIMPLEMENTED();
186 return {0, 0, 0};
187 }
188};
189
190u8 AlphaCombine(TevStageConfig::Operation op, const std::array<u8, 3>& input) {
191 switch (op) {
192 using Operation = TevStageConfig::Operation;
193 case Operation::Replace:
194 return input[0];
195
196 case Operation::Modulate:
197 return input[0] * input[1] / 255;
198
199 case Operation::Add:
200 return std::min(255, input[0] + input[1]);
201
202 case Operation::AddSigned: {
203 // TODO(bunnei): Verify that the color conversion from (float) 0.5f to (byte) 128 is correct
204 auto result = static_cast<int>(input[0]) + static_cast<int>(input[1]) - 128;
205 return static_cast<u8>(MathUtil::Clamp<int>(result, 0, 255));
206 }
207
208 case Operation::Lerp:
209 return (input[0] * input[2] + input[1] * (255 - input[2])) / 255;
210
211 case Operation::Subtract:
212 return std::max(0, (int)input[0] - (int)input[1]);
213
214 case Operation::MultiplyThenAdd:
215 return std::min(255, (input[0] * input[1] + 255 * input[2]) / 255);
216
217 case Operation::AddThenMultiply:
218 return (std::min(255, (input[0] + input[1])) * input[2]) / 255;
219
220 default:
221 LOG_ERROR(HW_GPU, "Unknown alpha combiner operation %d", (int)op);
222 UNIMPLEMENTED();
223 return 0;
224 }
225};
226
227} // namespace Rasterizer
228} // namespace Pica
diff --git a/src/video_core/swrasterizer/texturing.h b/src/video_core/swrasterizer/texturing.h
new file mode 100644
index 000000000..24f74a5a3
--- /dev/null
+++ b/src/video_core/swrasterizer/texturing.h
@@ -0,0 +1,28 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/common_types.h"
8#include "common/vector_math.h"
9#include "video_core/regs_texturing.h"
10
11namespace Pica {
12namespace Rasterizer {
13
14int GetWrappedTexCoord(TexturingRegs::TextureConfig::WrapMode mode, int val, unsigned size);
15
16Math::Vec3<u8> GetColorModifier(TexturingRegs::TevStageConfig::ColorModifier factor,
17 const Math::Vec4<u8>& values);
18
19u8 GetAlphaModifier(TexturingRegs::TevStageConfig::AlphaModifier factor,
20 const Math::Vec4<u8>& values);
21
22Math::Vec3<u8> ColorCombine(TexturingRegs::TevStageConfig::Operation op,
23 const Math::Vec3<u8> input[3]);
24
25u8 AlphaCombine(TexturingRegs::TevStageConfig::Operation op, const std::array<u8, 3>& input);
26
27} // namespace Rasterizer
28} // namespace Pica