CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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