#include "util.hpp" #include <3ds.h> #include #include #include TestQuad TestQuadBuilder::Build(int width, int height) const { for (auto& slot : attributes) { if (slot.coords_set && slot.coords_set != 0xf) { throw std::runtime_error("Did not set up attributes for all coordinates"); } } return TestQuad(*this, width, height); } // TODO: Default mosaic quad to pow2+1 x pow2+1 (e.g. 65x65) => interpolating from 0 to 1 yields clean fractions! TestMosaicQuad TestQuadBuilder::BuildMosaic(int width, int height) const { for (auto& slot : attributes) { if (slot.coords_set && slot.coords_set != 0xf) { throw std::runtime_error("Did not set up attributes for all coordinates"); } } return TestMosaicQuad(*this, width, height); } TestQuadBase::TestQuadBase(const TestQuadBuilder& config, int width, int height) : quad_width(width), quad_height(height) { if (quad_height <= 32) { // Hardware bug breaks 32x32 display transfers when de-tiling throw std::runtime_error("Cannot have test quads this small due to hardware bug"); } // NOTE: LCD scans out framebuffers rotated compared to the renderer's // coordinate system, so the width and height are swapped for the // render target test_target = C3D_RenderTargetCreate(quad_height, quad_width, GPU_RB_RGBA8, C3D_DEPTHTYPE { -1 }); if (!test_target) { throw std::runtime_error("Failed to create TestQuad render target"); } test_untiled = linearAlloc(quad_width * quad_height * 4); if (!test_untiled) { throw std::runtime_error("Failed to create TestQuad staging texture"); } untiled_rgb565 = linearAlloc(quad_width * quad_height * 2); InitShader(config); } TestQuad::TestQuad(const TestQuadBuilder& config, int width, int height) : TestQuadBase(config, width, height) { AttrInfo_Init(&attr_info); uint32_t num_attributes = 0; uint64_t permutation = 0x0; for (auto& attr : config.attributes) { if (attr.coords_set) { AttrInfo_AddLoader(&attr_info, num_attributes, GPU_FLOAT, 4); permutation |= uint64_t { num_attributes } << (4 * num_attributes); ++num_attributes; } } vertex_data = linearAlloc(sizeof(float) * 4 * num_attributes * 6); BufInfo_Init(&buf_info); BufInfo_Add(&buf_info, vertex_data, sizeof(float) * 4 * num_attributes, num_attributes, permutation); Modify(config); } void TestQuad::Modify(const TestQuadBuilder& config) { // TODO: Prohibit adding new attributes, since we'd need to recreate the entire quad in that case char* ptr = reinterpret_cast(vertex_data); using Slot = TestQuadBuilder::AttributeSlot; for (auto config_data : { &Slot::x0y0, &Slot::x1y0, &Slot::x0y1, &Slot::x1y1, &Slot::x0y1, &Slot::x1y0 }) { for (auto& attr : config.attributes) { if (attr.coords_set) { memcpy(ptr, (attr.*config_data).data(), sizeof(float) * 4); ptr += sizeof(float) * 4; } } } } void TestQuad::Begin() { memcpy(C3D_GetAttrInfo(), &attr_info, sizeof(attr_info)); memcpy(C3D_GetBufInfo(), &buf_info, sizeof(buf_info)); TestQuadBase::Begin(); } void TestQuadBase::Begin() { C3D_BindProgram(&program); C3D_FrameBegin(0); C3D_RenderTargetClear(test_target, C3D_CLEAR_ALL, 0, 0); C3D_FrameDrawOn(test_target); // Set up reasonable rendering defaults C3D_ColorLogicOp(GPU_LOGICOP_COPY); // Disable alpha blending C3D_DepthTest(false, GPU_GREATER, GPU_WRITE_ALL); } /** * Finalizes the test frame and copies the output to the un-tiled staging image. * * For debugging, the image is also copied onto the framebuffer console. */ void TestQuad::DrawAndFinish() { // Queue draw for the quad itself C3D_DrawArrays(GPU_TRIANGLES, 0, 6); TestQuadBase::DrawAndFinish(); } void TestQuadBase::DrawAndFinish() { // Queue copy to un-tiled memory // TODO: 32x32 somehow produces glitched output here, 16x16 even hangs. Implement a software-fallback for those dimensions C3D_SyncDisplayTransfer((u32*)test_target->frameBuf.colorBuf, GX_BUFFER_DIM(quad_height, quad_width), (u32*)test_untiled, GX_BUFFER_DIM(quad_height, quad_width), 0); // Finalize frame C3D_FrameEnd(0); // Wait for completion C3D_FrameSync(); // Display image to the framebuffer console auto out_buffer = gfxGetFramebuffer(GFX_TOP, GFX_LEFT, NULL, NULL); auto out_fmt = (int)gfxGetScreenFormat(GFX_TOP); if (out_fmt != GSP_RGB565_OES) { // libctru console is expected to hardcode RGB565 throw std::runtime_error("Unexpected framebuffer format for debug display"); } svcInvalidateProcessDataCache(0xFFFF8001, (uintptr_t)test_untiled, quad_width * quad_height * 4); for (int pixel = 0; pixel < quad_width * quad_height; ++pixel) { uint32_t* val = (uint32_t*)((uintptr_t)test_untiled + 4 * pixel); uint16_t r = ((*val >> 24) & 0xff) >> 3; uint16_t g = ((*val >> 16) & 0xff) >> 2; uint16_t b = ((*val >> 8) & 0xff) >> 3; *(uint16_t*)((uintptr_t)untiled_rgb565 + 2 * pixel) = (r << 11) | (g << 5) | b; } svcFlushProcessDataCache(0xFFFF8001, (uintptr_t)untiled_rgb565, quad_width * quad_height * 2); { // Display on un-tiled console buffer bool display_at_top = false; // TODO: Disabled since each line of text will scroll up the picture immediately... if (quad_height < 240) { // NOTE: Hardware doesn't support texture copies from buffers wider than the output C3D_SyncTextureCopy((u32*)untiled_rgb565, GX_BUFFER_DIM(quad_width * quad_height / 16, 0), (u32*)(out_buffer + display_at_top * 2 * (240 - quad_height)), GX_BUFFER_DIM(quad_height * 2 / 16, (240 - quad_height) * 2 / 16), quad_width * quad_height * 2, 0x0000008); } else { // Software fallback for dimensions unsupported by hardware for (int line = 0; line < std::min(400, quad_width); ++ line) { auto line_width = std::min(240, quad_height); memcpy((char*)out_buffer + 2 * line * 240 + display_at_top * 2 * (240 - line_width), (char*)untiled_rgb565 + 2 * line * quad_height + display_at_top * 2 * (quad_height - line_width), line_width * 2); } } } } void UnbindC3DProgram() { static DVLE_s dummy_dvle {}; static shaderInstance_s dummy_shader = { .dvle = &dummy_dvle }; static shaderProgram_s dummy_program = { .vertexShader = &dummy_shader }; C3D_BindProgram(&dummy_program); } TestQuadBase::~TestQuadBase() { UnbindC3DProgram(); // Explicitly unbind program since citro3d's dirty state tracking code will crash otherwise C3D_RenderTargetDelete(test_target); linearFree(test_untiled); linearFree(untiled_rgb565); shaderProgramFree(&program); DVLB_Free(vshader_dvlb); } TestQuad::~TestQuad() { linearFree(vertex_data); } void TestQuadBase::InitShader(const TestQuadBuilder& config) { vshader_dvlb = (decltype(vshader_dvlb))malloc(sizeof(*vshader_dvlb)); // TODO: DVLB and DVLP aren't actually needed auto& dvlb = vshader_dvlb; dvlb->numDVLE = 1; auto& dvlp = vshader_dvlb->DVLP; auto& dvle = *(DVLE_s*)malloc(sizeof(DVLE_s) * dvlb->numDVLE); dvlb->DVLE = &dvle; { std::vector outputs; for (int i = 0; i < config.attributes.size(); ++i) { if (config.attributes[i].coords_set) { outputs.push_back(static_cast(i)); } } dvlp.codeData = (uint32_t*)malloc(sizeof(nihstro::Instruction) * (outputs.size() + 1)); dvlp.opcdescData = (uint32_t*)malloc(sizeof(nihstro::SwizzlePattern) * 1); auto codeptr = dvlp.codeData; for (int i = 0; i < outputs.size(); ++i) { // Mov input -> output nihstro::Instruction instr { }; instr.opcode = nihstro::OpCode::Id::MOV; instr.common.src1 = nihstro::SourceRegister::FromTypeAndIndex(nihstro::RegisterType::Input, i); instr.common.dest = nihstro::DestRegister::FromTypeAndIndex(nihstro::RegisterType::Output, i); *codeptr++ = instr.hex; } { nihstro::Instruction instr { }; instr.opcode = nihstro::OpCode::Id::END; *codeptr++ = instr.hex; } dvlp.codeSize = (codeptr - dvlp.codeData); { nihstro::SwizzlePattern swizzle { }; swizzle.SetSelectorSrc1(0, nihstro::SwizzlePattern::Selector::x); swizzle.SetSelectorSrc1(1, nihstro::SwizzlePattern::Selector::y); swizzle.SetSelectorSrc1(2, nihstro::SwizzlePattern::Selector::z); swizzle.SetSelectorSrc1(3, nihstro::SwizzlePattern::Selector::w); swizzle.SetDestComponentEnabled(0, true); swizzle.SetDestComponentEnabled(1, true); swizzle.SetDestComponentEnabled(2, true); swizzle.SetDestComponentEnabled(3, true); dvlp.opdescSize = 1; dvlp.opcdescData[0] = swizzle.hex; } dvle = {}; dvle.type = VERTEX_SHDR; dvle.mergeOutmaps = false; dvle.mainOffset = 0; dvle.endmainOffset = dvle.mainOffset + dvlp.codeSize; dvle.constTableSize = 0; dvle.constTableData = nullptr; dvle.uniformTableSize = 0; dvle.uniformTableData = nullptr; dvle.symbolTableData = nullptr; dvle.outTableSize = outputs.size(); dvle.outTableData = (decltype(dvle.outTableData))malloc(sizeof(dvle.outTableData[0]) * dvle.outTableSize); for (int i = 0; i < outputs.size(); ++i) { dvle.outTableData[i].type = outputs[i]; dvle.outTableData[i].regID = i; dvle.outTableData[i].mask = 0xf; } DVLE_GenerateOutmap(&dvle); dvle.dvlp = &dvlp; } shaderProgramInit(&program); shaderProgramSetVsh(&program, &vshader_dvlb->DVLE[0]); // Workaround libctru bug: numFloat24Uniforms doesn't get initialized if no constant table is provided program.vertexShader->numFloat24Uniforms = 0; } TestMosaicQuad::TestMosaicQuad(const TestQuadBuilder& config, int width, int height) : TestQuadBase(config, width, height), attributes(config.attributes) { AttrInfo_Init(&attr_info); uint32_t num_attributes = 0; uint64_t permutation = 0x0; for (auto& attr : config.attributes) { if (attr.coords_set) { AttrInfo_AddLoader(&attr_info, num_attributes, GPU_FLOAT, 4); permutation |= uint64_t { num_attributes } << (4 * num_attributes); ++num_attributes; } } // Allocate memory for 2 triangles per pixel vertex_data = linearAlloc(sizeof(float) * 4 * num_attributes * 6 * width * height); BufInfo_Init(&buf_info); BufInfo_Add(&buf_info, vertex_data, sizeof(float) * 4 * num_attributes, num_attributes, permutation); Modify(config); } void TestMosaicQuad::Modify(const TestQuadBuilder& config) { // TODO: Prohibit adding new attributes, since we'd need to recreate the entire quad in that case // TODO: Prohibit modifying position attributes for mosaic // TODO: Use single triangles instead of rendering quads char* ptr = reinterpret_cast(vertex_data); using Slot = TestQuadBuilder::AttributeSlot; // For each pixel row... for (int y = 0; y < quad_height; ++y) { // For each pixel in the row... for (int x = 0; x < quad_width; ++x) { // For each of the 6 vertices that build the 1x1 quad... for (auto config_data : { &Slot::x0y1, &Slot::x1y0, &Slot::x0y0, &Slot::x0y0, &Slot::x1y1, &Slot::x1y0 }) { // Setup position // NOTE: x and y need to be inverted due to LCD rotation auto pos = config.attributes[RESULT_POSITION].x0y1; pos[0] -= 2.0 * y / quad_height; pos[1] -= 2.0 * x / quad_width; if (config_data == &Slot::x1y0 || config_data == &Slot::x1y1) { pos[0] -= 2.0 / quad_height; } if (config_data == &Slot::x0y0 || config_data == &Slot::x1y1) { pos[1] -= 2.0 / quad_width; } memcpy(ptr, pos.data(), sizeof(float) * 4); ptr += sizeof(float) * 4; // Setup other attributes as constants across the 1x1 quad const float factor_x = (float)x / (quad_width - 1); const float factor_y = (float)y / (quad_height - 1); for (auto& attr : config.attributes) { if (&attr == &config.attributes[RESULT_POSITION]) { // Position already handled above continue; } if (!attr.coords_set) { continue; } // TODO: Merge with InterpolatedAttributeAt for (int i = 0; i < 4; ++i) { float mean_bot = attr.x0y0[i] * (1.0 - factor_x) + attr.x1y0[i] * factor_x; float mean_top = attr.x0y1[i] * (1.0 - factor_x) + attr.x1y1[i] * factor_x; float mean = mean_top * (1.0 - factor_y) + mean_bot * factor_y; memcpy(ptr, &mean, sizeof(float)); ptr += sizeof(float); } } } } } } void TestMosaicQuad::Begin() { memcpy(C3D_GetAttrInfo(), &attr_info, sizeof(attr_info)); memcpy(C3D_GetBufInfo(), &buf_info, sizeof(buf_info)); TestQuadBase::Begin(); } void TestMosaicQuad::DrawAndFinish() { // Queue draw for the quad itself C3D_DrawArrays(GPU_TRIANGLES, 0, quad_height * quad_width * 6); TestQuadBase::DrawAndFinish(); } TestMosaicQuad::~TestMosaicQuad() { linearFree(vertex_data); }