debug_utils.cpp 30 KB

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