debug_utils.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 "common/log.h"
  15. #include "common/file_util.h"
  16. #include "video_core/pica.h"
  17. #include "debug_utils.h"
  18. namespace Pica {
  19. void DebugContext::OnEvent(Event event, void* data) {
  20. if (!breakpoints[event].enabled)
  21. return;
  22. {
  23. std::unique_lock<std::mutex> lock(breakpoint_mutex);
  24. // TODO: Should stop the CPU thread here once we multithread emulation.
  25. active_breakpoint = event;
  26. at_breakpoint = true;
  27. // Tell all observers that we hit a breakpoint
  28. for (auto& breakpoint_observer : breakpoint_observers) {
  29. breakpoint_observer->OnPicaBreakPointHit(event, data);
  30. }
  31. // Wait until another thread tells us to Resume()
  32. resume_from_breakpoint.wait(lock, [&]{ return !at_breakpoint; });
  33. }
  34. }
  35. void DebugContext::Resume() {
  36. {
  37. std::unique_lock<std::mutex> lock(breakpoint_mutex);
  38. // Tell all observers that we are about to resume
  39. for (auto& breakpoint_observer : breakpoint_observers) {
  40. breakpoint_observer->OnPicaResume();
  41. }
  42. // Resume the waiting thread (i.e. OnEvent())
  43. at_breakpoint = false;
  44. }
  45. resume_from_breakpoint.notify_one();
  46. }
  47. std::shared_ptr<DebugContext> g_debug_context; // TODO: Get rid of this global
  48. namespace DebugUtils {
  49. void GeometryDumper::AddTriangle(Vertex& v0, Vertex& v1, Vertex& v2) {
  50. vertices.push_back(v0);
  51. vertices.push_back(v1);
  52. vertices.push_back(v2);
  53. int num_vertices = vertices.size();
  54. faces.push_back({ num_vertices-3, num_vertices-2, num_vertices-1 });
  55. }
  56. void GeometryDumper::Dump() {
  57. // NOTE: Permanently enabling this just trashes the hard disk for no reason.
  58. // Hence, this is currently disabled.
  59. return;
  60. static int index = 0;
  61. std::string filename = std::string("geometry_dump") + std::to_string(++index) + ".obj";
  62. std::ofstream file(filename);
  63. for (const auto& vertex : vertices) {
  64. file << "v " << vertex.pos[0]
  65. << " " << vertex.pos[1]
  66. << " " << vertex.pos[2] << std::endl;
  67. }
  68. for (const Face& face : faces) {
  69. file << "f " << 1+face.index[0]
  70. << " " << 1+face.index[1]
  71. << " " << 1+face.index[2] << std::endl;
  72. }
  73. }
  74. #pragma pack(1)
  75. struct DVLBHeader {
  76. enum : u32 {
  77. MAGIC_WORD = 0x424C5644, // "DVLB"
  78. };
  79. u32 magic_word;
  80. u32 num_programs;
  81. // u32 dvle_offset_table[];
  82. };
  83. static_assert(sizeof(DVLBHeader) == 0x8, "Incorrect structure size");
  84. struct DVLPHeader {
  85. enum : u32 {
  86. MAGIC_WORD = 0x504C5644, // "DVLP"
  87. };
  88. u32 magic_word;
  89. u32 version;
  90. u32 binary_offset; // relative to DVLP start
  91. u32 binary_size_words;
  92. u32 swizzle_patterns_offset;
  93. u32 swizzle_patterns_num_entries;
  94. u32 unk2;
  95. };
  96. static_assert(sizeof(DVLPHeader) == 0x1C, "Incorrect structure size");
  97. struct DVLEHeader {
  98. enum : u32 {
  99. MAGIC_WORD = 0x454c5644, // "DVLE"
  100. };
  101. enum class ShaderType : u8 {
  102. VERTEX = 0,
  103. GEOMETRY = 1,
  104. };
  105. u32 magic_word;
  106. u16 pad1;
  107. ShaderType type;
  108. u8 pad2;
  109. u32 main_offset_words; // offset within binary blob
  110. u32 endmain_offset_words;
  111. u32 pad3;
  112. u32 pad4;
  113. u32 constant_table_offset;
  114. u32 constant_table_size; // number of entries
  115. u32 label_table_offset;
  116. u32 label_table_size;
  117. u32 output_register_table_offset;
  118. u32 output_register_table_size;
  119. u32 uniform_table_offset;
  120. u32 uniform_table_size;
  121. u32 symbol_table_offset;
  122. u32 symbol_table_size;
  123. };
  124. static_assert(sizeof(DVLEHeader) == 0x40, "Incorrect structure size");
  125. #pragma pack()
  126. void DumpShader(const u32* binary_data, u32 binary_size, const u32* swizzle_data, u32 swizzle_size,
  127. u32 main_offset, const Regs::VSOutputAttributes* output_attributes)
  128. {
  129. // NOTE: Permanently enabling this just trashes hard disks for no reason.
  130. // Hence, this is currently disabled.
  131. return;
  132. struct StuffToWrite {
  133. u8* pointer;
  134. u32 size;
  135. };
  136. std::vector<StuffToWrite> writing_queue;
  137. u32 write_offset = 0;
  138. auto QueueForWriting = [&writing_queue,&write_offset](u8* pointer, u32 size) {
  139. writing_queue.push_back({pointer, size});
  140. u32 old_write_offset = write_offset;
  141. write_offset += size;
  142. return old_write_offset;
  143. };
  144. // First off, try to translate Pica state (one enum for output attribute type and component)
  145. // into shbin format (separate type and component mask).
  146. union OutputRegisterInfo {
  147. enum Type : u64 {
  148. POSITION = 0,
  149. COLOR = 2,
  150. TEXCOORD0 = 3,
  151. TEXCOORD1 = 5,
  152. TEXCOORD2 = 6,
  153. };
  154. BitField< 0, 64, u64> hex;
  155. BitField< 0, 16, Type> type;
  156. BitField<16, 16, u64> id;
  157. BitField<32, 4, u64> component_mask;
  158. };
  159. // This is put into a try-catch block to make sure we notice unknown configurations.
  160. std::vector<OutputRegisterInfo> output_info_table;
  161. for (unsigned i = 0; i < 7; ++i) {
  162. using OutputAttributes = Pica::Regs::VSOutputAttributes;
  163. // TODO: It's still unclear how the attribute components map to the register!
  164. // Once we know that, this code probably will not make much sense anymore.
  165. std::map<OutputAttributes::Semantic, std::pair<OutputRegisterInfo::Type, u32> > map = {
  166. { OutputAttributes::POSITION_X, { OutputRegisterInfo::POSITION, 1} },
  167. { OutputAttributes::POSITION_Y, { OutputRegisterInfo::POSITION, 2} },
  168. { OutputAttributes::POSITION_Z, { OutputRegisterInfo::POSITION, 4} },
  169. { OutputAttributes::POSITION_W, { OutputRegisterInfo::POSITION, 8} },
  170. { OutputAttributes::COLOR_R, { OutputRegisterInfo::COLOR, 1} },
  171. { OutputAttributes::COLOR_G, { OutputRegisterInfo::COLOR, 2} },
  172. { OutputAttributes::COLOR_B, { OutputRegisterInfo::COLOR, 4} },
  173. { OutputAttributes::COLOR_A, { OutputRegisterInfo::COLOR, 8} },
  174. { OutputAttributes::TEXCOORD0_U, { OutputRegisterInfo::TEXCOORD0, 1} },
  175. { OutputAttributes::TEXCOORD0_V, { OutputRegisterInfo::TEXCOORD0, 2} },
  176. { OutputAttributes::TEXCOORD1_U, { OutputRegisterInfo::TEXCOORD1, 1} },
  177. { OutputAttributes::TEXCOORD1_V, { OutputRegisterInfo::TEXCOORD1, 2} },
  178. { OutputAttributes::TEXCOORD2_U, { OutputRegisterInfo::TEXCOORD2, 1} },
  179. { OutputAttributes::TEXCOORD2_V, { OutputRegisterInfo::TEXCOORD2, 2} }
  180. };
  181. for (const auto& semantic : std::vector<OutputAttributes::Semantic>{
  182. output_attributes[i].map_x,
  183. output_attributes[i].map_y,
  184. output_attributes[i].map_z,
  185. output_attributes[i].map_w }) {
  186. if (semantic == OutputAttributes::INVALID)
  187. continue;
  188. try {
  189. OutputRegisterInfo::Type type = map.at(semantic).first;
  190. u32 component_mask = map.at(semantic).second;
  191. auto it = std::find_if(output_info_table.begin(), output_info_table.end(),
  192. [&i, &type](const OutputRegisterInfo& info) {
  193. return info.id == i && info.type == type;
  194. }
  195. );
  196. if (it == output_info_table.end()) {
  197. output_info_table.push_back({});
  198. output_info_table.back().type = type;
  199. output_info_table.back().component_mask = component_mask;
  200. output_info_table.back().id = i;
  201. } else {
  202. it->component_mask = it->component_mask | component_mask;
  203. }
  204. } catch (const std::out_of_range& ) {
  205. _dbg_assert_msg_(GPU, 0, "Unknown output attribute mapping");
  206. ERROR_LOG(GPU, "Unknown output attribute mapping: %03x, %03x, %03x, %03x",
  207. (int)output_attributes[i].map_x.Value(),
  208. (int)output_attributes[i].map_y.Value(),
  209. (int)output_attributes[i].map_z.Value(),
  210. (int)output_attributes[i].map_w.Value());
  211. }
  212. }
  213. }
  214. struct {
  215. DVLBHeader header;
  216. u32 dvle_offset;
  217. } dvlb{ {DVLBHeader::MAGIC_WORD, 1 } }; // 1 DVLE
  218. DVLPHeader dvlp{ DVLPHeader::MAGIC_WORD };
  219. DVLEHeader dvle{ DVLEHeader::MAGIC_WORD };
  220. QueueForWriting((u8*)&dvlb, sizeof(dvlb));
  221. u32 dvlp_offset = QueueForWriting((u8*)&dvlp, sizeof(dvlp));
  222. dvlb.dvle_offset = QueueForWriting((u8*)&dvle, sizeof(dvle));
  223. // TODO: Reduce the amount of binary code written to relevant portions
  224. dvlp.binary_offset = write_offset - dvlp_offset;
  225. dvlp.binary_size_words = binary_size;
  226. QueueForWriting((u8*)binary_data, binary_size * sizeof(u32));
  227. dvlp.swizzle_patterns_offset = write_offset - dvlp_offset;
  228. dvlp.swizzle_patterns_num_entries = swizzle_size;
  229. u32 dummy = 0;
  230. for (unsigned int i = 0; i < swizzle_size; ++i) {
  231. QueueForWriting((u8*)&swizzle_data[i], sizeof(swizzle_data[i]));
  232. QueueForWriting((u8*)&dummy, sizeof(dummy));
  233. }
  234. dvle.main_offset_words = main_offset;
  235. dvle.output_register_table_offset = write_offset - dvlb.dvle_offset;
  236. dvle.output_register_table_size = output_info_table.size();
  237. QueueForWriting((u8*)output_info_table.data(), output_info_table.size() * sizeof(OutputRegisterInfo));
  238. // TODO: Create a label table for "main"
  239. // Write data to file
  240. static int dump_index = 0;
  241. std::string filename = std::string("shader_dump") + std::to_string(++dump_index) + std::string(".shbin");
  242. std::ofstream file(filename, std::ios_base::out | std::ios_base::binary);
  243. for (auto& chunk : writing_queue) {
  244. file.write((char*)chunk.pointer, chunk.size);
  245. }
  246. }
  247. static std::unique_ptr<PicaTrace> pica_trace;
  248. static std::mutex pica_trace_mutex;
  249. static int is_pica_tracing = false;
  250. void StartPicaTracing()
  251. {
  252. if (is_pica_tracing) {
  253. ERROR_LOG(GPU, "StartPicaTracing called even though tracing already running!");
  254. return;
  255. }
  256. pica_trace_mutex.lock();
  257. pica_trace = std::unique_ptr<PicaTrace>(new PicaTrace);
  258. is_pica_tracing = true;
  259. pica_trace_mutex.unlock();
  260. }
  261. bool IsPicaTracing()
  262. {
  263. return is_pica_tracing != 0;
  264. }
  265. void OnPicaRegWrite(u32 id, u32 value)
  266. {
  267. // Double check for is_pica_tracing to avoid pointless locking overhead
  268. if (!is_pica_tracing)
  269. return;
  270. std::unique_lock<std::mutex> lock(pica_trace_mutex);
  271. if (!is_pica_tracing)
  272. return;
  273. pica_trace->writes.push_back({id, value});
  274. }
  275. std::unique_ptr<PicaTrace> FinishPicaTracing()
  276. {
  277. if (!is_pica_tracing) {
  278. ERROR_LOG(GPU, "FinishPicaTracing called even though tracing already running!");
  279. return {};
  280. }
  281. // signalize that no further tracing should be performed
  282. is_pica_tracing = false;
  283. // Wait until running tracing is finished
  284. pica_trace_mutex.lock();
  285. std::unique_ptr<PicaTrace> ret(std::move(pica_trace));
  286. pica_trace_mutex.unlock();
  287. return std::move(ret);
  288. }
  289. void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) {
  290. // NOTE: Permanently enabling this just trashes hard disks for no reason.
  291. // Hence, this is currently disabled.
  292. return;
  293. #ifndef HAVE_PNG
  294. return;
  295. #else
  296. if (!data)
  297. return;
  298. // Write data to file
  299. static int dump_index = 0;
  300. std::string filename = std::string("texture_dump") + std::to_string(++dump_index) + std::string(".png");
  301. u32 row_stride = texture_config.width * 3;
  302. u8* buf;
  303. char title[] = "Citra texture dump";
  304. char title_key[] = "Title";
  305. png_structp png_ptr = nullptr;
  306. png_infop info_ptr = nullptr;
  307. // Open file for writing (binary mode)
  308. FileUtil::IOFile fp(filename, "wb");
  309. // Initialize write structure
  310. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  311. if (png_ptr == nullptr) {
  312. ERROR_LOG(GPU, "Could not allocate write struct\n");
  313. goto finalise;
  314. }
  315. // Initialize info structure
  316. info_ptr = png_create_info_struct(png_ptr);
  317. if (info_ptr == nullptr) {
  318. ERROR_LOG(GPU, "Could not allocate info struct\n");
  319. goto finalise;
  320. }
  321. // Setup Exception handling
  322. if (setjmp(png_jmpbuf(png_ptr))) {
  323. ERROR_LOG(GPU, "Error during png creation\n");
  324. goto finalise;
  325. }
  326. png_init_io(png_ptr, fp.GetHandle());
  327. // Write header (8 bit colour depth)
  328. png_set_IHDR(png_ptr, info_ptr, texture_config.width, texture_config.height,
  329. 8, PNG_COLOR_TYPE_RGB /*_ALPHA*/, PNG_INTERLACE_NONE,
  330. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  331. png_text title_text;
  332. title_text.compression = PNG_TEXT_COMPRESSION_NONE;
  333. title_text.key = title_key;
  334. title_text.text = title;
  335. png_set_text(png_ptr, info_ptr, &title_text, 1);
  336. png_write_info(png_ptr, info_ptr);
  337. buf = new u8[row_stride * texture_config.height];
  338. for (unsigned y = 0; y < texture_config.height; ++y) {
  339. for (unsigned x = 0; x < texture_config.width; ++x) {
  340. // Cf. rasterizer code for an explanation of this algorithm.
  341. int texel_index_within_tile = 0;
  342. for (int block_size_index = 0; block_size_index < 3; ++block_size_index) {
  343. int sub_tile_width = 1 << block_size_index;
  344. int sub_tile_height = 1 << block_size_index;
  345. int sub_tile_index = (x & sub_tile_width) << block_size_index;
  346. sub_tile_index += 2 * ((y & sub_tile_height) << block_size_index);
  347. texel_index_within_tile += sub_tile_index;
  348. }
  349. const int block_width = 8;
  350. const int block_height = 8;
  351. int coarse_x = (x / block_width) * block_width;
  352. int coarse_y = (y / block_height) * block_height;
  353. u8* source_ptr = (u8*)data + coarse_x * block_height * 3 + coarse_y * row_stride + texel_index_within_tile * 3;
  354. buf[3 * x + y * row_stride ] = source_ptr[2];
  355. buf[3 * x + y * row_stride + 1] = source_ptr[1];
  356. buf[3 * x + y * row_stride + 2] = source_ptr[0];
  357. }
  358. }
  359. // Write image data
  360. for (unsigned y = 0; y < texture_config.height; ++y)
  361. {
  362. u8* row_ptr = (u8*)buf + y * row_stride;
  363. u8* ptr = row_ptr;
  364. png_write_row(png_ptr, row_ptr);
  365. }
  366. delete[] buf;
  367. // End write
  368. png_write_end(png_ptr, nullptr);
  369. finalise:
  370. if (info_ptr != nullptr) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  371. if (png_ptr != nullptr) png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
  372. #endif
  373. }
  374. void DumpTevStageConfig(const std::array<Pica::Regs::TevStageConfig,6>& stages)
  375. {
  376. using Source = Pica::Regs::TevStageConfig::Source;
  377. using ColorModifier = Pica::Regs::TevStageConfig::ColorModifier;
  378. using AlphaModifier = Pica::Regs::TevStageConfig::AlphaModifier;
  379. using Operation = Pica::Regs::TevStageConfig::Operation;
  380. std::string stage_info = "Tev setup:\n";
  381. for (size_t index = 0; index < stages.size(); ++index) {
  382. const auto& tev_stage = stages[index];
  383. const std::map<Source, std::string> source_map = {
  384. { Source::PrimaryColor, "PrimaryColor" },
  385. { Source::Texture0, "Texture0" },
  386. { Source::Constant, "Constant" },
  387. { Source::Previous, "Previous" },
  388. };
  389. const std::map<ColorModifier, std::string> color_modifier_map = {
  390. { ColorModifier::SourceColor, { "%source.rgb" } }
  391. };
  392. const std::map<AlphaModifier, std::string> alpha_modifier_map = {
  393. { AlphaModifier::SourceAlpha, "%source.a" }
  394. };
  395. std::map<Operation, std::string> combiner_map = {
  396. { Operation::Replace, "%source1" },
  397. { Operation::Modulate, "(%source1 * %source2) / 255" },
  398. };
  399. auto ReplacePattern =
  400. [](const std::string& input, const std::string& pattern, const std::string& replacement) -> std::string {
  401. size_t start = input.find(pattern);
  402. if (start == std::string::npos)
  403. return input;
  404. std::string ret = input;
  405. ret.replace(start, pattern.length(), replacement);
  406. return ret;
  407. };
  408. auto GetColorSourceStr =
  409. [&source_map,&color_modifier_map,&ReplacePattern](const Source& src, const ColorModifier& modifier) {
  410. auto src_it = source_map.find(src);
  411. std::string src_str = "Unknown";
  412. if (src_it != source_map.end())
  413. src_str = src_it->second;
  414. auto modifier_it = color_modifier_map.find(modifier);
  415. std::string modifier_str = "%source.????";
  416. if (modifier_it != color_modifier_map.end())
  417. modifier_str = modifier_it->second;
  418. return ReplacePattern(modifier_str, "%source", src_str);
  419. };
  420. auto GetColorCombinerStr =
  421. [&](const Regs::TevStageConfig& tev_stage) {
  422. auto op_it = combiner_map.find(tev_stage.color_op);
  423. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  424. if (op_it != combiner_map.end())
  425. op_str = op_it->second;
  426. op_str = ReplacePattern(op_str, "%source1", GetColorSourceStr(tev_stage.color_source1, tev_stage.color_modifier1));
  427. op_str = ReplacePattern(op_str, "%source2", GetColorSourceStr(tev_stage.color_source2, tev_stage.color_modifier2));
  428. return ReplacePattern(op_str, "%source3", GetColorSourceStr(tev_stage.color_source3, tev_stage.color_modifier3));
  429. };
  430. auto GetAlphaSourceStr =
  431. [&source_map,&alpha_modifier_map,&ReplacePattern](const Source& src, const AlphaModifier& modifier) {
  432. auto src_it = source_map.find(src);
  433. std::string src_str = "Unknown";
  434. if (src_it != source_map.end())
  435. src_str = src_it->second;
  436. auto modifier_it = alpha_modifier_map.find(modifier);
  437. std::string modifier_str = "%source.????";
  438. if (modifier_it != alpha_modifier_map.end())
  439. modifier_str = modifier_it->second;
  440. return ReplacePattern(modifier_str, "%source", src_str);
  441. };
  442. auto GetAlphaCombinerStr =
  443. [&](const Regs::TevStageConfig& tev_stage) {
  444. auto op_it = combiner_map.find(tev_stage.alpha_op);
  445. std::string op_str = "Unknown op (%source1, %source2, %source3)";
  446. if (op_it != combiner_map.end())
  447. op_str = op_it->second;
  448. op_str = ReplacePattern(op_str, "%source1", GetAlphaSourceStr(tev_stage.alpha_source1, tev_stage.alpha_modifier1));
  449. op_str = ReplacePattern(op_str, "%source2", GetAlphaSourceStr(tev_stage.alpha_source2, tev_stage.alpha_modifier2));
  450. return ReplacePattern(op_str, "%source3", GetAlphaSourceStr(tev_stage.alpha_source3, tev_stage.alpha_modifier3));
  451. };
  452. stage_info += "Stage " + std::to_string(index) + ": " + GetColorCombinerStr(tev_stage) + " " + GetAlphaCombinerStr(tev_stage) + "\n";
  453. }
  454. DEBUG_LOG(GPU, "%s", stage_info.c_str());
  455. }
  456. } // namespace
  457. } // namespace