CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/GPU/Common/SoftwareTransformCommon.cpp
Views: 1401
// 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 "GPU/GPUState.h"25#include "GPU/Math3D.h"26#include "GPU/Common/FramebufferManagerCommon.h"27#include "GPU/Common/GPUStateUtils.h"28#include "GPU/Common/SoftwareTransformCommon.h"29#include "GPU/Common/TransformCommon.h"30#include "GPU/Common/TextureCacheCommon.h"31#include "GPU/Common/VertexDecoderCommon.h"3233// This is the software transform pipeline, which is necessary for supporting RECT34// primitives correctly without geometry shaders, and may be easier to use for35// debugging than the hardware transform pipeline.3637// There's code here that simply expands transformed RECTANGLES into plain triangles.3839// We're gonna have to keep software transforming RECTANGLES, unless we use a geom shader which we can't on OpenGL ES 2.0 or DX9.40// Usually, though, these primitives don't use lighting etc so it's no biggie performance wise, but it would be nice to get rid of41// this code.4243// Actually, if we find the camera-relative right and down vectors, it might even be possible to add the extra points in pre-transformed44// space and thus make decent use of hardware transform.4546// Actually again, single quads could be drawn more efficiently using GL_TRIANGLE_STRIP, no need to duplicate verts as for47// GL_TRIANGLES. Still need to sw transform to compute the extra two corners though.48//4950// The verts are in the order: BR BL TL TR51static void SwapUVs(TransformedVertex &a, TransformedVertex &b) {52float tempu = a.u;53float tempv = a.v;54a.u = b.u;55a.v = b.v;56b.u = tempu;57b.v = tempv;58}5960// 2 3 3 2 0 3 2 161// to to or62// 1 0 0 1 1 2 3 06364// Note: 0 is BR and 2 is TL.6566static void RotateUV(TransformedVertex v[4], bool flippedY) {67// We use the transformed tl/br coordinates to figure out whether they're flipped or not.68float ySign = flippedY ? -1.0 : 1.0;6970const float x1 = v[2].x;71const float x2 = v[0].x;72const float y1 = v[2].y * ySign;73const float y2 = v[0].y * ySign;7475if ((x1 < x2 && y1 < y2) || (x1 > x2 && y1 > y2))76SwapUVs(v[1], v[3]);77}7879static void RotateUVThrough(TransformedVertex v[4]) {80float x1 = v[2].x;81float x2 = v[0].x;82float y1 = v[2].y;83float y2 = v[0].y;8485if ((x1 < x2 && y1 > y2) || (x1 > x2 && y1 < y2))86SwapUVs(v[1], v[3]);87}8889// Clears on the PSP are best done by drawing a series of vertical strips90// in clear mode. This tries to detect that.91static bool IsReallyAClear(const TransformedVertex *transformed, int numVerts, float x2, float y2) {92if (transformed[0].x < 0.0f || transformed[0].y < 0.0f || transformed[0].x > 0.5f || transformed[0].y > 0.5f)93return false;9495const float originY = transformed[0].y;9697// Color and Z are decided by the second vertex, so only need to check those for matching color.98const u32 matchcolor = transformed[1].color0_32;99const float matchz = transformed[1].z;100101for (int i = 1; i < numVerts; i++) {102if ((i & 1) == 0) {103// Top left of a rectangle104if (transformed[i].y != originY)105return false;106float gap = fabsf(transformed[i].x - transformed[i - 1].x); // Should probably do some smarter check.107if (i > 0 && gap > 0.0625)108return false;109} else {110if (transformed[i].color0_32 != matchcolor || transformed[i].z != matchz)111return false;112// Bottom right113if (transformed[i].y < y2)114return false;115if (transformed[i].x <= transformed[i - 1].x)116return false;117}118}119120// The last vertical strip often extends outside the drawing area.121if (transformed[numVerts - 1].x < x2)122return false;123124return true;125}126127void SoftwareTransform::SetProjMatrix(const float mtx[14], bool invertedX, bool invertedY, const Lin::Vec3 &trans, const Lin::Vec3 &scale) {128memcpy(&projMatrix_.m, mtx, 16 * sizeof(float));129130if (invertedY) {131projMatrix_.xy = -projMatrix_.xy;132projMatrix_.yy = -projMatrix_.yy;133projMatrix_.zy = -projMatrix_.zy;134projMatrix_.wy = -projMatrix_.wy;135}136if (invertedX) {137projMatrix_.xx = -projMatrix_.xx;138projMatrix_.yx = -projMatrix_.yx;139projMatrix_.zx = -projMatrix_.zx;140projMatrix_.wx = -projMatrix_.wx;141}142143projMatrix_.translateAndScale(trans, scale);144}145146void SoftwareTransform::Transform(int prim, u32 vertType, const DecVtxFormat &decVtxFormat, int numDecodedVerts, SoftwareTransformResult *result) {147u8 *decoded = params_.decoded;148TransformedVertex *transformed = params_.transformed;149bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;150bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();151152float uscale = 1.0f;153float vscale = 1.0f;154if (throughmode && prim != GE_PRIM_RECTANGLES) {155// For through rectangles, we do this scaling in Expand.156uscale /= gstate_c.curTextureWidth;157vscale /= gstate_c.curTextureHeight;158}159160const int w = gstate.getTextureWidth(0);161const int h = gstate.getTextureHeight(0);162float widthFactor = (float) w / (float) gstate_c.curTextureWidth;163float heightFactor = (float) h / (float) gstate_c.curTextureHeight;164165Lighter lighter(vertType);166float fog_end = getFloat24(gstate.fog1);167float fog_slope = getFloat24(gstate.fog2);168// Same fixup as in ShaderManagerGLES.cpp169if (my_isnanorinf(fog_end)) {170// Not really sure what a sensible value might be, but let's try 64k.171fog_end = std::signbit(fog_end) ? -65535.0f : 65535.0f;172}173if (my_isnanorinf(fog_slope)) {174fog_slope = std::signbit(fog_slope) ? -65535.0f : 65535.0f;175}176177VertexReader reader(decoded, decVtxFormat, vertType);178if (throughmode) {179const u32 materialAmbientRGBA = gstate.getMaterialAmbientRGBA();180const bool hasColor = reader.hasColor0();181const bool hasUV = reader.hasUV();182for (int index = 0; index < numDecodedVerts; index++) {183// Do not touch the coordinates or the colors. No lighting.184reader.Goto(index);185// TODO: Write to a flexible buffer, we don't always need all four components.186TransformedVertex &vert = transformed[index];187reader.ReadPos(vert.pos);188vert.pos_w = 1.0f;189190if (hasColor) {191vert.color0_32 = reader.ReadColor0_8888();192} else {193vert.color0_32 = materialAmbientRGBA;194}195196if (hasUV) {197reader.ReadUV(vert.uv);198199vert.u *= uscale;200vert.v *= vscale;201} else {202vert.u = 0.0f;203vert.v = 0.0f;204}205vert.uv_w = 1.0f;206207// Ignore color1 and fog, never used in throughmode anyway.208// The w of uv is also never used (hardcoded to 1.0.)209}210} else {211const Vec4f materialAmbientRGBA = Vec4f::FromRGBA(gstate.getMaterialAmbientRGBA());212// Okay, need to actually perform the full transform.213for (int index = 0; index < numDecodedVerts; index++) {214reader.Goto(index);215216float v[3] = {0, 0, 0};217Vec4f c0 = Vec4f(1, 1, 1, 1);218Vec4f c1 = Vec4f(0, 0, 0, 0);219float uv[3] = {0, 0, 1};220float fogCoef = 1.0f;221222float out[3];223float pos[3];224Vec3f normal(0, 0, 1);225Vec3f worldnormal(0, 0, 1);226reader.ReadPos(pos);227228float ruv[2] = { 0.0f, 0.0f };229if (reader.hasUV())230reader.ReadUV(ruv);231232Vec4f unlitColor;233if (reader.hasColor0())234reader.ReadColor0(unlitColor.AsArray());235else236unlitColor = materialAmbientRGBA;237if (reader.hasNormal())238reader.ReadNrm(normal.AsArray());239240Vec3ByMatrix43(out, pos, gstate.worldMatrix);241if (reader.hasNormal()) {242if (gstate.areNormalsReversed()) {243normal = -normal;244}245Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);246worldnormal = worldnormal.NormalizedOr001(cpu_info.bSSE4_1);247}248249// Perform lighting here if enabled.250if (gstate.isLightingEnabled()) {251float litColor0[4];252float litColor1[4];253lighter.Light(litColor0, litColor1, unlitColor.AsArray(), out, worldnormal);254255// Don't ignore gstate.lmode - we should send two colors in that case256for (int j = 0; j < 4; j++) {257c0[j] = litColor0[j];258}259if (lmode) {260// Separate colors261for (int j = 0; j < 4; j++) {262c1[j] = litColor1[j];263}264} else {265// Summed color into c0 (will clamp in ToRGBA().)266for (int j = 0; j < 4; j++) {267c0[j] += litColor1[j];268}269}270} else {271for (int j = 0; j < 4; j++) {272c0[j] = unlitColor[j];273}274if (lmode) {275// c1 is already 0.276}277}278279// Perform texture coordinate generation after the transform and lighting - one style of UV depends on lights.280switch (gstate.getUVGenMode()) {281case GE_TEXMAP_TEXTURE_COORDS: // UV mapping282case GE_TEXMAP_UNKNOWN: // Seen in Riviera. Unsure of meaning, but this works.283// We always prescale in the vertex decoder now.284uv[0] = ruv[0];285uv[1] = ruv[1];286uv[2] = 1.0f;287break;288289case GE_TEXMAP_TEXTURE_MATRIX:290{291// Projection mapping292Vec3f source(0.0f, 0.0f, 1.0f);293switch (gstate.getUVProjMode()) {294case GE_PROJMAP_POSITION: // Use model space XYZ as source295source = pos;296break;297298case GE_PROJMAP_UV: // Use unscaled UV as source299source = Vec3f(ruv[0], ruv[1], 0.0f);300break;301302case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized normal as source303source = normal.Normalized(cpu_info.bSSE4_1);304if (!reader.hasNormal()) {305ERROR_LOG_REPORT(Log::G3D, "Normal projection mapping without normal?");306}307break;308309case GE_PROJMAP_NORMAL: // Use non-normalized normal as source!310source = normal;311if (!reader.hasNormal()) {312ERROR_LOG_REPORT(Log::G3D, "Normal projection mapping without normal?");313}314break;315}316317float uvw[3];318Vec3ByMatrix43(uvw, &source.x, gstate.tgenMatrix);319uv[0] = uvw[0];320uv[1] = uvw[1];321uv[2] = uvw[2];322}323break;324325case GE_TEXMAP_ENVIRONMENT_MAP:326// Shade mapping - use two light sources to generate U and V.327{328auto getLPosFloat = [&](int l, int i) {329return getFloat24(gstate.lpos[l * 3 + i]);330};331auto getLPos = [&](int l) {332return Vec3f(getLPosFloat(l, 0), getLPosFloat(l, 1), getLPosFloat(l, 2));333};334auto calcShadingLPos = [&](int l) {335Vec3f pos = getLPos(l);336return pos.NormalizedOr001(cpu_info.bSSE4_1);337};338// Might not have lighting enabled, so don't use lighter.339Vec3f lightpos0 = calcShadingLPos(gstate.getUVLS0());340Vec3f lightpos1 = calcShadingLPos(gstate.getUVLS1());341342uv[0] = (1.0f + Dot(lightpos0, worldnormal))/2.0f;343uv[1] = (1.0f + Dot(lightpos1, worldnormal))/2.0f;344uv[2] = 1.0f;345}346break;347348default:349// Illegal350ERROR_LOG_REPORT(Log::G3D, "Impossible UV gen mode? %d", gstate.getUVGenMode());351break;352}353354uv[0] = uv[0] * widthFactor;355uv[1] = uv[1] * heightFactor;356357// Transform the coord by the view matrix.358Vec3ByMatrix43(v, out, gstate.viewMatrix);359fogCoef = (v[2] + fog_end) * fog_slope;360361// TODO: Write to a flexible buffer, we don't always need all four components.362Vec3ByMatrix44(transformed[index].pos, v, projMatrix_.m);363transformed[index].fog = fogCoef;364memcpy(&transformed[index].uv, uv, 3 * sizeof(float));365transformed[index].color0_32 = c0.ToRGBA();366transformed[index].color1_32 = c1.ToRGBA();367368// Vertex depth rounding is done in the shader, to simulate the 16-bit depth buffer.369}370}371372// Here's the best opportunity to try to detect rectangles used to clear the screen, and373// replace them with real clears. This can provide a speedup on certain mobile chips.374//375// An alternative option is to simply ditch all the verts except the first and last to create a single376// rectangle out of many. Quite a small optimization though.377// TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not.378// TODO: Allow creating a depth clear and a color draw.379bool reallyAClear = false;380if (numDecodedVerts > 1 && prim == GE_PRIM_RECTANGLES && gstate.isModeClear() && throughmode) {381int scissorX2 = gstate.getScissorX2() + 1;382int scissorY2 = gstate.getScissorY2() + 1;383reallyAClear = IsReallyAClear(transformed, numDecodedVerts, scissorX2, scissorY2);384if (reallyAClear && gstate.getColorMask() != 0xFFFFFFFF && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask())) {385result->setSafeSize = true;386result->safeWidth = scissorX2;387result->safeHeight = scissorY2;388}389}390if (params_.allowClear && reallyAClear && gl_extensions.gpuVendor != GPU_VENDOR_IMGTEC) {391// If alpha is not allowed to be separate, it must match for both depth/stencil and color. Vulkan requires this.392bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask();393bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask();394bool matchingComponents = params_.allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil);395bool stencilNotMasked = !gstate.isClearModeAlphaMask() || gstate.getStencilWriteMask() == 0x00;396if (matchingComponents && stencilNotMasked) {397DepthScaleFactors depthScale = GetDepthScaleFactors(gstate_c.UseFlags());398result->color = transformed[1].color0_32;399// Need to rescale from a [0, 1] float. This is the final transformed value.400result->depth = depthScale.EncodeFromU16((float)(int)(transformed[1].z * 65535.0f));401result->action = SW_CLEAR;402gpuStats.numClears++;403return;404}405}406407// Detect full screen "clears" that might not be so obvious, to set the safe size if possible.408if (!result->setSafeSize && prim == GE_PRIM_RECTANGLES && numDecodedVerts == 2 && throughmode) {409bool clearingColor = gstate.isModeClear() && (gstate.isClearModeColorMask() || gstate.isClearModeAlphaMask());410bool writingColor = gstate.getColorMask() != 0xFFFFFFFF;411bool startsZeroX = transformed[0].x <= 0.0f && transformed[1].x > 0.0f && transformed[1].x > transformed[0].x;412bool startsZeroY = transformed[0].y <= 0.0f && transformed[1].y > 0.0f && transformed[1].y > transformed[0].y;413414if (startsZeroX && startsZeroY && (clearingColor || writingColor)) {415int scissorX2 = gstate.getScissorX2() + 1;416int scissorY2 = gstate.getScissorY2() + 1;417result->setSafeSize = true;418result->safeWidth = std::min(scissorX2, (int)transformed[1].x);419result->safeHeight = std::min(scissorY2, (int)transformed[1].y);420}421}422}423424void SoftwareTransform::BuildDrawingParams(int prim, int vertexCount, u32 vertType, u16 *&inds, int indsSize, int &numDecodedVerts, int vertsSize, SoftwareTransformResult *result) {425TransformedVertex *transformed = params_.transformed;426TransformedVertex *transformedExpanded = params_.transformedExpanded;427bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;428429// Step 2: expand and process primitives.430result->drawBuffer = transformed;431int numTrans = 0;432433FramebufferManagerCommon *fbman = params_.fbman;434bool useBufferedRendering = fbman->UseBufferedRendering();435436if (prim == GE_PRIM_RECTANGLES) {437if (!ExpandRectangles(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode, &result->pixelMapped)) {438result->drawNumTrans = 0;439result->pixelMapped = false;440return;441}442result->drawBuffer = transformedExpanded;443444// We don't know the color until here, so we have to do it now, instead of in StateMapping.445// Might want to reconsider the order of things later...446if (gstate.isModeClear() && gstate.isClearModeAlphaMask()) {447result->setStencil = true;448if (vertexCount > 1) {449// Take the bottom right alpha value of the first rect as the stencil value.450// Technically, each rect could individually fill its stencil, but most of the451// time they use the same one.452result->stencilValue = transformed[inds[1]].color0[3];453} else {454result->stencilValue = 0;455}456}457} else if (prim == GE_PRIM_POINTS) {458result->pixelMapped = false;459if (!ExpandPoints(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode)) {460result->drawNumTrans = 0;461return;462}463result->drawBuffer = transformedExpanded;464} else if (prim == GE_PRIM_LINES) {465result->pixelMapped = false;466if (!ExpandLines(vertexCount, numDecodedVerts, vertsSize, inds, indsSize, transformed, transformedExpanded, numTrans, throughmode)) {467result->drawNumTrans = 0;468return;469}470result->drawBuffer = transformedExpanded;471} else {472// We can simply draw the unexpanded buffer.473numTrans = vertexCount;474result->pixelMapped = false;475476// If we don't support custom cull in the shader, process it here.477if (!gstate_c.Use(GPU_USE_CULL_DISTANCE) && vertexCount > 0 && !throughmode) {478const u16 *indsIn = (const u16 *)inds;479u16 *newInds = inds + vertexCount;480u16 *indsOut = newInds;481482float minZValue, maxZValue;483CalcCullParams(minZValue, maxZValue);484485std::vector<int> outsideZ;486outsideZ.resize(vertexCount);487488// First, check inside/outside directions for each index.489for (int i = 0; i < vertexCount; ++i) {490float z = transformed[indsIn[i]].z / transformed[indsIn[i]].pos_w;491if (z > maxZValue)492outsideZ[i] = 1;493else if (z < minZValue)494outsideZ[i] = -1;495else496outsideZ[i] = 0;497}498499// Now, for each primitive type, throw away the indices if:500// - Depth clamp on, and ALL verts are outside *in the same direction*.501// - Depth clamp off, and ANY vert is outside.502if (prim == GE_PRIM_TRIANGLES && gstate.isDepthClampEnabled()) {503numTrans = 0;504for (int i = 0; i < vertexCount - 2; i += 3) {505if (outsideZ[i + 0] != 0 && outsideZ[i + 0] == outsideZ[i + 1] && outsideZ[i + 0] == outsideZ[i + 2]) {506// All outside, and all the same direction. Nuke this triangle.507continue;508}509510memcpy(indsOut, indsIn + i, 3 * sizeof(uint16_t));511indsOut += 3;512numTrans += 3;513}514515inds = newInds;516} else if (prim == GE_PRIM_TRIANGLES) {517numTrans = 0;518for (int i = 0; i < vertexCount - 2; i += 3) {519if (outsideZ[i + 0] != 0 || outsideZ[i + 1] != 0 || outsideZ[i + 2] != 0) {520// Even one outside, and we cull.521continue;522}523524memcpy(indsOut, indsIn + i, 3 * sizeof(uint16_t));525indsOut += 3;526numTrans += 3;527}528529inds = newInds;530}531} else if (throughmode && g_Config.bSmart2DTexFiltering && !gstate_c.textureIsVideo) {532// We check some common cases for pixel mapping.533// TODO: It's not really optimal that some previous step has removed the triangle strip.534if (vertexCount <= 6 && prim == GE_PRIM_TRIANGLES) {535// It's enough to check UV deltas vs pos deltas between vertex pairs:536// 0-1 1-3 3-2 2-0. Maybe can even skip the last one. Probably some simple math can get us that sequence.537// Unfortunately we need to reverse the previous UV scaling operation. Fortunately these are powers of two538// so the operations are exact.539bool pixelMapped = true;540const u16 *indsIn = (const u16 *)inds;541for (int t = 0; t < vertexCount; t += 3) {542float uscale = gstate_c.curTextureWidth;543float vscale = gstate_c.curTextureHeight;544struct { int a; int b; } pairs[] = { {0, 1}, {1, 2}, {2, 0} };545for (int i = 0; i < ARRAY_SIZE(pairs); i++) {546int a = indsIn[t + pairs[i].a];547int b = indsIn[t + pairs[i].b];548float du = fabsf((transformed[a].u - transformed[b].u) * uscale);549float dv = fabsf((transformed[a].v - transformed[b].v) * vscale);550float dx = fabsf(transformed[a].x - transformed[b].x);551float dy = fabsf(transformed[a].y - transformed[b].y);552if (du != dx || dv != dy) {553pixelMapped = false;554}555}556if (!pixelMapped) {557break;558}559}560result->pixelMapped = pixelMapped;561}562}563}564565if (gstate.isModeClear()) {566gpuStats.numClears++;567}568569result->action = SW_DRAW_INDEXED;570result->drawNumTrans = numTrans;571}572573void SoftwareTransform::CalcCullParams(float &minZValue, float &maxZValue) const {574// The projected Z can be up to 0x3F8000FF, which is where this constant is from.575// It seems like it may only maintain 15 mantissa bits (excluding implied.)576maxZValue = 1.000030517578125f * gstate_c.vpDepthScale;577minZValue = -maxZValue;578// Scale and offset the Z appropriately, since we baked that into a projection transform.579if (params_.usesHalfZ) {580maxZValue = maxZValue * 0.5f + 0.5f + gstate_c.vpZOffset * 0.5f;581minZValue = minZValue * 0.5f + 0.5f + gstate_c.vpZOffset * 0.5f;582} else {583maxZValue += gstate_c.vpZOffset;584minZValue += gstate_c.vpZOffset;585}586// In case scale was negative, flip.587if (minZValue > maxZValue)588std::swap(minZValue, maxZValue);589}590591bool SoftwareTransform::ExpandRectangles(int vertexCount, int &numDecodedVerts, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode, bool *pixelMappedExactly) const {592// Before we start, do a sanity check - does the output fit?593if ((vertexCount / 2) * 6 > indsSize) {594// Won't fit, kill the draw.595return false;596}597if ((vertexCount / 2) * 4 > vertsSize) {598// Won't fit, kill the draw.599return false;600}601602// Rectangles always need 2 vertices, disregard the last one if there's an odd number.603vertexCount = vertexCount & ~1;604numTrans = 0;605TransformedVertex *trans = &transformedExpanded[0];606607const u16 *indsIn = (const u16 *)inds;608u16 *newInds = inds + vertexCount;609u16 *indsOut = newInds;610611numDecodedVerts = 4 * (vertexCount / 2);612613float uscale = 1.0f;614float vscale = 1.0f;615if (throughmode) {616uscale /= gstate_c.curTextureWidth;617vscale /= gstate_c.curTextureHeight;618}619620bool pixelMapped = g_Config.bSmart2DTexFiltering && !gstate_c.textureIsVideo;621622for (int i = 0; i < vertexCount; i += 2) {623const TransformedVertex &transVtxTL = transformed[indsIn[i + 0]];624const TransformedVertex &transVtxBR = transformed[indsIn[i + 1]];625626if (pixelMapped) {627float dx = transVtxBR.x - transVtxTL.x;628float dy = transVtxBR.y - transVtxTL.y;629float du = transVtxBR.u - transVtxTL.u;630float dv = transVtxBR.v - transVtxTL.v;631632// NOTE: We will accept it as pixel mapped if only one dimension is stretched. This fixes dialog frames in FFI.633// Though, there could be false positives in other games due to this. Let's see if it is a problem...634if (dx <= 0 || dy <= 0 || (dx != du && dy != dv)) {635pixelMapped = false;636}637}638639// We have to turn the rectangle into two triangles, so 6 points.640// This is 4 verts + 6 indices.641642// bottom right643trans[0] = transVtxBR;644trans[0].u = transVtxBR.u * uscale;645trans[0].v = transVtxBR.v * vscale;646647// top right648trans[1] = transVtxBR;649trans[1].y = transVtxTL.y;650trans[1].u = transVtxBR.u * uscale;651trans[1].v = transVtxTL.v * vscale;652653// top left654trans[2] = transVtxBR;655trans[2].x = transVtxTL.x;656trans[2].y = transVtxTL.y;657trans[2].u = transVtxTL.u * uscale;658trans[2].v = transVtxTL.v * vscale;659660// bottom left661trans[3] = transVtxBR;662trans[3].x = transVtxTL.x;663trans[3].u = transVtxTL.u * uscale;664trans[3].v = transVtxBR.v * vscale;665666// That's the four corners. Now process UV rotation.667if (throughmode) {668RotateUVThrough(trans);669} else {670RotateUV(trans, params_.flippedY);671}672673// Triangle: BR-TR-TL674indsOut[0] = i * 2 + 0;675indsOut[1] = i * 2 + 1;676indsOut[2] = i * 2 + 2;677// Triangle: BL-BR-TL678indsOut[3] = i * 2 + 3;679indsOut[4] = i * 2 + 0;680indsOut[5] = i * 2 + 2;681682trans += 4;683indsOut += 6;684685numTrans += 6;686}687inds = newInds;688*pixelMappedExactly = pixelMapped;689return true;690}691692// In-place. So, better not be doing this on GPU memory!693void IndexBufferProvokingLastToFirst(int prim, u16 *inds, int indsSize) {694switch (prim) {695case GE_PRIM_LINES:696// Swap every two indices.697for (int i = 0; i < indsSize - 1; i += 2) {698u16 temp = inds[i];699inds[i] = inds[i + 1];700inds[i + 1] = temp;701}702break;703case GE_PRIM_TRIANGLES:704// Rotate the triangle so the last becomes the first, without changing the winding order.705// This could be done with a series of pshufb.706for (int i = 0; i < indsSize - 2; i += 3) {707u16 temp = inds[i + 2];708inds[i + 2] = inds[i + 1];709inds[i + 1] = inds[i];710inds[i] = temp;711}712break;713case GE_PRIM_POINTS:714// Nothing to do,715break;716case GE_PRIM_RECTANGLES:717// Nothing to do, already using the 2nd vertex.718break;719default:720_dbg_assert_msg_(false, "IndexBufferProvokingFirstToLast: Only works with plain indexed primitives, no strips or fans")721}722}723724bool SoftwareTransform::ExpandLines(int vertexCount, int &numDecodedVerts, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode) {725// Before we start, do a sanity check - does the output fit?726if ((vertexCount / 2) * 6 > indsSize) {727// Won't fit, kill the draw.728return false;729}730if ((vertexCount / 2) * 4 > vertsSize) {731return false;732}733734// Lines always need 2 vertices, disregard the last one if there's an odd number.735vertexCount = vertexCount & ~1;736numTrans = 0;737TransformedVertex *trans = &transformedExpanded[0];738739const u16 *indsIn = (const u16 *)inds;740u16 *newInds = inds + vertexCount;741u16 *indsOut = newInds;742743float dx = 1.0f * gstate_c.vpWidthScale * (1.0f / fabsf(gstate.getViewportXScale()));744float dy = 1.0f * gstate_c.vpHeightScale * (1.0f / fabsf(gstate.getViewportYScale()));745float du = 1.0f / gstate_c.curTextureWidth;746float dv = 1.0f / gstate_c.curTextureHeight;747748if (throughmode) {749dx = 1.0f;750dy = 1.0f;751}752753numDecodedVerts = 4 * (vertexCount / 2);754755if (PSP_CoreParameter().compat.flags().CenteredLines) {756// Lines meant to be pretty in 3D like in Echochrome.757758// We expand them in both directions for symmetry, so we need to halve the expansion.759dx *= 0.5f;760dy *= 0.5f;761762for (int i = 0; i < vertexCount; i += 2) {763const TransformedVertex &transVtx1 = transformed[indsIn[i + 0]];764const TransformedVertex &transVtx2 = transformed[indsIn[i + 1]];765766// Okay, let's calculate the perpendicular.767float horizontal = transVtx2.x * transVtx2.pos_w - transVtx1.x * transVtx1.pos_w;768float vertical = transVtx2.y * transVtx2.pos_w - transVtx1.y * transVtx1.pos_w;769770Vec2f addWidth = Vec2f(-vertical, horizontal).Normalized();771772float xoff = addWidth.x * dx;773float yoff = addWidth.y * dy;774775// bottom right776trans[0].CopyFromWithOffset(transVtx2, xoff * transVtx2.pos_w, yoff * transVtx2.pos_w);777// top right778trans[1].CopyFromWithOffset(transVtx1, xoff * transVtx1.pos_w, yoff * transVtx1.pos_w);779// top left780trans[2].CopyFromWithOffset(transVtx1, -xoff * transVtx1.pos_w, -yoff * transVtx1.pos_w);781// bottom left782trans[3].CopyFromWithOffset(transVtx2, -xoff * transVtx2.pos_w, -yoff * transVtx2.pos_w);783784// Triangle: BR-TR-TL785indsOut[0] = i * 2 + 0;786indsOut[1] = i * 2 + 1;787indsOut[2] = i * 2 + 2;788// Triangle: BL-BR-TL789indsOut[3] = i * 2 + 3;790indsOut[4] = i * 2 + 0;791indsOut[5] = i * 2 + 2;792trans += 4;793indsOut += 6;794795numTrans += 6;796}797} else {798// Lines meant to be as closely compatible with upscaled 2D drawing as possible.799// We use this as default.800801for (int i = 0; i < vertexCount; i += 2) {802const TransformedVertex &transVtx1 = transformed[indsIn[i + 0]];803const TransformedVertex &transVtx2 = transformed[indsIn[i + 1]];804805const TransformedVertex &transVtxT = transVtx1.y <= transVtx2.y ? transVtx1 : transVtx2;806const TransformedVertex &transVtxB = transVtx1.y <= transVtx2.y ? transVtx2 : transVtx1;807const TransformedVertex &transVtxL = transVtx1.x <= transVtx2.x ? transVtx1 : transVtx2;808const TransformedVertex &transVtxR = transVtx1.x <= transVtx2.x ? transVtx2 : transVtx1;809810// Sort the points so our perpendicular will bias the right direction.811const TransformedVertex &transVtxTL = (transVtxT.y != transVtxB.y || transVtxT.x > transVtxB.x) ? transVtxT : transVtxB;812const TransformedVertex &transVtxBL = (transVtxT.y != transVtxB.y || transVtxT.x > transVtxB.x) ? transVtxB : transVtxT;813814// Okay, let's calculate the perpendicular.815float horizontal = transVtxTL.x * transVtxTL.pos_w - transVtxBL.x * transVtxBL.pos_w;816float vertical = transVtxTL.y * transVtxTL.pos_w - transVtxBL.y * transVtxBL.pos_w;817Vec2f addWidth = Vec2f(-vertical, horizontal).Normalized();818819// bottom right820trans[0] = transVtxBL;821trans[0].x += addWidth.x * dx * trans[0].pos_w;822trans[0].y += addWidth.y * dy * trans[0].pos_w;823trans[0].u += addWidth.x * du * trans[0].uv_w;824trans[0].v += addWidth.y * dv * trans[0].uv_w;825826// top right827trans[1] = transVtxTL;828trans[1].x += addWidth.x * dx * trans[1].pos_w;829trans[1].y += addWidth.y * dy * trans[1].pos_w;830trans[1].u += addWidth.x * du * trans[1].uv_w;831trans[1].v += addWidth.y * dv * trans[1].uv_w;832833// top left834trans[2] = transVtxTL;835836// bottom left837trans[3] = transVtxBL;838839// Triangle: BR-TR-TL840indsOut[0] = i * 2 + 0;841indsOut[1] = i * 2 + 1;842indsOut[2] = i * 2 + 2;843// Triangle: BL-BR-TL844indsOut[3] = i * 2 + 3;845indsOut[4] = i * 2 + 0;846indsOut[5] = i * 2 + 2;847trans += 4;848indsOut += 6;849850numTrans += 6;851}852}853854inds = newInds;855return true;856}857858bool SoftwareTransform::ExpandPoints(int vertexCount, int &maxIndex, int vertsSize, u16 *&inds, int indsSize, const TransformedVertex *transformed, TransformedVertex *transformedExpanded, int &numTrans, bool throughmode) {859// Before we start, do a sanity check - does the output fit?860if (vertexCount * 6 > indsSize) {861// Won't fit, kill the draw.862return false;863}864if (vertexCount * 4 > vertsSize) {865// Won't fit, kill the draw.866return false;867}868869numTrans = 0;870TransformedVertex *trans = &transformedExpanded[0];871872const u16 *indsIn = (const u16 *)inds;873u16 *newInds = inds + vertexCount;874u16 *indsOut = newInds;875876float dx = 1.0f * gstate_c.vpWidthScale * (1.0f / gstate.getViewportXScale());877float dy = 1.0f * gstate_c.vpHeightScale * (1.0f / gstate.getViewportYScale());878float du = 1.0f / gstate_c.curTextureWidth;879float dv = 1.0f / gstate_c.curTextureHeight;880881if (throughmode) {882dx = 1.0f;883dy = 1.0f;884}885886maxIndex = 4 * vertexCount;887for (int i = 0; i < vertexCount; ++i) {888const TransformedVertex &transVtxTL = transformed[indsIn[i]];889890// Create the bottom right version.891TransformedVertex transVtxBR = transVtxTL;892transVtxBR.x += dx * transVtxTL.pos_w;893transVtxBR.y += dy * transVtxTL.pos_w;894transVtxBR.u += du * transVtxTL.uv_w;895transVtxBR.v += dv * transVtxTL.uv_w;896897// We have to turn the rectangle into two triangles, so 6 points.898// This is 4 verts + 6 indices.899900// bottom right901trans[0] = transVtxBR;902903// top right904trans[1] = transVtxBR;905trans[1].y = transVtxTL.y;906trans[1].v = transVtxTL.v;907908// top left909trans[2] = transVtxBR;910trans[2].x = transVtxTL.x;911trans[2].y = transVtxTL.y;912trans[2].u = transVtxTL.u;913trans[2].v = transVtxTL.v;914915// bottom left916trans[3] = transVtxBR;917trans[3].x = transVtxTL.x;918trans[3].u = transVtxTL.u;919920// Triangle: BR-TR-TL921indsOut[0] = i * 4 + 0;922indsOut[1] = i * 4 + 1;923indsOut[2] = i * 4 + 2;924// Triangle: BL-BR-TL925indsOut[3] = i * 4 + 3;926indsOut[4] = i * 4 + 0;927indsOut[5] = i * 4 + 2;928trans += 4;929indsOut += 6;930931numTrans += 6;932}933inds = newInds;934return true;935}936937938