Path: blob/master/GPU/Common/SoftwareTransformCommon.cpp
3186 views
// Copyright (c) 2013- PPSSPP Project.12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include <algorithm>18#include <cmath>1920#include "Common/CPUDetect.h"21#include "Common/Math/math_util.h"22#include "Common/GPU/OpenGL/GLFeatures.h"23#include "Core/Config.h"24#include "Core/System.h"25#include "GPU/GPUState.h"26#include "GPU/Math3D.h"27#include "GPU/Common/FramebufferManagerCommon.h"28#include "GPU/Common/GPUStateUtils.h"29#include "GPU/Common/SoftwareTransformCommon.h"30#include "GPU/Common/TransformCommon.h"31#include "GPU/Common/VertexDecoderCommon.h"32#include "GPU/Common/DrawEngineCommon.h"3334// This is the software transform pipeline, which is necessary for supporting RECT35// primitives correctly without geometry shaders, and may be easier to use for36// debugging than the hardware transform pipeline.3738// There's code here that simply expands transformed RECTANGLES into plain triangles.3940// We're gonna have to keep software transforming RECTANGLES, unless we use a geom shader which we can't on OpenGL ES 2.0.41// Usually, though, these primitives don't use lighting etc so it's no biggie performance wise, but it would be nice to get rid of42// this code.4344// Actually, if we find the camera-relative right and down vectors, it might even be possible to add the extra points in pre-transformed45// space and thus make decent use of hardware transform.4647// Actually again, single quads could be drawn more efficiently using GL_TRIANGLE_STRIP, no need to duplicate verts as for48// GL_TRIANGLES. Still need to sw transform to compute the extra two corners though.49//5051// The verts are in the order: BR BL TL TR52static void SwapUVs(TransformedVertex &a, TransformedVertex &b) {53float tempu = a.u;54float tempv = a.v;55a.u = b.u;56a.v = b.v;57b.u = tempu;58b.v = tempv;59}6061// 2 3 3 2 0 3 2 162// to to or63// 1 0 0 1 1 2 3 06465// Note: 0 is BR and 2 is TL.6667static void RotateUV(TransformedVertex v[4], bool flippedY) {68// We use the transformed tl/br coordinates to figure out whether they're flipped or not.69float ySign = flippedY ? -1.0 : 1.0;7071const float x1 = v[2].x;72const float x2 = v[0].x;73const float y1 = v[2].y * ySign;74const float y2 = v[0].y * ySign;7576if ((x1 < x2 && y1 < y2) || (x1 > x2 && y1 > y2))77SwapUVs(v[1], v[3]);78}7980static void RotateUVThrough(TransformedVertex v[4]) {81float x1 = v[2].x;82float x2 = v[0].x;83float y1 = v[2].y;84float y2 = v[0].y;8586if ((x1 < x2 && y1 > y2) || (x1 > x2 && y1 < y2))87SwapUVs(v[1], v[3]);88}8990// Clears on the PSP are best done by drawing a series of vertical strips91// in clear mode. This tries to detect that.92static bool IsReallyAClear(const TransformedVertex *transformed, int numVerts, float x2, float y2) {93if (transformed[0].x < 0.0f || transformed[0].y < 0.0f || transformed[0].x > 0.5f || transformed[0].y > 0.5f)94return false;9596const float originY = transformed[0].y;9798// Color and Z are decided by the second vertex, so only need to check those for matching color.99const u32 matchcolor = transformed[1].color0_32;100const float matchz = transformed[1].z;101102for (int i = 1; i < numVerts; i++) {103if ((i & 1) == 0) {104// Top left of a rectangle105if (transformed[i].y != originY)106return false;107float gap = fabsf(transformed[i].x - transformed[i - 1].x); // Should probably do some smarter check.108if (i > 0 && gap > 0.0625)109return false;110} else {111if (transformed[i].color0_32 != matchcolor || transformed[i].z != matchz)112return false;113// Bottom right114if (transformed[i].y < y2)115return false;116if (transformed[i].x <= transformed[i - 1].x)117return false;118}119}120121// The last vertical strip often extends outside the drawing area.122if (transformed[numVerts - 1].x < x2)123return false;124125return true;126}127128void SoftwareTransform::SetProjMatrix(const float mtx[14], bool invertedX, bool invertedY, const Lin::Vec3 &trans, const Lin::Vec3 &scale) {129memcpy(&projMatrix_.m, mtx, 16 * sizeof(float));130131if (invertedY) {132projMatrix_.xy = -projMatrix_.xy;133projMatrix_.yy = -projMatrix_.yy;134projMatrix_.zy = -projMatrix_.zy;135projMatrix_.wy = -projMatrix_.wy;136}137if (invertedX) {138projMatrix_.xx = -projMatrix_.xx;139projMatrix_.yx = -projMatrix_.yx;140projMatrix_.zx = -projMatrix_.zx;141projMatrix_.wx = -projMatrix_.wx;142}143144projMatrix_.translateAndScale(trans, scale);145}146147void SoftwareTransform::Transform(int prim, u32 vertType, const DecVtxFormat &decVtxFormat, int numDecodedVerts, SoftwareTransformResult *result) {148u8 *decoded = params_.decoded;149TransformedVertex *transformed = params_.transformed;150bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;151bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();152153float uscale = 1.0f;154float vscale = 1.0f;155if (throughmode && prim != GE_PRIM_RECTANGLES) {156// For through rectangles, we do this scaling in Expand.157uscale /= gstate_c.curTextureWidth;158vscale /= gstate_c.curTextureHeight;159}160161const int w = gstate.getTextureWidth(0);162const int h = gstate.getTextureHeight(0);163float widthFactor = (float) w / (float) gstate_c.curTextureWidth;164float heightFactor = (float) h / (float) gstate_c.curTextureHeight;165166Lighter lighter(vertType);167float fog_end = getFloat24(gstate.fog1);168float fog_slope = getFloat24(gstate.fog2);169// Same fixup as in ShaderManagerGLES.cpp170if (my_isnanorinf(fog_end)) {171// Not really sure what a sensible value might be, but let's try 64k.172fog_end = std::signbit(fog_end) ? -65535.0f : 65535.0f;173}174if (my_isnanorinf(fog_slope)) {175fog_slope = std::signbit(fog_slope) ? -65535.0f : 65535.0f;176}177178VertexReader reader(decoded, decVtxFormat, vertType);179if (throughmode) {180const u32 materialAmbientRGBA = gstate.getMaterialAmbientRGBA();181const bool hasColor = reader.hasColor0();182const bool hasUV = reader.hasUV();183for (int index = 0; index < numDecodedVerts; index++) {184// Do not touch the coordinates or the colors. No lighting.185reader.Goto(index);186// TODO: Write to a flexible buffer, we don't always need all four components.187TransformedVertex &vert = transformed[index];188reader.ReadPosThrough(vert.pos);189vert.pos_w = 1.0f;190191if (hasColor) {192vert.color0_32 = reader.ReadColor0_8888();193} else {194vert.color0_32 = materialAmbientRGBA;195}196197if (hasUV) {198reader.ReadUV(vert.uv);199200vert.u *= uscale;201vert.v *= vscale;202} else {203vert.u = 0.0f;204vert.v = 0.0f;205}206vert.uv_w = 1.0f;207208// Ignore color1 and fog, never used in throughmode anyway.209// The w of uv is also never used (hardcoded to 1.0.)210}211} else {212const Vec4f materialAmbientRGBA = Vec4f::FromRGBA(gstate.getMaterialAmbientRGBA());213// Okay, need to actually perform the full transform.214for (int index = 0; index < numDecodedVerts; index++) {215reader.Goto(index);216217float v[3] = {0, 0, 0};218Vec4f c0 = Vec4f(1, 1, 1, 1);219Vec4f c1 = Vec4f(0, 0, 0, 0);220float uv[3] = {0, 0, 1};221float fogCoef = 1.0f;222223float out[3];224float pos[3];225Vec3f normal(0, 0, 1);226Vec3f worldnormal(0, 0, 1);227reader.ReadPosNonThrough(pos);228229float ruv[2] = { 0.0f, 0.0f };230if (reader.hasUV())231reader.ReadUV(ruv);232233Vec4f unlitColor;234if (reader.hasColor0())235reader.ReadColor0(unlitColor.AsArray());236else237unlitColor = materialAmbientRGBA;238if (reader.hasNormal())239reader.ReadNrm(normal.AsArray());240241Vec3ByMatrix43(out, pos, gstate.worldMatrix);242if (reader.hasNormal()) {243if (gstate.areNormalsReversed()) {244normal = -normal;245}246Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);247worldnormal = worldnormal.NormalizedOr001(cpu_info.bSSE4_1);248}249250// Perform lighting here if enabled.251if (gstate.isLightingEnabled()) {252float litColor0[4];253float litColor1[4];254lighter.Light(litColor0, litColor1, unlitColor.AsArray(), out, worldnormal);255256// Don't ignore gstate.lmode - we should send two colors in that case257for (int j = 0; j < 4; j++) {258c0[j] = litColor0[j];259}260if (lmode) {261// Separate colors262for (int j = 0; j < 4; j++) {263c1[j] = litColor1[j];264}265} else {266// Summed color into c0 (will clamp in ToRGBA().)267for (int j = 0; j < 4; j++) {268c0[j] += litColor1[j];269}270}271} else {272for (int j = 0; j < 4; j++) {273c0[j] = unlitColor[j];274}275if (lmode) {276// c1 is already 0.277}278}279280// Perform texture coordinate generation after the transform and lighting - one style of UV depends on lights.281switch (gstate.getUVGenMode()) {282case GE_TEXMAP_TEXTURE_COORDS: // UV mapping283case GE_TEXMAP_UNKNOWN: // Seen in Riviera. Unsure of meaning, but this works.284// We always prescale in the vertex decoder now.285uv[0] = ruv[0];286uv[1] = ruv[1];287uv[2] = 1.0f;288break;289290case GE_TEXMAP_TEXTURE_MATRIX:291{292// Projection mapping293Vec3f source(0.0f, 0.0f, 1.0f);294switch (gstate.getUVProjMode()) {295case GE_PROJMAP_POSITION: // Use model space XYZ as source296source = pos;297break;298299case GE_PROJMAP_UV: // Use unscaled UV as source300source = Vec3f(ruv[0], ruv[1], 0.0f);301break;302303case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized normal as source304source = normal.Normalized(cpu_info.bSSE4_1);305break;306307case GE_PROJMAP_NORMAL: // Use non-normalized normal as source!308source = normal;309break;310}311312float uvw[3];313Vec3ByMatrix43(uvw, &source.x, gstate.tgenMatrix);314uv[0] = uvw[0];315uv[1] = uvw[1];316uv[2] = uvw[2];317}318break;319320case GE_TEXMAP_ENVIRONMENT_MAP:321// Shade mapping - use two light sources to generate U and V.322{323auto getLPosFloat = [&](int l, int i) {324return getFloat24(gstate.lpos[l * 3 + i]);325};326auto getLPos = [&](int l) {327return Vec3f(getLPosFloat(l, 0), getLPosFloat(l, 1), getLPosFloat(l, 2));328};329auto calcShadingLPos = [&](int l) {330Vec3f pos = getLPos(l);331return pos.NormalizedOr001(cpu_info.bSSE4_1);332};333334// Might not have lighting enabled, so don't use lighter.335Vec3f lightpos0 = calcShadingLPos(gstate.getUVLS0());336Vec3f lightpos1 = calcShadingLPos(gstate.getUVLS1());337338uv[0] = (1.0f + Dot(lightpos0, worldnormal))/2.0f;339uv[1] = (1.0f + Dot(lightpos1, worldnormal))/2.0f;340uv[2] = 1.0f;341}342break;343default:344break;345}346347uv[0] = uv[0] * widthFactor;348uv[1] = uv[1] * heightFactor;349350// Transform the coord by the view matrix.351Vec3ByMatrix43(v, out, gstate.viewMatrix);352fogCoef = (v[2] + fog_end) * fog_slope;353354// TODO: Write to a flexible buffer, we don't always need all four components.355Vec3ByMatrix44(transformed[index].pos, v, projMatrix_.m);356transformed[index].fog = fogCoef;357memcpy(&transformed[index].uv, uv, 3 * sizeof(float));358transformed[index].color0_32 = c0.ToRGBA();359transformed[index].color1_32 = c1.ToRGBA();360361// Vertex depth rounding is done in the shader, to simulate the 16-bit depth buffer.362}363}364365// Here's the best opportunity to try to detect rectangles used to clear the screen, and366// replace them with real clears. This can provide a speedup on certain mobile chips.367//368// An alternative option is to simply ditch all the verts except the first and last to create a single369// rectangle out of many. Quite a small optimization though.370// TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not.371// TODO: Allow creating a depth clear and a color draw.372bool reallyAClear = false;373if (numDecodedVerts > 1 && prim == GE_PRIM_RECTANGLES && gstate.isModeClear() && throughmode) {374int scissorX2 = gstate.getScissorX2() + 1;375int scissorY2 = gstate.getScissorY2() + 1;376reallyAClear = IsReallyAClear(transformed, numDecodedVerts, scissorX2, scissorY2);377if (reallyAClear && gstate.getColorMask() != 0xFFFFFFFF && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask())) {378result->setSafeSize = true;379result->safeWidth = scissorX2;380result->safeHeight = scissorY2;381}382}383if (params_.allowClear && reallyAClear && gl_extensions.gpuVendor != GPU_VENDOR_IMGTEC) {384// If alpha is not allowed to be separate, it must match for both depth/stencil and color. Vulkan requires this.385bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask();386bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask();387bool matchingComponents = params_.allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil);388bool stencilNotMasked = !gstate.isClearModeAlphaMask() || gstate.getStencilWriteMask() == 0x00;389if (matchingComponents && stencilNotMasked) {390DepthScaleFactors depthScale = GetDepthScaleFactors(gstate_c.UseFlags());391result->color = transformed[1].color0_32;392// Need to rescale from a [0, 1] float. This is the final transformed value.393result->depth = depthScale.EncodeFromU16((float)(int)(transformed[1].z * 65535.0f));394result->action = SW_CLEAR;395gpuStats.numClears++;396return;397}398}399400// Detect full screen "clears" that might not be so obvious, to set the safe size if possible.401if (!result->setSafeSize && prim == GE_PRIM_RECTANGLES && numDecodedVerts == 2 && throughmode) {402bool clearingColor = gstate.isModeClear() && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask());403bool writingColor = gstate.getColorMask() != 0xFFFFFFFF;404bool startsZeroX = transformed[0].x <= 0.0f && transformed[1].x > 0.0f && transformed[1].x > transformed[0].x;405bool startsZeroY = transformed[0].y <= 0.0f && transformed[1].y > 0.0f && transformed[1].y > transformed[0].y;406407if (startsZeroX && startsZeroY && (clearingColor || writingColor)) {408int scissorX2 = gstate.getScissorX2() + 1;409int scissorY2 = gstate.getScissorY2() + 1;410result->setSafeSize = true;411result->safeWidth = std::min(scissorX2, (int)transformed[1].x);412result->safeHeight = std::min(scissorY2, (int)transformed[1].y);413}414}415}416417void SoftwareTransform::BuildDrawingParams(int prim, int vertexCount, u32 vertType, u16 *&inds, int indsSize, int &numDecodedVerts, int vertsSize, SoftwareTransformResult *result) {418TransformedVertex *transformed = params_.transformed;419TransformedVertex *transformedExpanded = params_.transformedExpanded;420bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;421422// Step 2: expand and process primitives.423result->drawBuffer = transformed;424int numTrans = 0;425426FramebufferManagerCommon *fbman = params_.fbman;427bool useBufferedRendering = fbman->UseBufferedRendering();428429if (prim == GE_PRIM_RECTANGLES) {430if (!ExpandRectangles(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode, &result->pixelMapped)) {431result->drawNumTrans = 0;432result->pixelMapped = false;433return;434}435result->drawBuffer = transformedExpanded;436437// We don't know the color until here, so we have to do it now, instead of in StateMapping.438// Might want to reconsider the order of things later...439if (gstate.isModeClear() && gstate.isClearModeAlphaMask()) {440result->setStencil = true;441if (vertexCount > 1) {442// Take the bottom right alpha value of the first rect as the stencil value.443// Technically, each rect could individually fill its stencil, but most of the444// time they use the same one.445result->stencilValue = transformed[inds[1]].color0[3];446} else {447result->stencilValue = 0;448}449}450} else if (prim == GE_PRIM_POINTS) {451result->pixelMapped = false;452if (!ExpandPoints(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode)) {453result->drawNumTrans = 0;454return;455}456result->drawBuffer = transformedExpanded;457} else if (prim == GE_PRIM_LINES) {458result->pixelMapped = false;459if (!ExpandLines(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode)) {460result->drawNumTrans = 0;461return;462}463result->drawBuffer = transformedExpanded;464} else {465// We can simply draw the unexpanded buffer.466numTrans = vertexCount;467result->pixelMapped = false;468469// If we don't support custom cull in the shader, process it here.470if (!gstate_c.Use(GPU_USE_CULL_DISTANCE) && vertexCount > 0 && !throughmode) {471const u16 *indsIn = (const u16 *)inds;472u16 *newInds = inds + vertexCount;473u16 *indsOut = newInds;474475float minZValue, maxZValue;476CalcCullParams(minZValue, maxZValue);477478std::vector<int> outsideZ;479outsideZ.resize(vertexCount);480481// First, check inside/outside directions for each index.482for (int i = 0; i < vertexCount; ++i) {483float z = transformed[indsIn[i]].z / transformed[indsIn[i]].pos_w;484if (z > maxZValue)485outsideZ[i] = 1;486else if (z < minZValue)487outsideZ[i] = -1;488else489outsideZ[i] = 0;490}491492// Now, for each primitive type, throw away the indices if:493// - Depth clamp on, and ALL verts are outside *in the same direction*.494// - Depth clamp off, and ANY vert is outside.495if (prim == GE_PRIM_TRIANGLES && gstate.isDepthClampEnabled()) {496numTrans = 0;497for (int i = 0; i < vertexCount - 2; i += 3) {498if (outsideZ[i + 0] != 0 && outsideZ[i + 0] == outsideZ[i + 1] && outsideZ[i + 0] == outsideZ[i + 2]) {499// All outside, and all the same direction. Nuke this triangle.500continue;501}502503memcpy(indsOut, indsIn + i, 3 * sizeof(uint16_t));504indsOut += 3;505numTrans += 3;506}507508inds = newInds;509} else if (prim == GE_PRIM_TRIANGLES) {510numTrans = 0;511for (int i = 0; i < vertexCount - 2; i += 3) {512if (outsideZ[i + 0] != 0 || outsideZ[i + 1] != 0 || outsideZ[i + 2] != 0) {513// Even one outside, and we cull.514continue;515}516517memcpy(indsOut, indsIn + i, 3 * sizeof(uint16_t));518indsOut += 3;519numTrans += 3;520}521522inds = newInds;523}524} else if (throughmode && g_Config.bSmart2DTexFiltering && !gstate_c.textureIsVideo) {525// We check some common cases for pixel mapping.526// TODO: It's not really optimal that some previous step has removed the triangle strip.527if (vertexCount <= 6 && prim == GE_PRIM_TRIANGLES) {528// It's enough to check UV deltas vs pos deltas between vertex pairs:529// 0-1 1-3 3-2 2-0. Maybe can even skip the last one. Probably some simple math can get us that sequence.530// Unfortunately we need to reverse the previous UV scaling operation. Fortunately these are powers of two531// so the operations are exact.532bool pixelMapped = true;533const u16 *indsIn = (const u16 *)inds;534const float uscale = gstate_c.curTextureWidth;535const float vscale = gstate_c.curTextureHeight;536for (int t = 0; t < vertexCount; t += 3) {537struct { int a; int b; } pairs[] = { {0, 1}, {1, 2}, {2, 0} };538for (int i = 0; i < ARRAY_SIZE(pairs); i++) {539int a = indsIn[t + pairs[i].a];540int b = indsIn[t + pairs[i].b];541float du = fabsf((transformed[a].u - transformed[b].u) * uscale);542float dv = fabsf((transformed[a].v - transformed[b].v) * vscale);543float dx = fabsf(transformed[a].x - transformed[b].x);544float dy = fabsf(transformed[a].y - transformed[b].y);545if (du != dx || dv != dy) {546pixelMapped = false;547}548}549if (!pixelMapped) {550break;551}552}553result->pixelMapped = pixelMapped;554}555}556}557558if (gstate.isModeClear()) {559gpuStats.numClears++;560}561562result->action = SW_DRAW_INDEXED;563result->drawNumTrans = numTrans;564}565566void SoftwareTransform::CalcCullParams(float &minZValue, float &maxZValue) const {567// The projected Z can be up to 0x3F8000FF, which is where this constant is from.568// It seems like it may only maintain 15 mantissa bits (excluding implied.)569maxZValue = 1.000030517578125f * gstate_c.vpDepthScale;570minZValue = -maxZValue;571// Scale and offset the Z appropriately, since we baked that into a projection transform.572if (params_.usesHalfZ) {573maxZValue = maxZValue * 0.5f + 0.5f + gstate_c.vpZOffset * 0.5f;574minZValue = minZValue * 0.5f + 0.5f + gstate_c.vpZOffset * 0.5f;575} else {576maxZValue += gstate_c.vpZOffset;577minZValue += gstate_c.vpZOffset;578}579// In case scale was negative, flip.580if (minZValue > maxZValue)581std::swap(minZValue, maxZValue);582}583584bool SoftwareTransform::ExpandRectangles(int vertexCount, int &numDecodedVerts, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode, bool *pixelMappedExactly) const {585// Before we start, do a sanity check - does the output fit?586if ((vertexCount / 2) * 6 > indsSize) {587// Won't fit, kill the draw.588return false;589}590if ((vertexCount / 2) * 4 > vertsSize) {591// Won't fit, kill the draw.592return false;593}594595// Rectangles always need 2 vertices, disregard the last one if there's an odd number.596vertexCount = vertexCount & ~1;597numTrans = 0;598TransformedVertex *trans = &transformedExpanded[0];599600const u16 *indsIn = (const u16 *)inds;601u16 *newInds = inds + vertexCount;602u16 *indsOut = newInds;603604numDecodedVerts = 4 * (vertexCount / 2);605606float uscale = 1.0f;607float vscale = 1.0f;608if (throughmode) {609uscale /= gstate_c.curTextureWidth;610vscale /= gstate_c.curTextureHeight;611}612613bool pixelMapped = g_Config.bSmart2DTexFiltering && !gstate_c.textureIsVideo;614615for (int i = 0; i < vertexCount; i += 2) {616const TransformedVertex &transVtxTL = transformed[indsIn[i + 0]];617const TransformedVertex &transVtxBR = transformed[indsIn[i + 1]];618619if (pixelMapped) {620float dx = transVtxBR.x - transVtxTL.x;621float dy = transVtxBR.y - transVtxTL.y;622float du = transVtxBR.u - transVtxTL.u;623float dv = transVtxBR.v - transVtxTL.v;624625// NOTE: We will accept it as pixel mapped if only one dimension is stretched. This fixes dialog frames in FFI.626// Though, there could be false positives in other games due to this. Let's see if it is a problem...627if (dx <= 0 || dy <= 0 || (dx != du && dy != dv)) {628pixelMapped = false;629}630}631632// We have to turn the rectangle into two triangles, so 6 points.633// This is 4 verts + 6 indices.634635// bottom right636trans[0] = transVtxBR;637trans[0].u = transVtxBR.u * uscale;638trans[0].v = transVtxBR.v * vscale;639640// top right641trans[1] = transVtxBR;642trans[1].y = transVtxTL.y;643trans[1].u = transVtxBR.u * uscale;644trans[1].v = transVtxTL.v * vscale;645646// top left647trans[2] = transVtxBR;648trans[2].x = transVtxTL.x;649trans[2].y = transVtxTL.y;650trans[2].u = transVtxTL.u * uscale;651trans[2].v = transVtxTL.v * vscale;652653// bottom left654trans[3] = transVtxBR;655trans[3].x = transVtxTL.x;656trans[3].u = transVtxTL.u * uscale;657trans[3].v = transVtxBR.v * vscale;658659// That's the four corners. Now process UV rotation.660if (throughmode) {661RotateUVThrough(trans);662} else {663RotateUV(trans, params_.flippedY);664}665666// Triangle: BR-TR-TL667indsOut[0] = i * 2 + 0;668indsOut[1] = i * 2 + 1;669indsOut[2] = i * 2 + 2;670// Triangle: BL-BR-TL671indsOut[3] = i * 2 + 3;672indsOut[4] = i * 2 + 0;673indsOut[5] = i * 2 + 2;674675trans += 4;676indsOut += 6;677678numTrans += 6;679}680inds = newInds;681*pixelMappedExactly = pixelMapped;682return true;683}684685// In-place. So, better not be doing this on GPU memory!686void IndexBufferProvokingLastToFirst(int prim, u16 *inds, int indsSize) {687switch (prim) {688case GE_PRIM_LINES:689// Swap every two indices.690for (int i = 0; i < indsSize - 1; i += 2) {691u16 temp = inds[i];692inds[i] = inds[i + 1];693inds[i + 1] = temp;694}695break;696case GE_PRIM_TRIANGLES:697// Rotate the triangle so the last becomes the first, without changing the winding order.698// This could be done with a series of pshufb.699for (int i = 0; i < indsSize - 2; i += 3) {700u16 temp = inds[i + 2];701inds[i + 2] = inds[i + 1];702inds[i + 1] = inds[i];703inds[i] = temp;704}705break;706case GE_PRIM_POINTS:707// Nothing to do,708break;709case GE_PRIM_RECTANGLES:710// Nothing to do, already using the 2nd vertex.711break;712default:713_dbg_assert_msg_(false, "IndexBufferProvokingFirstToLast: Only works with plain indexed primitives, no strips or fans")714}715}716717bool SoftwareTransform::ExpandLines(int vertexCount, int &numDecodedVerts, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode) {718// Before we start, do a sanity check - does the output fit?719if ((vertexCount / 2) * 6 > indsSize) {720// Won't fit, kill the draw.721return false;722}723if ((vertexCount / 2) * 4 > vertsSize) {724return false;725}726727// Lines always need 2 vertices, disregard the last one if there's an odd number.728vertexCount = vertexCount & ~1;729numTrans = 0;730TransformedVertex *trans = &transformedExpanded[0];731732const u16 *indsIn = (const u16 *)inds;733u16 *newInds = inds + vertexCount;734u16 *indsOut = newInds;735736float dx = 1.0f * gstate_c.vpWidthScale * (1.0f / fabsf(gstate.getViewportXScale()));737float dy = 1.0f * gstate_c.vpHeightScale * (1.0f / fabsf(gstate.getViewportYScale()));738float du = 1.0f / gstate_c.curTextureWidth;739float dv = 1.0f / gstate_c.curTextureHeight;740741if (throughmode) {742dx = 1.0f;743dy = 1.0f;744}745746numDecodedVerts = 4 * (vertexCount / 2);747748if (PSP_CoreParameter().compat.flags().CenteredLines) {749// Lines meant to be pretty in 3D like in Echochrome.750751// We expand them in both directions for symmetry, so we need to halve the expansion.752dx *= 0.5f;753dy *= 0.5f;754755for (int i = 0; i < vertexCount; i += 2) {756const TransformedVertex &transVtx1 = transformed[indsIn[i + 0]];757const TransformedVertex &transVtx2 = transformed[indsIn[i + 1]];758759// Okay, let's calculate the perpendicular.760float horizontal = transVtx2.x * transVtx2.pos_w - transVtx1.x * transVtx1.pos_w;761float vertical = transVtx2.y * transVtx2.pos_w - transVtx1.y * transVtx1.pos_w;762763Vec2f addWidth = Vec2f(-vertical, horizontal).Normalized();764765float xoff = addWidth.x * dx;766float yoff = addWidth.y * dy;767768// bottom right769trans[0].CopyFromWithOffset(transVtx2, xoff * transVtx2.pos_w, yoff * transVtx2.pos_w);770// top right771trans[1].CopyFromWithOffset(transVtx1, xoff * transVtx1.pos_w, yoff * transVtx1.pos_w);772// top left773trans[2].CopyFromWithOffset(transVtx1, -xoff * transVtx1.pos_w, -yoff * transVtx1.pos_w);774// bottom left775trans[3].CopyFromWithOffset(transVtx2, -xoff * transVtx2.pos_w, -yoff * transVtx2.pos_w);776777// Triangle: BR-TR-TL778indsOut[0] = i * 2 + 0;779indsOut[1] = i * 2 + 1;780indsOut[2] = i * 2 + 2;781// Triangle: BL-BR-TL782indsOut[3] = i * 2 + 3;783indsOut[4] = i * 2 + 0;784indsOut[5] = i * 2 + 2;785trans += 4;786indsOut += 6;787788numTrans += 6;789}790} else {791// Lines meant to be as closely compatible with upscaled 2D drawing as possible.792// We use this as default.793794for (int i = 0; i < vertexCount; i += 2) {795const TransformedVertex &transVtx1 = transformed[indsIn[i + 0]];796const TransformedVertex &transVtx2 = transformed[indsIn[i + 1]];797798const TransformedVertex &transVtxT = transVtx1.y <= transVtx2.y ? transVtx1 : transVtx2;799const TransformedVertex &transVtxB = transVtx1.y <= transVtx2.y ? transVtx2 : transVtx1;800const TransformedVertex &transVtxL = transVtx1.x <= transVtx2.x ? transVtx1 : transVtx2;801const TransformedVertex &transVtxR = transVtx1.x <= transVtx2.x ? transVtx2 : transVtx1;802803// Sort the points so our perpendicular will bias the right direction.804const TransformedVertex &transVtxTL = (transVtxT.y != transVtxB.y || transVtxT.x > transVtxB.x) ? transVtxT : transVtxB;805const TransformedVertex &transVtxBL = (transVtxT.y != transVtxB.y || transVtxT.x > transVtxB.x) ? transVtxB : transVtxT;806807// Okay, let's calculate the perpendicular.808float horizontal = transVtxTL.x * transVtxTL.pos_w - transVtxBL.x * transVtxBL.pos_w;809float vertical = transVtxTL.y * transVtxTL.pos_w - transVtxBL.y * transVtxBL.pos_w;810Vec2f addWidth = Vec2f(-vertical, horizontal).Normalized();811812// bottom right813trans[0] = transVtxBL;814trans[0].x += addWidth.x * dx * trans[0].pos_w;815trans[0].y += addWidth.y * dy * trans[0].pos_w;816trans[0].u += addWidth.x * du * trans[0].uv_w;817trans[0].v += addWidth.y * dv * trans[0].uv_w;818819// top right820trans[1] = transVtxTL;821trans[1].x += addWidth.x * dx * trans[1].pos_w;822trans[1].y += addWidth.y * dy * trans[1].pos_w;823trans[1].u += addWidth.x * du * trans[1].uv_w;824trans[1].v += addWidth.y * dv * trans[1].uv_w;825826// top left827trans[2] = transVtxTL;828829// bottom left830trans[3] = transVtxBL;831832// Triangle: BR-TR-TL833indsOut[0] = i * 2 + 0;834indsOut[1] = i * 2 + 1;835indsOut[2] = i * 2 + 2;836// Triangle: BL-BR-TL837indsOut[3] = i * 2 + 3;838indsOut[4] = i * 2 + 0;839indsOut[5] = i * 2 + 2;840trans += 4;841indsOut += 6;842843numTrans += 6;844}845}846847inds = newInds;848return true;849}850851bool SoftwareTransform::ExpandPoints(int vertexCount, int &maxIndex, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode) {852// Before we start, do a sanity check - does the output fit?853if (vertexCount * 6 > indsSize) {854// Won't fit, kill the draw.855return false;856}857if (vertexCount * 4 > vertsSize) {858// Won't fit, kill the draw.859return false;860}861862numTrans = 0;863TransformedVertex *trans = &transformedExpanded[0];864865const u16 *indsIn = (const u16 *)inds;866u16 *newInds = inds + vertexCount;867u16 *indsOut = newInds;868869float dx = 1.0f * gstate_c.vpWidthScale * (1.0f / gstate.getViewportXScale());870float dy = 1.0f * gstate_c.vpHeightScale * (1.0f / gstate.getViewportYScale());871float du = 1.0f / gstate_c.curTextureWidth;872float dv = 1.0f / gstate_c.curTextureHeight;873874if (throughmode) {875dx = 1.0f;876dy = 1.0f;877}878879maxIndex = 4 * vertexCount;880for (int i = 0; i < vertexCount; ++i) {881const TransformedVertex &transVtxTL = transformed[indsIn[i]];882883// Create the bottom right version.884TransformedVertex transVtxBR = transVtxTL;885transVtxBR.x += dx * transVtxTL.pos_w;886transVtxBR.y += dy * transVtxTL.pos_w;887transVtxBR.u += du * transVtxTL.uv_w;888transVtxBR.v += dv * transVtxTL.uv_w;889890// We have to turn the rectangle into two triangles, so 6 points.891// This is 4 verts + 6 indices.892893// bottom right894trans[0] = transVtxBR;895896// top right897trans[1] = transVtxBR;898trans[1].y = transVtxTL.y;899trans[1].v = transVtxTL.v;900901// top left902trans[2] = transVtxBR;903trans[2].x = transVtxTL.x;904trans[2].y = transVtxTL.y;905trans[2].u = transVtxTL.u;906trans[2].v = transVtxTL.v;907908// bottom left909trans[3] = transVtxBR;910trans[3].x = transVtxTL.x;911trans[3].u = transVtxTL.u;912913// Triangle: BR-TR-TL914indsOut[0] = i * 4 + 0;915indsOut[1] = i * 4 + 1;916indsOut[2] = i * 4 + 2;917// Triangle: BL-BR-TL918indsOut[3] = i * 4 + 3;919indsOut[4] = i * 4 + 0;920indsOut[5] = i * 4 + 2;921trans += 4;922indsOut += 6;923924numTrans += 6;925}926inds = newInds;927return true;928}929930// This normalizes a set of vertices in any format to SimpleVertex format, by processing away morphing AND skinning.931// The rest of the transform pipeline like lighting will go as normal, either hardware or software.932// The implementation is initially a bit inefficient but shouldn't be a big deal.933// An intermediate buffer of not-easy-to-predict size is stored at bufPtr.934u32 NormalizeVertices(SimpleVertex *sverts, u8 *bufPtr, const u8 *inPtr, int lowerBound, int upperBound, const VertexDecoder *dec, u32 vertType) {935// First, decode the vertices into a GPU compatible format. This step can be eliminated but will need a separate936// implementation of the vertex decoder.937dec->DecodeVerts(bufPtr, inPtr, &gstate_c.uv, lowerBound, upperBound);938939// OK, morphing eliminated but bones still remain to be taken care of.940// Let's do a partial software transform where we only do skinning.941942VertexReader reader(bufPtr, dec->GetDecVtxFmt(), vertType);943944const u8 defaultColor[4] = {945(u8)gstate.getMaterialAmbientR(),946(u8)gstate.getMaterialAmbientG(),947(u8)gstate.getMaterialAmbientB(),948(u8)gstate.getMaterialAmbientA(),949};950951// Let's have two separate loops, one for non skinning and one for skinning.952if (!dec->skinInDecode && (vertType & GE_VTYPE_WEIGHT_MASK) != GE_VTYPE_WEIGHT_NONE) {953int numBoneWeights = vertTypeGetNumBoneWeights(vertType);954for (int i = lowerBound; i <= upperBound; i++) {955reader.Goto(i - lowerBound);956SimpleVertex &sv = sverts[i];957if (vertType & GE_VTYPE_TC_MASK) {958reader.ReadUV(sv.uv);959}960961if (vertType & GE_VTYPE_COL_MASK) {962sv.color_32 = reader.ReadColor0_8888();963} else {964memcpy(sv.color, defaultColor, 4);965}966967float nrm[3], pos[3];968float bnrm[3], bpos[3];969970if (vertType & GE_VTYPE_NRM_MASK) {971// Normals are generated during tessellation anyway, not sure if any need to supply972reader.ReadNrm(nrm);973} else {974nrm[0] = 0;975nrm[1] = 0;976nrm[2] = 1.0f;977}978reader.ReadPosAuto(pos);979980// Apply skinning transform directly981float weights[8];982reader.ReadWeights(weights);983// Skinning984Vec3Packedf psum(0, 0, 0);985Vec3Packedf nsum(0, 0, 0);986for (int w = 0; w < numBoneWeights; w++) {987if (weights[w] != 0.0f) {988Vec3ByMatrix43(bpos, pos, gstate.boneMatrix + w * 12);989Vec3Packedf tpos(bpos);990psum += tpos * weights[w];991992Norm3ByMatrix43(bnrm, nrm, gstate.boneMatrix + w * 12);993Vec3Packedf tnorm(bnrm);994nsum += tnorm * weights[w];995}996}997sv.pos = psum;998sv.nrm = nsum;999}1000} else {1001for (int i = lowerBound; i <= upperBound; i++) {1002reader.Goto(i - lowerBound);1003SimpleVertex &sv = sverts[i];1004if (vertType & GE_VTYPE_TC_MASK) {1005reader.ReadUV(sv.uv);1006} else {1007sv.uv[0] = 0.0f; // This will get filled in during tessellation1008sv.uv[1] = 0.0f;1009}1010if (vertType & GE_VTYPE_COL_MASK) {1011sv.color_32 = reader.ReadColor0_8888();1012} else {1013memcpy(sv.color, defaultColor, 4);1014}1015if (vertType & GE_VTYPE_NRM_MASK) {1016// Normals are generated during tessellation anyway, not sure if any need to supply1017reader.ReadNrm((float *)&sv.nrm);1018} else {1019sv.nrm.x = 0.0f;1020sv.nrm.y = 0.0f;1021sv.nrm.z = 1.0f;1022}1023reader.ReadPosAuto((float *)&sv.pos);1024}1025}10261027// Okay, there we are! Return the new type (but keep the index bits)1028return GE_VTYPE_TC_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_NRM_FLOAT | GE_VTYPE_POS_FLOAT | (vertType & (GE_VTYPE_IDX_MASK | GE_VTYPE_THROUGH));1029}10301031// clip space to screen space1032Vec3f ClipToScreen(const Vec4f& coords) {1033float xScale = gstate.getViewportXScale();1034float xCenter = gstate.getViewportXCenter();1035float yScale = gstate.getViewportYScale();1036float yCenter = gstate.getViewportYCenter();1037float zScale = gstate.getViewportZScale();1038float zCenter = gstate.getViewportZCenter();10391040float x = coords.x * xScale / coords.w + xCenter;1041float y = coords.y * yScale / coords.w + yCenter;1042float z = coords.z * zScale / coords.w + zCenter;10431044// 16 = 0xFFFF / 4095.93751045return Vec3f(x * 16 - gstate.getOffsetX16(), y * 16 - gstate.getOffsetY16(), z);1046}10471048static Vec3f ScreenToDrawing(const Vec3f& coords) {1049Vec3f ret;1050ret.x = coords.x * (1.0f / 16.0f);1051ret.y = coords.y * (1.0f / 16.0f);1052ret.z = coords.z;1053return ret;1054}10551056// TODO: This probably is not the best interface.1057// drawEngine is just for the vertex decoder lookup.1058// This is really just for vertex preview in the debugger, not for actual rendering!1059bool GetCurrentDrawAsDebugVertices(DrawEngineCommon *drawEngine, int count, std::vector<GPUDebugVertex> &vertices, std::vector<u16> &indices) {1060// This is always for the current vertices.1061u16 indexLowerBound = 0;1062u16 indexUpperBound = count - 1;10631064if (!Memory::IsValidAddress(gstate_c.vertexAddr) || count == 0)1065return false;10661067bool savedVertexFullAlpha = gstate_c.vertexFullAlpha;10681069if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) {1070const u8 *inds = Memory::GetPointer(gstate_c.indexAddr);1071const u16_le *inds16 = (const u16_le *)inds;1072const u32_le *inds32 = (const u32_le *)inds;10731074if (inds) {1075GetIndexBounds(inds, count, gstate.vertType, &indexLowerBound, &indexUpperBound);1076indices.resize(count);1077switch (gstate.vertType & GE_VTYPE_IDX_MASK) {1078case GE_VTYPE_IDX_8BIT:1079for (int i = 0; i < count; ++i) {1080indices[i] = inds[i];1081}1082break;1083case GE_VTYPE_IDX_16BIT:1084for (int i = 0; i < count; ++i) {1085indices[i] = inds16[i];1086}1087break;1088case GE_VTYPE_IDX_32BIT:1089for (int i = 0; i < count; ++i) {1090// These are rare. Only the bottom 16 bits are used.1091indices[i] = (u16)inds32[i];1092}1093break;1094}1095} else {1096indices.clear();1097}1098} else {1099indices.clear();1100}11011102static std::vector<u32> temp_buffer;1103static std::vector<SimpleVertex> simpleVertices;1104temp_buffer.resize(std::max((int)indexUpperBound, 8192) * 128 / sizeof(u32));1105simpleVertices.resize(indexUpperBound + 1);11061107// We always want "applyskinindecode" here, faster than letting NormalizeVertices handle it.1108const u32 vertTypeID = GetVertTypeID(gstate.vertType, gstate.getUVGenMode(), true);1109VertexDecoder *dec = drawEngine->GetVertexDecoder(vertTypeID);1110NormalizeVertices(&simpleVertices[0], (u8 *)(&temp_buffer[0]), Memory::GetPointerUnchecked(gstate_c.vertexAddr), indexLowerBound, indexUpperBound, dec, gstate.vertType);11111112float world[16];1113float view[16];1114float worldview[16];1115float worldviewproj[16];1116ConvertMatrix4x3To4x4(world, gstate.worldMatrix);1117ConvertMatrix4x3To4x4(view, gstate.viewMatrix);1118Matrix4ByMatrix4(worldview, world, view);1119Matrix4ByMatrix4(worldviewproj, worldview, gstate.projMatrix);11201121// This transforms the vertices.1122// NOTE: We really should just run the full software transform?11231124vertices.resize(indexUpperBound + 1);1125uint32_t vertType = gstate.vertType;1126for (int i = indexLowerBound; i <= indexUpperBound; ++i) {1127const SimpleVertex &vert = simpleVertices[i];11281129if ((vertType & GE_VTYPE_THROUGH) != 0) {1130if (vertType & GE_VTYPE_TC_MASK) {1131vertices[i].u = vert.uv[0];1132vertices[i].v = vert.uv[1];1133} else {1134vertices[i].u = 0.0f;1135vertices[i].v = 0.0f;1136}1137vertices[i].x = vert.pos.x;1138vertices[i].y = vert.pos.y;1139vertices[i].z = vert.pos.z;1140if (vertType & GE_VTYPE_COL_MASK) {1141memcpy(vertices[i].c, vert.color, sizeof(vertices[i].c));1142} else {1143memset(vertices[i].c, 0, sizeof(vertices[i].c));1144}1145vertices[i].nx = 0.0f; // No meaningful normals in through mode1146vertices[i].ny = 0.0f;1147vertices[i].nz = 1.0f;1148} else {1149float clipPos[4];1150Vec3ByMatrix44(clipPos, vert.pos.AsArray(), worldviewproj);1151Vec3f screenPos = ClipToScreen(clipPos);1152Vec3f drawPos = ScreenToDrawing(screenPos);11531154if (vertType & GE_VTYPE_TC_MASK) {1155vertices[i].u = vert.uv[0] * (float)gstate.getTextureWidth(0);1156vertices[i].v = vert.uv[1] * (float)gstate.getTextureHeight(0);1157} else {1158vertices[i].u = 0.0f;1159vertices[i].v = 0.0f;1160}1161// Should really have separate coordinates for before and after transform.1162vertices[i].x = drawPos.x;1163vertices[i].y = drawPos.y;1164vertices[i].z = drawPos.z;1165if (vertType & GE_VTYPE_COL_MASK) {1166memcpy(vertices[i].c, vert.color, sizeof(vertices[i].c));1167} else {1168memset(vertices[i].c, 0, sizeof(vertices[i].c));1169}1170vertices[i].nx = vert.nrm.x;1171vertices[i].ny = vert.nrm.y;1172vertices[i].nz = vert.nrm.z;1173}1174}11751176gstate_c.vertexFullAlpha = savedVertexFullAlpha;11771178return true;1179}118011811182