debug_utils.cpp 30 KB

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