debug_utils.cpp 30 KB

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