Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/GPU/Software/TransformUnit.cpp
5656 views
1
// Copyright (c) 2013- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include "ppsspp_config.h"
19
20
#include <cmath>
21
22
#include "Common/Common.h"
23
#include "Common/CPUDetect.h"
24
#include "Common/Math/math_util.h"
25
#include "Common/MemoryUtil.h"
26
#include "Common/Profiler/Profiler.h"
27
#include "GPU/GPUState.h"
28
#include "GPU/Common/DrawEngineCommon.h"
29
#include "GPU/Common/VertexDecoderCommon.h"
30
#include "GPU/Common/SoftwareTransformCommon.h"
31
#include "Common/Math/SIMDHeaders.h"
32
#include "GPU/Software/BinManager.h"
33
#include "GPU/Software/Clipper.h"
34
#include "GPU/Software/Lighting.h"
35
#include "GPU/Software/RasterizerRectangle.h"
36
#include "GPU/Software/TransformUnit.h"
37
38
// For the SSE4 stuff
39
#if PPSSPP_ARCH(SSE2)
40
#include <smmintrin.h>
41
#endif
42
43
#define TRANSFORM_BUF_SIZE (65536 * 48)
44
45
TransformUnit::TransformUnit() {
46
decoded_ = (u8 *)AllocateAlignedMemory(TRANSFORM_BUF_SIZE, 16);
47
_assert_(decoded_);
48
binner_ = new BinManager();
49
}
50
51
TransformUnit::~TransformUnit() {
52
FreeAlignedMemory(decoded_);
53
delete binner_;
54
}
55
56
bool TransformUnit::IsStarted() {
57
return binner_ && decoded_;
58
}
59
60
SoftwareDrawEngine::SoftwareDrawEngine() {
61
flushOnParams_ = false;
62
}
63
64
SoftwareDrawEngine::~SoftwareDrawEngine() {}
65
66
void SoftwareDrawEngine::NotifyConfigChanged() {
67
DrawEngineCommon::NotifyConfigChanged();
68
applySkinInDecode_ = true;
69
}
70
71
void SoftwareDrawEngine::Flush() {
72
transformUnit.Flush(gpuCommon_, "debug");
73
}
74
75
void SoftwareDrawEngine::DispatchSubmitPrim(const void *verts, const void *inds, GEPrimitiveType prim, int vertexCount, u32 vertTypeID, bool clockwise, int *bytesRead) {
76
_assert_msg_(clockwise, "Mixed cull mode not supported.");
77
transformUnit.SubmitPrimitive(verts, inds, prim, vertexCount, vertTypeID, bytesRead, this);
78
}
79
80
void SoftwareDrawEngine::DispatchSubmitImm(GEPrimitiveType prim, TransformedVertex *buffer, int vertexCount, int cullMode, bool continuation) {
81
uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);
82
83
int flipCull = cullMode != gstate.getCullMode() ? 1 : 0;
84
// TODO: For now, just setting all dirty.
85
transformUnit.SetDirty(SoftDirty(-1));
86
gstate.cullmode ^= flipCull;
87
88
// TODO: This is a bit ugly. Should bypass when clipping...
89
uint32_t xScale = gstate.viewportxscale;
90
uint32_t xCenter = gstate.viewportxcenter;
91
uint32_t yScale = gstate.viewportyscale;
92
uint32_t yCenter = gstate.viewportycenter;
93
uint32_t zScale = gstate.viewportzscale;
94
uint32_t zCenter = gstate.viewportzcenter;
95
96
// Force scale to 1 and center to zero.
97
gstate.viewportxscale = (GE_CMD_VIEWPORTXSCALE << 24) | 0x3F8000;
98
gstate.viewportxcenter = (GE_CMD_VIEWPORTXCENTER << 24) | 0x000000;
99
gstate.viewportyscale = (GE_CMD_VIEWPORTYSCALE << 24) | 0x3F8000;
100
gstate.viewportycenter = (GE_CMD_VIEWPORTYCENTER << 24) | 0x000000;
101
// Z we scale to 65535 for neg z clipping.
102
gstate.viewportzscale = (GE_CMD_VIEWPORTZSCALE << 24) | 0x477FFF;
103
gstate.viewportzcenter = (GE_CMD_VIEWPORTZCENTER << 24) | 0x000000;
104
105
// Before we start, submit 0 prims to reset the prev prim type.
106
// Following submits will always be KEEP_PREVIOUS.
107
if (!continuation)
108
transformUnit.SubmitPrimitive(nullptr, nullptr, prim, 0, vertTypeID, nullptr, this);
109
110
for (int i = 0; i < vertexCount; i++) {
111
ClipVertexData vert;
112
vert.clippos = ClipCoords(buffer[i].pos);
113
vert.v.texturecoords.x = buffer[i].u;
114
vert.v.texturecoords.y = buffer[i].v;
115
vert.v.texturecoords.z = buffer[i].uv_w;
116
if (gstate.isModeThrough()) {
117
vert.v.texturecoords.x *= gstate.getTextureWidth(0);
118
vert.v.texturecoords.y *= gstate.getTextureHeight(0);
119
} else {
120
vert.clippos.z *= 1.0f / 65535.0f;
121
}
122
vert.v.clipw = buffer[i].pos_w;
123
vert.v.color0 = buffer[i].color0_32;
124
vert.v.color1 = gstate.isUsingSecondaryColor() && !gstate.isModeThrough() ? buffer[i].color1_32 : 0;
125
vert.v.fogdepth = buffer[i].fog;
126
vert.v.screenpos.x = (int)(buffer[i].x * 16.0f);
127
vert.v.screenpos.y = (int)(buffer[i].y * 16.0f);
128
vert.v.screenpos.z = (u16)(u32)buffer[i].z;
129
130
transformUnit.SubmitImmVertex(vert, this);
131
}
132
133
gstate.viewportxscale = xScale;
134
gstate.viewportxcenter = xCenter;
135
gstate.viewportyscale = yScale;
136
gstate.viewportycenter = yCenter;
137
gstate.viewportzscale = zScale;
138
gstate.viewportzcenter = zCenter;
139
140
gstate.cullmode ^= flipCull;
141
// TODO: Should really clear, but a bunch of values are forced so we this is safest.
142
transformUnit.SetDirty(SoftDirty(-1));
143
}
144
145
VertexDecoder *SoftwareDrawEngine::FindVertexDecoder(u32 vtype) {
146
const u32 vertTypeID = GetVertTypeID(vtype, gstate.getUVGenMode(), true);
147
return DrawEngineCommon::GetVertexDecoder(vertTypeID);
148
}
149
150
WorldCoords TransformUnit::ModelToWorld(const ModelCoords &coords) {
151
return Vec3ByMatrix43(coords, gstate.worldMatrix);
152
}
153
154
WorldCoords TransformUnit::ModelToWorldNormal(const ModelCoords &coords) {
155
return Norm3ByMatrix43(coords, gstate.worldMatrix);
156
}
157
158
template <bool depthClamp, bool alwaysCheckRange>
159
static ScreenCoords ClipToScreenInternal(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag) {
160
ScreenCoords ret;
161
162
// Account for rounding for X and Y.
163
// TODO: Validate actual rounding range.
164
const float SCREEN_BOUND = 4095.0f + (15.5f / 16.0f);
165
166
// This matches hardware tests - depth is clamped when this flag is on.
167
if constexpr (depthClamp) {
168
// Note: if the depth is clipped (z/w <= -1.0), the outside_range_flag should NOT be set, even for x and y.
169
if ((alwaysCheckRange || coords.z > -coords.w) && (scaled.x >= SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0)) {
170
*outside_range_flag = true;
171
}
172
173
if (scaled.z < 0.f)
174
scaled.z = 0.f;
175
else if (scaled.z > 65535.0f)
176
scaled.z = 65535.0f;
177
} else if (scaled.x > SCREEN_BOUND || scaled.y >= SCREEN_BOUND || scaled.x < 0 || scaled.y < 0 || scaled.z < 0.0f || scaled.z >= 65536.0f) {
178
*outside_range_flag = true;
179
}
180
181
// 16 = 0xFFFF / 4095.9375
182
// Round up at 0.625 to the nearest subpixel.
183
static_assert(SCREEN_SCALE_FACTOR == 16, "Currently only supports scale 16");
184
int x = (int)(scaled.x * 16.0f + 0.375f - gstate.getOffsetX16());
185
int y = (int)(scaled.y * 16.0f + 0.375f - gstate.getOffsetY16());
186
return ScreenCoords(x, y, scaled.z);
187
}
188
189
static inline ScreenCoords ClipToScreenInternal(const ClipCoords &coords, bool *outside_range_flag) {
190
// Parameters here can seem invalid, but the PSP is fine with negative viewport widths etc.
191
// The checking that OpenGL and D3D do is actually quite superflous as the calculations still "work"
192
// with some pretty crazy inputs, which PSP games are happy to do at times.
193
float xScale = gstate.getViewportXScale();
194
float xCenter = gstate.getViewportXCenter();
195
float yScale = gstate.getViewportYScale();
196
float yCenter = gstate.getViewportYCenter();
197
float zScale = gstate.getViewportZScale();
198
float zCenter = gstate.getViewportZCenter();
199
200
float x = coords.x * xScale / coords.w + xCenter;
201
float y = coords.y * yScale / coords.w + yCenter;
202
float z = coords.z * zScale / coords.w + zCenter;
203
204
if (gstate.isDepthClampEnabled()) {
205
return ClipToScreenInternal<true, true>(Vec3f(x, y, z), coords, outside_range_flag);
206
}
207
return ClipToScreenInternal<false, true>(Vec3f(x, y, z), coords, outside_range_flag);
208
}
209
210
ScreenCoords TransformUnit::ClipToScreen(const ClipCoords &coords, bool *outsideRangeFlag) {
211
return ClipToScreenInternal(coords, outsideRangeFlag);
212
}
213
214
ScreenCoords TransformUnit::DrawingToScreen(const DrawingCoords &coords, u16 z) {
215
ScreenCoords ret;
216
ret.x = (u32)coords.x * SCREEN_SCALE_FACTOR;
217
ret.y = (u32)coords.y * SCREEN_SCALE_FACTOR;
218
ret.z = z;
219
return ret;
220
}
221
222
enum class MatrixMode {
223
POS_TO_CLIP = 1,
224
WORLD_TO_CLIP = 2,
225
};
226
227
struct TransformState {
228
Lighting::State lightingState;
229
230
float matrix[16];
231
Vec4f posToFog;
232
Vec3f screenScale;
233
Vec3f screenAdd;
234
235
ScreenCoords(*roundToScreen)(Vec3f scaled, const ClipCoords &coords, bool *outside_range_flag);
236
237
struct {
238
bool enableTransform : 1;
239
bool enableLighting : 1;
240
bool enableFog : 1;
241
bool readUV : 1;
242
bool negateNormals : 1;
243
uint8_t uvGenMode : 2;
244
uint8_t matrixMode : 2;
245
};
246
};
247
248
void ComputeTransformState(TransformState *state, const VertexReader &vreader) {
249
state->enableTransform = !vreader.isThrough();
250
state->enableLighting = gstate.isLightingEnabled();
251
state->enableFog = gstate.isFogEnabled();
252
state->readUV = !gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV();
253
state->negateNormals = gstate.areNormalsReversed();
254
255
state->uvGenMode = gstate.getUVGenMode();
256
if (state->uvGenMode == GE_TEXMAP_UNKNOWN)
257
state->uvGenMode = GE_TEXMAP_TEXTURE_COORDS;
258
259
if (state->enableTransform) {
260
bool canSkipWorldPos = true;
261
if (state->enableLighting) {
262
Lighting::ComputeState(&state->lightingState, vreader.hasColor0());
263
canSkipWorldPos = !state->lightingState.usesWorldPos;
264
} else {
265
state->lightingState.usesWorldNormal = state->uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP;
266
}
267
268
float world[16];
269
float view[16];
270
float worldview[16];
271
ConvertMatrix4x3To4x4(view, gstate.viewMatrix);
272
if (state->enableFog || canSkipWorldPos) {
273
ConvertMatrix4x3To4x4(world, gstate.worldMatrix);
274
Matrix4ByMatrix4(worldview, world, view);
275
}
276
277
if (canSkipWorldPos) {
278
state->matrixMode = (uint8_t)MatrixMode::POS_TO_CLIP;
279
Matrix4ByMatrix4(state->matrix, worldview, gstate.projMatrix);
280
} else {
281
state->matrixMode = (uint8_t)MatrixMode::WORLD_TO_CLIP;
282
Matrix4ByMatrix4(state->matrix, view, gstate.projMatrix);
283
}
284
285
if (state->enableFog) {
286
float fogEnd = getFloat24(gstate.fog1);
287
float fogSlope = getFloat24(gstate.fog2);
288
289
// We bake fog end and slope into the dot product.
290
state->posToFog = Vec4f(worldview[2], worldview[6], worldview[10], worldview[14] + fogEnd);
291
292
// If either are NAN/INF, we simplify so there's no inf + -inf muddying things.
293
// This is required for Outrun to render proper skies, for example.
294
// The PSP treats these exponents as if they were valid.
295
if (my_isnanorinf(fogEnd)) {
296
bool sign = std::signbit(fogEnd);
297
// The multiply would reverse it if it wasn't infinity (doesn't matter if it's infnan.)
298
if (std::signbit(fogSlope))
299
sign = !sign;
300
// Also allow a multiply by zero (slope) to result in zero, regardless of sign.
301
// Act like it was negative and clamped to zero.
302
if (fogSlope == 0.0f)
303
sign = true;
304
305
// Since this is constant for the entire draw, we don't even use infinity.
306
float forced = sign ? 0.0f : 1.0f;
307
state->posToFog = Vec4f(0.0f, 0.0f, 0.0f, forced);
308
} else if (my_isnanorinf(fogSlope)) {
309
// We can't have signs differ with infinities, so we use a large value.
310
// Anything outside [0, 1] will clamp, so this essentially forces extremes.
311
fogSlope = std::signbit(fogSlope) ? -262144.0f : 262144.0f;
312
state->posToFog *= fogSlope;
313
} else {
314
state->posToFog *= fogSlope;
315
}
316
}
317
318
state->screenScale = Vec3f(gstate.getViewportXScale(), gstate.getViewportYScale(), gstate.getViewportZScale());
319
state->screenAdd = Vec3f(gstate.getViewportXCenter(), gstate.getViewportYCenter(), gstate.getViewportZCenter());
320
}
321
322
if (gstate.isDepthClampEnabled())
323
state->roundToScreen = &ClipToScreenInternal<true, false>;
324
else
325
state->roundToScreen = &ClipToScreenInternal<false, false>;
326
}
327
328
#if defined(_M_SSE)
329
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)
330
[[gnu::target("sse4.1")]]
331
#endif
332
static inline __m128 Dot43SSE4(__m128 a, __m128 b) {
333
__m128 multiplied = _mm_mul_ps(a, _mm_insert_ps(b, _mm_set1_ps(1.0f), 0x30));
334
__m128 lanes3311 = _mm_movehdup_ps(multiplied);
335
__m128 partial = _mm_add_ps(multiplied, lanes3311);
336
return _mm_add_ss(partial, _mm_movehl_ps(lanes3311, partial));
337
}
338
#endif
339
340
static inline float Dot43(const Vec4f &a, const Vec3f &b) {
341
#if defined(_M_SSE) && !PPSSPP_ARCH(X86)
342
if (cpu_info.bSSE4_1)
343
return _mm_cvtss_f32(Dot43SSE4(a.vec, b.vec));
344
#elif PPSSPP_ARCH(ARM64_NEON)
345
float32x4_t multipled = vmulq_f32(a.vec, vsetq_lane_f32(1.0f, b.vec, 3));
346
float32x2_t add1 = vget_low_f32(vpaddq_f32(multipled, multipled));
347
float32x2_t add2 = vpadd_f32(add1, add1);
348
return vget_lane_f32(add2, 0);
349
#endif
350
return Dot(a, Vec4f(b, 1.0f));
351
}
352
353
ClipVertexData TransformUnit::ReadVertex(const VertexReader &vreader, const TransformState &state) {
354
PROFILE_THIS_SCOPE("read_vert");
355
// If we ever thread this, we'll have to change this.
356
ClipVertexData vertex;
357
358
ModelCoords pos;
359
// VertexDecoder normally scales z, but we want it unscaled.
360
vreader.ReadPosThroughZ16(pos.AsArray());
361
362
static Vec3Packedf lastTC;
363
if (state.readUV) {
364
vreader.ReadUV(vertex.v.texturecoords.AsArray());
365
vertex.v.texturecoords.q() = 0.0f;
366
lastTC = vertex.v.texturecoords;
367
} else {
368
vertex.v.texturecoords = lastTC;
369
}
370
371
static Vec3f lastnormal;
372
if (vreader.hasNormal())
373
vreader.ReadNrm(lastnormal.AsArray());
374
Vec3f normal = lastnormal;
375
if (state.negateNormals)
376
normal = -normal;
377
378
if (vreader.hasColor0()) {
379
vertex.v.color0 = vreader.ReadColor0_8888();
380
} else {
381
vertex.v.color0 = gstate.getMaterialAmbientRGBA();
382
}
383
384
vertex.v.color1 = 0;
385
386
if (state.enableTransform) {
387
WorldCoords worldpos;
388
389
switch (MatrixMode(state.matrixMode)) {
390
case MatrixMode::POS_TO_CLIP:
391
vertex.clippos = Vec3ByMatrix44(pos, state.matrix);
392
break;
393
394
case MatrixMode::WORLD_TO_CLIP:
395
worldpos = TransformUnit::ModelToWorld(pos);
396
vertex.clippos = Vec3ByMatrix44(worldpos, state.matrix);
397
break;
398
}
399
400
Vec3f screenScaled;
401
#ifdef _M_SSE
402
screenScaled.vec = _mm_mul_ps(vertex.clippos.vec, state.screenScale.vec);
403
screenScaled.vec = _mm_div_ps(screenScaled.vec, _mm_shuffle_ps(vertex.clippos.vec, vertex.clippos.vec, _MM_SHUFFLE(3, 3, 3, 3)));
404
screenScaled.vec = _mm_add_ps(screenScaled.vec, state.screenAdd.vec);
405
#else
406
screenScaled = vertex.clippos.xyz() * state.screenScale / vertex.clippos.w + state.screenAdd;
407
#endif
408
bool outside_range_flag = false;
409
vertex.v.screenpos = state.roundToScreen(screenScaled, vertex.clippos, &outside_range_flag);
410
if (outside_range_flag) {
411
// We use this, essentially, as the flag.
412
vertex.v.screenpos.x = 0x7FFFFFFF;
413
return vertex;
414
}
415
416
if (state.enableFog) {
417
vertex.v.fogdepth = Dot43(state.posToFog, pos);
418
} else {
419
vertex.v.fogdepth = 1.0f;
420
}
421
vertex.v.clipw = vertex.clippos.w;
422
423
Vec3<float> worldnormal;
424
if (state.lightingState.usesWorldNormal) {
425
worldnormal = TransformUnit::ModelToWorldNormal(normal);
426
worldnormal.NormalizeOr001();
427
}
428
429
// Time to generate some texture coords. Lighting will handle shade mapping.
430
if (state.uvGenMode == GE_TEXMAP_TEXTURE_MATRIX) {
431
Vec3f source;
432
switch (gstate.getUVProjMode()) {
433
case GE_PROJMAP_POSITION:
434
source = pos;
435
break;
436
437
case GE_PROJMAP_UV:
438
source = Vec3f(vertex.v.texturecoords.uv(), 0.0f);
439
break;
440
441
case GE_PROJMAP_NORMALIZED_NORMAL:
442
// This does not use 0, 0, 1 if length is zero.
443
source = normal.Normalized(cpu_info.bSSE4_1);
444
break;
445
446
case GE_PROJMAP_NORMAL:
447
source = normal;
448
break;
449
}
450
451
// Note that UV scale/offset are not used in this mode.
452
Vec3<float> stq = Vec3ByMatrix43(source, gstate.tgenMatrix);
453
vertex.v.texturecoords = Vec3Packedf(stq.x, stq.y, stq.z);
454
} else if (state.uvGenMode == GE_TEXMAP_ENVIRONMENT_MAP) {
455
Lighting::GenerateLightST(vertex.v, worldnormal);
456
}
457
458
PROFILE_THIS_SCOPE("light");
459
if (state.enableLighting)
460
Lighting::Process(vertex.v, worldpos, worldnormal, state.lightingState);
461
} else {
462
vertex.v.screenpos.x = (int)(pos[0] * SCREEN_SCALE_FACTOR);
463
vertex.v.screenpos.y = (int)(pos[1] * SCREEN_SCALE_FACTOR);
464
vertex.v.screenpos.z = pos[2];
465
vertex.v.clipw = 1.0f;
466
vertex.v.fogdepth = 1.0f;
467
}
468
469
return vertex;
470
}
471
472
void TransformUnit::SetDirty(SoftDirty flags) {
473
binner_->SetDirty(flags);
474
}
475
SoftDirty TransformUnit::GetDirty() {
476
return binner_->GetDirty();
477
}
478
479
class SoftwareVertexReader {
480
public:
481
SoftwareVertexReader(u8 *base, VertexDecoder &vdecoder, u32 vertex_type, int vertex_count, const void *vertices, const void *indices, const TransformState &transformState, TransformUnit &transform)
482
: vreader_(base, vdecoder.GetDecVtxFmt(), vertex_type), conv_(vertex_type, indices), transformState_(transformState), transform_(transform) {
483
useIndices_ = indices != nullptr;
484
lowerBound_ = 0;
485
upperBound_ = vertex_count == 0 ? 0 : vertex_count - 1;
486
487
if (useIndices_)
488
GetIndexBounds(indices, vertex_count, vertex_type, &lowerBound_, &upperBound_);
489
if (vertex_count != 0) {
490
const int count = upperBound_ - lowerBound_ + 1;
491
vdecoder.DecodeVerts(base, (const u8 *)vertices + vdecoder.VertexSize() * lowerBound_, &gstate_c.uv, count);
492
}
493
494
// If we're only using a subset of verts, it's better to decode with random access (usually.)
495
// However, if we're reusing a lot of verts, we should read and cache them.
496
useCache_ = useIndices_ && vertex_count > (upperBound_ - lowerBound_ + 1);
497
if (useCache_ && (int)cached_.size() < upperBound_ - lowerBound_ + 1)
498
cached_.resize(std::max(128, upperBound_ - lowerBound_ + 1));
499
}
500
501
const VertexReader &GetVertexReader() const {
502
return vreader_;
503
}
504
505
bool IsThrough() const {
506
return vreader_.isThrough();
507
}
508
509
void UpdateCache() {
510
if (!useCache_)
511
return;
512
513
for (int i = 0; i < upperBound_ - lowerBound_ + 1; ++i) {
514
vreader_.Goto(i);
515
cached_[i] = transform_.ReadVertex(vreader_, transformState_);
516
}
517
}
518
519
inline ClipVertexData Read(int vtx) {
520
if (useIndices_) {
521
if (useCache_) {
522
return cached_[conv_(vtx) - lowerBound_];
523
}
524
vreader_.Goto(conv_(vtx) - lowerBound_);
525
} else {
526
vreader_.Goto(vtx);
527
}
528
529
return transform_.ReadVertex(vreader_, transformState_);
530
};
531
532
protected:
533
VertexReader vreader_;
534
const IndexConverter conv_;
535
const TransformState &transformState_;
536
TransformUnit &transform_;
537
uint16_t lowerBound_;
538
uint16_t upperBound_;
539
static std::vector<ClipVertexData> cached_;
540
bool useIndices_ = false;
541
bool useCache_ = false;
542
};
543
544
// Static to reduce allocations mid-frame.
545
std::vector<ClipVertexData> SoftwareVertexReader::cached_;
546
547
void TransformUnit::SubmitPrimitive(const void* vertices, const void* indices, GEPrimitiveType prim_type, int vertex_count, u32 vertex_type, int *bytesRead, SoftwareDrawEngine *drawEngine)
548
{
549
VertexDecoder &vdecoder = *drawEngine->FindVertexDecoder(vertex_type);
550
551
if (bytesRead)
552
*bytesRead = vertex_count * vdecoder.VertexSize();
553
554
// Frame skipping.
555
if (gstate_c.skipDrawReason & SKIPDRAW_SKIPFRAME) {
556
return;
557
}
558
// Vertices without position are just entirely culled.
559
// Note: Throughmode does draw 8-bit primitives, but positions are always zero - handled in decode.
560
if ((vertex_type & GE_VTYPE_POS_MASK) == 0)
561
return;
562
563
static TransformState transformState;
564
SoftwareVertexReader vreader(decoded_, vdecoder, vertex_type, vertex_count, vertices, indices, transformState, *this);
565
566
if (prim_type != GE_PRIM_KEEP_PREVIOUS) {
567
data_index_ = 0;
568
prev_prim_ = prim_type;
569
} else {
570
prim_type = prev_prim_;
571
}
572
573
binner_->UpdateState();
574
hasDraws_ = true;
575
576
if (binner_->HasDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL)) {
577
ComputeTransformState(&transformState, vreader.GetVertexReader());
578
binner_->ClearDirty(SoftDirty::LIGHT_ALL | SoftDirty::TRANSFORM_ALL);
579
}
580
vreader.UpdateCache();
581
582
bool skipCull = !gstate.isCullEnabled() || gstate.isModeClear();
583
const CullType cullType = skipCull ? CullType::OFF : (gstate.getCullMode() ? CullType::CCW : CullType::CW);
584
585
if (vreader.IsThrough() && cullType == CullType::OFF && prim_type == GE_PRIM_TRIANGLES && data_index_ == 0 && vertex_count >= 6 && ((vertex_count) % 6) == 0) {
586
// Some games send rectangles as a series of regular triangles.
587
// We look for this, but only in throughmode.
588
ClipVertexData buf[6];
589
// Could start at data_index_ and copy to buf, but there's little reason.
590
int buf_index = 0;
591
_assert_(data_index_ == 0);
592
593
for (int vtx = 0; vtx < vertex_count; ++vtx) {
594
buf[buf_index++] = vreader.Read(vtx);
595
if (buf_index < 6)
596
continue;
597
598
int tl = -1, br = -1;
599
if (Rasterizer::DetectRectangleFromPair(binner_->State(), buf, &tl, &br)) {
600
Clipper::ProcessRect(buf[tl], buf[br], *binner_);
601
} else {
602
SendTriangle(cullType, &buf[0]);
603
SendTriangle(cullType, &buf[3]);
604
}
605
606
buf_index = 0;
607
}
608
609
if (buf_index >= 3) {
610
SendTriangle(cullType, &buf[0]);
611
data_index_ = 0;
612
for (int i = 3; i < buf_index; ++i) {
613
data_[data_index_++] = buf[i];
614
}
615
} else if (buf_index > 0) {
616
for (int i = 0; i < buf_index; ++i) {
617
data_[i] = buf[i];
618
}
619
data_index_ = buf_index;
620
} else {
621
data_index_ = 0;
622
}
623
624
return;
625
}
626
627
// Note: intentionally, these allow for the case of vertex_count == 0, but data_index_ > 0.
628
// This is used for immediate-mode primitives.
629
switch (prim_type) {
630
case GE_PRIM_POINTS:
631
for (int i = 0; i < data_index_; ++i)
632
Clipper::ProcessPoint(data_[i], *binner_);
633
data_index_ = 0;
634
for (int vtx = 0; vtx < vertex_count; ++vtx) {
635
data_[0] = vreader.Read(vtx);
636
Clipper::ProcessPoint(data_[0], *binner_);
637
}
638
break;
639
640
case GE_PRIM_LINES:
641
for (int i = 0; i < data_index_ - 1; i += 2)
642
Clipper::ProcessLine(data_[i + 0], data_[i + 1], *binner_);
643
data_index_ &= 1;
644
for (int vtx = 0; vtx < vertex_count; ++vtx) {
645
data_[data_index_++] = vreader.Read(vtx);
646
if (data_index_ == 2) {
647
Clipper::ProcessLine(data_[0], data_[1], *binner_);
648
data_index_ = 0;
649
}
650
}
651
break;
652
653
case GE_PRIM_TRIANGLES:
654
for (int vtx = 0; vtx < vertex_count; ++vtx) {
655
data_[data_index_++] = vreader.Read(vtx);
656
if (data_index_ < 3) {
657
// Keep reading. Note: an incomplete prim will stay read for GE_PRIM_KEEP_PREVIOUS.
658
continue;
659
}
660
// Okay, we've got enough verts. Reset the index for next time.
661
data_index_ = 0;
662
663
SendTriangle(cullType, &data_[0]);
664
}
665
// In case vertex_count was 0.
666
if (data_index_ >= 3) {
667
SendTriangle(cullType, &data_[0]);
668
data_index_ = 0;
669
}
670
break;
671
672
case GE_PRIM_RECTANGLES:
673
for (int vtx = 0; vtx < vertex_count; ++vtx) {
674
data_[data_index_++] = vreader.Read(vtx);
675
676
if (data_index_ == 4 && vreader.IsThrough() && cullType == CullType::OFF) {
677
if (Rasterizer::DetectRectangleThroughModeSlices(binner_->State(), data_)) {
678
data_[1] = data_[3];
679
data_index_ = 2;
680
}
681
}
682
683
if (data_index_ == 4) {
684
Clipper::ProcessRect(data_[0], data_[1], *binner_);
685
Clipper::ProcessRect(data_[2], data_[3], *binner_);
686
data_index_ = 0;
687
}
688
}
689
690
if (data_index_ >= 2) {
691
Clipper::ProcessRect(data_[0], data_[1], *binner_);
692
data_index_ -= 2;
693
}
694
break;
695
696
case GE_PRIM_LINE_STRIP:
697
{
698
// Don't draw a line when loading the first vertex.
699
// If data_index_ is 1 or 2, etc., it means we're continuing a line strip.
700
int skip_count = data_index_ == 0 ? 1 : 0;
701
for (int vtx = 0; vtx < vertex_count; ++vtx) {
702
data_[(data_index_++) & 1] = vreader.Read(vtx);
703
704
if (skip_count) {
705
--skip_count;
706
} else {
707
// We already incremented data_index_, so data_index_ & 1 is previous one.
708
Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);
709
}
710
}
711
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
712
if (isImmDraw_ && data_index_ >= 2)
713
Clipper::ProcessLine(data_[data_index_ & 1], data_[(data_index_ & 1) ^ 1], *binner_);
714
break;
715
}
716
717
case GE_PRIM_TRIANGLE_STRIP:
718
{
719
// Don't draw a triangle when loading the first two vertices.
720
int skip_count = data_index_ >= 2 ? 0 : 2 - data_index_;
721
int start_vtx = 0;
722
723
// If index count == 4, check if we can convert to a rectangle.
724
// This is for Darkstalkers (and should speed up many 2D games).
725
if (data_index_ == 0 && vertex_count >= 4 && (vertex_count & 1) == 0 && cullType == CullType::OFF) {
726
for (int base = 0; base < vertex_count - 2; base += 2) {
727
for (int vtx = base == 0 ? 0 : 2; vtx < 4; ++vtx) {
728
data_[vtx] = vreader.Read(base + vtx);
729
}
730
731
// If a strip is effectively a rectangle, draw it as such!
732
int tl = -1, br = -1;
733
if (Rasterizer::DetectRectangleFromStrip(binner_->State(), data_, &tl, &br)) {
734
Clipper::ProcessRect(data_[tl], data_[br], *binner_);
735
start_vtx += 2;
736
skip_count = 2;
737
if (base + 4 >= vertex_count) {
738
start_vtx = vertex_count;
739
break;
740
}
741
742
// Just copy the first two so we can detect easier.
743
// TODO: Maybe should give detection two halves?
744
data_[0] = data_[2];
745
data_[1] = data_[3];
746
data_index_ = 2;
747
} else {
748
// Go into triangle mode. Unfortunately, we re-read the verts.
749
break;
750
}
751
}
752
}
753
754
for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {
755
int provoking_index = (data_index_++) % 3;
756
data_[provoking_index] = vreader.Read(vtx);
757
--skip_count;
758
++start_vtx;
759
}
760
761
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
762
int provoking_index = (data_index_++) % 3;
763
data_[provoking_index] = vreader.Read(vtx);
764
765
int wind = (data_index_ - 1) % 2;
766
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
767
SendTriangle(altCullType, &data_[0], provoking_index);
768
}
769
770
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
771
if (isImmDraw_ && data_index_ >= 3) {
772
int provoking_index = (data_index_ - 1) % 3;
773
int wind = (data_index_ - 1) % 2;
774
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
775
SendTriangle(altCullType, &data_[0], provoking_index);
776
}
777
break;
778
}
779
780
case GE_PRIM_TRIANGLE_FAN:
781
{
782
// Don't draw a triangle when loading the first two vertices.
783
// (this doesn't count the central one.)
784
int skip_count = data_index_ <= 1 ? 1 : 0;
785
int start_vtx = 0;
786
787
// Only read the central vertex if we're not continuing.
788
if (data_index_ == 0 && vertex_count > 0) {
789
data_[0] = vreader.Read(0);
790
data_index_++;
791
start_vtx = 1;
792
}
793
794
if (data_index_ == 1 && vertex_count == 4 && cullType == CullType::OFF) {
795
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
796
data_[vtx] = vreader.Read(vtx);
797
}
798
799
int tl = -1, br = -1;
800
if (Rasterizer::DetectRectangleFromFan(binner_->State(), data_, &tl, &br)) {
801
Clipper::ProcessRect(data_[tl], data_[br], *binner_);
802
break;
803
}
804
}
805
806
for (int vtx = start_vtx; vtx < vertex_count && skip_count > 0; ++vtx) {
807
int provoking_index = 2 - ((data_index_++) % 2);
808
data_[provoking_index] = vreader.Read(vtx);
809
--skip_count;
810
++start_vtx;
811
}
812
813
for (int vtx = start_vtx; vtx < vertex_count; ++vtx) {
814
int provoking_index = 2 - ((data_index_++) % 2);
815
data_[provoking_index] = vreader.Read(vtx);
816
817
int wind = (data_index_ - 1) % 2;
818
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
819
SendTriangle(altCullType, &data_[0], provoking_index);
820
}
821
822
// If this is from immediate-mode drawing, we always had one new vert (already in data_.)
823
if (isImmDraw_ && data_index_ >= 3) {
824
int wind = (data_index_ - 1) % 2;
825
int provoking_index = 2 - wind;
826
CullType altCullType = cullType == CullType::OFF ? cullType : CullType((int)cullType ^ wind);
827
SendTriangle(altCullType, &data_[0], provoking_index);
828
}
829
break;
830
}
831
832
default:
833
ERROR_LOG(Log::G3D, "Unexpected prim type: %d", prim_type);
834
break;
835
}
836
}
837
838
void TransformUnit::SubmitImmVertex(const ClipVertexData &vert, SoftwareDrawEngine *drawEngine) {
839
// Where we put it is different for STRIP/FAN types.
840
switch (prev_prim_) {
841
case GE_PRIM_POINTS:
842
case GE_PRIM_LINES:
843
case GE_PRIM_TRIANGLES:
844
case GE_PRIM_RECTANGLES:
845
// This is the easy one. SubmitPrimitive resets data_index_.
846
data_[data_index_++] = vert;
847
break;
848
849
case GE_PRIM_LINE_STRIP:
850
// This one alternates, and data_index_ > 0 means it draws a segment.
851
data_[(data_index_++) & 1] = vert;
852
break;
853
854
case GE_PRIM_TRIANGLE_STRIP:
855
data_[(data_index_++) % 3] = vert;
856
break;
857
858
case GE_PRIM_TRIANGLE_FAN:
859
if (data_index_ == 0) {
860
data_[data_index_++] = vert;
861
} else {
862
int provoking_index = 2 - ((data_index_++) % 2);
863
data_[provoking_index] = vert;
864
}
865
break;
866
867
default:
868
_assert_msg_(false, "Invalid prim type: %d", (int)prev_prim_);
869
break;
870
}
871
872
uint32_t vertTypeID = GetVertTypeID(gstate.vertType | GE_VTYPE_POS_FLOAT, gstate.getUVGenMode(), true);
873
// This now processes the step with shared logic, given the existing data_.
874
isImmDraw_ = true;
875
SubmitPrimitive(nullptr, nullptr, GE_PRIM_KEEP_PREVIOUS, 0, vertTypeID, nullptr, drawEngine);
876
isImmDraw_ = false;
877
}
878
879
void TransformUnit::SendTriangle(CullType cullType, const ClipVertexData *verts, int provoking) {
880
if (cullType == CullType::OFF) {
881
Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);
882
Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);
883
} else if (cullType == CullType::CW) {
884
Clipper::ProcessTriangle(verts[2], verts[1], verts[0], verts[provoking], *binner_);
885
} else {
886
Clipper::ProcessTriangle(verts[0], verts[1], verts[2], verts[provoking], *binner_);
887
}
888
}
889
890
void TransformUnit::Flush(GPUCommon *common, const char *reason) {
891
if (!hasDraws_)
892
return;
893
894
binner_->Flush(reason);
895
common->NotifyFlush();
896
hasDraws_ = false;
897
}
898
899
void TransformUnit::GetStats(char *buffer, size_t bufsize) {
900
// TODO: More stats?
901
binner_->GetStats(buffer, bufsize);
902
}
903
904
void TransformUnit::FlushIfOverlap(GPUCommon *common, const char *reason, bool modifying, uint32_t addr, uint32_t stride, uint32_t w, uint32_t h) {
905
if (!hasDraws_)
906
return;
907
908
if (binner_->HasPendingWrite(addr, stride, w, h))
909
Flush(common, reason);
910
if (modifying && binner_->HasPendingRead(addr, stride, w, h))
911
Flush(common, reason);
912
}
913
914
void TransformUnit::NotifyClutUpdate(const void *src) {
915
binner_->UpdateClut(src);
916
}
917
918
// TODO: This probably is not the best interface.
919
// Also, we should try to merge this into the similar function in DrawEngineCommon.
920
bool TransformUnit::GetCurrentDrawAsDebugVertices(int count, std::vector<GPUDebugVertex> &vertices, std::vector<u16> &indices) {
921
// This is always for the current vertices.
922
u16 indexLowerBound = 0;
923
u16 indexUpperBound = count - 1;
924
925
if (!Memory::IsValidAddress(gstate_c.vertexAddr) || count == 0)
926
return false;
927
928
if (count > 0 && (gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) {
929
const u8 *inds = Memory::GetPointer(gstate_c.indexAddr);
930
const u16_le *inds16 = (const u16_le *)inds;
931
const u32_le *inds32 = (const u32_le *)inds;
932
933
if (inds) {
934
GetIndexBounds(inds, count, gstate.vertType, &indexLowerBound, &indexUpperBound);
935
indices.resize(count);
936
switch (gstate.vertType & GE_VTYPE_IDX_MASK) {
937
case GE_VTYPE_IDX_8BIT:
938
for (int i = 0; i < count; ++i) {
939
indices[i] = inds[i];
940
}
941
break;
942
case GE_VTYPE_IDX_16BIT:
943
for (int i = 0; i < count; ++i) {
944
indices[i] = inds16[i];
945
}
946
break;
947
case GE_VTYPE_IDX_32BIT:
948
WARN_LOG_REPORT_ONCE(simpleIndexes32, Log::G3D, "SimpleVertices: Decoding 32-bit indexes");
949
for (int i = 0; i < count; ++i) {
950
// These aren't documented and should be rare. Let's bounds check each one.
951
if (inds32[i] != (u16)inds32[i]) {
952
ERROR_LOG_REPORT_ONCE(simpleIndexes32Bounds, Log::G3D, "SimpleVertices: Index outside 16-bit range");
953
}
954
indices[i] = (u16)inds32[i];
955
}
956
break;
957
}
958
} else {
959
indices.clear();
960
}
961
} else {
962
indices.clear();
963
}
964
965
static std::vector<u32> temp_buffer;
966
static std::vector<SimpleVertex> simpleVertices;
967
temp_buffer.resize(std::max((int)indexUpperBound, 8192) * 128 / sizeof(u32));
968
simpleVertices.resize(indexUpperBound + 1);
969
970
VertexDecoder vdecoder;
971
VertexDecoderOptions options{};
972
u32 vertTypeID = GetVertTypeID(gstate.vertType, gstate.getUVGenMode(), true);
973
vdecoder.SetVertexType(vertTypeID, options);
974
975
if (!Memory::IsValidRange(gstate_c.vertexAddr, (indexUpperBound + 1) * vdecoder.VertexSize()))
976
return false;
977
978
::NormalizeVertices(&simpleVertices[0], (u8 *)(&temp_buffer[0]), Memory::GetPointer(gstate_c.vertexAddr), indexLowerBound, indexUpperBound, &vdecoder, gstate.vertType);
979
980
float world[16];
981
float view[16];
982
float worldview[16];
983
float worldviewproj[16];
984
ConvertMatrix4x3To4x4(world, gstate.worldMatrix);
985
ConvertMatrix4x3To4x4(view, gstate.viewMatrix);
986
Matrix4ByMatrix4(worldview, world, view);
987
Matrix4ByMatrix4(worldviewproj, worldview, gstate.projMatrix);
988
989
const float zScale = gstate.getViewportZScale();
990
const float zCenter = gstate.getViewportZCenter();
991
992
vertices.resize(indexUpperBound + 1);
993
for (int i = indexLowerBound; i <= indexUpperBound; ++i) {
994
const SimpleVertex &vert = simpleVertices[i];
995
996
if (gstate.isModeThrough()) {
997
if (gstate.vertType & GE_VTYPE_TC_MASK) {
998
vertices[i].u = vert.uv[0];
999
vertices[i].v = vert.uv[1];
1000
} else {
1001
vertices[i].u = 0.0f;
1002
vertices[i].v = 0.0f;
1003
}
1004
vertices[i].x = vert.pos.x;
1005
vertices[i].y = vert.pos.y;
1006
vertices[i].z = vert.pos.z;
1007
} else {
1008
Vec4f clipPos = Vec3ByMatrix44(vert.pos, worldviewproj);
1009
bool outsideRangeFlag;
1010
ScreenCoords screenPos = ClipToScreen(clipPos, &outsideRangeFlag);
1011
float z = clipPos.z * zScale / clipPos.w + zCenter;
1012
1013
if (gstate.vertType & GE_VTYPE_TC_MASK) {
1014
vertices[i].u = vert.uv[0] * (float)gstate.getTextureWidth(0);
1015
vertices[i].v = vert.uv[1] * (float)gstate.getTextureHeight(0);
1016
} else {
1017
vertices[i].u = 0.0f;
1018
vertices[i].v = 0.0f;
1019
}
1020
vertices[i].x = (float)screenPos.x / SCREEN_SCALE_FACTOR;
1021
vertices[i].y = (float)screenPos.y / SCREEN_SCALE_FACTOR;
1022
vertices[i].z = screenPos.z <= 0 || screenPos.z >= 0xFFFF ? z : (float)screenPos.z;
1023
}
1024
1025
if (gstate.vertType & GE_VTYPE_COL_MASK) {
1026
memcpy(vertices[i].c, vert.color, sizeof(vertices[i].c));
1027
} else {
1028
memset(vertices[i].c, 0, sizeof(vertices[i].c));
1029
}
1030
vertices[i].nx = vert.nrm.x;
1031
vertices[i].ny = vert.nrm.y;
1032
vertices[i].nz = vert.nrm.z;
1033
}
1034
1035
// The GE debugger expects these to be set.
1036
gstate_c.curTextureWidth = gstate.getTextureWidth(0);
1037
gstate_c.curTextureHeight = gstate.getTextureHeight(0);
1038
1039
return true;
1040
}
1041
1042