debug_utils.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <condition_variable>
  6. #include <list>
  7. #include <map>
  8. #include <fstream>
  9. #include <mutex>
  10. #include <string>
  11. #ifdef HAVE_PNG
  12. #include <png.h>
  13. #endif
  14. #include <nihstro/shader_binary.h>
  15. #include "common/assert.h"
  16. #include "common/file_util.h"
  17. #include "common/math_util.h"
  18. #include "video_core/color.h"
  19. #include "video_core/math.h"
  20. #include "video_core/pica.h"
  21. #include "debug_utils.h"
  22. using nihstro::DVLBHeader;
  23. using nihstro::DVLEHeader;
  24. using nihstro::DVLPHeader;
  25. namespace Pica {
  26. void DebugContext::OnEvent(Event event, void* data) {
  27. if (!breakpoints[event].enabled)
  28. return;
  29. {
  30. std::unique_lock<std::mutex> lock(breakpoint_mutex);
  31. // TODO: Should stop the CPU thread here once we multithread emulation.
  32. active_breakpoint = event;
  33. at_breakpoint = true;
  34. // Tell all observers that we hit a breakpoint
  35. for (auto& breakpoint_observer : breakpoint_observers) {
  36. breakpoint_observer->OnPicaBreakPointHit(event, data);
  37. }
  38. // Wait until another thread tells us to Resume()
  39. resume_from_breakpoint.wait(lock, [&]{ return !at_breakpoint; });
  40. }
  41. }
  42. void DebugContext::Resume() {
  43. {
  44. std::unique_lock<std::mutex> lock(breakpoint_mutex);
  45. // Tell all observers that we are about to resume
  46. for (auto& breakpoint_observer : breakpoint_observers) {
  47. breakpoint_observer->OnPicaResume();
  48. }
  49. // Resume the waiting thread (i.e. OnEvent())
  50. at_breakpoint = false;
  51. }
  52. resume_from_breakpoint.notify_one();
  53. }
  54. std::shared_ptr<DebugContext> g_debug_context; // TODO: Get rid of this global
  55. namespace DebugUtils {
  56. void GeometryDumper::AddTriangle(Vertex& v0, Vertex& v1, Vertex& v2) {
  57. vertices.push_back(v0);
  58. vertices.push_back(v1);
  59. vertices.push_back(v2);
  60. int num_vertices = vertices.size();
  61. faces.push_back({ num_vertices-3, num_vertices-2, num_vertices-1 });
  62. }
  63. void GeometryDumper::Dump() {
  64. // NOTE: Permanently enabling this just trashes the hard disk for no reason.
  65. // Hence, this is currently disabled.
  66. return;
  67. static int index = 0;
  68. std::string filename = std::string("geometry_dump") + std::to_string(++index) + ".obj";
  69. std::ofstream file(filename);
  70. for (const auto& vertex : vertices) {
  71. file << "v " << vertex.pos[0]
  72. << " " << vertex.pos[1]
  73. << " " << vertex.pos[2] << std::endl;
  74. }
  75. for (const Face& face : faces) {
  76. file << "f " << 1+face.index[0]
  77. << " " << 1+face.index[1]
  78. << " " << 1+face.index[2] << std::endl;
  79. }
  80. }
  81. void DumpShader(const u32* binary_data, u32 binary_size, const u32* swizzle_data, u32 swizzle_size,
  82. u32 main_offset, const Regs::VSOutputAttributes* output_attributes)
  83. {
  84. // NOTE: Permanently enabling this just trashes hard disks for no reason.
  85. // Hence, this is currently disabled.
  86. return;
  87. struct StuffToWrite {
  88. u8* pointer;
  89. u32 size;
  90. };
  91. std::vector<StuffToWrite> writing_queue;
  92. u32 write_offset = 0;
  93. auto QueueForWriting = [&writing_queue,&write_offset](u8* pointer, u32 size) {
  94. writing_queue.push_back({pointer, size});
  95. u32 old_write_offset = write_offset;
  96. write_offset += size;
  97. return old_write_offset;
  98. };
  99. // First off, try to translate Pica state (one enum for output attribute type and component)
  100. // into shbin format (separate type and component mask).
  101. union OutputRegisterInfo {
  102. enum Type : u64 {
  103. POSITION = 0,
  104. COLOR = 2,
  105. TEXCOORD0 = 3,
  106. TEXCOORD1 = 5,
  107. TEXCOORD2 = 6,
  108. };
  109. BitField< 0, 64, u64> hex;
  110. BitField< 0, 16, Type> type;
  111. BitField<16, 16, u64> id;
  112. BitField<32, 4, u64> component_mask;
  113. };
  114. // This is put into a try-catch block to make sure we notice unknown configurations.
  115. std::vector<OutputRegisterInfo> output_info_table;
  116. for (unsigned i = 0; i < 7; ++i) {
  117. using OutputAttributes = Pica::Regs::VSOutputAttributes;
  118. // TODO: It's still unclear how the attribute components map to the register!
  119. // Once we know that, this code probably will not make much sense anymore.
  120. std::map<OutputAttributes::Semantic, std::pair<OutputRegisterInfo::Type, u32> > map = {
  121. { OutputAttributes::POSITION_X, { OutputRegisterInfo::POSITION, 1} },
  122. { OutputAttributes::POSITION_Y, { OutputRegisterInfo::POSITION, 2} },
  123. { OutputAttributes::POSITION_Z, { OutputRegisterInfo::POSITION, 4} },
  124. { OutputAttributes::POSITION_W, { OutputRegisterInfo::POSITION, 8} },
  125. { OutputAttributes::COLOR_R, { OutputRegisterInfo::COLOR, 1} },
  126. { OutputAttributes::COLOR_G, { OutputRegisterInfo::COLOR, 2} },
  127. { OutputAttributes::COLOR_B, { OutputRegisterInfo::COLOR, 4} },
  128. { OutputAttributes::COLOR_A, { OutputRegisterInfo::COLOR, 8} },
  129. { OutputAttributes::TEXCOORD0_U, { OutputRegisterInfo::TEXCOORD0, 1} },
  130. { OutputAttributes::TEXCOORD0_V, { OutputRegisterInfo::TEXCOORD0, 2} },
  131. { OutputAttributes::TEXCOORD1_U, { OutputRegisterInfo::TEXCOORD1, 1} },
  132. { OutputAttributes::TEXCOORD1_V, { OutputRegisterInfo::TEXCOORD1, 2} },
  133. { OutputAttributes::TEXCOORD2_U, { OutputRegisterInfo::TEXCOORD2, 1} },
  134. { OutputAttributes::TEXCOORD2_V, { OutputRegisterInfo::TEXCOORD2, 2} }
  135. };
  136. for (const auto& semantic : std::vector<OutputAttributes::Semantic>{
  137. output_attributes[i].map_x,
  138. output_attributes[i].map_y,
  139. output_attributes[i].map_z,
  140. output_attributes[i].map_w }) {
  141. if (semantic == OutputAttributes::INVALID)
  142. continue;
  143. try {
  144. OutputRegisterInfo::Type type = map.at(semantic).first;
  145. u32 component_mask = map.at(semantic).second;
  146. auto it = std::find_if(output_info_table.begin(), output_info_table.end(),
  147. [&i, &type](const OutputRegisterInfo& info) {
  148. return info.id == i && info.type == type;
  149. }
  150. );
  151. if (it == output_info_table.end()) {
  152. output_info_table.emplace_back();
  153. output_info_table.back().type = type;
  154. output_info_table.back().component_mask = component_mask;
  155. output_info_table.back().id = i;
  156. } else {
  157. it->component_mask = it->component_mask | component_mask;
  158. }
  159. } catch (const std::out_of_range& ) {
  160. DEBUG_ASSERT_MSG(false, "Unknown output attribute mapping");
  161. LOG_ERROR(HW_GPU, "Unknown output attribute mapping: %03x, %03x, %03x, %03x",
  162. (int)output_attributes[i].map_x.Value(),
  163. (int)output_attributes[i].map_y.Value(),
  164. (int)output_attributes[i].map_z.Value(),
  165. (int)output_attributes[i].map_w.Value());
  166. }
  167. }
  168. }
  169. struct {
  170. DVLBHeader header;
  171. u32 dvle_offset;
  172. } dvlb{ {DVLBHeader::MAGIC_WORD, 1 } }; // 1 DVLE
  173. DVLPHeader dvlp{ DVLPHeader::MAGIC_WORD };
  174. DVLEHeader dvle{ DVLEHeader::MAGIC_WORD };
  175. QueueForWriting((u8*)&dvlb, sizeof(dvlb));
  176. u32 dvlp_offset = QueueForWriting((u8*)&dvlp, sizeof(dvlp));
  177. dvlb.dvle_offset = QueueForWriting((u8*)&dvle, sizeof(dvle));
  178. // TODO: Reduce the amount of binary code written to relevant portions
  179. dvlp.binary_offset = write_offset - dvlp_offset;
  180. dvlp.binary_size_words = binary_size;
  181. QueueForWriting((u8*)binary_data, binary_size * sizeof(u32));
  182. dvlp.swizzle_info_offset = write_offset - dvlp_offset;
  183. dvlp.swizzle_info_num_entries = swizzle_size;
  184. u32 dummy = 0;
  185. for (unsigned int i = 0; i < swizzle_size; ++i) {
  186. QueueForWriting((u8*)&swizzle_data[i], sizeof(swizzle_data[i]));
  187. QueueForWriting((u8*)&dummy, sizeof(dummy));
  188. }
  189. dvle.main_offset_words = main_offset;
  190. dvle.output_register_table_offset = write_offset - dvlb.dvle_offset;
  191. dvle.output_register_table_size = output_info_table.size();
  192. QueueForWriting((u8*)output_info_table.data(), output_info_table.size() * sizeof(OutputRegisterInfo));
  193. // TODO: Create a label table for "main"
  194. // Write data to file
  195. static int dump_index = 0;
  196. std::string filename = std::string("shader_dump") + std::to_string(++dump_index) + std::string(".shbin");
  197. std::ofstream file(filename, std::ios_base::out | std::ios_base::binary);
  198. for (auto& chunk : writing_queue) {
  199. file.write((char*)chunk.pointer, chunk.size);
  200. }
  201. }
  202. static std::unique_ptr<PicaTrace> pica_trace;
  203. static std::mutex pica_trace_mutex;
  204. static int is_pica_tracing = false;
  205. void StartPicaTracing()
  206. {
  207. if (is_pica_tracing) {
  208. LOG_WARNING(HW_GPU, "StartPicaTracing called even though tracing already running!");
  209. return;
  210. }
  211. pica_trace_mutex.lock();
  212. pica_trace = std::unique_ptr<PicaTrace>(new PicaTrace);
  213. is_pica_tracing = true;
  214. pica_trace_mutex.unlock();
  215. }
  216. bool IsPicaTracing()
  217. {
  218. return is_pica_tracing != 0;
  219. }
  220. void OnPicaRegWrite(u32 id, u32 value)
  221. {
  222. // Double check for is_pica_tracing to avoid pointless locking overhead
  223. if (!is_pica_tracing)
  224. return;
  225. std::unique_lock<std::mutex> lock(pica_trace_mutex);
  226. if (!is_pica_tracing)
  227. return;
  228. pica_trace->writes.emplace_back(id, value);
  229. }
  230. std::unique_ptr<PicaTrace> FinishPicaTracing()
  231. {
  232. if (!is_pica_tracing) {
  233. LOG_WARNING(HW_GPU, "FinishPicaTracing called even though tracing isn't running!");
  234. return {};
  235. }
  236. // signalize that no further tracing should be performed
  237. is_pica_tracing = false;
  238. // Wait until running tracing is finished
  239. pica_trace_mutex.lock();
  240. std::unique_ptr<PicaTrace> ret(std::move(pica_trace));
  241. pica_trace_mutex.unlock();
  242. return std::move(ret);
  243. }
  244. const Math::Vec4<u8> LookupTexture(const u8* source, int x, int y, const TextureInfo& info, bool disable_alpha) {
  245. // Images are split into 8x8 tiles. Each tile is composed of four 4x4 subtiles each
  246. // of which is composed of four 2x2 subtiles each of which is composed of four texels.
  247. // Each structure is embedded into the next-bigger one in a diagonal pattern, e.g.
  248. // texels are laid out in a 2x2 subtile like this:
  249. // 2 3
  250. // 0 1
  251. //
  252. // The full 8x8 tile has the texels arranged like this:
  253. //
  254. // 42 43 46 47 58 59 62 63
  255. // 40 41 44 45 56 57 60 61
  256. // 34 35 38 39 50 51 54 55
  257. // 32 33 36 37 48 49 52 53
  258. // 10 11 14 15 26 27 30 31
  259. // 08 09 12 13 24 25 28 29
  260. // 02 03 06 07 18 19 22 23
  261. // 00 01 04 05 16 17 20 21
  262. const unsigned int block_width = 8;
  263. const unsigned int block_height = 8;
  264. const unsigned int coarse_x = x & ~7;
  265. const unsigned int coarse_y = y & ~7;
  266. // Interleave the lower 3 bits of each coordinate to get the intra-block offsets, which are
  267. // arranged in a Z-order curve. More details on the bit manipulation at:
  268. // https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
  269. unsigned int i = (x & 7) | ((y & 7) << 8); // ---- -210
  270. i = (i ^ (i << 2)) & 0x1313; // ---2 --10
  271. i = (i ^ (i << 1)) & 0x1515; // ---2 -1-0
  272. i = (i | (i >> 7)) & 0x3F;
  273. if (info.format != Regs::TextureFormat::ETC1 &&
  274. info.format != Regs::TextureFormat::ETC1A4) {
  275. // TODO(neobrain): Fix code design to unify vertical block offsets!
  276. source += coarse_y * info.stride;
  277. }
  278. const unsigned int offset = coarse_x * block_height;
  279. // TODO: Assert that width/height are multiples of block dimensions
  280. switch (info.format) {
  281. case Regs::TextureFormat::RGBA8:
  282. {
  283. const u8* source_ptr = source + offset * 4 + i * 4;
  284. return { source_ptr[3], source_ptr[2], source_ptr[1], disable_alpha ? (u8)255 : source_ptr[0] };
  285. }
  286. case Regs::TextureFormat::RGB8:
  287. {
  288. const u8* source_ptr = source + offset * 3 + i * 3;
  289. return { source_ptr[2], source_ptr[1], source_ptr[0], 255 };
  290. }
  291. case Regs::TextureFormat::RGBA5551:
  292. {
  293. const u16 source_ptr = *(const u16*)(source + offset * 2 + i * 2);
  294. u8 r = (source_ptr >> 11) & 0x1F;
  295. u8 g = ((source_ptr) >> 6) & 0x1F;
  296. u8 b = (source_ptr >> 1) & 0x1F;
  297. u8 a = source_ptr & 1;
  298. return Math::MakeVec<u8>(Color::Convert5To8(r), Color::Convert5To8(g),
  299. Color::Convert5To8(b), disable_alpha ? 255 : Color::Convert1To8(a));
  300. }
  301. case Regs::TextureFormat::RGB565:
  302. {
  303. const u16 source_ptr = *(const u16*)(source + offset * 2 + i * 2);
  304. u8 r = Color::Convert5To8((source_ptr >> 11) & 0x1F);
  305. u8 g = Color::Convert6To8(((source_ptr) >> 5) & 0x3F);
  306. u8 b = Color::Convert5To8((source_ptr) & 0x1F);
  307. return Math::MakeVec<u8>(r, g, b, 255);
  308. }
  309. case Regs::TextureFormat::RGBA4:
  310. {
  311. const u8* source_ptr = source + offset * 2 + i * 2;
  312. u8 r = Color::Convert4To8(source_ptr[1] >> 4);
  313. u8 g = Color::Convert4To8(source_ptr[1] & 0xF);
  314. u8 b = Color::Convert4To8(source_ptr[0] >> 4);
  315. u8 a = Color::Convert4To8(source_ptr[0] & 0xF);
  316. return { r, g, b, disable_alpha ? (u8)255 : a };
  317. }
  318. case Regs::TextureFormat::IA8:
  319. {
  320. const u8* source_ptr = source + offset * 2 + i * 2;
  321. if (disable_alpha) {
  322. // Show intensity as red, alpha as green
  323. return { source_ptr[1], source_ptr[0], 0, 255 };
  324. } else {
  325. return { source_ptr[1], source_ptr[1], source_ptr[1], source_ptr[0]};
  326. }
  327. }
  328. case Regs::TextureFormat::I8:
  329. {
  330. const u8* source_ptr = source + offset + i;
  331. return { *source_ptr, *source_ptr, *source_ptr, 255 };
  332. }
  333. case Regs::TextureFormat::A8:
  334. {
  335. const u8* source_ptr = source + offset + i;
  336. if (disable_alpha) {
  337. return { *source_ptr, *source_ptr, *source_ptr, 255 };
  338. } else {
  339. return { 0, 0, 0, *source_ptr };
  340. }
  341. }
  342. case Regs::TextureFormat::IA4:
  343. {
  344. const u8* source_ptr = source + offset + i;
  345. u8 i = Color::Convert4To8(((*source_ptr) & 0xF0) >> 4);
  346. u8 a = Color::Convert4To8((*source_ptr) & 0xF);
  347. if (disable_alpha) {
  348. // Show intensity as red, alpha as green
  349. return { i, a, 0, 255 };
  350. } else {
  351. return { i, i, i, a };
  352. }
  353. }
  354. case Regs::TextureFormat::A4:
  355. {
  356. const u8* source_ptr = source + (offset + i) / 2;
  357. u8 a = (i % 2) ? ((*source_ptr & 0xF0) >> 4) : (*source_ptr & 0xF);
  358. a = Color::Convert4To8(a);
  359. if (disable_alpha) {
  360. return { a, a, a, 255 };
  361. } else {
  362. return { 0, 0, 0, a };
  363. }
  364. }
  365. case Regs::TextureFormat::ETC1:
  366. case Regs::TextureFormat::ETC1A4:
  367. {
  368. bool has_alpha = (info.format == Regs::TextureFormat::ETC1A4);
  369. // ETC1 further subdivides each 8x8 tile into four 4x4 subtiles
  370. const int subtile_width = 4;
  371. const int subtile_height = 4;
  372. int subtile_index = ((x / subtile_width) & 1) + 2 * ((y / subtile_height) & 1);
  373. unsigned subtile_bytes = has_alpha ? 2 : 1; // TODO: Name...
  374. const u64* source_ptr = (const u64*)(source
  375. + coarse_x * subtile_bytes * 4
  376. + coarse_y * subtile_bytes * 4 * (info.width / 8)
  377. + subtile_index * subtile_bytes * 8);
  378. u64 alpha = 0xFFFFFFFFFFFFFFFF;
  379. if (has_alpha) {
  380. alpha = *source_ptr;
  381. source_ptr++;
  382. }
  383. union ETC1Tile {
  384. // Each of these two is a collection of 16 bits (one per lookup value)
  385. BitField< 0, 16, u64> table_subindexes;
  386. BitField<16, 16, u64> negation_flags;
  387. unsigned GetTableSubIndex(unsigned index) const {
  388. return (table_subindexes >> index) & 1;
  389. }
  390. bool GetNegationFlag(unsigned index) const {
  391. return ((negation_flags >> index) & 1) == 1;
  392. }
  393. BitField<32, 1, u64> flip;
  394. BitField<33, 1, u64> differential_mode;
  395. BitField<34, 3, u64> table_index_2;
  396. BitField<37, 3, u64> table_index_1;
  397. union {
  398. // delta value + base value
  399. BitField<40, 3, s64> db;
  400. BitField<43, 5, u64> b;
  401. BitField<48, 3, s64> dg;
  402. BitField<51, 5, u64> g;
  403. BitField<56, 3, s64> dr;
  404. BitField<59, 5, u64> r;
  405. } differential;
  406. union {
  407. BitField<40, 4, u64> b2;
  408. BitField<44, 4, u64> b1;
  409. BitField<48, 4, u64> g2;
  410. BitField<52, 4, u64> g1;
  411. BitField<56, 4, u64> r2;
  412. BitField<60, 4, u64> r1;
  413. } separate;
  414. const Math::Vec3<u8> GetRGB(int x, int y) const {
  415. int texel = 4 * x + y;
  416. if (flip)
  417. std::swap(x, y);
  418. // Lookup base value
  419. Math::Vec3<int> ret;
  420. if (differential_mode) {
  421. ret.r() = differential.r;
  422. ret.g() = differential.g;
  423. ret.b() = differential.b;
  424. if (x >= 2) {
  425. ret.r() += differential.dr;
  426. ret.g() += differential.dg;
  427. ret.b() += differential.db;
  428. }
  429. ret.r() = Color::Convert5To8(ret.r());
  430. ret.g() = Color::Convert5To8(ret.g());
  431. ret.b() = Color::Convert5To8(ret.b());
  432. } else {
  433. if (x < 2) {
  434. ret.r() = Color::Convert4To8(separate.r1);
  435. ret.g() = Color::Convert4To8(separate.g1);
  436. ret.b() = Color::Convert4To8(separate.b1);
  437. } else {
  438. ret.r() = Color::Convert4To8(separate.r2);
  439. ret.g() = Color::Convert4To8(separate.g2);
  440. ret.b() = Color::Convert4To8(separate.b2);
  441. }
  442. }
  443. // Add modifier
  444. unsigned table_index = (x < 2) ? table_index_2.Value() : table_index_1.Value();
  445. static const auto etc1_modifier_table = std::array<std::array<u8, 2>, 8>{{
  446. { 2, 8 }, { 5, 17 }, { 9, 29 }, { 13, 42 },
  447. { 18, 60 }, { 24, 80 }, { 33, 106 }, { 47, 183 }
  448. }};
  449. int modifier = etc1_modifier_table.at(table_index).at(GetTableSubIndex(texel));
  450. if (GetNegationFlag(texel))
  451. modifier *= -1;
  452. ret.r() = MathUtil::Clamp(ret.r() + modifier, 0, 255);
  453. ret.g() = MathUtil::Clamp(ret.g() + modifier, 0, 255);
  454. ret.b() = MathUtil::Clamp(ret.b() + modifier, 0, 255);
  455. return ret.Cast<u8>();
  456. }
  457. } const *etc1_tile = reinterpret_cast<const ETC1Tile*>(source_ptr);
  458. alpha >>= 4 * ((x & 3) * 4 + (y & 3));
  459. return Math::MakeVec(etc1_tile->GetRGB(x & 3, y & 3),
  460. disable_alpha ? (u8)255 : Color::Convert4To8(alpha & 0xF));
  461. }
  462. default:
  463. LOG_ERROR(HW_GPU, "Unknown texture format: %x", (u32)info.format);
  464. DEBUG_ASSERT(false);
  465. return {};
  466. }
  467. }
  468. TextureInfo TextureInfo::FromPicaRegister(const Regs::TextureConfig& config,
  469. const Regs::TextureFormat& format)
  470. {
  471. TextureInfo info;
  472. info.physical_address = config.GetPhysicalAddress();
  473. info.width = config.width;
  474. info.height = config.height;
  475. info.format = format;
  476. info.stride = Pica::Regs::NibblesPerPixel(info.format) * info.width / 2;
  477. return info;
  478. }
  479. void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) {
  480. // NOTE: Permanently enabling this just trashes hard disks for no reason.
  481. // Hence, this is currently disabled.
  482. return;
  483. #ifndef HAVE_PNG
  484. return;
  485. #else
  486. if (!data)
  487. return;
  488. // Write data to file
  489. static int dump_index = 0;
  490. std::string filename = std::string("texture_dump") + std::to_string(++dump_index) + std::string(".png");
  491. u32 row_stride = texture_config.width * 3;
  492. u8* buf;
  493. char title[] = "Citra texture dump";
  494. char title_key[] = "Title";
  495. png_structp png_ptr = nullptr;
  496. png_infop info_ptr = nullptr;
  497. // Open file for writing (binary mode)
  498. FileUtil::IOFile fp(filename, "wb");
  499. // Initialize write structure
  500. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  501. if (png_ptr == nullptr) {
  502. LOG_ERROR(Debug_GPU, "Could not allocate write struct\n");
  503. goto finalise;
  504. }
  505. // Initialize info structure
  506. info_ptr = png_create_info_struct(png_ptr);
  507. if (info_ptr == nullptr) {
  508. LOG_ERROR(Debug_GPU, "Could not allocate info struct\n");
  509. goto finalise;
  510. }
  511. // Setup Exception handling
  512. if (setjmp(png_jmpbuf(png_ptr))) {
  513. LOG_ERROR(Debug_GPU, "Error during png creation\n");
  514. goto finalise;
  515. }
  516. png_init_io(png_ptr, fp.GetHandle());
  517. // Write header (8 bit colour depth)
  518. png_set_IHDR(png_ptr, info_ptr, texture_config.width, texture_config.height,
  519. 8, PNG_COLOR_TYPE_RGB /*_ALPHA*/, PNG_INTERLACE_NONE,
  520. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  521. png_text title_text;
  522. title_text.compression = PNG_TEXT_COMPRESSION_NONE;
  523. title_text.key = title_key;
  524. title_text.text = title;
  525. png_set_text(png_ptr, info_ptr, &title_text, 1);
  526. png_write_info(png_ptr, info_ptr);
  527. buf = new u8[row_stride * texture_config.height];
  528. for (unsigned y = 0; y < texture_config.height; ++y) {
  529. for (unsigned x = 0; x < texture_config.width; ++x) {
  530. TextureInfo info;
  531. info.width = texture_config.width;
  532. info.height = texture_config.height;
  533. info.stride = row_stride;
  534. info.format = registers.texture0_format;
  535. Math::Vec4<u8> texture_color = LookupTexture(data, x, y, info);
  536. buf[3 * x + y * row_stride ] = texture_color.r();
  537. buf[3 * x + y * row_stride + 1] = texture_color.g();
  538. buf[3 * x + y * row_stride + 2] = texture_color.b();
  539. }
  540. }
  541. // Write image data
  542. for (unsigned y = 0; y < texture_config.height; ++y)
  543. {
  544. u8* row_ptr = (u8*)buf + y * row_stride;
  545. u8* ptr = row_ptr;
  546. png_write_row(png_ptr, row_ptr);
  547. }
  548. delete[] buf;
  549. // End write
  550. png_write_end(png_ptr, nullptr);
  551. finalise:
  552. if (info_ptr != nullptr) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  553. if (png_ptr != nullptr) png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
  554. #endif
  555. }
  556. void DumpTevStageConfig(const std::array<Pica::Regs::TevStageConfig,6>& stages)
  557. {
  558. using Source = Pica::Regs::TevStageConfig::Source;
  559. using ColorModifier = Pica::Regs::TevStageConfig::ColorModifier;
  560. using AlphaModifier = Pica::Regs::TevStageConfig::AlphaModifier;
  561. using Operation = Pica::Regs::TevStageConfig::Operation;
  562. std::string stage_info = "Tev setup:\n";
  563. for (size_t index = 0; index < stages.size(); ++index) {
  564. const auto& tev_stage = stages[index];
  565. static const std::map<Source, std::string> source_map = {
  566. { Source::PrimaryColor, "PrimaryColor" },
  567. { Source::Texture0, "Texture0" },
  568. { Source::Texture1, "Texture1" },
  569. { Source::Texture2, "Texture2" },
  570. { Source::Constant, "Constant" },
  571. { Source::Previous, "Previous" },
  572. };
  573. static const std::map<ColorModifier, std::string> color_modifier_map = {
  574. { ColorModifier::SourceColor, { "%source.rgb" } },
  575. { ColorModifier::SourceAlpha, { "%source.aaa" } },
  576. };
  577. static const std::map<AlphaModifier, std::string> alpha_modifier_map = {
  578. { AlphaModifier::SourceAlpha, "%source.a" },
  579. { AlphaModifier::OneMinusSourceAlpha, "(255 - %source.a)" },
  580. };
  581. static const std::map<Operation, std::string> combiner_map = {
  582. { Operation::Replace, "%source1" },
  583. { Operation::Modulate, "(%source1 * %source2) / 255" },
  584. { Operation::Add, "(%source1 + %source2)" },
  585. { Operation::Lerp, "lerp(%source1, %source2, %source3)" },
  586. };
  587. static auto ReplacePattern =
  588. [](const std::string& input, const std::string& pattern, const std::string& replacement) -> std::string {
  589. size_t start = input.find(pattern);
  590. if (start == std::string::npos)
  591. return input;
  592. std::string ret = input;
  593. ret.replace(start, pattern.length(), replacement);
  594. return ret;
  595. };
  596. static auto GetColorSourceStr =
  597. [](const Source& src, const ColorModifier& modifier) {
  598. auto src_it = source_map.find(src);
  599. std::string src_str = "Unknown";
  600. if (src_it != source_map.end())
  601. src_str = src_it->second;
  602. auto modifier_it = color_modifier_map.find(modifier);
  603. std::string modifier_str = "%source.????";
  604. if (modifier_it != color_modifier_map.end())
  605. modifier_str = modifier_it->second;
  606. return ReplacePattern(modifier_str, "%source", src_str);
  607. };
  608. static auto GetColorCombinerStr =
  609. [](const Regs::TevStageConfig& tev_stage) {
  610. auto op_it = combiner_map.find(tev_stage.color_op);
  611. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  612. if (op_it != combiner_map.end())
  613. op_str = op_it->second;
  614. op_str = ReplacePattern(op_str, "%source1", GetColorSourceStr(tev_stage.color_source1, tev_stage.color_modifier1));
  615. op_str = ReplacePattern(op_str, "%source2", GetColorSourceStr(tev_stage.color_source2, tev_stage.color_modifier2));
  616. return ReplacePattern(op_str, "%source3", GetColorSourceStr(tev_stage.color_source3, tev_stage.color_modifier3));
  617. };
  618. static auto GetAlphaSourceStr =
  619. [](const Source& src, const AlphaModifier& modifier) {
  620. auto src_it = source_map.find(src);
  621. std::string src_str = "Unknown";
  622. if (src_it != source_map.end())
  623. src_str = src_it->second;
  624. auto modifier_it = alpha_modifier_map.find(modifier);
  625. std::string modifier_str = "%source.????";
  626. if (modifier_it != alpha_modifier_map.end())
  627. modifier_str = modifier_it->second;
  628. return ReplacePattern(modifier_str, "%source", src_str);
  629. };
  630. static auto GetAlphaCombinerStr =
  631. [](const Regs::TevStageConfig& tev_stage) {
  632. auto op_it = combiner_map.find(tev_stage.alpha_op);
  633. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  634. if (op_it != combiner_map.end())
  635. op_str = op_it->second;
  636. op_str = ReplacePattern(op_str, "%source1", GetAlphaSourceStr(tev_stage.alpha_source1, tev_stage.alpha_modifier1));
  637. op_str = ReplacePattern(op_str, "%source2", GetAlphaSourceStr(tev_stage.alpha_source2, tev_stage.alpha_modifier2));
  638. return ReplacePattern(op_str, "%source3", GetAlphaSourceStr(tev_stage.alpha_source3, tev_stage.alpha_modifier3));
  639. };
  640. stage_info += "Stage " + std::to_string(index) + ": " + GetColorCombinerStr(tev_stage) + " " + GetAlphaCombinerStr(tev_stage) + "\n";
  641. }
  642. LOG_TRACE(HW_GPU, "%s", stage_info.c_str());
  643. }
  644. } // namespace
  645. } // namespace