From c4691b784bd7746c5845df00a82ea0909b37ec0f Mon Sep 17 00:00:00 2001
From: Tony Wasserka <NeoBrainX@gmail.com>
Date: Sat, 16 Aug 2014 14:06:40 +0200
Subject: [PATCH] Pica: Add support for dumping textures.

---
 CMakeLists.txt                             |   5 +
 src/citra/CMakeLists.txt                   |   2 +-
 src/citra_qt/CMakeLists.txt                |   2 +-
 src/video_core/debug_utils/debug_utils.cpp | 131 +++++++++++++++++++++
 src/video_core/debug_utils/debug_utils.h   |   2 +
 src/video_core/pica.h                      |  45 ++++++-
 6 files changed, 184 insertions(+), 3 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 56f5d02b0..4c7b3dd73 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -9,6 +9,11 @@ add_definitions(-Wno-attributes)
 add_definitions(-DSINGLETHREADED)
 add_definitions(${CXX_COMPILE_FLAGS})
 
+find_package(PNG)
+if (PNG_FOUND)
+    add_definitions(-DHAVE_PNG)
+endif ()
+
 # dependency checking
 list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/externals/cmake-modules/")
 set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/CMakeTests)
diff --git a/src/citra/CMakeLists.txt b/src/citra/CMakeLists.txt
index b1ab67598..1cbe22cc0 100644
--- a/src/citra/CMakeLists.txt
+++ b/src/citra/CMakeLists.txt
@@ -12,7 +12,7 @@ add_executable(citra ${SRCS} ${HEADERS})
 if (APPLE)
     target_link_libraries(citra core common video_core iconv pthread ${COREFOUNDATION_LIBRARY} ${OPENGL_LIBRARIES} ${GLEW_LIBRARY} ${GLFW_LIBRARIES})
 else()
-    target_link_libraries(citra core common video_core GLEW pthread X11 Xxf86vm Xi Xcursor ${OPENGL_LIBRARIES} ${GLFW_LIBRARIES} rt ${X11_Xrandr_LIB} ${X11_xv86vmode_LIB})
+    target_link_libraries(citra core common video_core GLEW pthread X11 Xxf86vm Xi Xcursor ${OPENGL_LIBRARIES} ${GLFW_LIBRARIES} rt ${X11_Xrandr_LIB} ${X11_xv86vmode_LIB} ${PNG_LIBRARIES})
 endif()
 
 #install(TARGETS citra RUNTIME DESTINATION ${bindir})
diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt
index ff1fbc460..8ad6759b7 100644
--- a/src/citra_qt/CMakeLists.txt
+++ b/src/citra_qt/CMakeLists.txt
@@ -47,7 +47,7 @@ else()
 	set(RT_LIBRARY rt)
 endif()
 
-target_link_libraries(citra-qt core common video_core qhexedit ${ICONV_LIBRARY} ${COREFOUNDATION_LIBRARY} ${QT_LIBRARIES} ${OPENGL_LIBRARIES} ${RT_LIBRARY} ${GLEW_LIBRARY})
+target_link_libraries(citra-qt core common video_core qhexedit ${ICONV_LIBRARY} ${COREFOUNDATION_LIBRARY} ${QT_LIBRARIES} ${OPENGL_LIBRARIES} ${RT_LIBRARY} ${GLEW_LIBRARY} ${PNG_LIBRARIES})
 if(USE_QT5)
     target_link_libraries(citra-qt Qt5::Gui Qt5::Widgets Qt5::OpenGL)
 endif()
diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp
index 1bbc0330c..753de41e8 100644
--- a/src/video_core/debug_utils/debug_utils.cpp
+++ b/src/video_core/debug_utils/debug_utils.cpp
@@ -3,10 +3,17 @@
 // Refer to the license.txt file included.
 
 #include <algorithm>
+#include <map>
 #include <fstream>
 #include <mutex>
 #include <string>
 
+#ifdef HAVE_PNG
+#include <png.h>
+#endif
+
+#include "common/file_util.h"
+
 #include "video_core/pica.h"
 
 #include "debug_utils.h"
@@ -315,6 +322,130 @@ std::unique_ptr<PicaTrace> FinishPicaTracing()
     return std::move(ret);
 }
 
+void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) {
+    // NOTE: Permanently enabling this just trashes hard disks for no reason.
+    //       Hence, this is currently disabled.
+    return;
+
+#ifndef HAVE_PNG
+	return;
+#else
+	if (!data)
+        return;
+
+    // Write data to file
+    static int dump_index = 0;
+    std::string filename = std::string("texture_dump") + std::to_string(++dump_index) + std::string(".png");
+    u32 row_stride = texture_config.width * 3;
+
+    u8* buf;
+
+    char title[] = "Citra texture dump";
+    char title_key[] = "Title";
+    png_structp png_ptr = nullptr;
+    png_infop info_ptr = nullptr;
+
+    // Open file for writing (binary mode)
+    File::IOFile fp(filename, "wb");
+
+    // Initialize write structure
+    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
+    if (png_ptr == nullptr) {
+        ERROR_LOG(GPU, "Could not allocate write struct\n");
+        goto finalise;
+
+    }
+
+    // Initialize info structure
+    info_ptr = png_create_info_struct(png_ptr);
+    if (info_ptr == nullptr) {
+        ERROR_LOG(GPU, "Could not allocate info struct\n");
+        goto finalise;
+    }
+
+    // Setup Exception handling
+    if (setjmp(png_jmpbuf(png_ptr))) {
+        ERROR_LOG(GPU, "Error during png creation\n");
+        goto finalise;
+    }
+
+    png_init_io(png_ptr, fp.GetHandle());
+
+    // Write header (8 bit colour depth)
+    png_set_IHDR(png_ptr, info_ptr, texture_config.width, texture_config.height,
+        8, PNG_COLOR_TYPE_RGB /*_ALPHA*/, PNG_INTERLACE_NONE,
+        PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+
+    png_text title_text;
+    title_text.compression = PNG_TEXT_COMPRESSION_NONE;
+    title_text.key = title_key;
+    title_text.text = title;
+    png_set_text(png_ptr, info_ptr, &title_text, 1);
+
+    png_write_info(png_ptr, info_ptr);
+
+    buf = new u8[row_stride * texture_config.height];
+    for (int y = 0; y < texture_config.height; ++y) {
+        for (int x = 0; x < texture_config.width; ++x) {
+            // Images are split into 8x8 tiles. Each tile is composed of four 4x4 subtiles each
+            // of which is composed of four 2x2 subtiles each of which is composed of four texels.
+            // Each structure is embedded into the next-bigger one in a diagonal pattern, e.g.
+            // texels are laid out in a 2x2 subtile like this:
+            // 2 3
+            // 0 1
+            //
+            // The full 8x8 tile has the texels arranged like this:
+            //
+            // 42 43 46 47 58 59 62 63
+            // 40 41 44 45 56 57 60 61
+            // 34 35 38 39 50 51 54 55
+            // 32 33 36 37 48 49 52 53
+            // 10 11 14 15 26 27 30 31
+            // 08 09 12 13 24 25 28 29
+            // 02 03 06 07 18 19 22 23
+            // 00 01 04 05 16 17 20 21
+            int texel_index_within_tile = 0;
+            for (int block_size_index = 0; block_size_index < 3; ++block_size_index) {
+                int sub_tile_width = 1 << block_size_index;
+                int sub_tile_height = 1 << block_size_index;
+
+                int sub_tile_index = (x & sub_tile_width) << block_size_index;
+                sub_tile_index += 2 * ((y & sub_tile_height) << block_size_index);
+                texel_index_within_tile += sub_tile_index;
+            }
+
+            const int block_width = 8;
+            const int block_height = 8;
+
+            int coarse_x = (x / block_width) * block_width;
+            int coarse_y = (y / block_height) * block_height;
+
+            u8* source_ptr = (u8*)data + coarse_x * block_height * 3 + coarse_y * row_stride + texel_index_within_tile * 3;
+            buf[3 * x + y * row_stride    ] = source_ptr[2];
+            buf[3 * x + y * row_stride + 1] = source_ptr[1];
+            buf[3 * x + y * row_stride + 2] = source_ptr[0];
+        }
+    }
+
+    // Write image data
+    for (auto y = 0; y < texture_config.height; ++y)
+    {
+        u8* row_ptr = (u8*)buf + y * row_stride;
+        u8* ptr = row_ptr;
+        png_write_row(png_ptr, row_ptr);
+    }
+
+    delete[] buf;
+
+    // End write
+    png_write_end(png_ptr, nullptr);
+
+finalise:
+    if (info_ptr != nullptr) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
+    if (png_ptr != nullptr) png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
+#endif
+}
+
 } // namespace
 
 } // namespace
diff --git a/src/video_core/debug_utils/debug_utils.h b/src/video_core/debug_utils/debug_utils.h
index 023500066..49b19b28a 100644
--- a/src/video_core/debug_utils/debug_utils.h
+++ b/src/video_core/debug_utils/debug_utils.h
@@ -59,6 +59,8 @@ bool IsPicaTracing();
 void OnPicaRegWrite(u32 id, u32 value);
 std::unique_ptr<PicaTrace> FinishPicaTracing();
 
+void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data);
+
 } // namespace
 
 } // namespace
diff --git a/src/video_core/pica.h b/src/video_core/pica.h
index fe886c16f..f288615b8 100644
--- a/src/video_core/pica.h
+++ b/src/video_core/pica.h
@@ -94,7 +94,46 @@ struct Regs {
         BitField<16, 16, u32> y;
     } viewport_corner;
 
-    INSERT_PADDING_WORDS(0xa7);
+    INSERT_PADDING_WORDS(0x18);
+
+    struct TextureConfig {
+        INSERT_PADDING_WORDS(0x1);
+
+        union {
+            BitField< 0, 16, u32> height;
+            BitField<16, 16, u32> width;
+        };
+
+        INSERT_PADDING_WORDS(0x2);
+
+        u32 address;
+
+        u32 GetPhysicalAddress() {
+            return DecodeAddressRegister(address) - Memory::FCRAM_PADDR + Memory::HEAP_GSP_VADDR;
+        }
+
+        // texture1 and texture2 store the texture format directly after the address
+        // whereas texture0 inserts some additional flags inbetween.
+        // Hence, we store the format separately so that all other parameters can be described
+        // in a single structure.
+    };
+
+    enum class TextureFormat : u32 {
+        RGBA8        =  0,
+        RGB8         =  1,
+        RGBA5551     =  2,
+        RGB565       =  3,
+        RGBA4        =  4,
+
+        // TODO: Support for the other formats is not implemented, yet.
+        // Seems like they are luminance formats and compressed textures.
+    };
+
+    TextureConfig texture0;
+    INSERT_PADDING_WORDS(0x8);
+    BitField<0, 4, TextureFormat> texture0_format;
+
+    INSERT_PADDING_WORDS(0x81);
 
     struct {
         enum ColorFormat : u32 {
@@ -403,6 +442,8 @@ struct Regs {
         ADD_FIELD(viewport_depth_range);
         ADD_FIELD(viewport_depth_far_plane);
         ADD_FIELD(viewport_corner);
+        ADD_FIELD(texture0);
+        ADD_FIELD(texture0_format);
         ADD_FIELD(framebuffer);
         ADD_FIELD(vertex_attributes);
         ADD_FIELD(index_array);
@@ -460,6 +501,8 @@ ASSERT_REG_POSITION(viewport_depth_far_plane, 0x4e);
 ASSERT_REG_POSITION(vs_output_attributes[0], 0x50);
 ASSERT_REG_POSITION(vs_output_attributes[1], 0x51);
 ASSERT_REG_POSITION(viewport_corner, 0x68);
+ASSERT_REG_POSITION(texture0, 0x81);
+ASSERT_REG_POSITION(texture0_format, 0x8e);
 ASSERT_REG_POSITION(framebuffer, 0x110);
 ASSERT_REG_POSITION(vertex_attributes, 0x200);
 ASSERT_REG_POSITION(index_array, 0x227);