summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.github/ISSUE_TEMPLATE.md21
-rwxr-xr-x.travis/linux/docker.sh4
-rwxr-xr-x.travis/macos/build.sh2
-rw-r--r--CMakeLists.txt8
-rw-r--r--CMakeModules/CopyYuzuQt5Deps.cmake31
-rw-r--r--CONTRIBUTING.md137
-rw-r--r--appveyor.yml3
m---------externals/fmt0
-rw-r--r--src/audio_core/algorithm/interpolate.cpp5
-rw-r--r--src/audio_core/audio_out.cpp6
-rw-r--r--src/audio_core/audio_renderer.cpp17
-rw-r--r--src/audio_core/audio_renderer.h7
-rw-r--r--src/audio_core/cubeb_sink.cpp2
-rw-r--r--src/audio_core/cubeb_sink.h2
-rw-r--r--src/audio_core/null_sink.h2
-rw-r--r--src/audio_core/sink_details.cpp53
-rw-r--r--src/audio_core/sink_details.h25
-rw-r--r--src/audio_core/stream.cpp9
-rw-r--r--src/audio_core/time_stretch.cpp4
-rw-r--r--src/common/CMakeLists.txt1
-rw-r--r--src/common/bit_util.h61
-rw-r--r--src/common/logging/backend.cpp4
-rw-r--r--src/common/quaternion.h2
-rw-r--r--src/common/thread_queue_list.h16
-rw-r--r--src/core/CMakeLists.txt23
-rw-r--r--src/core/arm/arm_interface.cpp27
-rw-r--r--src/core/arm/arm_interface.h8
-rw-r--r--src/core/arm/dynarmic/arm_dynarmic.cpp1
-rw-r--r--src/core/arm/unicorn/arm_unicorn.cpp1
-rw-r--r--src/core/core.cpp51
-rw-r--r--src/core/core.h19
-rw-r--r--src/core/crypto/key_manager.cpp3
-rw-r--r--src/core/file_sys/content_archive.cpp6
-rw-r--r--src/core/file_sys/content_archive.h10
-rw-r--r--src/core/file_sys/control_metadata.cpp28
-rw-r--r--src/core/file_sys/control_metadata.h30
-rw-r--r--src/core/file_sys/directory.h27
-rw-r--r--src/core/file_sys/patch_manager.cpp82
-rw-r--r--src/core/file_sys/patch_manager.h5
-rw-r--r--src/core/file_sys/program_metadata.cpp21
-rw-r--r--src/core/file_sys/program_metadata.h6
-rw-r--r--src/core/file_sys/registered_cache.cpp53
-rw-r--r--src/core/file_sys/romfs.cpp3
-rw-r--r--src/core/file_sys/romfs.h5
-rw-r--r--src/core/file_sys/romfs_factory.cpp2
-rw-r--r--src/core/file_sys/savedata_factory.cpp39
-rw-r--r--src/core/file_sys/savedata_factory.h12
-rw-r--r--src/core/file_sys/system_archive/ng_word.cpp81
-rw-r--r--src/core/file_sys/system_archive/ng_word.h14
-rw-r--r--src/core/file_sys/system_archive/system_archive.cpp90
-rw-r--r--src/core/file_sys/system_archive/system_archive.h14
-rw-r--r--src/core/file_sys/vfs.cpp46
-rw-r--r--src/core/file_sys/vfs.h24
-rw-r--r--src/core/file_sys/vfs_vector.cpp1
-rw-r--r--src/core/file_sys/vfs_vector.h53
-rw-r--r--src/core/frontend/applets/profile_select.cpp19
-rw-r--r--src/core/frontend/applets/profile_select.h27
-rw-r--r--src/core/frontend/applets/web_browser.cpp24
-rw-r--r--src/core/frontend/applets/web_browser.h28
-rw-r--r--src/core/frontend/framebuffer_layout.cpp15
-rw-r--r--src/core/frontend/framebuffer_layout.h7
-rw-r--r--src/core/frontend/scope_acquire_window_context.cpp18
-rw-r--r--src/core/frontend/scope_acquire_window_context.h23
-rw-r--r--src/core/gdbstub/gdbstub.cpp4
-rw-r--r--src/core/hle/ipc_helpers.h23
-rw-r--r--src/core/hle/kernel/client_session.cpp1
-rw-r--r--src/core/hle/kernel/client_session.h4
-rw-r--r--src/core/hle/kernel/errors.h4
-rw-r--r--src/core/hle/kernel/event.cpp53
-rw-r--r--src/core/hle/kernel/handle_table.cpp5
-rw-r--r--src/core/hle/kernel/handle_table.h7
-rw-r--r--src/core/hle/kernel/hle_ipc.cpp34
-rw-r--r--src/core/hle/kernel/hle_ipc.h21
-rw-r--r--src/core/hle/kernel/kernel.cpp13
-rw-r--r--src/core/hle/kernel/kernel.h4
-rw-r--r--src/core/hle/kernel/object.cpp6
-rw-r--r--src/core/hle/kernel/object.h8
-rw-r--r--src/core/hle/kernel/process.cpp164
-rw-r--r--src/core/hle/kernel/process.h139
-rw-r--r--src/core/hle/kernel/process_capability.cpp355
-rw-r--r--src/core/hle/kernel/process_capability.h264
-rw-r--r--src/core/hle/kernel/readable_event.cpp51
-rw-r--r--src/core/hle/kernel/readable_event.h (renamed from src/core/hle/kernel/event.h)48
-rw-r--r--src/core/hle/kernel/scheduler.cpp66
-rw-r--r--src/core/hle/kernel/scheduler.h69
-rw-r--r--src/core/hle/kernel/server_session.cpp1
-rw-r--r--src/core/hle/kernel/server_session.h1
-rw-r--r--src/core/hle/kernel/shared_memory.cpp14
-rw-r--r--src/core/hle/kernel/shared_memory.h6
-rw-r--r--src/core/hle/kernel/svc.cpp802
-rw-r--r--src/core/hle/kernel/svc.h16
-rw-r--r--src/core/hle/kernel/svc_wrap.h47
-rw-r--r--src/core/hle/kernel/thread.cpp51
-rw-r--r--src/core/hle/kernel/thread.h42
-rw-r--r--src/core/hle/kernel/timer.cpp3
-rw-r--r--src/core/hle/kernel/vm_manager.cpp131
-rw-r--r--src/core/hle/kernel/vm_manager.h317
-rw-r--r--src/core/hle/kernel/wait_object.cpp2
-rw-r--r--src/core/hle/kernel/wait_object.h1
-rw-r--r--src/core/hle/kernel/writable_event.cpp52
-rw-r--r--src/core/hle/kernel/writable_event.h61
-rw-r--r--src/core/hle/service/acc/acc.cpp5
-rw-r--r--src/core/hle/service/am/am.cpp327
-rw-r--r--src/core/hle/service/am/am.h18
-rw-r--r--src/core/hle/service/am/applet_ae.cpp66
-rw-r--r--src/core/hle/service/am/applet_oe.cpp27
-rw-r--r--src/core/hle/service/am/applets/applets.cpp35
-rw-r--r--src/core/hle/service/am/applets/applets.h19
-rw-r--r--src/core/hle/service/am/applets/profile_select.cpp77
-rw-r--r--src/core/hle/service/am/applets/profile_select.h50
-rw-r--r--src/core/hle/service/am/applets/software_keyboard.cpp3
-rw-r--r--src/core/hle/service/am/applets/web_browser.cpp190
-rw-r--r--src/core/hle/service/am/applets/web_browser.h44
-rw-r--r--src/core/hle/service/aoc/aoc_u.cpp32
-rw-r--r--src/core/hle/service/aoc/aoc_u.h6
-rw-r--r--src/core/hle/service/apm/interface.cpp16
-rw-r--r--src/core/hle/service/arp/arp.cpp4
-rw-r--r--src/core/hle/service/audio/audout_u.cpp26
-rw-r--r--src/core/hle/service/audio/audren_u.cpp79
-rw-r--r--src/core/hle/service/audio/hwopus.cpp46
-rw-r--r--src/core/hle/service/bcat/module.cpp3
-rw-r--r--src/core/hle/service/btdrv/btdrv.cpp19
-rw-r--r--src/core/hle/service/btm/btm.cpp65
-rw-r--r--src/core/hle/service/erpt/erpt.cpp12
-rw-r--r--src/core/hle/service/fatal/fatal.cpp3
-rw-r--r--src/core/hle/service/fgm/fgm.cpp4
-rw-r--r--src/core/hle/service/filesystem/filesystem.cpp67
-rw-r--r--src/core/hle/service/filesystem/filesystem.h21
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.cpp65
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp82
-rw-r--r--src/core/hle/service/hid/controllers/npad.h13
-rw-r--r--src/core/hle/service/hid/hid.cpp1103
-rw-r--r--src/core/hle/service/hid/hid.h110
-rw-r--r--src/core/hle/service/hid/irs.cpp54
-rw-r--r--src/core/hle/service/lbl/lbl.cpp12
-rw-r--r--src/core/hle/service/ldn/ldn.cpp12
-rw-r--r--src/core/hle/service/ldr/ldr.cpp58
-rw-r--r--src/core/hle/service/lm/lm.cpp4
-rw-r--r--src/core/hle/service/mm/mm_u.cpp14
-rw-r--r--src/core/hle/service/nfc/nfc.cpp24
-rw-r--r--src/core/hle/service/nfp/nfp.cpp64
-rw-r--r--src/core/hle/service/nfp/nfp.h7
-rw-r--r--src/core/hle/service/nifm/nifm.cpp43
-rw-r--r--src/core/hle/service/nim/nim.cpp43
-rw-r--r--src/core/hle/service/ns/ns.cpp8
-rw-r--r--src/core/hle/service/ns/pl_u.cpp10
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp2
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp7
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp29
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_nvdec.cpp1
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_nvjpg.cpp1
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_vic.cpp1
-rw-r--r--src/core/hle/service/nvdrv/devices/nvmap.cpp16
-rw-r--r--src/core/hle/service/nvdrv/interface.cpp15
-rw-r--r--src/core/hle/service/nvdrv/interface.h7
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.cpp24
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.h11
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.cpp45
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.h20
-rw-r--r--src/core/hle/service/pctl/module.cpp8
-rw-r--r--src/core/hle/service/pm/pm.cpp15
-rw-r--r--src/core/hle/service/pm/pm.h7
-rw-r--r--src/core/hle/service/psc/psc.cpp4
-rw-r--r--src/core/hle/service/service.cpp31
-rw-r--r--src/core/hle/service/service.h8
-rw-r--r--src/core/hle/service/set/set.cpp52
-rw-r--r--src/core/hle/service/set/set.h1
-rw-r--r--src/core/hle/service/set/set_sys.cpp8
-rw-r--r--src/core/hle/service/sm/controller.cpp11
-rw-r--r--src/core/hle/service/sm/sm.cpp21
-rw-r--r--src/core/hle/service/spl/module.cpp3
-rw-r--r--src/core/hle/service/ssl/ssl.cpp2
-rw-r--r--src/core/hle/service/time/time.cpp59
-rw-r--r--src/core/hle/service/time/time.h12
-rw-r--r--src/core/hle/service/usb/usb.cpp6
-rw-r--r--src/core/hle/service/vi/vi.cpp322
-rw-r--r--src/core/loader/deconstructed_rom_directory.cpp8
-rw-r--r--src/core/loader/deconstructed_rom_directory.h2
-rw-r--r--src/core/loader/elf.h2
-rw-r--r--src/core/loader/loader.cpp4
-rw-r--r--src/core/loader/loader.h31
-rw-r--r--src/core/loader/nax.cpp11
-rw-r--r--src/core/loader/nax.h5
-rw-r--r--src/core/loader/nca.cpp19
-rw-r--r--src/core/loader/nca.h5
-rw-r--r--src/core/loader/nro.cpp15
-rw-r--r--src/core/loader/nro.h10
-rw-r--r--src/core/loader/nso.cpp8
-rw-r--r--src/core/loader/nso.h10
-rw-r--r--src/core/loader/nsp.cpp24
-rw-r--r--src/core/loader/nsp.h7
-rw-r--r--src/core/loader/xci.cpp25
-rw-r--r--src/core/loader/xci.h7
-rw-r--r--src/core/memory.cpp20
-rw-r--r--src/core/settings.cpp29
-rw-r--r--src/core/settings.h12
-rw-r--r--src/core/telemetry_session.cpp12
-rw-r--r--src/video_core/CMakeLists.txt35
-rw-r--r--src/video_core/command_processor.cpp142
-rw-r--r--src/video_core/command_processor.h53
-rw-r--r--src/video_core/dma_pusher.cpp123
-rw-r--r--src/video_core/dma_pusher.h99
-rw-r--r--src/video_core/engines/fermi_2d.cpp8
-rw-r--r--src/video_core/engines/fermi_2d.h2
-rw-r--r--src/video_core/engines/kepler_memory.cpp10
-rw-r--r--src/video_core/engines/kepler_memory.h3
-rw-r--r--src/video_core/engines/maxwell_3d.cpp85
-rw-r--r--src/video_core/engines/maxwell_3d.h39
-rw-r--r--src/video_core/engines/maxwell_compute.cpp8
-rw-r--r--src/video_core/engines/maxwell_compute.h3
-rw-r--r--src/video_core/engines/maxwell_dma.cpp8
-rw-r--r--src/video_core/engines/maxwell_dma.h2
-rw-r--r--src/video_core/engines/shader_bytecode.h27
-rw-r--r--src/video_core/engines/shader_header.h2
-rw-r--r--src/video_core/gpu.cpp218
-rw-r--r--src/video_core/gpu.h98
-rw-r--r--src/video_core/macro_interpreter.cpp4
-rw-r--r--src/video_core/morton.cpp5
-rw-r--r--src/video_core/rasterizer_interface.h9
-rw-r--r--src/video_core/renderer_base.cpp12
-rw-r--r--src/video_core/renderer_base.h27
-rw-r--r--src/video_core/renderer_opengl/gl_buffer_cache.cpp2
-rw-r--r--src/video_core/renderer_opengl/gl_global_cache.cpp94
-rw-r--r--src/video_core/renderer_opengl/gl_global_cache.h78
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp407
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h89
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.cpp276
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.h88
-rw-r--r--src/video_core/renderer_opengl/gl_resource_manager.cpp5
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.cpp199
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.h96
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.cpp4801
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.h103
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.cpp118
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.h160
-rw-r--r--src/video_core/renderer_opengl/gl_shader_manager.h21
-rw-r--r--src/video_core/renderer_opengl/gl_state.cpp55
-rw-r--r--src/video_core/renderer_opengl/gl_state.h17
-rw-r--r--src/video_core/renderer_opengl/gl_stream_buffer.cpp26
-rw-r--r--src/video_core/renderer_opengl/gl_stream_buffer.h3
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.cpp89
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.h19
-rw-r--r--src/video_core/shader/decode.cpp206
-rw-r--r--src/video_core/shader/decode/arithmetic.cpp155
-rw-r--r--src/video_core/shader/decode/arithmetic_half.cpp70
-rw-r--r--src/video_core/shader/decode/arithmetic_half_immediate.cpp51
-rw-r--r--src/video_core/shader/decode/arithmetic_immediate.cpp52
-rw-r--r--src/video_core/shader/decode/arithmetic_integer.cpp287
-rw-r--r--src/video_core/shader/decode/arithmetic_integer_immediate.cpp96
-rw-r--r--src/video_core/shader/decode/bfe.cpp49
-rw-r--r--src/video_core/shader/decode/bfi.cpp41
-rw-r--r--src/video_core/shader/decode/conversion.cpp149
-rw-r--r--src/video_core/shader/decode/decode_integer_set.cpp0
-rw-r--r--src/video_core/shader/decode/ffma.cpp59
-rw-r--r--src/video_core/shader/decode/float_set.cpp58
-rw-r--r--src/video_core/shader/decode/float_set_predicate.cpp56
-rw-r--r--src/video_core/shader/decode/half_set.cpp67
-rw-r--r--src/video_core/shader/decode/half_set_predicate.cpp62
-rw-r--r--src/video_core/shader/decode/hfma2.cpp76
-rw-r--r--src/video_core/shader/decode/integer_set.cpp50
-rw-r--r--src/video_core/shader/decode/integer_set_predicate.cpp53
-rw-r--r--src/video_core/shader/decode/memory.cpp737
-rw-r--r--src/video_core/shader/decode/other.cpp178
-rw-r--r--src/video_core/shader/decode/predicate_set_predicate.cpp67
-rw-r--r--src/video_core/shader/decode/predicate_set_register.cpp46
-rw-r--r--src/video_core/shader/decode/register_set_predicate.cpp51
-rw-r--r--src/video_core/shader/decode/shift.cpp55
-rw-r--r--src/video_core/shader/decode/video.cpp111
-rw-r--r--src/video_core/shader/decode/xmad.cpp97
-rw-r--r--src/video_core/shader/shader_ir.cpp444
-rw-r--r--src/video_core/shader/shader_ir.h823
-rw-r--r--src/video_core/shader/track.cpp76
-rw-r--r--src/video_core/surface.cpp32
-rw-r--r--src/video_core/surface.h630
-rw-r--r--src/video_core/textures/decoders.cpp2
-rw-r--r--src/video_core/video_core.cpp9
-rw-r--r--src/video_core/video_core.h2
-rw-r--r--src/yuzu/CMakeLists.txt23
-rw-r--r--src/yuzu/applets/profile_select.cpp168
-rw-r--r--src/yuzu/applets/profile_select.h73
-rw-r--r--src/yuzu/applets/web_browser.cpp113
-rw-r--r--src/yuzu/applets/web_browser.h52
-rw-r--r--src/yuzu/bootmanager.cpp29
-rw-r--r--src/yuzu/bootmanager.h9
-rw-r--r--src/yuzu/configuration/config.cpp148
-rw-r--r--src/yuzu/configuration/config.h1
-rw-r--r--src/yuzu/configuration/configure.ui147
-rw-r--r--src/yuzu/configuration/configure_audio.cpp7
-rw-r--r--src/yuzu/configuration/configure_audio.h5
-rw-r--r--src/yuzu/configuration/configure_debug.cpp1
-rw-r--r--src/yuzu/configuration/configure_debug.h3
-rw-r--r--src/yuzu/configuration/configure_dialog.cpp49
-rw-r--r--src/yuzu/configuration/configure_dialog.h5
-rw-r--r--src/yuzu/configuration/configure_gamelist.h2
-rw-r--r--src/yuzu/configuration/configure_general.cpp2
-rw-r--r--src/yuzu/configuration/configure_general.h2
-rw-r--r--src/yuzu/configuration/configure_general.ui7
-rw-r--r--src/yuzu/configuration/configure_graphics.h3
-rw-r--r--src/yuzu/configuration/configure_input.cpp56
-rw-r--r--src/yuzu/configuration/configure_input.h9
-rw-r--r--src/yuzu/configuration/configure_input.ui48
-rw-r--r--src/yuzu/configuration/configure_input_player.cpp2
-rw-r--r--src/yuzu/configuration/configure_input_player.h8
-rw-r--r--src/yuzu/configuration/configure_input_simple.cpp137
-rw-r--r--src/yuzu/configuration/configure_input_simple.h40
-rw-r--r--src/yuzu/configuration/configure_input_simple.ui97
-rw-r--r--src/yuzu/configuration/configure_per_general.cpp169
-rw-r--r--src/yuzu/configuration/configure_per_general.h50
-rw-r--r--src/yuzu/configuration/configure_per_general.ui276
-rw-r--r--src/yuzu/configuration/configure_profile_manager.cpp300
-rw-r--r--src/yuzu/configuration/configure_profile_manager.h57
-rw-r--r--src/yuzu/configuration/configure_profile_manager.ui172
-rw-r--r--src/yuzu/configuration/configure_system.cpp286
-rw-r--r--src/yuzu/configuration/configure_system.h27
-rw-r--r--src/yuzu/configuration/configure_system.ui217
-rw-r--r--src/yuzu/configuration/configure_touchscreen_advanced.h2
-rw-r--r--src/yuzu/configuration/configure_web.cpp11
-rw-r--r--src/yuzu/configuration/configure_web.h5
-rw-r--r--src/yuzu/debugger/graphics/graphics_surface.cpp1
-rw-r--r--src/yuzu/debugger/wait_tree.cpp24
-rw-r--r--src/yuzu/debugger/wait_tree.h6
-rw-r--r--src/yuzu/game_list.cpp8
-rw-r--r--src/yuzu/game_list.h1
-rw-r--r--src/yuzu/game_list_worker.cpp137
-rw-r--r--src/yuzu/loading_screen.cpp213
-rw-r--r--src/yuzu/loading_screen.h92
-rw-r--r--src/yuzu/loading_screen.ui161
-rw-r--r--src/yuzu/main.cpp341
-rw-r--r--src/yuzu/main.h15
-rw-r--r--src/yuzu/main.ui88
-rw-r--r--src/yuzu/ui_settings.h9
-rw-r--r--src/yuzu_cmd/config.cpp30
-rw-r--r--src/yuzu_cmd/default_ini.h13
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.cpp3
334 files changed, 16910 insertions, 8078 deletions
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 986efcfb9..70e1bba67 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -1,16 +1,27 @@
<!--
Please keep in mind yuzu is EXPERIMENTAL SOFTWARE.
-Please read the FAQ: https://yuzu-emu.org/wiki/faq/
+Please read the FAQ:
+https://yuzu-emu.org/wiki/faq/
-When submitting an issue, please do the following:
+THIS IS NOT A SUPPORT FORUM, FOR SUPPORT GO TO:
+https://community.citra-emu.org/
-- Provide the version (commit hash) of yuzu you are using.
-- Provide sufficient detail for the issue to be reproduced.
-- Provide:
+If the FAQ does not answer your question, please go to:
+https://community.citra-emu.org/
+
+When submitting an issue, please check the following:
+
+- You have read the above.
+- You have provided the version (commit hash) of yuzu you are using.
+- You have provided sufficient detail for the issue to be reproduced.
+- You have provided system specs (if relevant).
+- Please also provide:
+ - For any issues, a log file
- For crashes, a backtrace.
- For graphical issues, comparison screenshots with real hardware.
- For emulation inaccuracies, a test-case (if able).
+
-->
diff --git a/.travis/linux/docker.sh b/.travis/linux/docker.sh
index 4fe3326f9..8b7e65911 100755
--- a/.travis/linux/docker.sh
+++ b/.travis/linux/docker.sh
@@ -1,12 +1,12 @@
#!/bin/bash -ex
apt-get update
-apt-get install --no-install-recommends -y build-essential git libqt5opengl5-dev libsdl2-dev libssl-dev python qtbase5-dev wget cmake ninja-build ccache
+apt-get install --no-install-recommends -y build-essential git libqt5opengl5-dev libsdl2-dev libssl-dev python qtbase5-dev qtwebengine5-dev wget cmake ninja-build ccache
cd /yuzu
mkdir build && cd build
-cmake .. -DYUZU_USE_BUNDLED_UNICORN=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=/usr/lib/ccache/gcc -DCMAKE_CXX_COMPILER=/usr/lib/ccache/g++ -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${ENABLE_COMPATIBILITY_REPORTING:-"OFF"} -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DUSE_DISCORD_PRESENCE=ON -G Ninja
+cmake .. -DYUZU_USE_BUNDLED_UNICORN=ON -DYUZU_USE_QT_WEB_ENGINE=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=/usr/lib/ccache/gcc -DCMAKE_CXX_COMPILER=/usr/lib/ccache/g++ -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${ENABLE_COMPATIBILITY_REPORTING:-"OFF"} -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DUSE_DISCORD_PRESENCE=ON -G Ninja
ninja
ccache -s
diff --git a/.travis/macos/build.sh b/.travis/macos/build.sh
index dce12099b..4a14837fc 100755
--- a/.travis/macos/build.sh
+++ b/.travis/macos/build.sh
@@ -9,7 +9,7 @@ export PATH="/usr/local/opt/ccache/libexec:$PATH"
mkdir build && cd build
cmake --version
-cmake .. -DYUZU_USE_BUNDLED_UNICORN=ON -DCMAKE_BUILD_TYPE=Release -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${ENABLE_COMPATIBILITY_REPORTING:-"OFF"} -DUSE_DISCORD_PRESENCE=ON
+cmake .. -DYUZU_USE_BUNDLED_UNICORN=ON -DYUZU_USE_QT_WEB_ENGINE=ON -DCMAKE_BUILD_TYPE=Release -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${ENABLE_COMPATIBILITY_REPORTING:-"OFF"} -DUSE_DISCORD_PRESENCE=ON
make -j4
ccache -s
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1f71f9fd9..871e0ca1a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -19,6 +19,8 @@ option(ENABLE_WEB_SERVICE "Enable web services (telemetry, etc.)" ON)
option(YUZU_USE_BUNDLED_UNICORN "Build/Download bundled Unicorn" ON)
+option(YUZU_USE_QT_WEB_ENGINE "Use QtWebEngine for web applet implementation" OFF)
+
option(ENABLE_CUBEB "Enables the cubeb audio backend" ON)
option(USE_DISCORD_PRESENCE "Enables Discord Rich Presence" OFF)
@@ -302,7 +304,7 @@ endif()
if (ENABLE_QT)
if (YUZU_USE_BUNDLED_QT)
if ((MSVC_VERSION GREATER_EQUAL 1910 AND MSVC_VERSION LESS 1920) AND ARCHITECTURE_x86_64)
- set(QT_VER qt-5.10.0-msvc2015_64)
+ set(QT_VER qt-5.12.0-msvc2017_64)
else()
message(FATAL_ERROR "No bundled Qt binaries for your toolchain. Disable YUZU_USE_BUNDLED_QT and provide your own.")
endif()
@@ -319,6 +321,10 @@ if (ENABLE_QT)
endif()
find_package(Qt5 REQUIRED COMPONENTS Widgets OpenGL ${QT_PREFIX_HINT})
+
+ if (YUZU_USE_QT_WEB_ENGINE)
+ find_package(Qt5 REQUIRED COMPONENTS WebEngineCore WebEngineWidgets ${QT_PREFIX_HINT})
+ endif ()
endif()
# Platform-specific library requirements
diff --git a/CMakeModules/CopyYuzuQt5Deps.cmake b/CMakeModules/CopyYuzuQt5Deps.cmake
index aaf80b77b..1e9810bba 100644
--- a/CMakeModules/CopyYuzuQt5Deps.cmake
+++ b/CMakeModules/CopyYuzuQt5Deps.cmake
@@ -5,6 +5,7 @@ function(copy_yuzu_Qt5_deps target_dir)
set(Qt5_PLATFORMS_DIR "${Qt5_DIR}/../../../plugins/platforms/")
set(Qt5_STYLES_DIR "${Qt5_DIR}/../../../plugins/styles/")
set(Qt5_IMAGEFORMATS_DIR "${Qt5_DIR}/../../../plugins/imageformats/")
+ set(Qt5_RESOURCES_DIR "${Qt5_DIR}/../../../resources/")
set(PLATFORMS ${DLL_DEST}platforms/)
set(STYLES ${DLL_DEST}styles/)
set(IMAGEFORMATS ${DLL_DEST}imageformats/)
@@ -17,7 +18,35 @@ function(copy_yuzu_Qt5_deps target_dir)
Qt5OpenGL$<$<CONFIG:Debug>:d>.*
Qt5Widgets$<$<CONFIG:Debug>:d>.*
)
+
+ if (YUZU_USE_QT_WEB_ENGINE)
+ windows_copy_files(${target_dir} ${Qt5_DLL_DIR} ${DLL_DEST}
+ Qt5Network$<$<CONFIG:Debug>:d>.*
+ Qt5Positioning$<$<CONFIG:Debug>:d>.*
+ Qt5PrintSupport$<$<CONFIG:Debug>:d>.*
+ Qt5Qml$<$<CONFIG:Debug>:d>.*
+ Qt5Quick$<$<CONFIG:Debug>:d>.*
+ Qt5QuickWidgets$<$<CONFIG:Debug>:d>.*
+ Qt5WebChannel$<$<CONFIG:Debug>:d>.*
+ Qt5WebEngine$<$<CONFIG:Debug>:d>.*
+ Qt5WebEngineCore$<$<CONFIG:Debug>:d>.*
+ Qt5WebEngineWidgets$<$<CONFIG:Debug>:d>.*
+ QtWebEngineProcess$<$<CONFIG:Debug>:d>.*
+ )
+
+ windows_copy_files(${target_dir} ${Qt5_RESOURCES_DIR} ${DLL_DEST}
+ qtwebengine_resources.pak
+ qtwebengine_devtools_resources.pak
+ qtwebengine_resources_100p.pak
+ qtwebengine_resources_200p.pak
+ icudtl.dat
+ )
+ endif ()
+
windows_copy_files(yuzu ${Qt5_PLATFORMS_DIR} ${PLATFORMS} qwindows$<$<CONFIG:Debug>:d>.*)
windows_copy_files(yuzu ${Qt5_STYLES_DIR} ${STYLES} qwindowsvistastyle$<$<CONFIG:Debug>:d>.*)
- windows_copy_files(yuzu ${Qt5_IMAGEFORMATS_DIR} ${IMAGEFORMATS} qjpeg$<$<CONFIG:Debug>:d>.*)
+ windows_copy_files(yuzu ${Qt5_IMAGEFORMATS_DIR} ${IMAGEFORMATS}
+ qjpeg$<$<CONFIG:Debug>:d>.*
+ qgif$<$<CONFIG:Debug>:d>.*
+ )
endfunction(copy_yuzu_Qt5_deps)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1b2056885..01109785d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,136 +1 @@
-# Reporting Issues
-
-**The issue tracker is not a support forum.** Unless you can provide precise *technical information* regarding an issue, you *should not post in it*. If you need support, first read the [FAQ](https://github.com/yuzu-emu/yuzu/wiki/FAQ) and then either visit our [Discord server](https://discordapp.com/invite/u77vRWY), [our forum](https://community.citra-emu.org) or ask in a general emulation forum such as [/r/emulation](https://www.reddit.com/r/emulation/). If you post support questions, generic messages to the developers or vague reports without technical details, they will be closed and locked.
-
-If you believe you have a valid issue report, please post text or a screenshot from the log (the console window that opens alongside yuzu) and build version (hex string visible in the titlebar and zip filename), as well as your hardware and software information if applicable.
-
-# Contributing
-yuzu is a brand new project, so we have a great opportunity to keep things clean and well organized early on. As such, coding style is very important when making commits. We run clang-format on our CI to check the code. Please use it to format your code when contributing. However, it doesn't cover all the rules below. Some of them aren't very strict rules since we want to be flexible and we understand that under certain circumstances some of them can be counterproductive. Just try to follow as many of them as possible.
-
-# Using clang format (version 6.0)
-When generating the native build script for your toolset, cmake will try to find the correct version of clang format (or will download it on windows). Before running cmake, please install clang format version 6.0 for your platform as follows:
-
-* Windows: do nothing; cmake will download a pre built binary for MSVC and MINGW. MSVC users can additionally install a clang format Visual Studio extension to add features like format on save.
-* OSX: run `brew install clang-format`.
-* Linux: use your package manager to get an appropriate binary.
-
-If clang format is found, then cmake will add a custom build target that can be run at any time to run clang format against *all* source files and update the formatting in them. This should be used before making a pull request so that the reviewers can spend more time reviewing the code instead of having to worry about minor style violations. On MSVC, you can run clang format by building the clang-format project in the solution. On OSX, you can either use the Makefile target `make clang-format` or by building the clang-format target in XCode. For Makefile builds, you can use the clang-format target with `make clang-format`
-
-### General Rules
-* A lot of code was taken from other projects (e.g. Citra, Dolphin, PPSSPP, Gekko). In general, when editing other people's code, follow the style of the module you're in (or better yet, fix the style if it drastically differs from our guide).
-* Line width is typically 100 characters. Please do not use 80-characters.
-* Don't ever introduce new external dependencies into Core
-* Don't use any platform specific code in Core
-* Use namespaces often
-* Avoid the use of C-style casts and instead prefer C++-style `static_cast` and `reinterpret_cast`. Try to avoid using `dynamic_cast`. Never use `const_cast`.
-
-### Naming Rules
-* Functions: `PascalCase`
-* Variables: `lower_case_underscored`. Prefix with `g_` if global.
-* Classes: `PascalCase`
-* Files and Directories: `lower_case_underscored`
-* Namespaces: `PascalCase`, `_` may also be used for clarity (e.g. `ARM_InitCore`)
-
-### Indentation/Whitespace Style
-Follow the indentation/whitespace style shown below. Do not use tabs, use 4-spaces instead.
-
-### Comments
-* For regular comments, use C++ style (`//`) comments, even for multi-line ones.
-* For doc-comments (Doxygen comments), use `/// ` if it's a single line, else use the `/**` `*/` style featured in the example. Start the text on the second line, not the first containing `/**`.
-* For items that are both defined and declared in two separate files, put the doc-comment only next to the associated declaration. (In a header file, usually.) Otherwise, put it next to the implementation. Never duplicate doc-comments in both places.
-
-```cpp
-// Includes should be sorted lexicographically
-// STD includes first
-#include <map>
-#include <memory>
-
-// then, library includes
-#include <nihstro/shared_binary.h>
-
-// finally, yuzu includes
-#include "common/math_util.h"
-#include "common/vector_math.h"
-
-// each major module is separated
-#include "video_core/pica.h"
-#include "video_core/video_core.h"
-
-namespace Example {
-
-// Namespace contents are not indented
-
-// Declare globals at the top
-int g_foo{}; // {} can be used to initialize types as 0, false, or nullptr
-char* g_some_pointer{}; // Pointer * and reference & stick to the type name, and make sure to initialize as nullptr!
-
-/// A colorful enum.
-enum SomeEnum {
- ColorRed, ///< The color of fire.
- ColorGreen, ///< The color of grass.
- ColorBlue, ///< Not actually the color of water.
-};
-
-/**
- * Very important struct that does a lot of stuff.
- * Note that the asterisks are indented by one space to align to the first line.
- */
-struct Position {
- int x{}, y{}; // Always intitialize member variables!
-};
-
-// Use "typename" rather than "class" here
-template <typename T>
-void FooBar() {
- const std::string some_string{ "prefer uniform initialization" };
-
- int some_array[]{
- 5,
- 25,
- 7,
- 42,
- };
-
- if (note == the_space_after_the_if) {
- CallAfunction();
- } else {
- // Use a space after the // when commenting
- }
-
- // Place a single space after the for loop semicolons, prefer pre-increment
- for (int i{}; i != 25; ++i) {
- // This is how we write loops
- }
-
- DoStuff(this, function, call, takes, up, multiple,
- lines, like, this);
-
- if (this || condition_takes_up_multiple &&
- lines && like && this || everything ||
- alright || then) {
-
- // Leave a blank space before the if block body if the condition was continued across
- // several lines.
- }
-
- switch (var) {
- // No indentation for case label
- case 1: {
- int case_var{ var + 3 };
- DoSomething(case_var);
- break;
- }
- case 3:
- DoSomething(var);
- return;
-
- default:
- // Yes, even break for the last case
- break;
- }
-
- std::vector<T> you_can_declare, a_few, variables, like_this;
-}
-
-}
-```
+**The Contributor's Guide has moved to [the Citra wiki](https://github.com/citra-emu/citra/wiki/Contributing).**
diff --git a/appveyor.yml b/appveyor.yml
index d6a69fbc2..cef19c259 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -42,7 +42,7 @@ before_build:
$COMPAT = if ($env:ENABLE_COMPATIBILITY_REPORTING -eq $null) {0} else {$env:ENABLE_COMPATIBILITY_REPORTING}
if ($env:BUILD_TYPE -eq 'msvc') {
# redirect stderr and change the exit code to prevent powershell from cancelling the build if cmake prints a warning
- cmd /C 'cmake -G "Visual Studio 15 2017 Win64" -DYUZU_USE_BUNDLED_QT=1 -DYUZU_USE_BUNDLED_SDL2=1 -DYUZU_USE_BUNDLED_UNICORN=1 -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${COMPAT} -DUSE_DISCORD_PRESENCE=ON .. 2>&1 && exit 0'
+ cmd /C 'cmake -G "Visual Studio 15 2017 Win64" -DYUZU_USE_BUNDLED_QT=1 -DYUZU_USE_BUNDLED_SDL2=1 -DYUZU_USE_BUNDLED_UNICORN=1 -DYUZU_USE_QT_WEB_ENGINE=ON -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${COMPAT} -DUSE_DISCORD_PRESENCE=ON .. 2>&1 && exit 0'
} else {
C:\msys64\usr\bin\bash.exe -lc "cmake -G 'MSYS Makefiles' -DYUZU_BUILD_UNICORN=1 -DCMAKE_BUILD_TYPE=Release -DENABLE_COMPATIBILITY_LIST_DOWNLOAD=ON -DYUZU_ENABLE_COMPATIBILITY_REPORTING=${COMPAT} -DUSE_DISCORD_PRESENCE=ON .. 2>&1"
}
@@ -94,6 +94,7 @@ after_build:
Copy-Item "$BUILD_DIR\*" -Destination $RELEASE_DIST -Recurse
rm "$RELEASE_DIST\*.exe"
Get-ChildItem "$BUILD_DIR" -Recurse -Filter "yuzu*.exe" | Copy-Item -destination $RELEASE_DIST
+ Get-ChildItem "$BUILD_DIR" -Recurse -Filter "QtWebEngineProcess*.exe" | Copy-Item -destination $RELEASE_DIST
Copy-Item .\license.txt -Destination $RELEASE_DIST
Copy-Item .\README.md -Destination $RELEASE_DIST
7z a -tzip $MSVC_BUILD_ZIP $RELEASE_DIST\*
diff --git a/externals/fmt b/externals/fmt
-Subproject 3e75ad9822980e41bc591938f26548f24eb8890
+Subproject 9e554999ce02cf86fcdfe74fe740c4fe3f5a56d
diff --git a/src/audio_core/algorithm/interpolate.cpp b/src/audio_core/algorithm/interpolate.cpp
index 3aea9b0f2..5005ba519 100644
--- a/src/audio_core/algorithm/interpolate.cpp
+++ b/src/audio_core/algorithm/interpolate.cpp
@@ -54,8 +54,9 @@ std::vector<s16> Interpolate(InterpolationState& state, std::vector<s16> input,
double l = 0.0;
double r = 0.0;
for (std::size_t j = 0; j < h.size(); j++) {
- l += Lanczos(taps, pos + j - taps + 1) * h[j][0];
- r += Lanczos(taps, pos + j - taps + 1) * h[j][1];
+ const double lanczos_calc = Lanczos(taps, pos + j - taps + 1);
+ l += lanczos_calc * h[j][0];
+ r += lanczos_calc * h[j][1];
}
output.emplace_back(static_cast<s16>(std::clamp(l, -32768.0, 32767.0)));
output.emplace_back(static_cast<s16>(std::clamp(r, -32768.0, 32767.0)));
diff --git a/src/audio_core/audio_out.cpp b/src/audio_core/audio_out.cpp
index 0c8f5b18e..50d2a1ed3 100644
--- a/src/audio_core/audio_out.cpp
+++ b/src/audio_core/audio_out.cpp
@@ -22,16 +22,14 @@ static Stream::Format ChannelsToStreamFormat(u32 num_channels) {
return Stream::Format::Multi51Channel16;
}
- LOG_CRITICAL(Audio, "Unimplemented num_channels={}", num_channels);
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented num_channels={}", num_channels);
return {};
}
StreamPtr AudioOut::OpenStream(u32 sample_rate, u32 num_channels, std::string&& name,
Stream::ReleaseCallback&& release_callback) {
if (!sink) {
- const SinkDetails& sink_details = GetSinkDetails(Settings::values.sink_id);
- sink = sink_details.factory(Settings::values.audio_device_id);
+ sink = CreateSinkFromID(Settings::values.sink_id, Settings::values.audio_device_id);
}
return std::make_shared<Stream>(
diff --git a/src/audio_core/audio_renderer.cpp b/src/audio_core/audio_renderer.cpp
index 23e5d3f10..00c026511 100644
--- a/src/audio_core/audio_renderer.cpp
+++ b/src/audio_core/audio_renderer.cpp
@@ -8,7 +8,7 @@
#include "audio_core/codec.h"
#include "common/assert.h"
#include "common/logging/log.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/memory.h"
namespace AudioCore {
@@ -72,7 +72,7 @@ private:
EffectInStatus info{};
};
AudioRenderer::AudioRenderer(AudioRendererParameter params,
- Kernel::SharedPtr<Kernel::Event> buffer_event)
+ Kernel::SharedPtr<Kernel::WritableEvent> buffer_event)
: worker_params{params}, buffer_event{buffer_event}, voices(params.voice_count),
effects(params.effect_count) {
@@ -260,8 +260,7 @@ void AudioRenderer::VoiceState::RefreshBuffer() {
break;
}
default:
- LOG_CRITICAL(Audio, "Unimplemented sample_format={}", info.sample_format);
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented sample_format={}", info.sample_format);
break;
}
@@ -280,13 +279,15 @@ void AudioRenderer::VoiceState::RefreshBuffer() {
break;
}
default:
- LOG_CRITICAL(Audio, "Unimplemented channel_count={}", info.channel_count);
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented channel_count={}", info.channel_count);
break;
}
- samples =
- Interpolate(interp_state, std::move(samples), GetInfo().sample_rate, STREAM_SAMPLE_RATE);
+ // Only interpolate when necessary, expensive.
+ if (GetInfo().sample_rate != STREAM_SAMPLE_RATE) {
+ samples = Interpolate(interp_state, std::move(samples), GetInfo().sample_rate,
+ STREAM_SAMPLE_RATE);
+ }
is_refresh_pending = false;
}
diff --git a/src/audio_core/audio_renderer.h b/src/audio_core/audio_renderer.h
index 71ba4be40..7826881bf 100644
--- a/src/audio_core/audio_renderer.h
+++ b/src/audio_core/audio_renderer.h
@@ -15,7 +15,7 @@
#include "core/hle/kernel/object.h"
namespace Kernel {
-class Event;
+class WritableEvent;
}
namespace AudioCore {
@@ -208,7 +208,8 @@ static_assert(sizeof(UpdateDataHeader) == 0x40, "UpdateDataHeader has wrong size
class AudioRenderer {
public:
- AudioRenderer(AudioRendererParameter params, Kernel::SharedPtr<Kernel::Event> buffer_event);
+ AudioRenderer(AudioRendererParameter params,
+ Kernel::SharedPtr<Kernel::WritableEvent> buffer_event);
~AudioRenderer();
std::vector<u8> UpdateAudioRenderer(const std::vector<u8>& input_params);
@@ -224,7 +225,7 @@ private:
class VoiceState;
AudioRendererParameter worker_params;
- Kernel::SharedPtr<Kernel::Event> buffer_event;
+ Kernel::SharedPtr<Kernel::WritableEvent> buffer_event;
std::vector<VoiceState> voices;
std::vector<EffectState> effects;
std::unique_ptr<AudioOut> audio_out;
diff --git a/src/audio_core/cubeb_sink.cpp b/src/audio_core/cubeb_sink.cpp
index d31a1c844..097328901 100644
--- a/src/audio_core/cubeb_sink.cpp
+++ b/src/audio_core/cubeb_sink.cpp
@@ -107,7 +107,7 @@ private:
static void StateCallback(cubeb_stream* stream, void* user_data, cubeb_state state);
};
-CubebSink::CubebSink(std::string target_device_name) {
+CubebSink::CubebSink(std::string_view target_device_name) {
if (cubeb_init(&ctx, "yuzu", nullptr) != CUBEB_OK) {
LOG_CRITICAL(Audio_Sink, "cubeb_init failed");
return;
diff --git a/src/audio_core/cubeb_sink.h b/src/audio_core/cubeb_sink.h
index 59cbf05e9..efb9d1634 100644
--- a/src/audio_core/cubeb_sink.h
+++ b/src/audio_core/cubeb_sink.h
@@ -15,7 +15,7 @@ namespace AudioCore {
class CubebSink final : public Sink {
public:
- explicit CubebSink(std::string device_id);
+ explicit CubebSink(std::string_view device_id);
~CubebSink() override;
SinkStream& AcquireSinkStream(u32 sample_rate, u32 num_channels,
diff --git a/src/audio_core/null_sink.h b/src/audio_core/null_sink.h
index a78d78893..61a28d542 100644
--- a/src/audio_core/null_sink.h
+++ b/src/audio_core/null_sink.h
@@ -10,7 +10,7 @@ namespace AudioCore {
class NullSink final : public Sink {
public:
- explicit NullSink(std::string){};
+ explicit NullSink(std::string_view) {}
~NullSink() override = default;
SinkStream& AcquireSinkStream(u32 /*sample_rate*/, u32 /*num_channels*/,
diff --git a/src/audio_core/sink_details.cpp b/src/audio_core/sink_details.cpp
index 67cf1f3b2..a848eb1c9 100644
--- a/src/audio_core/sink_details.cpp
+++ b/src/audio_core/sink_details.cpp
@@ -14,31 +14,68 @@
#include "common/logging/log.h"
namespace AudioCore {
+namespace {
+struct SinkDetails {
+ using FactoryFn = std::unique_ptr<Sink> (*)(std::string_view);
+ using ListDevicesFn = std::vector<std::string> (*)();
-// g_sink_details is ordered in terms of desirability, with the best choice at the top.
-const std::vector<SinkDetails> g_sink_details = {
+ /// Name for this sink.
+ const char* id;
+ /// A method to call to construct an instance of this type of sink.
+ FactoryFn factory;
+ /// A method to call to list available devices.
+ ListDevicesFn list_devices;
+};
+
+// sink_details is ordered in terms of desirability, with the best choice at the top.
+constexpr SinkDetails sink_details[] = {
#ifdef HAVE_CUBEB
- SinkDetails{"cubeb", &std::make_unique<CubebSink, std::string>, &ListCubebSinkDevices},
+ SinkDetails{"cubeb",
+ [](std::string_view device_id) -> std::unique_ptr<Sink> {
+ return std::make_unique<CubebSink>(device_id);
+ },
+ &ListCubebSinkDevices},
#endif
- SinkDetails{"null", &std::make_unique<NullSink, std::string>,
+ SinkDetails{"null",
+ [](std::string_view device_id) -> std::unique_ptr<Sink> {
+ return std::make_unique<NullSink>(device_id);
+ },
[] { return std::vector<std::string>{"null"}; }},
};
const SinkDetails& GetSinkDetails(std::string_view sink_id) {
auto iter =
- std::find_if(g_sink_details.begin(), g_sink_details.end(),
+ std::find_if(std::begin(sink_details), std::end(sink_details),
[sink_id](const auto& sink_detail) { return sink_detail.id == sink_id; });
- if (sink_id == "auto" || iter == g_sink_details.end()) {
+ if (sink_id == "auto" || iter == std::end(sink_details)) {
if (sink_id != "auto") {
LOG_ERROR(Audio, "AudioCore::SelectSink given invalid sink_id {}", sink_id);
}
// Auto-select.
- // g_sink_details is ordered in terms of desirability, with the best choice at the front.
- iter = g_sink_details.begin();
+ // sink_details is ordered in terms of desirability, with the best choice at the front.
+ iter = std::begin(sink_details);
}
return *iter;
}
+} // Anonymous namespace
+
+std::vector<const char*> GetSinkIDs() {
+ std::vector<const char*> sink_ids(std::size(sink_details));
+
+ std::transform(std::begin(sink_details), std::end(sink_details), std::begin(sink_ids),
+ [](const auto& sink) { return sink.id; });
+
+ return sink_ids;
+}
+
+std::vector<std::string> GetDeviceListForSink(std::string_view sink_id) {
+ return GetSinkDetails(sink_id).list_devices();
+}
+
+std::unique_ptr<Sink> CreateSinkFromID(std::string_view sink_id, std::string_view device_id) {
+ return GetSinkDetails(sink_id).factory(device_id);
+}
} // namespace AudioCore
diff --git a/src/audio_core/sink_details.h b/src/audio_core/sink_details.h
index 03534b187..bc8786270 100644
--- a/src/audio_core/sink_details.h
+++ b/src/audio_core/sink_details.h
@@ -4,34 +4,21 @@
#pragma once
-#include <functional>
-#include <memory>
#include <string>
#include <string_view>
-#include <utility>
#include <vector>
namespace AudioCore {
class Sink;
-struct SinkDetails {
- using FactoryFn = std::function<std::unique_ptr<Sink>(std::string)>;
- using ListDevicesFn = std::function<std::vector<std::string>()>;
+/// Retrieves the IDs for all available audio sinks.
+std::vector<const char*> GetSinkIDs();
- SinkDetails(const char* id_, FactoryFn factory_, ListDevicesFn list_devices_)
- : id(id_), factory(std::move(factory_)), list_devices(std::move(list_devices_)) {}
+/// Gets the list of devices for a particular sink identified by the given ID.
+std::vector<std::string> GetDeviceListForSink(std::string_view sink_id);
- /// Name for this sink.
- const char* id;
- /// A method to call to construct an instance of this type of sink.
- FactoryFn factory;
- /// A method to call to list available devices.
- ListDevicesFn list_devices;
-};
-
-extern const std::vector<SinkDetails> g_sink_details;
-
-const SinkDetails& GetSinkDetails(std::string_view sink_id);
+/// Creates an audio sink identified by the given device ID.
+std::unique_ptr<Sink> CreateSinkFromID(std::string_view sink_id, std::string_view device_id);
} // namespace AudioCore
diff --git a/src/audio_core/stream.cpp b/src/audio_core/stream.cpp
index f35628e45..4ce2d374e 100644
--- a/src/audio_core/stream.cpp
+++ b/src/audio_core/stream.cpp
@@ -28,8 +28,7 @@ u32 Stream::GetNumChannels() const {
case Format::Multi51Channel16:
return 6;
}
- LOG_CRITICAL(Audio, "Unimplemented format={}", static_cast<u32>(format));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented format={}", static_cast<u32>(format));
return {};
}
@@ -49,7 +48,7 @@ void Stream::Play() {
void Stream::Stop() {
state = State::Stopped;
- ASSERT_MSG(false, "Unimplemented");
+ UNIMPLEMENTED();
}
Stream::State Stream::GetState() const {
@@ -69,7 +68,7 @@ static void VolumeAdjustSamples(std::vector<s16>& samples) {
}
// Implementation of a volume slider with a dynamic range of 60 dB
- const float volume_scale_factor{std::exp(6.90775f * volume) * 0.001f};
+ const float volume_scale_factor = volume == 0 ? 0 : std::exp(6.90775f * volume) * 0.001f;
for (auto& sample : samples) {
sample = static_cast<s16>(sample * volume_scale_factor);
}
@@ -120,7 +119,7 @@ bool Stream::QueueBuffer(BufferPtr&& buffer) {
}
bool Stream::ContainsBuffer(Buffer::Tag tag) const {
- ASSERT_MSG(false, "Unimplemented");
+ UNIMPLEMENTED();
return {};
}
diff --git a/src/audio_core/time_stretch.cpp b/src/audio_core/time_stretch.cpp
index 2fe0b3aef..726591fce 100644
--- a/src/audio_core/time_stretch.cpp
+++ b/src/audio_core/time_stretch.cpp
@@ -53,8 +53,8 @@ std::size_t TimeStretcher::Process(const s16* in, std::size_t num_in, s16* out,
const double lpf_gain = 1.0 - std::exp(-time_delta / lpf_time_scale);
m_stretch_ratio += lpf_gain * (current_ratio - m_stretch_ratio);
- // Place a lower limit of 5% speed. When a game boots up, there will be
- // many silence samples. These do not need to be timestretched.
+ // Place a lower limit of 5% speed. When a game boots up, there will be
+ // many silence samples. These do not need to be timestretched.
m_stretch_ratio = std::max(m_stretch_ratio, 0.05);
m_sound_touch.setTempo(m_stretch_ratio);
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt
index a5e71d879..845626fc5 100644
--- a/src/common/CMakeLists.txt
+++ b/src/common/CMakeLists.txt
@@ -44,6 +44,7 @@ add_library(common STATIC
detached_tasks.cpp
detached_tasks.h
bit_field.h
+ bit_util.h
cityhash.cpp
cityhash.h
color.h
diff --git a/src/common/bit_util.h b/src/common/bit_util.h
new file mode 100644
index 000000000..1eea17ba1
--- /dev/null
+++ b/src/common/bit_util.h
@@ -0,0 +1,61 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <climits>
+#include <cstddef>
+
+#ifdef _MSC_VER
+#include <intrin.h>
+#endif
+
+#include "common/common_types.h"
+
+namespace Common {
+
+/// Gets the size of a specified type T in bits.
+template <typename T>
+constexpr std::size_t BitSize() {
+ return sizeof(T) * CHAR_BIT;
+}
+
+#ifdef _MSC_VER
+inline u32 CountLeadingZeroes32(u32 value) {
+ unsigned long leading_zero = 0;
+
+ if (_BitScanReverse(&leading_zero, value) != 0) {
+ return 31 - leading_zero;
+ }
+
+ return 32;
+}
+
+inline u64 CountLeadingZeroes64(u64 value) {
+ unsigned long leading_zero = 0;
+
+ if (_BitScanReverse64(&leading_zero, value) != 0) {
+ return 63 - leading_zero;
+ }
+
+ return 64;
+}
+#else
+inline u32 CountLeadingZeroes32(u32 value) {
+ if (value == 0) {
+ return 32;
+ }
+
+ return __builtin_clz(value);
+}
+
+inline u64 CountLeadingZeroes64(u64 value) {
+ if (value == 0) {
+ return 64;
+ }
+
+ return __builtin_clzll(value);
+}
+#endif
+} // namespace Common
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 5753b871a..12f6d0114 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -13,7 +13,7 @@
#include <vector>
#ifdef _WIN32
#include <share.h> // For _SH_DENYWR
-#include <windows.h> // For OutputDebugStringA
+#include <windows.h> // For OutputDebugStringW
#else
#define _SH_DENYWR 0
#endif
@@ -148,7 +148,7 @@ void FileBackend::Write(const Entry& entry) {
void DebuggerBackend::Write(const Entry& entry) {
#ifdef _WIN32
- ::OutputDebugStringA(FormatLogMessage(entry).append(1, '\n').c_str());
+ ::OutputDebugStringW(Common::UTF8ToUTF16W(FormatLogMessage(entry).append(1, '\n')).c_str());
#endif
}
diff --git a/src/common/quaternion.h b/src/common/quaternion.h
index ea39298c1..c528c0b68 100644
--- a/src/common/quaternion.h
+++ b/src/common/quaternion.h
@@ -12,7 +12,7 @@ template <typename T>
class Quaternion {
public:
Math::Vec3<T> xyz;
- T w;
+ T w{};
Quaternion<decltype(-T{})> Inverse() const {
return {-xyz, w};
diff --git a/src/common/thread_queue_list.h b/src/common/thread_queue_list.h
index 133122c5f..e7594db68 100644
--- a/src/common/thread_queue_list.h
+++ b/src/common/thread_queue_list.h
@@ -49,6 +49,22 @@ struct ThreadQueueList {
return T();
}
+ template <typename UnaryPredicate>
+ T get_first_filter(UnaryPredicate filter) const {
+ const Queue* cur = first;
+ while (cur != nullptr) {
+ if (!cur->data.empty()) {
+ for (const auto& item : cur->data) {
+ if (filter(item))
+ return item;
+ }
+ }
+ cur = cur->next_nonempty;
+ }
+
+ return T();
+ }
+
T pop_first() {
Queue* cur = first;
while (cur != nullptr) {
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index e1f21a764..965c28787 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -1,5 +1,6 @@
add_library(core STATIC
arm/arm_interface.h
+ arm/arm_interface.cpp
arm/exclusive_monitor.cpp
arm/exclusive_monitor.h
arm/unicorn/arm_unicorn.cpp
@@ -63,6 +64,10 @@ add_library(core STATIC
file_sys/sdmc_factory.h
file_sys/submission_package.cpp
file_sys/submission_package.h
+ file_sys/system_archive/ng_word.cpp
+ file_sys/system_archive/ng_word.h
+ file_sys/system_archive/system_archive.cpp
+ file_sys/system_archive/system_archive.h
file_sys/vfs.cpp
file_sys/vfs.h
file_sys/vfs_concat.cpp
@@ -79,13 +84,19 @@ add_library(core STATIC
file_sys/vfs_vector.h
file_sys/xts_archive.cpp
file_sys/xts_archive.h
+ frontend/applets/profile_select.cpp
+ frontend/applets/profile_select.h
frontend/applets/software_keyboard.cpp
frontend/applets/software_keyboard.h
+ frontend/applets/web_browser.cpp
+ frontend/applets/web_browser.h
frontend/emu_window.cpp
frontend/emu_window.h
frontend/framebuffer_layout.cpp
frontend/framebuffer_layout.h
frontend/input.h
+ frontend/scope_acquire_window_context.cpp
+ frontend/scope_acquire_window_context.h
gdbstub/gdbstub.cpp
gdbstub/gdbstub.h
hle/ipc.h
@@ -97,8 +108,6 @@ add_library(core STATIC
hle/kernel/client_session.cpp
hle/kernel/client_session.h
hle/kernel/errors.h
- hle/kernel/event.cpp
- hle/kernel/event.h
hle/kernel/handle_table.cpp
hle/kernel/handle_table.h
hle/kernel/hle_ipc.cpp
@@ -111,6 +120,10 @@ add_library(core STATIC
hle/kernel/object.h
hle/kernel/process.cpp
hle/kernel/process.h
+ hle/kernel/process_capability.cpp
+ hle/kernel/process_capability.h
+ hle/kernel/readable_event.cpp
+ hle/kernel/readable_event.h
hle/kernel/resource_limit.cpp
hle/kernel/resource_limit.h
hle/kernel/scheduler.cpp
@@ -133,6 +146,8 @@ add_library(core STATIC
hle/kernel/vm_manager.h
hle/kernel/wait_object.cpp
hle/kernel/wait_object.h
+ hle/kernel/writable_event.cpp
+ hle/kernel/writable_event.h
hle/lock.cpp
hle/lock.h
hle/result.h
@@ -156,10 +171,14 @@ add_library(core STATIC
hle/service/am/applet_oe.h
hle/service/am/applets/applets.cpp
hle/service/am/applets/applets.h
+ hle/service/am/applets/profile_select.cpp
+ hle/service/am/applets/profile_select.h
hle/service/am/applets/software_keyboard.cpp
hle/service/am/applets/software_keyboard.h
hle/service/am/applets/stub_applet.cpp
hle/service/am/applets/stub_applet.h
+ hle/service/am/applets/web_browser.cpp
+ hle/service/am/applets/web_browser.h
hle/service/am/idle.cpp
hle/service/am/idle.h
hle/service/am/omm.cpp
diff --git a/src/core/arm/arm_interface.cpp b/src/core/arm/arm_interface.cpp
new file mode 100644
index 000000000..2223cbeed
--- /dev/null
+++ b/src/core/arm/arm_interface.cpp
@@ -0,0 +1,27 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/common_types.h"
+#include "common/logging/log.h"
+#include "core/arm/arm_interface.h"
+#include "core/memory.h"
+
+namespace Core {
+void ARM_Interface::LogBacktrace() const {
+ VAddr fp = GetReg(29);
+ VAddr lr = GetReg(30);
+ const VAddr sp = GetReg(13);
+ const VAddr pc = GetPC();
+
+ LOG_ERROR(Core_ARM, "Backtrace, sp={:016X}, pc={:016X}", sp, pc);
+ while (true) {
+ LOG_ERROR(Core_ARM, "{:016X}", lr);
+ if (!fp) {
+ break;
+ }
+ lr = Memory::Read64(fp + 8) - 4;
+ fp = Memory::Read64(fp);
+ }
+}
+} // namespace Core
diff --git a/src/core/arm/arm_interface.h b/src/core/arm/arm_interface.h
index 59da33f30..4dfd41b43 100644
--- a/src/core/arm/arm_interface.h
+++ b/src/core/arm/arm_interface.h
@@ -141,6 +141,14 @@ public:
/// Prepare core for thread reschedule (if needed to correctly handle state)
virtual void PrepareReschedule() = 0;
+
+ /// fp (= r29) points to the last frame record.
+ /// Note that this is the frame record for the *previous* frame, not the current one.
+ /// Note we need to subtract 4 from our last read to get the proper address
+ /// Frame records are two words long:
+ /// fp+0 : pointer to previous frame record
+ /// fp+8 : value of lr for frame
+ void LogBacktrace() const;
};
} // namespace Core
diff --git a/src/core/arm/dynarmic/arm_dynarmic.cpp b/src/core/arm/dynarmic/arm_dynarmic.cpp
index 4d2491870..afbda8d8b 100644
--- a/src/core/arm/dynarmic/arm_dynarmic.cpp
+++ b/src/core/arm/dynarmic/arm_dynarmic.cpp
@@ -151,6 +151,7 @@ std::unique_ptr<Dynarmic::A64::Jit> ARM_Dynarmic::MakeJit() const {
config.tpidr_el0 = &cb->tpidr_el0;
config.dczid_el0 = 4;
config.ctr_el0 = 0x8444c004;
+ config.cntfrq_el0 = 19200000; // Value from fusee.
// Unpredictable instructions
config.define_unpredictable_behaviour = true;
diff --git a/src/core/arm/unicorn/arm_unicorn.cpp b/src/core/arm/unicorn/arm_unicorn.cpp
index ded4dd359..c455c81fb 100644
--- a/src/core/arm/unicorn/arm_unicorn.cpp
+++ b/src/core/arm/unicorn/arm_unicorn.cpp
@@ -10,6 +10,7 @@
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/kernel/svc.h"
+#include "core/memory.h"
namespace Core {
diff --git a/src/core/core.cpp b/src/core/core.cpp
index 795fabc65..572814e4b 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -8,6 +8,7 @@
#include <thread>
#include <utility>
+#include "common/file_util.h"
#include "common/logging/log.h"
#include "common/string_util.h"
#include "core/arm/exclusive_monitor.h"
@@ -29,8 +30,11 @@
#include "core/hle/service/sm/sm.h"
#include "core/loader/loader.h"
#include "core/perf_stats.h"
+#include "core/settings.h"
#include "core/telemetry_session.h"
+#include "frontend/applets/profile_select.h"
#include "frontend/applets/software_keyboard.h"
+#include "frontend/applets/web_browser.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/gpu.h"
#include "video_core/renderer_base.h"
@@ -40,7 +44,6 @@ namespace Core {
/*static*/ System System::s_instance;
-namespace {
FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
const std::string& path) {
// To account for split 00+01+etc files.
@@ -69,11 +72,13 @@ FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
}
+ if (FileUtil::IsDirectory(path))
+ return vfs->OpenFile(path + "/" + "main", FileSys::Mode::Read);
+
return vfs->OpenFile(path, FileSys::Mode::Read);
}
-} // Anonymous namespace
-
struct System::Impl {
+
Cpu& CurrentCpuCore() {
return cpu_core_manager.GetCurrentCore();
}
@@ -92,13 +97,22 @@ struct System::Impl {
CoreTiming::Init();
kernel.Initialize();
+ const auto current_time = std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch());
+ Settings::values.custom_rtc_differential =
+ Settings::values.custom_rtc.value_or(current_time) - current_time;
+
// Create a default fs if one doesn't already exist.
if (virtual_filesystem == nullptr)
virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
/// Create default implementations of applets if one is not provided.
+ if (profile_selector == nullptr)
+ profile_selector = std::make_unique<Core::Frontend::DefaultProfileSelectApplet>();
if (software_keyboard == nullptr)
software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
+ if (web_browser == nullptr)
+ web_browser = std::make_unique<Core::Frontend::DefaultWebBrowserApplet>();
auto main_process = Kernel::Process::Create(kernel, "main");
kernel.MakeCurrentProcess(main_process.get());
@@ -195,6 +209,11 @@ struct System::Impl {
// Close app loader
app_loader.reset();
+ // Clear all applets
+ profile_selector.reset();
+ software_keyboard.reset();
+ web_browser.reset();
+
LOG_DEBUG(Core, "Shutdown OK");
}
@@ -227,7 +246,9 @@ struct System::Impl {
bool is_powered_on = false;
/// Frontend applets
+ std::unique_ptr<Core::Frontend::ProfileSelectApplet> profile_selector;
std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
+ std::unique_ptr<Core::Frontend::WebBrowserApplet> web_browser;
/// Service manager
std::shared_ptr<Service::SM::ServiceManager> service_manager;
@@ -422,14 +443,34 @@ std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
return impl->virtual_filesystem;
}
-void System::SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet) {
+void System::SetProfileSelector(std::unique_ptr<Frontend::ProfileSelectApplet> applet) {
+ impl->profile_selector = std::move(applet);
+}
+
+const Frontend::ProfileSelectApplet& System::GetProfileSelector() const {
+ return *impl->profile_selector;
+}
+
+void System::SetSoftwareKeyboard(std::unique_ptr<Frontend::SoftwareKeyboardApplet> applet) {
impl->software_keyboard = std::move(applet);
}
-const Core::Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
+const Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
return *impl->software_keyboard;
}
+void System::SetWebBrowser(std::unique_ptr<Frontend::WebBrowserApplet> applet) {
+ impl->web_browser = std::move(applet);
+}
+
+Frontend::WebBrowserApplet& System::GetWebBrowser() {
+ return *impl->web_browser;
+}
+
+const Frontend::WebBrowserApplet& System::GetWebBrowser() const {
+ return *impl->web_browser;
+}
+
System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
return impl->Init(*this, emu_window);
}
diff --git a/src/core/core.h b/src/core/core.h
index be71bd437..511a5ad3a 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -9,11 +9,14 @@
#include <string>
#include "common/common_types.h"
+#include "core/file_sys/vfs_types.h"
#include "core/hle/kernel/object.h"
namespace Core::Frontend {
class EmuWindow;
+class ProfileSelectApplet;
class SoftwareKeyboardApplet;
+class WebBrowserApplet;
} // namespace Core::Frontend
namespace FileSys {
@@ -55,6 +58,9 @@ class TelemetrySession;
struct PerfStatsResults;
+FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
+ const std::string& path);
+
class System {
public:
System(const System&) = delete;
@@ -237,9 +243,18 @@ public:
std::shared_ptr<FileSys::VfsFilesystem> GetFilesystem() const;
- void SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet);
+ void SetProfileSelector(std::unique_ptr<Frontend::ProfileSelectApplet> applet);
+
+ const Frontend::ProfileSelectApplet& GetProfileSelector() const;
+
+ void SetSoftwareKeyboard(std::unique_ptr<Frontend::SoftwareKeyboardApplet> applet);
+
+ const Frontend::SoftwareKeyboardApplet& GetSoftwareKeyboard() const;
+
+ void SetWebBrowser(std::unique_ptr<Frontend::WebBrowserApplet> applet);
- const Core::Frontend::SoftwareKeyboardApplet& GetSoftwareKeyboard() const;
+ Frontend::WebBrowserApplet& GetWebBrowser();
+ const Frontend::WebBrowserApplet& GetWebBrowser() const;
private:
System();
diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp
index 904afa039..ca12fb4ab 100644
--- a/src/core/crypto/key_manager.cpp
+++ b/src/core/crypto/key_manager.cpp
@@ -246,7 +246,6 @@ std::vector<TicketRaw> GetTicketblob(const FileUtil::IOFile& ticket_save) {
}
std::vector<TicketRaw> out;
- u32 magic{};
for (std::size_t offset = 0; offset + 0x4 < buffer.size(); ++offset) {
if (buffer[offset] == 0x4 && buffer[offset + 1] == 0x0 && buffer[offset + 2] == 0x1 &&
buffer[offset + 3] == 0x0) {
@@ -794,7 +793,7 @@ void KeyManager::DeriveBase() {
void KeyManager::DeriveETicket(PartitionDataManager& data) {
// ETicket keys
- const auto es = Service::FileSystem::GetUnionContents()->GetEntry(
+ const auto es = Service::FileSystem::GetUnionContents().GetEntry(
0x0100000000000033, FileSys::ContentRecordType::Program);
if (es == nullptr)
diff --git a/src/core/file_sys/content_archive.cpp b/src/core/file_sys/content_archive.cpp
index 19b6f8600..5aa3b600b 100644
--- a/src/core/file_sys/content_archive.cpp
+++ b/src/core/file_sys/content_archive.cpp
@@ -359,6 +359,8 @@ bool NCA::ReadPFS0Section(const NCASectionHeader& section, const NCASectionTable
dirs.push_back(std::move(npfs));
if (IsDirectoryExeFS(dirs.back()))
exefs = dirs.back();
+ else if (IsDirectoryLogoPartition(dirs.back()))
+ logo = dirs.back();
} else {
if (has_rights_id)
status = Loader::ResultStatus::ErrorIncorrectTitlekeyOrTitlekek;
@@ -546,4 +548,8 @@ u64 NCA::GetBaseIVFCOffset() const {
return ivfc_offset;
}
+VirtualDir NCA::GetLogoPartition() const {
+ return logo;
+}
+
} // namespace FileSys
diff --git a/src/core/file_sys/content_archive.h b/src/core/file_sys/content_archive.h
index 99294cbb4..5d4d05c82 100644
--- a/src/core/file_sys/content_archive.h
+++ b/src/core/file_sys/content_archive.h
@@ -74,6 +74,13 @@ inline bool IsDirectoryExeFS(const std::shared_ptr<VfsDirectory>& pfs) {
return pfs->GetFile("main") != nullptr && pfs->GetFile("main.npdm") != nullptr;
}
+inline bool IsDirectoryLogoPartition(const VirtualDir& pfs) {
+ // NintendoLogo is the static image in the top left corner while StartupMovie is the animation
+ // in the bottom right corner.
+ return pfs->GetFile("NintendoLogo.png") != nullptr &&
+ pfs->GetFile("StartupMovie.gif") != nullptr;
+}
+
// An implementation of VfsDirectory that represents a Nintendo Content Archive (NCA) conatiner.
// After construction, use GetStatus to determine if the file is valid and ready to be used.
class NCA : public ReadOnlyVfsDirectory {
@@ -102,6 +109,8 @@ public:
// Returns the base ivfc offset used in BKTR patching.
u64 GetBaseIVFCOffset() const;
+ VirtualDir GetLogoPartition() const;
+
private:
bool CheckSupportedNCA(const NCAHeader& header);
bool HandlePotentialHeaderDecryption();
@@ -122,6 +131,7 @@ private:
VirtualFile romfs = nullptr;
VirtualDir exefs = nullptr;
+ VirtualDir logo = nullptr;
VirtualFile file;
VirtualFile bktr_base_romfs;
u64 ivfc_offset = 0;
diff --git a/src/core/file_sys/control_metadata.cpp b/src/core/file_sys/control_metadata.cpp
index e065e592f..83c184750 100644
--- a/src/core/file_sys/control_metadata.cpp
+++ b/src/core/file_sys/control_metadata.cpp
@@ -36,18 +36,20 @@ std::string LanguageEntry::GetDeveloperName() const {
developer_name.size());
}
-NACP::NACP(VirtualFile file) : raw(std::make_unique<RawNACP>()) {
- file->ReadObject(raw.get());
+NACP::NACP() = default;
+
+NACP::NACP(VirtualFile file) {
+ file->ReadObject(&raw);
}
NACP::~NACP() = default;
const LanguageEntry& NACP::GetLanguageEntry(Language language) const {
if (language != Language::Default) {
- return raw->language_entries.at(static_cast<u8>(language));
+ return raw.language_entries.at(static_cast<u8>(language));
}
- for (const auto& language_entry : raw->language_entries) {
+ for (const auto& language_entry : raw.language_entries) {
if (!language_entry.GetApplicationName().empty())
return language_entry;
}
@@ -65,21 +67,29 @@ std::string NACP::GetDeveloperName(Language language) const {
}
u64 NACP::GetTitleId() const {
- return raw->title_id;
+ return raw.title_id;
}
u64 NACP::GetDLCBaseTitleId() const {
- return raw->dlc_base_title_id;
+ return raw.dlc_base_title_id;
}
std::string NACP::GetVersionString() const {
- return Common::StringFromFixedZeroTerminatedBuffer(raw->version_string.data(),
- raw->version_string.size());
+ return Common::StringFromFixedZeroTerminatedBuffer(raw.version_string.data(),
+ raw.version_string.size());
+}
+
+u64 NACP::GetDefaultNormalSaveSize() const {
+ return raw.normal_save_data_size;
+}
+
+u64 NACP::GetDefaultJournalSaveSize() const {
+ return raw.journal_sava_data_size;
}
std::vector<u8> NACP::GetRawBytes() const {
std::vector<u8> out(sizeof(RawNACP));
- std::memcpy(out.data(), raw.get(), sizeof(RawNACP));
+ std::memcpy(out.data(), &raw, sizeof(RawNACP));
return out;
}
} // namespace FileSys
diff --git a/src/core/file_sys/control_metadata.h b/src/core/file_sys/control_metadata.h
index bfaad46b4..7b9cdc910 100644
--- a/src/core/file_sys/control_metadata.h
+++ b/src/core/file_sys/control_metadata.h
@@ -28,17 +28,30 @@ static_assert(sizeof(LanguageEntry) == 0x300, "LanguageEntry has incorrect size.
// The raw file format of a NACP file.
struct RawNACP {
std::array<LanguageEntry, 16> language_entries;
- INSERT_PADDING_BYTES(0x38);
+ std::array<u8, 0x25> isbn;
+ u8 startup_user_account;
+ INSERT_PADDING_BYTES(2);
+ u32_le application_attribute;
+ u32_le supported_languages;
+ u32_le parental_control;
+ bool screenshot_enabled;
+ u8 video_capture_mode;
+ bool data_loss_confirmation;
+ INSERT_PADDING_BYTES(1);
u64_le title_id;
- INSERT_PADDING_BYTES(0x20);
+ std::array<u8, 0x20> rating_age;
std::array<char, 0x10> version_string;
u64_le dlc_base_title_id;
u64_le title_id_2;
- INSERT_PADDING_BYTES(0x28);
+ u64_le normal_save_data_size;
+ u64_le journal_sava_data_size;
+ INSERT_PADDING_BYTES(0x18);
u64_le product_code;
- u64_le title_id_3;
- std::array<u64_le, 0x7> title_id_array;
- INSERT_PADDING_BYTES(0x8);
+ std::array<u64_le, 0x8> local_communication;
+ u8 logo_type;
+ u8 logo_handling;
+ bool runtime_add_on_content_install;
+ INSERT_PADDING_BYTES(5);
u64_le title_id_update;
std::array<u8, 0x40> bcat_passphrase;
INSERT_PADDING_BYTES(0xEC0);
@@ -72,6 +85,7 @@ extern const std::array<const char*, 15> LANGUAGE_NAMES;
// These store application name, dev name, title id, and other miscellaneous data.
class NACP {
public:
+ explicit NACP();
explicit NACP(VirtualFile file);
~NACP();
@@ -81,10 +95,12 @@ public:
u64 GetTitleId() const;
u64 GetDLCBaseTitleId() const;
std::string GetVersionString() const;
+ u64 GetDefaultNormalSaveSize() const;
+ u64 GetDefaultJournalSaveSize() const;
std::vector<u8> GetRawBytes() const;
private:
- std::unique_ptr<RawNACP> raw;
+ RawNACP raw{};
};
} // namespace FileSys
diff --git a/src/core/file_sys/directory.h b/src/core/file_sys/directory.h
index 12bb90ec8..7b5c509fb 100644
--- a/src/core/file_sys/directory.h
+++ b/src/core/file_sys/directory.h
@@ -29,8 +29,8 @@ struct Entry {
filename[copy_size] = '\0';
}
- char filename[0x300];
- INSERT_PADDING_BYTES(4);
+ char filename[0x301];
+ INSERT_PADDING_BYTES(3);
EntryType type;
INSERT_PADDING_BYTES(3);
u64 file_size;
@@ -39,27 +39,4 @@ static_assert(sizeof(Entry) == 0x310, "Directory Entry struct isn't exactly 0x31
static_assert(offsetof(Entry, type) == 0x304, "Wrong offset for type in Entry.");
static_assert(offsetof(Entry, file_size) == 0x308, "Wrong offset for file_size in Entry.");
-class DirectoryBackend : NonCopyable {
-public:
- DirectoryBackend() {}
- virtual ~DirectoryBackend() {}
-
- /**
- * List files contained in the directory
- * @param count Number of entries to return at once in entries
- * @param entries Buffer to read data into
- * @return Number of entries listed
- */
- virtual u64 Read(const u64 count, Entry* entries) = 0;
-
- /// Returns the number of entries still left to read.
- virtual u64 GetEntryCount() const = 0;
-
- /**
- * Close the directory
- * @return true if the directory closed correctly
- */
- virtual bool Close() const = 0;
-};
-
} // namespace FileSys
diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp
index e8df08724..61706966e 100644
--- a/src/core/file_sys/patch_manager.cpp
+++ b/src/core/file_sys/patch_manager.cpp
@@ -56,6 +56,10 @@ PatchManager::PatchManager(u64 title_id) : title_id(title_id) {}
PatchManager::~PatchManager() = default;
+u64 PatchManager::GetTitleID() const {
+ return title_id;
+}
+
VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
LOG_INFO(Loader, "Patching ExeFS for title_id={:016X}", title_id);
@@ -73,14 +77,18 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
const auto installed = Service::FileSystem::GetUnionContents();
+ const auto& disabled = Settings::values.disabled_addons[title_id];
+ const auto update_disabled =
+ std::find(disabled.begin(), disabled.end(), "Update") != disabled.end();
+
// Game Updates
const auto update_tid = GetUpdateTitleID(title_id);
- const auto update = installed->GetEntry(update_tid, ContentRecordType::Program);
+ const auto update = installed.GetEntry(update_tid, ContentRecordType::Program);
- if (update != nullptr && update->GetExeFS() != nullptr &&
+ if (!update_disabled && update != nullptr && update->GetExeFS() != nullptr &&
update->GetStatus() == Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
LOG_INFO(Loader, " ExeFS: Update ({}) applied successfully",
- FormatTitleVersion(installed->GetEntryVersion(update_tid).value_or(0)));
+ FormatTitleVersion(installed.GetEntryVersion(update_tid).value_or(0)));
exefs = update->GetExeFS();
}
@@ -95,6 +103,9 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
std::vector<VirtualDir> layers;
layers.reserve(patch_dirs.size() + 1);
for (const auto& subdir : patch_dirs) {
+ if (std::find(disabled.begin(), disabled.end(), subdir->GetName()) != disabled.end())
+ continue;
+
auto exefs_dir = subdir->GetSubdirectory("exefs");
if (exefs_dir != nullptr)
layers.push_back(std::move(exefs_dir));
@@ -111,11 +122,16 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
return exefs;
}
-static std::vector<VirtualFile> CollectPatches(const std::vector<VirtualDir>& patch_dirs,
- const std::string& build_id) {
+std::vector<VirtualFile> PatchManager::CollectPatches(const std::vector<VirtualDir>& patch_dirs,
+ const std::string& build_id) const {
+ const auto& disabled = Settings::values.disabled_addons[title_id];
+
std::vector<VirtualFile> out;
out.reserve(patch_dirs.size());
for (const auto& subdir : patch_dirs) {
+ if (std::find(disabled.begin(), disabled.end(), subdir->GetName()) != disabled.end())
+ continue;
+
auto exefs_dir = subdir->GetSubdirectory("exefs");
if (exefs_dir != nullptr) {
for (const auto& file : exefs_dir->GetFiles()) {
@@ -228,6 +244,7 @@ static void ApplyLayeredFS(VirtualFile& romfs, u64 title_id, ContentRecordType t
return;
}
+ const auto& disabled = Settings::values.disabled_addons[title_id];
auto patch_dirs = load_dir->GetSubdirectories();
std::sort(patch_dirs.begin(), patch_dirs.end(),
[](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); });
@@ -237,6 +254,9 @@ static void ApplyLayeredFS(VirtualFile& romfs, u64 title_id, ContentRecordType t
layers.reserve(patch_dirs.size() + 1);
layers_ext.reserve(patch_dirs.size() + 1);
for (const auto& subdir : patch_dirs) {
+ if (std::find(disabled.begin(), disabled.end(), subdir->GetName()) != disabled.end())
+ continue;
+
auto romfs_dir = subdir->GetSubdirectory("romfs");
if (romfs_dir != nullptr)
layers.push_back(std::move(romfs_dir));
@@ -266,13 +286,12 @@ static void ApplyLayeredFS(VirtualFile& romfs, u64 title_id, ContentRecordType t
VirtualFile PatchManager::PatchRomFS(VirtualFile romfs, u64 ivfc_offset, ContentRecordType type,
VirtualFile update_raw) const {
const auto log_string = fmt::format("Patching RomFS for title_id={:016X}, type={:02X}",
- title_id, static_cast<u8>(type))
- .c_str();
+ title_id, static_cast<u8>(type));
if (type == ContentRecordType::Program || type == ContentRecordType::Data)
- LOG_INFO(Loader, log_string);
+ LOG_INFO(Loader, "{}", log_string);
else
- LOG_DEBUG(Loader, log_string);
+ LOG_DEBUG(Loader, "{}", log_string);
if (romfs == nullptr)
return romfs;
@@ -281,16 +300,21 @@ VirtualFile PatchManager::PatchRomFS(VirtualFile romfs, u64 ivfc_offset, Content
// Game Updates
const auto update_tid = GetUpdateTitleID(title_id);
- const auto update = installed->GetEntryRaw(update_tid, type);
- if (update != nullptr) {
+ const auto update = installed.GetEntryRaw(update_tid, type);
+
+ const auto& disabled = Settings::values.disabled_addons[title_id];
+ const auto update_disabled =
+ std::find(disabled.begin(), disabled.end(), "Update") != disabled.end();
+
+ if (!update_disabled && update != nullptr) {
const auto new_nca = std::make_shared<NCA>(update, romfs, ivfc_offset);
if (new_nca->GetStatus() == Loader::ResultStatus::Success &&
new_nca->GetRomFS() != nullptr) {
LOG_INFO(Loader, " RomFS: Update ({}) applied successfully",
- FormatTitleVersion(installed->GetEntryVersion(update_tid).value_or(0)));
+ FormatTitleVersion(installed.GetEntryVersion(update_tid).value_or(0)));
romfs = new_nca->GetRomFS();
}
- } else if (update_raw != nullptr) {
+ } else if (!update_disabled && update_raw != nullptr) {
const auto new_nca = std::make_shared<NCA>(update_raw, romfs, ivfc_offset);
if (new_nca->GetStatus() == Loader::ResultStatus::Success &&
new_nca->GetRomFS() != nullptr) {
@@ -320,25 +344,30 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
VirtualFile update_raw) const {
std::map<std::string, std::string, std::less<>> out;
const auto installed = Service::FileSystem::GetUnionContents();
+ const auto& disabled = Settings::values.disabled_addons[title_id];
// Game Updates
const auto update_tid = GetUpdateTitleID(title_id);
PatchManager update{update_tid};
auto [nacp, discard_icon_file] = update.GetControlMetadata();
+ const auto update_disabled =
+ std::find(disabled.begin(), disabled.end(), "Update") != disabled.end();
+ const auto update_label = update_disabled ? "[D] Update" : "Update";
+
if (nacp != nullptr) {
- out.insert_or_assign("Update", nacp->GetVersionString());
+ out.insert_or_assign(update_label, nacp->GetVersionString());
} else {
- if (installed->HasEntry(update_tid, ContentRecordType::Program)) {
- const auto meta_ver = installed->GetEntryVersion(update_tid);
+ if (installed.HasEntry(update_tid, ContentRecordType::Program)) {
+ const auto meta_ver = installed.GetEntryVersion(update_tid);
if (meta_ver.value_or(0) == 0) {
- out.insert_or_assign("Update", "");
+ out.insert_or_assign(update_label, "");
} else {
out.insert_or_assign(
- "Update", FormatTitleVersion(*meta_ver, TitleVersionFormat::ThreeElements));
+ update_label, FormatTitleVersion(*meta_ver, TitleVersionFormat::ThreeElements));
}
} else if (update_raw != nullptr) {
- out.insert_or_assign("Update", "PACKED");
+ out.insert_or_assign(update_label, "PACKED");
}
}
@@ -378,19 +407,20 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
if (types.empty())
continue;
- out.insert_or_assign(mod->GetName(), types);
+ const auto mod_disabled =
+ std::find(disabled.begin(), disabled.end(), mod->GetName()) != disabled.end();
+ out.insert_or_assign(mod_disabled ? "[D] " + mod->GetName() : mod->GetName(), types);
}
}
// DLC
- const auto dlc_entries = installed->ListEntriesFilter(TitleType::AOC, ContentRecordType::Data);
+ const auto dlc_entries = installed.ListEntriesFilter(TitleType::AOC, ContentRecordType::Data);
std::vector<RegisteredCacheEntry> dlc_match;
dlc_match.reserve(dlc_entries.size());
std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
[this, &installed](const RegisteredCacheEntry& entry) {
return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == title_id &&
- installed->GetEntry(entry)->GetStatus() ==
- Loader::ResultStatus::Success;
+ installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
});
if (!dlc_match.empty()) {
// Ensure sorted so DLC IDs show in order.
@@ -402,7 +432,9 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
list += fmt::format("{}", dlc_match.back().title_id & 0x7FF);
- out.insert_or_assign("DLC", std::move(list));
+ const auto dlc_disabled =
+ std::find(disabled.begin(), disabled.end(), "DLC") != disabled.end();
+ out.insert_or_assign(dlc_disabled ? "[D] DLC" : "DLC", std::move(list));
}
return out;
@@ -411,7 +443,7 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
std::pair<std::unique_ptr<NACP>, VirtualFile> PatchManager::GetControlMetadata() const {
const auto installed{Service::FileSystem::GetUnionContents()};
- const auto base_control_nca = installed->GetEntry(title_id, ContentRecordType::Control);
+ const auto base_control_nca = installed.GetEntry(title_id, ContentRecordType::Control);
if (base_control_nca == nullptr)
return {};
diff --git a/src/core/file_sys/patch_manager.h b/src/core/file_sys/patch_manager.h
index 7d168837f..b8a1652fd 100644
--- a/src/core/file_sys/patch_manager.h
+++ b/src/core/file_sys/patch_manager.h
@@ -30,6 +30,8 @@ public:
explicit PatchManager(u64 title_id);
~PatchManager();
+ u64 GetTitleID() const;
+
// Currently tracked ExeFS patches:
// - Game Updates
VirtualDir PatchExeFS(VirtualDir exefs) const;
@@ -63,6 +65,9 @@ public:
std::pair<std::unique_ptr<NACP>, VirtualFile> ParseControlNCA(const NCA& nca) const;
private:
+ std::vector<VirtualFile> CollectPatches(const std::vector<VirtualDir>& patch_dirs,
+ const std::string& build_id) const;
+
u64 title_id;
};
diff --git a/src/core/file_sys/program_metadata.cpp b/src/core/file_sys/program_metadata.cpp
index 8903ed1d3..d3e00437f 100644
--- a/src/core/file_sys/program_metadata.cpp
+++ b/src/core/file_sys/program_metadata.cpp
@@ -40,6 +40,13 @@ Loader::ResultStatus ProgramMetadata::Load(VirtualFile file) {
if (sizeof(FileAccessHeader) != file->ReadObject(&aci_file_access, aci_header.fah_offset))
return Loader::ResultStatus::ErrorBadFileAccessHeader;
+ aci_kernel_capabilities.resize(aci_header.kac_size / sizeof(u32));
+ const u64 read_size = aci_header.kac_size;
+ const u64 read_offset = npdm_header.aci_offset + aci_header.kac_offset;
+ if (file->ReadBytes(aci_kernel_capabilities.data(), read_size, read_offset) != read_size) {
+ return Loader::ResultStatus::ErrorBadKernelCapabilityDescriptors;
+ }
+
return Loader::ResultStatus::Success;
}
@@ -71,6 +78,10 @@ u64 ProgramMetadata::GetFilesystemPermissions() const {
return aci_file_access.permissions;
}
+const ProgramMetadata::KernelCapabilityDescriptors& ProgramMetadata::GetKernelCapabilities() const {
+ return aci_kernel_capabilities;
+}
+
void ProgramMetadata::Print() const {
LOG_DEBUG(Service_FS, "Magic: {:.4}", npdm_header.magic.data());
LOG_DEBUG(Service_FS, "Main thread priority: 0x{:02X}", npdm_header.main_thread_priority);
@@ -81,16 +92,20 @@ void ProgramMetadata::Print() const {
LOG_DEBUG(Service_FS, " > 64-bit instructions: {}",
npdm_header.has_64_bit_instructions ? "YES" : "NO");
- auto address_space = "Unknown";
+ const char* address_space = "Unknown";
switch (npdm_header.address_space_type) {
case ProgramAddressSpaceType::Is36Bit:
+ address_space = "64-bit (36-bit address space)";
+ break;
case ProgramAddressSpaceType::Is39Bit:
- address_space = "64-bit";
+ address_space = "64-bit (39-bit address space)";
break;
case ProgramAddressSpaceType::Is32Bit:
- case ProgramAddressSpaceType::Is32BitNoMap:
address_space = "32-bit";
break;
+ case ProgramAddressSpaceType::Is32BitNoMap:
+ address_space = "32-bit (no map region)";
+ break;
}
LOG_DEBUG(Service_FS, " > Address space: {}\n", address_space);
diff --git a/src/core/file_sys/program_metadata.h b/src/core/file_sys/program_metadata.h
index e4470d6f0..0033ba347 100644
--- a/src/core/file_sys/program_metadata.h
+++ b/src/core/file_sys/program_metadata.h
@@ -5,6 +5,7 @@
#pragma once
#include <array>
+#include <vector>
#include "common/bit_field.h"
#include "common/common_types.h"
#include "common/swap.h"
@@ -38,6 +39,8 @@ enum class ProgramFilePermission : u64 {
*/
class ProgramMetadata {
public:
+ using KernelCapabilityDescriptors = std::vector<u32>;
+
ProgramMetadata();
~ProgramMetadata();
@@ -50,6 +53,7 @@ public:
u32 GetMainThreadStackSize() const;
u64 GetTitleID() const;
u64 GetFilesystemPermissions() const;
+ const KernelCapabilityDescriptors& GetKernelCapabilities() const;
void Print() const;
@@ -154,6 +158,8 @@ private:
FileAccessControl acid_file_access;
FileAccessHeader aci_file_access;
+
+ KernelCapabilityDescriptors aci_kernel_capabilities;
};
} // namespace FileSys
diff --git a/src/core/file_sys/registered_cache.cpp b/src/core/file_sys/registered_cache.cpp
index 07c3af64a..128199063 100644
--- a/src/core/file_sys/registered_cache.cpp
+++ b/src/core/file_sys/registered_cache.cpp
@@ -107,42 +107,41 @@ static ContentRecordType GetCRTypeFromNCAType(NCAContentType type) {
VirtualFile RegisteredCache::OpenFileOrDirectoryConcat(const VirtualDir& dir,
std::string_view path) const {
const auto file = dir->GetFileRelative(path);
- if (file != nullptr)
+ if (file != nullptr) {
return file;
+ }
const auto nca_dir = dir->GetDirectoryRelative(path);
- if (nca_dir != nullptr) {
- const auto nca_dir = dir->GetDirectoryRelative(path);
- VirtualFile file = nullptr;
+ if (nca_dir == nullptr) {
+ return nullptr;
+ }
- const auto files = nca_dir->GetFiles();
- if (files.size() == 1 && files[0]->GetName() == "00") {
- file = files[0];
+ const auto files = nca_dir->GetFiles();
+ if (files.size() == 1 && files[0]->GetName() == "00") {
+ return files[0];
+ }
+
+ std::vector<VirtualFile> concat;
+ // Since the files are a two-digit hex number, max is FF.
+ for (std::size_t i = 0; i < 0x100; ++i) {
+ auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
+ if (next != nullptr) {
+ concat.push_back(std::move(next));
} else {
- std::vector<VirtualFile> concat;
- // Since the files are a two-digit hex number, max is FF.
- for (std::size_t i = 0; i < 0x100; ++i) {
- auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
- if (next != nullptr) {
- concat.push_back(std::move(next));
- } else {
- next = nca_dir->GetFile(fmt::format("{:02x}", i));
- if (next != nullptr)
- concat.push_back(std::move(next));
- else
- break;
- }
+ next = nca_dir->GetFile(fmt::format("{:02x}", i));
+ if (next != nullptr) {
+ concat.push_back(std::move(next));
+ } else {
+ break;
}
-
- if (concat.empty())
- return nullptr;
-
- file = ConcatenatedVfsFile::MakeConcatenatedFile(concat, concat.front()->GetName());
}
+ }
- return file;
+ if (concat.empty()) {
+ return nullptr;
}
- return nullptr;
+
+ return ConcatenatedVfsFile::MakeConcatenatedFile(concat, concat.front()->GetName());
}
VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
diff --git a/src/core/file_sys/romfs.cpp b/src/core/file_sys/romfs.cpp
index 81e1f66ac..ebbdf081e 100644
--- a/src/core/file_sys/romfs.cpp
+++ b/src/core/file_sys/romfs.cpp
@@ -119,6 +119,9 @@ VirtualDir ExtractRomFS(VirtualFile file, RomFSExtractionType type) {
VirtualDir out = std::move(root);
+ if (type == RomFSExtractionType::SingleDiscard)
+ return out->GetSubdirectories().front();
+
while (out->GetSubdirectories().size() == 1 && out->GetFiles().empty()) {
if (out->GetSubdirectories().front()->GetName() == "data" &&
type == RomFSExtractionType::Truncated)
diff --git a/src/core/file_sys/romfs.h b/src/core/file_sys/romfs.h
index 0ec404731..0f35639bc 100644
--- a/src/core/file_sys/romfs.h
+++ b/src/core/file_sys/romfs.h
@@ -33,8 +33,9 @@ struct IVFCHeader {
static_assert(sizeof(IVFCHeader) == 0xE0, "IVFCHeader has incorrect size.");
enum class RomFSExtractionType {
- Full, // Includes data directory
- Truncated, // Traverses into data directory
+ Full, // Includes data directory
+ Truncated, // Traverses into data directory
+ SingleDiscard, // Traverses into the first subdirectory of root
};
// Converts a RomFS binary blob to VFS Filesystem
diff --git a/src/core/file_sys/romfs_factory.cpp b/src/core/file_sys/romfs_factory.cpp
index 0b645b106..6ad1e4f86 100644
--- a/src/core/file_sys/romfs_factory.cpp
+++ b/src/core/file_sys/romfs_factory.cpp
@@ -48,7 +48,7 @@ ResultVal<VirtualFile> RomFSFactory::Open(u64 title_id, StorageId storage, Conte
switch (storage) {
case StorageId::None:
- res = Service::FileSystem::GetUnionContents()->GetEntry(title_id, type);
+ res = Service::FileSystem::GetUnionContents().GetEntry(title_id, type);
break;
case StorageId::NandSystem:
res = Service::FileSystem::GetSystemNANDContents()->GetEntry(title_id, type);
diff --git a/src/core/file_sys/savedata_factory.cpp b/src/core/file_sys/savedata_factory.cpp
index 5434f2149..1913dc956 100644
--- a/src/core/file_sys/savedata_factory.cpp
+++ b/src/core/file_sys/savedata_factory.cpp
@@ -13,12 +13,18 @@
namespace FileSys {
+constexpr char SAVE_DATA_SIZE_FILENAME[] = ".yuzu_save_size";
+
std::string SaveDataDescriptor::DebugInfo() const {
return fmt::format("[type={:02X}, title_id={:016X}, user_id={:016X}{:016X}, save_id={:016X}]",
static_cast<u8>(type), title_id, user_id[1], user_id[0], save_id);
}
-SaveDataFactory::SaveDataFactory(VirtualDir save_directory) : dir(std::move(save_directory)) {}
+SaveDataFactory::SaveDataFactory(VirtualDir save_directory) : dir(std::move(save_directory)) {
+ // Delete all temporary storages
+ // On hardware, it is expected that temporary storage be empty at first use.
+ dir->DeleteSubdirectoryRecursive("temp");
+}
SaveDataFactory::~SaveDataFactory() = default;
@@ -120,9 +126,40 @@ std::string SaveDataFactory::GetFullPath(SaveDataSpaceId space, SaveDataType typ
case SaveDataType::TemporaryStorage:
return fmt::format("{}{:016X}/{:016X}{:016X}/{:016X}", out, 0, user_id[1], user_id[0],
title_id);
+ case SaveDataType::CacheStorage:
+ return fmt::format("{}save/cache/{:016X}", out, title_id);
default:
ASSERT_MSG(false, "Unrecognized SaveDataType: {:02X}", static_cast<u8>(type));
+ return fmt::format("{}save/unknown_{:X}/{:016X}", out, static_cast<u8>(type), title_id);
}
}
+SaveDataSize SaveDataFactory::ReadSaveDataSize(SaveDataType type, u64 title_id,
+ u128 user_id) const {
+ const auto path = GetFullPath(SaveDataSpaceId::NandUser, type, title_id, user_id, 0);
+ const auto dir = GetOrCreateDirectoryRelative(this->dir, path);
+
+ const auto size_file = dir->GetFile(SAVE_DATA_SIZE_FILENAME);
+ if (size_file == nullptr || size_file->GetSize() < sizeof(SaveDataSize))
+ return {0, 0};
+
+ SaveDataSize out;
+ if (size_file->ReadObject(&out) != sizeof(SaveDataSize))
+ return {0, 0};
+ return out;
+}
+
+void SaveDataFactory::WriteSaveDataSize(SaveDataType type, u64 title_id, u128 user_id,
+ SaveDataSize new_value) {
+ const auto path = GetFullPath(SaveDataSpaceId::NandUser, type, title_id, user_id, 0);
+ const auto dir = GetOrCreateDirectoryRelative(this->dir, path);
+
+ const auto size_file = dir->CreateFile(SAVE_DATA_SIZE_FILENAME);
+ if (size_file == nullptr)
+ return;
+
+ size_file->Resize(sizeof(SaveDataSize));
+ size_file->WriteObject(new_value);
+}
+
} // namespace FileSys
diff --git a/src/core/file_sys/savedata_factory.h b/src/core/file_sys/savedata_factory.h
index 2a0088040..3a1caf292 100644
--- a/src/core/file_sys/savedata_factory.h
+++ b/src/core/file_sys/savedata_factory.h
@@ -17,8 +17,10 @@ namespace FileSys {
enum class SaveDataSpaceId : u8 {
NandSystem = 0,
NandUser = 1,
- SdCard = 2,
+ SdCardSystem = 2,
TemporaryStorage = 3,
+ SdCardUser = 4,
+ ProperSystem = 100,
};
enum class SaveDataType : u8 {
@@ -44,6 +46,11 @@ struct SaveDataDescriptor {
};
static_assert(sizeof(SaveDataDescriptor) == 0x40, "SaveDataDescriptor has incorrect size.");
+struct SaveDataSize {
+ u64 normal;
+ u64 journal;
+};
+
/// File system interface to the SaveData archive
class SaveDataFactory {
public:
@@ -58,6 +65,9 @@ public:
static std::string GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
u128 user_id, u64 save_id);
+ SaveDataSize ReadSaveDataSize(SaveDataType type, u64 title_id, u128 user_id) const;
+ void WriteSaveDataSize(SaveDataType type, u64 title_id, u128 user_id, SaveDataSize new_value);
+
private:
VirtualDir dir;
};
diff --git a/src/core/file_sys/system_archive/ng_word.cpp b/src/core/file_sys/system_archive/ng_word.cpp
new file mode 100644
index 000000000..f4443784d
--- /dev/null
+++ b/src/core/file_sys/system_archive/ng_word.cpp
@@ -0,0 +1,81 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <fmt/format.h>
+#include "common/common_types.h"
+#include "core/file_sys/system_archive/ng_word.h"
+#include "core/file_sys/vfs_vector.h"
+
+namespace FileSys::SystemArchive {
+
+namespace NgWord1Data {
+
+constexpr std::size_t NUMBER_WORD_TXT_FILES = 0x10;
+
+// Should this archive replacement mysteriously not work on a future game, consider updating.
+constexpr std::array<u8, 4> VERSION_DAT{0x0, 0x0, 0x0, 0x19}; // 5.1.0 System Version
+
+constexpr std::array<u8, 30> WORD_TXT{
+ 0xFE, 0xFF, 0x00, 0x5E, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x79, 0x00, 0x62, 0x00,
+ 0x61, 0x00, 0x64, 0x00, 0x77, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x64, 0x00, 0x24, 0x00, 0x0A,
+}; // "^verybadword$" in UTF-16
+
+} // namespace NgWord1Data
+
+VirtualDir NgWord1() {
+ std::vector<VirtualFile> files(NgWord1Data::NUMBER_WORD_TXT_FILES);
+
+ for (std::size_t i = 0; i < files.size(); ++i) {
+ files[i] = std::make_shared<ArrayVfsFile<NgWord1Data::WORD_TXT.size()>>(
+ NgWord1Data::WORD_TXT, fmt::format("{}.txt", i));
+ }
+
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord1Data::WORD_TXT.size()>>(
+ NgWord1Data::WORD_TXT, "common.txt"));
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord1Data::VERSION_DAT.size()>>(
+ NgWord1Data::VERSION_DAT, "version.dat"));
+
+ return std::make_shared<VectorVfsDirectory>(files, std::vector<VirtualDir>{}, "data");
+}
+
+namespace NgWord2Data {
+
+constexpr std::size_t NUMBER_AC_NX_FILES = 0x10;
+
+// Should this archive replacement mysteriously not work on a future game, consider updating.
+constexpr std::array<u8, 4> VERSION_DAT{0x0, 0x0, 0x0, 0x15}; // 5.1.0 System Version
+
+constexpr std::array<u8, 0x2C> AC_NX_DATA{
+ 0x1F, 0x8B, 0x08, 0x08, 0xD5, 0x2C, 0x09, 0x5C, 0x04, 0x00, 0x61, 0x63, 0x72, 0x61, 0x77,
+ 0x00, 0xED, 0xC1, 0x01, 0x0D, 0x00, 0x00, 0x00, 0xC2, 0x20, 0xFB, 0xA7, 0xB6, 0xC7, 0x07,
+ 0x0C, 0x00, 0x00, 0x00, 0xC8, 0x3B, 0x11, 0x00, 0x1C, 0xC7, 0x00, 0x10, 0x00, 0x00,
+}; // Deserializes to no bad words
+
+} // namespace NgWord2Data
+
+VirtualDir NgWord2() {
+ std::vector<VirtualFile> files(NgWord2Data::NUMBER_AC_NX_FILES * 3);
+
+ for (std::size_t i = 0; i < NgWord2Data::NUMBER_AC_NX_FILES; ++i) {
+ files[3 * i] = std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, fmt::format("ac_{}_b1_nx", i));
+ files[3 * i + 1] = std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, fmt::format("ac_{}_b2_nx", i));
+ files[3 * i + 2] = std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, fmt::format("ac_{}_not_b_nx", i));
+ }
+
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, "ac_common_b1_nx"));
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, "ac_common_b2_nx"));
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord2Data::AC_NX_DATA.size()>>(
+ NgWord2Data::AC_NX_DATA, "ac_common_not_b_nx"));
+ files.push_back(std::make_shared<ArrayVfsFile<NgWord2Data::VERSION_DAT.size()>>(
+ NgWord2Data::VERSION_DAT, "version.dat"));
+
+ return std::make_shared<VectorVfsDirectory>(files, std::vector<VirtualDir>{}, "data");
+}
+
+} // namespace FileSys::SystemArchive
diff --git a/src/core/file_sys/system_archive/ng_word.h b/src/core/file_sys/system_archive/ng_word.h
new file mode 100644
index 000000000..cd81e0abb
--- /dev/null
+++ b/src/core/file_sys/system_archive/ng_word.h
@@ -0,0 +1,14 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "core/file_sys/vfs_types.h"
+
+namespace FileSys::SystemArchive {
+
+VirtualDir NgWord1();
+VirtualDir NgWord2();
+
+} // namespace FileSys::SystemArchive
diff --git a/src/core/file_sys/system_archive/system_archive.cpp b/src/core/file_sys/system_archive/system_archive.cpp
new file mode 100644
index 000000000..e3e79f40a
--- /dev/null
+++ b/src/core/file_sys/system_archive/system_archive.cpp
@@ -0,0 +1,90 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/logging/log.h"
+#include "core/file_sys/romfs.h"
+#include "core/file_sys/system_archive/ng_word.h"
+#include "core/file_sys/system_archive/system_archive.h"
+
+namespace FileSys::SystemArchive {
+
+constexpr u64 SYSTEM_ARCHIVE_BASE_TITLE_ID = 0x0100000000000800;
+constexpr std::size_t SYSTEM_ARCHIVE_COUNT = 0x28;
+
+using SystemArchiveSupplier = VirtualDir (*)();
+
+struct SystemArchiveDescriptor {
+ u64 title_id;
+ const char* name;
+ SystemArchiveSupplier supplier;
+};
+
+constexpr std::array<SystemArchiveDescriptor, SYSTEM_ARCHIVE_COUNT> SYSTEM_ARCHIVES{{
+ {0x0100000000000800, "CertStore", nullptr},
+ {0x0100000000000801, "ErrorMessage", nullptr},
+ {0x0100000000000802, "MiiModel", nullptr},
+ {0x0100000000000803, "BrowserDll", nullptr},
+ {0x0100000000000804, "Help", nullptr},
+ {0x0100000000000805, "SharedFont", nullptr},
+ {0x0100000000000806, "NgWord", &NgWord1},
+ {0x0100000000000807, "SsidList", nullptr},
+ {0x0100000000000808, "Dictionary", nullptr},
+ {0x0100000000000809, "SystemVersion", nullptr},
+ {0x010000000000080A, "AvatarImage", nullptr},
+ {0x010000000000080B, "LocalNews", nullptr},
+ {0x010000000000080C, "Eula", nullptr},
+ {0x010000000000080D, "UrlBlackList", nullptr},
+ {0x010000000000080E, "TimeZoneBinary", nullptr},
+ {0x010000000000080F, "CertStoreCruiser", nullptr},
+ {0x0100000000000810, "FontNintendoExtension", nullptr},
+ {0x0100000000000811, "FontStandard", nullptr},
+ {0x0100000000000812, "FontKorean", nullptr},
+ {0x0100000000000813, "FontChineseTraditional", nullptr},
+ {0x0100000000000814, "FontChineseSimple", nullptr},
+ {0x0100000000000815, "FontBfcpx", nullptr},
+ {0x0100000000000816, "SystemUpdate", nullptr},
+ {0x0100000000000817, "0100000000000817", nullptr},
+ {0x0100000000000818, "FirmwareDebugSettings", nullptr},
+ {0x0100000000000819, "BootImagePackage", nullptr},
+ {0x010000000000081A, "BootImagePackageSafe", nullptr},
+ {0x010000000000081B, "BootImagePackageExFat", nullptr},
+ {0x010000000000081C, "BootImagePackageExFatSafe", nullptr},
+ {0x010000000000081D, "FatalMessage", nullptr},
+ {0x010000000000081E, "ControllerIcon", nullptr},
+ {0x010000000000081F, "PlatformConfigIcosa", nullptr},
+ {0x0100000000000820, "PlatformConfigCopper", nullptr},
+ {0x0100000000000821, "PlatformConfigHoag", nullptr},
+ {0x0100000000000822, "ControllerFirmware", nullptr},
+ {0x0100000000000823, "NgWord2", &NgWord2},
+ {0x0100000000000824, "PlatformConfigIcosaMariko", nullptr},
+ {0x0100000000000825, "ApplicationBlackList", nullptr},
+ {0x0100000000000826, "RebootlessSystemUpdateVersion", nullptr},
+ {0x0100000000000827, "ContentActionTable", nullptr},
+}};
+
+VirtualFile SynthesizeSystemArchive(const u64 title_id) {
+ if (title_id < SYSTEM_ARCHIVES.front().title_id || title_id > SYSTEM_ARCHIVES.back().title_id)
+ return nullptr;
+
+ const auto& desc = SYSTEM_ARCHIVES[title_id - SYSTEM_ARCHIVE_BASE_TITLE_ID];
+
+ LOG_INFO(Service_FS, "Synthesizing system archive '{}' (0x{:016X}).", desc.name, desc.title_id);
+
+ if (desc.supplier == nullptr)
+ return nullptr;
+
+ const auto dir = desc.supplier();
+
+ if (dir == nullptr)
+ return nullptr;
+
+ const auto romfs = CreateRomFS(dir);
+
+ if (romfs == nullptr)
+ return nullptr;
+
+ LOG_INFO(Service_FS, " - System archive generation successful!");
+ return romfs;
+}
+} // namespace FileSys::SystemArchive
diff --git a/src/core/file_sys/system_archive/system_archive.h b/src/core/file_sys/system_archive/system_archive.h
new file mode 100644
index 000000000..724a8eb17
--- /dev/null
+++ b/src/core/file_sys/system_archive/system_archive.h
@@ -0,0 +1,14 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "common/common_types.h"
+#include "core/file_sys/vfs_types.h"
+
+namespace FileSys::SystemArchive {
+
+VirtualFile SynthesizeSystemArchive(u64 title_id);
+
+} // namespace FileSys::SystemArchive
diff --git a/src/core/file_sys/vfs.cpp b/src/core/file_sys/vfs.cpp
index 7b584de7f..e33327ef0 100644
--- a/src/core/file_sys/vfs.cpp
+++ b/src/core/file_sys/vfs.cpp
@@ -384,6 +384,28 @@ bool VfsDirectory::DeleteSubdirectoryRecursive(std::string_view name) {
return success;
}
+bool VfsDirectory::CleanSubdirectoryRecursive(std::string_view name) {
+ auto dir = GetSubdirectory(name);
+ if (dir == nullptr) {
+ return false;
+ }
+
+ bool success = true;
+ for (const auto& file : dir->GetFiles()) {
+ if (!dir->DeleteFile(file->GetName())) {
+ success = false;
+ }
+ }
+
+ for (const auto& sdir : dir->GetSubdirectories()) {
+ if (!dir->DeleteSubdirectoryRecursive(sdir->GetName())) {
+ success = false;
+ }
+ }
+
+ return success;
+}
+
bool VfsDirectory::Copy(std::string_view src, std::string_view dest) {
const auto f1 = GetFile(src);
auto f2 = CreateFile(dest);
@@ -431,10 +453,34 @@ std::shared_ptr<VfsFile> ReadOnlyVfsDirectory::CreateFile(std::string_view name)
return nullptr;
}
+std::shared_ptr<VfsFile> ReadOnlyVfsDirectory::CreateFileAbsolute(std::string_view path) {
+ return nullptr;
+}
+
+std::shared_ptr<VfsFile> ReadOnlyVfsDirectory::CreateFileRelative(std::string_view path) {
+ return nullptr;
+}
+
+std::shared_ptr<VfsDirectory> ReadOnlyVfsDirectory::CreateDirectoryAbsolute(std::string_view path) {
+ return nullptr;
+}
+
+std::shared_ptr<VfsDirectory> ReadOnlyVfsDirectory::CreateDirectoryRelative(std::string_view path) {
+ return nullptr;
+}
+
bool ReadOnlyVfsDirectory::DeleteSubdirectory(std::string_view name) {
return false;
}
+bool ReadOnlyVfsDirectory::DeleteSubdirectoryRecursive(std::string_view name) {
+ return false;
+}
+
+bool ReadOnlyVfsDirectory::CleanSubdirectoryRecursive(std::string_view name) {
+ return false;
+}
+
bool ReadOnlyVfsDirectory::DeleteFile(std::string_view name) {
return false;
}
diff --git a/src/core/file_sys/vfs.h b/src/core/file_sys/vfs.h
index 002f99d4e..954094772 100644
--- a/src/core/file_sys/vfs.h
+++ b/src/core/file_sys/vfs.h
@@ -150,7 +150,7 @@ public:
template <typename T>
std::size_t WriteArray(const T* data, std::size_t number_elements, std::size_t offset = 0) {
static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
- return Write(data, number_elements * sizeof(T), offset);
+ return Write(reinterpret_cast<const u8*>(data), number_elements * sizeof(T), offset);
}
// Writes size bytes starting at memory location data to offset in file.
@@ -166,7 +166,7 @@ public:
template <typename T>
std::size_t WriteObject(const T& data, std::size_t offset = 0) {
static_assert(std::is_trivially_copyable_v<T>, "Data type must be trivially copyable.");
- return Write(&data, sizeof(T), offset);
+ return Write(reinterpret_cast<const u8*>(&data), sizeof(T), offset);
}
// Renames the file to name. Returns whether or not the operation was successsful.
@@ -245,12 +245,18 @@ public:
// any failure.
virtual std::shared_ptr<VfsDirectory> CreateDirectoryAbsolute(std::string_view path);
- // Deletes the subdirectory with name and returns true on success.
+ // Deletes the subdirectory with the given name and returns true on success.
virtual bool DeleteSubdirectory(std::string_view name) = 0;
- // Deletes all subdirectories and files of subdirectory with name recirsively and then deletes
- // the subdirectory. Returns true on success.
+
+ // Deletes all subdirectories and files within the provided directory and then deletes
+ // the directory itself. Returns true on success.
virtual bool DeleteSubdirectoryRecursive(std::string_view name);
- // Returnes whether or not the file with name name was deleted successfully.
+
+ // Deletes all subdirectories and files within the provided directory.
+ // Unlike DeleteSubdirectoryRecursive, this does not delete the provided directory.
+ virtual bool CleanSubdirectoryRecursive(std::string_view name);
+
+ // Returns whether or not the file with name name was deleted successfully.
virtual bool DeleteFile(std::string_view name) = 0;
// Returns whether or not this directory was renamed to name.
@@ -276,7 +282,13 @@ public:
bool IsReadable() const override;
std::shared_ptr<VfsDirectory> CreateSubdirectory(std::string_view name) override;
std::shared_ptr<VfsFile> CreateFile(std::string_view name) override;
+ std::shared_ptr<VfsFile> CreateFileAbsolute(std::string_view path) override;
+ std::shared_ptr<VfsFile> CreateFileRelative(std::string_view path) override;
+ std::shared_ptr<VfsDirectory> CreateDirectoryAbsolute(std::string_view path) override;
+ std::shared_ptr<VfsDirectory> CreateDirectoryRelative(std::string_view path) override;
bool DeleteSubdirectory(std::string_view name) override;
+ bool DeleteSubdirectoryRecursive(std::string_view name) override;
+ bool CleanSubdirectoryRecursive(std::string_view name) override;
bool DeleteFile(std::string_view name) override;
bool Rename(std::string_view name) override;
};
diff --git a/src/core/file_sys/vfs_vector.cpp b/src/core/file_sys/vfs_vector.cpp
index 808f31e81..515626658 100644
--- a/src/core/file_sys/vfs_vector.cpp
+++ b/src/core/file_sys/vfs_vector.cpp
@@ -3,7 +3,6 @@
// Refer to the license.txt file included.
#include <algorithm>
-#include <cstring>
#include <utility>
#include "core/file_sys/vfs_vector.h"
diff --git a/src/core/file_sys/vfs_vector.h b/src/core/file_sys/vfs_vector.h
index 3e3f790c3..ac36cb2ee 100644
--- a/src/core/file_sys/vfs_vector.h
+++ b/src/core/file_sys/vfs_vector.h
@@ -4,10 +4,63 @@
#pragma once
+#include <cstring>
#include "core/file_sys/vfs.h"
namespace FileSys {
+// An implementation of VfsFile that is backed by a statically-sized array
+template <std::size_t size>
+class ArrayVfsFile : public VfsFile {
+public:
+ ArrayVfsFile(std::array<u8, size> data, std::string name = "", VirtualDir parent = nullptr)
+ : data(data), name(std::move(name)), parent(std::move(parent)) {}
+
+ std::string GetName() const override {
+ return name;
+ }
+
+ std::size_t GetSize() const override {
+ return size;
+ }
+
+ bool Resize(std::size_t new_size) override {
+ return false;
+ }
+
+ std::shared_ptr<VfsDirectory> GetContainingDirectory() const override {
+ return parent;
+ }
+
+ bool IsWritable() const override {
+ return false;
+ }
+
+ bool IsReadable() const override {
+ return true;
+ }
+
+ std::size_t Read(u8* data_, std::size_t length, std::size_t offset) const override {
+ const auto read = std::min(length, size - offset);
+ std::memcpy(data_, data.data() + offset, read);
+ return read;
+ }
+
+ std::size_t Write(const u8* data, std::size_t length, std::size_t offset) override {
+ return 0;
+ }
+
+ bool Rename(std::string_view name) override {
+ this->name = name;
+ return true;
+ }
+
+private:
+ std::array<u8, size> data;
+ std::string name;
+ VirtualDir parent;
+};
+
// An implementation of VfsFile that is backed by a vector optionally supplied upon construction
class VectorVfsFile : public VfsFile {
public:
diff --git a/src/core/frontend/applets/profile_select.cpp b/src/core/frontend/applets/profile_select.cpp
new file mode 100644
index 000000000..fbf5f2a9e
--- /dev/null
+++ b/src/core/frontend/applets/profile_select.cpp
@@ -0,0 +1,19 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "core/frontend/applets/profile_select.h"
+#include "core/settings.h"
+
+namespace Core::Frontend {
+
+ProfileSelectApplet::~ProfileSelectApplet() = default;
+
+void DefaultProfileSelectApplet::SelectProfile(
+ std::function<void(std::optional<Service::Account::UUID>)> callback) const {
+ Service::Account::ProfileManager manager;
+ callback(manager.GetUser(Settings::values.current_user).value_or(Service::Account::UUID{}));
+ LOG_INFO(Service_ACC, "called, selecting current user instead of prompting...");
+}
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/profile_select.h b/src/core/frontend/applets/profile_select.h
new file mode 100644
index 000000000..fc8f7ae94
--- /dev/null
+++ b/src/core/frontend/applets/profile_select.h
@@ -0,0 +1,27 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <functional>
+#include <optional>
+#include "core/hle/service/acc/profile_manager.h"
+
+namespace Core::Frontend {
+
+class ProfileSelectApplet {
+public:
+ virtual ~ProfileSelectApplet();
+
+ virtual void SelectProfile(
+ std::function<void(std::optional<Service::Account::UUID>)> callback) const = 0;
+};
+
+class DefaultProfileSelectApplet final : public ProfileSelectApplet {
+public:
+ void SelectProfile(
+ std::function<void(std::optional<Service::Account::UUID>)> callback) const override;
+};
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/web_browser.cpp b/src/core/frontend/applets/web_browser.cpp
new file mode 100644
index 000000000..3a3d3d0bf
--- /dev/null
+++ b/src/core/frontend/applets/web_browser.cpp
@@ -0,0 +1,24 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/logging/log.h"
+#include "core/frontend/applets/web_browser.h"
+
+namespace Core::Frontend {
+
+WebBrowserApplet::~WebBrowserApplet() = default;
+
+DefaultWebBrowserApplet::~DefaultWebBrowserApplet() = default;
+
+void DefaultWebBrowserApplet::OpenPage(std::string_view filename,
+ std::function<void()> unpack_romfs_callback,
+ std::function<void()> finished_callback) {
+ LOG_INFO(Service_AM,
+ "(STUBBED) called - No suitable web browser implementation found to open website page "
+ "at '{}'!",
+ filename);
+ finished_callback();
+}
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/web_browser.h b/src/core/frontend/applets/web_browser.h
new file mode 100644
index 000000000..f952856af
--- /dev/null
+++ b/src/core/frontend/applets/web_browser.h
@@ -0,0 +1,28 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <functional>
+#include <string_view>
+
+namespace Core::Frontend {
+
+class WebBrowserApplet {
+public:
+ virtual ~WebBrowserApplet();
+
+ virtual void OpenPage(std::string_view url, std::function<void()> unpack_romfs_callback,
+ std::function<void()> finished_callback) = 0;
+};
+
+class DefaultWebBrowserApplet final : public WebBrowserApplet {
+public:
+ ~DefaultWebBrowserApplet() override;
+
+ void OpenPage(std::string_view url, std::function<void()> unpack_romfs_callback,
+ std::function<void()> finished_callback) override;
+};
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/framebuffer_layout.cpp b/src/core/frontend/framebuffer_layout.cpp
index 8f07aedc9..f8662d193 100644
--- a/src/core/frontend/framebuffer_layout.cpp
+++ b/src/core/frontend/framebuffer_layout.cpp
@@ -6,6 +6,7 @@
#include "common/assert.h"
#include "core/frontend/framebuffer_layout.h"
+#include "core/settings.h"
namespace Layout {
@@ -42,4 +43,18 @@ FramebufferLayout DefaultFrameLayout(unsigned width, unsigned height) {
return res;
}
+FramebufferLayout FrameLayoutFromResolutionScale(u16 res_scale) {
+ int width, height;
+
+ if (Settings::values.use_docked_mode) {
+ width = ScreenDocked::WidthDocked * res_scale;
+ height = ScreenDocked::HeightDocked * res_scale;
+ } else {
+ width = ScreenUndocked::Width * res_scale;
+ height = ScreenUndocked::Height * res_scale;
+ }
+
+ return DefaultFrameLayout(width, height);
+}
+
} // namespace Layout
diff --git a/src/core/frontend/framebuffer_layout.h b/src/core/frontend/framebuffer_layout.h
index f3fddfa94..e06647794 100644
--- a/src/core/frontend/framebuffer_layout.h
+++ b/src/core/frontend/framebuffer_layout.h
@@ -9,6 +9,7 @@
namespace Layout {
enum ScreenUndocked : unsigned { Width = 1280, Height = 720 };
+enum ScreenDocked : unsigned { WidthDocked = 1920, HeightDocked = 1080 };
/// Describes the layout of the window framebuffer
struct FramebufferLayout {
@@ -34,4 +35,10 @@ struct FramebufferLayout {
*/
FramebufferLayout DefaultFrameLayout(unsigned width, unsigned height);
+/**
+ * Convenience method to get frame layout by resolution scale
+ * @param res_scale resolution scale factor
+ */
+FramebufferLayout FrameLayoutFromResolutionScale(u16 res_scale);
+
} // namespace Layout
diff --git a/src/core/frontend/scope_acquire_window_context.cpp b/src/core/frontend/scope_acquire_window_context.cpp
new file mode 100644
index 000000000..3663dad17
--- /dev/null
+++ b/src/core/frontend/scope_acquire_window_context.cpp
@@ -0,0 +1,18 @@
+// Copyright 2019 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "core/frontend/emu_window.h"
+#include "core/frontend/scope_acquire_window_context.h"
+
+namespace Core::Frontend {
+
+ScopeAcquireWindowContext::ScopeAcquireWindowContext(Core::Frontend::EmuWindow& emu_window_)
+ : emu_window{emu_window_} {
+ emu_window.MakeCurrent();
+}
+ScopeAcquireWindowContext::~ScopeAcquireWindowContext() {
+ emu_window.DoneCurrent();
+}
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/scope_acquire_window_context.h b/src/core/frontend/scope_acquire_window_context.h
new file mode 100644
index 000000000..2d9f6e825
--- /dev/null
+++ b/src/core/frontend/scope_acquire_window_context.h
@@ -0,0 +1,23 @@
+// Copyright 2019 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "common/common_types.h"
+
+namespace Core::Frontend {
+
+class EmuWindow;
+
+/// Helper class to acquire/release window context within a given scope
+class ScopeAcquireWindowContext : NonCopyable {
+public:
+ explicit ScopeAcquireWindowContext(Core::Frontend::EmuWindow& window);
+ ~ScopeAcquireWindowContext();
+
+private:
+ Core::Frontend::EmuWindow& emu_window;
+};
+
+} // namespace Core::Frontend
diff --git a/src/core/gdbstub/gdbstub.cpp b/src/core/gdbstub/gdbstub.cpp
index e6b5171ee..a1cad4fcb 100644
--- a/src/core/gdbstub/gdbstub.cpp
+++ b/src/core/gdbstub/gdbstub.cpp
@@ -201,11 +201,11 @@ void RegisterModule(std::string name, VAddr beg, VAddr end, bool add_elf_ext) {
modules.push_back(std::move(module));
}
-static Kernel::Thread* FindThreadById(int id) {
+static Kernel::Thread* FindThreadById(s64 id) {
for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
for (auto& thread : threads) {
- if (thread->GetThreadID() == static_cast<u32>(id)) {
+ if (thread->GetThreadID() == static_cast<u64>(id)) {
current_core = core;
return thread.get();
}
diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h
index 0a7142ada..90f276ee8 100644
--- a/src/core/hle/ipc_helpers.h
+++ b/src/core/hle/ipc_helpers.h
@@ -18,7 +18,7 @@
#include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/object.h"
-#include "core/hle/kernel/server_port.h"
+#include "core/hle/kernel/server_session.h"
namespace IPC {
@@ -217,6 +217,11 @@ private:
/// Push ///
template <>
+inline void ResponseBuilder::Push(s32 value) {
+ cmdbuf[index++] = static_cast<u32>(value);
+}
+
+template <>
inline void ResponseBuilder::Push(u32 value) {
cmdbuf[index++] = value;
}
@@ -235,6 +240,22 @@ inline void ResponseBuilder::Push(ResultCode value) {
}
template <>
+inline void ResponseBuilder::Push(s8 value) {
+ PushRaw(value);
+}
+
+template <>
+inline void ResponseBuilder::Push(s16 value) {
+ PushRaw(value);
+}
+
+template <>
+inline void ResponseBuilder::Push(s64 value) {
+ Push(static_cast<u32>(value));
+ Push(static_cast<u32>(value >> 32));
+}
+
+template <>
inline void ResponseBuilder::Push(u8 value) {
PushRaw(value);
}
diff --git a/src/core/hle/kernel/client_session.cpp b/src/core/hle/kernel/client_session.cpp
index c114eaf99..704e82824 100644
--- a/src/core/hle/kernel/client_session.cpp
+++ b/src/core/hle/kernel/client_session.cpp
@@ -8,6 +8,7 @@
#include "core/hle/kernel/server_session.h"
#include "core/hle/kernel/session.h"
#include "core/hle/kernel/thread.h"
+#include "core/hle/result.h"
namespace Kernel {
diff --git a/src/core/hle/kernel/client_session.h b/src/core/hle/kernel/client_session.h
index 439fbdb35..4c18de69c 100644
--- a/src/core/hle/kernel/client_session.h
+++ b/src/core/hle/kernel/client_session.h
@@ -6,9 +6,9 @@
#include <memory>
#include <string>
-#include "common/common_types.h"
#include "core/hle/kernel/object.h"
-#include "core/hle/result.h"
+
+union ResultCode;
namespace Kernel {
diff --git a/src/core/hle/kernel/errors.h b/src/core/hle/kernel/errors.h
index 8b58d701d..d17eb0cb6 100644
--- a/src/core/hle/kernel/errors.h
+++ b/src/core/hle/kernel/errors.h
@@ -11,6 +11,7 @@ namespace Kernel {
// Confirmed Switch kernel error codes
constexpr ResultCode ERR_MAX_CONNECTIONS_REACHED{ErrorModule::Kernel, 7};
+constexpr ResultCode ERR_INVALID_CAPABILITY_DESCRIPTOR{ErrorModule::Kernel, 14};
constexpr ResultCode ERR_INVALID_SIZE{ErrorModule::Kernel, 101};
constexpr ResultCode ERR_INVALID_ADDRESS{ErrorModule::Kernel, 102};
constexpr ResultCode ERR_HANDLE_TABLE_FULL{ErrorModule::Kernel, 105};
@@ -27,9 +28,10 @@ constexpr ResultCode ERR_SYNCHRONIZATION_CANCELED{ErrorModule::Kernel, 118};
constexpr ResultCode ERR_OUT_OF_RANGE{ErrorModule::Kernel, 119};
constexpr ResultCode ERR_INVALID_ENUM_VALUE{ErrorModule::Kernel, 120};
constexpr ResultCode ERR_NOT_FOUND{ErrorModule::Kernel, 121};
-constexpr ResultCode ERR_ALREADY_REGISTERED{ErrorModule::Kernel, 122};
+constexpr ResultCode ERR_BUSY{ErrorModule::Kernel, 122};
constexpr ResultCode ERR_SESSION_CLOSED_BY_REMOTE{ErrorModule::Kernel, 123};
constexpr ResultCode ERR_INVALID_STATE{ErrorModule::Kernel, 125};
+constexpr ResultCode ERR_RESERVED_VALUE{ErrorModule::Kernel, 126};
constexpr ResultCode ERR_RESOURCE_LIMIT_EXCEEDED{ErrorModule::Kernel, 132};
} // namespace Kernel
diff --git a/src/core/hle/kernel/event.cpp b/src/core/hle/kernel/event.cpp
deleted file mode 100644
index 8967e602e..000000000
--- a/src/core/hle/kernel/event.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2014 Citra Emulator Project
-// Licensed under GPLv2 or any later version
-// Refer to the license.txt file included.
-
-#include <algorithm>
-#include "common/assert.h"
-#include "core/hle/kernel/event.h"
-#include "core/hle/kernel/object.h"
-#include "core/hle/kernel/thread.h"
-
-namespace Kernel {
-
-Event::Event(KernelCore& kernel) : WaitObject{kernel} {}
-Event::~Event() = default;
-
-SharedPtr<Event> Event::Create(KernelCore& kernel, ResetType reset_type, std::string name) {
- SharedPtr<Event> evt(new Event(kernel));
-
- evt->signaled = false;
- evt->reset_type = reset_type;
- evt->name = std::move(name);
-
- return evt;
-}
-
-bool Event::ShouldWait(Thread* thread) const {
- return !signaled;
-}
-
-void Event::Acquire(Thread* thread) {
- ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
-
- if (reset_type == ResetType::OneShot)
- signaled = false;
-}
-
-void Event::Signal() {
- signaled = true;
- WakeupAllWaitingThreads();
-}
-
-void Event::Clear() {
- signaled = false;
-}
-
-void Event::WakeupAllWaitingThreads() {
- WaitObject::WakeupAllWaitingThreads();
-
- if (reset_type == ResetType::Pulse)
- signaled = false;
-}
-
-} // namespace Kernel
diff --git a/src/core/hle/kernel/handle_table.cpp b/src/core/hle/kernel/handle_table.cpp
index 1bf79b692..c8acde5b1 100644
--- a/src/core/hle/kernel/handle_table.cpp
+++ b/src/core/hle/kernel/handle_table.cpp
@@ -42,9 +42,10 @@ ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) {
u16 generation = next_generation++;
// Overflow count so it fits in the 15 bits dedicated to the generation in the handle.
- // CTR-OS doesn't use generation 0, so skip straight to 1.
- if (next_generation >= (1 << 15))
+ // Horizon OS uses zero to represent an invalid handle, so skip to 1.
+ if (next_generation >= (1 << 15)) {
next_generation = 1;
+ }
generations[slot] = generation;
objects[slot] = std::move(obj);
diff --git a/src/core/hle/kernel/handle_table.h b/src/core/hle/kernel/handle_table.h
index e3f3e3fb8..89a3bc740 100644
--- a/src/core/hle/kernel/handle_table.h
+++ b/src/core/hle/kernel/handle_table.h
@@ -13,6 +13,7 @@
namespace Kernel {
enum KernelHandle : Handle {
+ InvalidHandle = 0,
CurrentThread = 0xFFFF8000,
CurrentProcess = 0xFFFF8001,
};
@@ -42,6 +43,9 @@ enum KernelHandle : Handle {
*/
class HandleTable final : NonCopyable {
public:
+ /// This is the maximum limit of handles allowed per process in Horizon
+ static constexpr std::size_t MAX_COUNT = 1024;
+
HandleTable();
~HandleTable();
@@ -90,9 +94,6 @@ public:
void Clear();
private:
- /// This is the maximum limit of handles allowed per process in Horizon
- static constexpr std::size_t MAX_COUNT = 1024;
-
/// Stores the Object referenced by the handle or null if the slot is empty.
std::array<SharedPtr<Object>, MAX_COUNT> objects;
diff --git a/src/core/hle/kernel/hle_ipc.cpp b/src/core/hle/kernel/hle_ipc.cpp
index 68d5376cb..5dd855db8 100644
--- a/src/core/hle/kernel/hle_ipc.cpp
+++ b/src/core/hle/kernel/hle_ipc.cpp
@@ -15,17 +15,23 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/object.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/readable_event.h"
#include "core/hle/kernel/server_session.h"
+#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/memory.h"
namespace Kernel {
+SessionRequestHandler::SessionRequestHandler() = default;
+
+SessionRequestHandler::~SessionRequestHandler() = default;
+
void SessionRequestHandler::ClientConnected(SharedPtr<ServerSession> server_session) {
server_session->SetHleHandler(shared_from_this());
connected_sessions.push_back(std::move(server_session));
@@ -36,11 +42,9 @@ void SessionRequestHandler::ClientDisconnected(const SharedPtr<ServerSession>& s
boost::range::remove_erase(connected_sessions, server_session);
}
-SharedPtr<Event> HLERequestContext::SleepClientThread(SharedPtr<Thread> thread,
- const std::string& reason, u64 timeout,
- WakeupCallback&& callback,
- Kernel::SharedPtr<Kernel::Event> event) {
-
+SharedPtr<WritableEvent> HLERequestContext::SleepClientThread(
+ SharedPtr<Thread> thread, const std::string& reason, u64 timeout, WakeupCallback&& callback,
+ SharedPtr<WritableEvent> writable_event) {
// Put the client thread to sleep until the wait event is signaled or the timeout expires.
thread->SetWakeupCallback([context = *this, callback](
ThreadWakeupReason reason, SharedPtr<Thread> thread,
@@ -51,23 +55,25 @@ SharedPtr<Event> HLERequestContext::SleepClientThread(SharedPtr<Thread> thread,
return true;
});
- if (!event) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ if (!writable_event) {
// Create event if not provided
- auto& kernel = Core::System::GetInstance().Kernel();
- event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "HLE Pause Event: " + reason);
+ const auto pair = WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "HLE Pause Event: " + reason);
+ writable_event = pair.writable;
}
- event->Clear();
+ const auto readable_event{writable_event->GetReadableEvent()};
+ writable_event->Clear();
thread->SetStatus(ThreadStatus::WaitHLEEvent);
- thread->SetWaitObjects({event});
- event->AddWaitingThread(thread);
+ thread->SetWaitObjects({readable_event});
+ readable_event->AddWaitingThread(thread);
if (timeout > 0) {
thread->WakeAfterDelay(timeout);
}
- return event;
+ return writable_event;
}
HLERequestContext::HLERequestContext(SharedPtr<Kernel::ServerSession> server_session)
diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h
index a38e34b74..cb1c5aff3 100644
--- a/src/core/hle/kernel/hle_ipc.h
+++ b/src/core/hle/kernel/hle_ipc.h
@@ -14,8 +14,6 @@
#include "common/swap.h"
#include "core/hle/ipc.h"
#include "core/hle/kernel/object.h"
-#include "core/hle/kernel/server_session.h"
-#include "core/hle/kernel/thread.h"
namespace Service {
class ServiceFrameworkBase;
@@ -24,10 +22,15 @@ class ServiceFrameworkBase;
namespace Kernel {
class Domain;
-class Event;
class HandleTable;
class HLERequestContext;
class Process;
+class ServerSession;
+class Thread;
+class ReadableEvent;
+class WritableEvent;
+
+enum class ThreadWakeupReason;
/**
* Interface implemented by HLE Session handlers.
@@ -36,7 +39,8 @@ class Process;
*/
class SessionRequestHandler : public std::enable_shared_from_this<SessionRequestHandler> {
public:
- virtual ~SessionRequestHandler() = default;
+ SessionRequestHandler();
+ virtual ~SessionRequestHandler();
/**
* Handles a sync request from the emulated application.
@@ -119,12 +123,13 @@ public:
* @param callback Callback to be invoked when the thread is resumed. This callback must write
* the entire command response once again, regardless of the state of it before this function
* was called.
- * @param event Event to use to wake up the thread. If unspecified, an event will be created.
+ * @param writable_event Event to use to wake up the thread. If unspecified, an event will be
+ * created.
* @returns Event that when signaled will resume the thread and call the callback function.
*/
- SharedPtr<Event> SleepClientThread(SharedPtr<Thread> thread, const std::string& reason,
- u64 timeout, WakeupCallback&& callback,
- Kernel::SharedPtr<Kernel::Event> event = nullptr);
+ SharedPtr<WritableEvent> SleepClientThread(SharedPtr<Thread> thread, const std::string& reason,
+ u64 timeout, WakeupCallback&& callback,
+ SharedPtr<WritableEvent> writable_event = nullptr);
/// Populates this context with data from the requesting process/thread.
ResultCode PopulateFromIncomingCommandBuffer(const HandleTable& handle_table,
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index e441c5bc6..67674cd47 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -2,7 +2,6 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
-#include <array>
#include <atomic>
#include <memory>
#include <mutex>
@@ -112,7 +111,7 @@ struct KernelCore::Impl {
void Shutdown() {
next_object_id = 0;
- next_process_id = 10;
+ next_process_id = Process::ProcessIDMin;
next_thread_id = 1;
process_list.clear();
@@ -153,10 +152,8 @@ struct KernelCore::Impl {
}
std::atomic<u32> next_object_id{0};
- // TODO(Subv): Start the process ids from 10 for now, as lower PIDs are
- // reserved for low-level services
- std::atomic<u32> next_process_id{10};
- std::atomic<u32> next_thread_id{1};
+ std::atomic<u64> next_process_id{Process::ProcessIDMin};
+ std::atomic<u64> next_thread_id{1};
// Lists all processes that exist in the current session.
std::vector<SharedPtr<Process>> process_list;
@@ -242,11 +239,11 @@ u32 KernelCore::CreateNewObjectID() {
return impl->next_object_id++;
}
-u32 KernelCore::CreateNewThreadID() {
+u64 KernelCore::CreateNewThreadID() {
return impl->next_thread_id++;
}
-u32 KernelCore::CreateNewProcessID() {
+u64 KernelCore::CreateNewProcessID() {
return impl->next_process_id++;
}
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index ea00c89f5..58c9d108b 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -88,10 +88,10 @@ private:
u32 CreateNewObjectID();
/// Creates a new process ID, incrementing the internal process ID counter;
- u32 CreateNewProcessID();
+ u64 CreateNewProcessID();
/// Creates a new thread ID, incrementing the internal thread ID counter.
- u32 CreateNewThreadID();
+ u64 CreateNewThreadID();
/// Creates a timer callback handle for the given timer.
ResultVal<Handle> CreateTimerCallbackHandle(const SharedPtr<Timer>& timer);
diff --git a/src/core/hle/kernel/object.cpp b/src/core/hle/kernel/object.cpp
index d87a62bb9..806078638 100644
--- a/src/core/hle/kernel/object.cpp
+++ b/src/core/hle/kernel/object.cpp
@@ -13,16 +13,17 @@ Object::~Object() = default;
bool Object::IsWaitable() const {
switch (GetHandleType()) {
- case HandleType::Event:
+ case HandleType::ReadableEvent:
case HandleType::Thread:
+ case HandleType::Process:
case HandleType::Timer:
case HandleType::ServerPort:
case HandleType::ServerSession:
return true;
case HandleType::Unknown:
+ case HandleType::WritableEvent:
case HandleType::SharedMemory:
- case HandleType::Process:
case HandleType::AddressArbiter:
case HandleType::ResourceLimit:
case HandleType::ClientPort:
@@ -31,6 +32,7 @@ bool Object::IsWaitable() const {
}
UNREACHABLE();
+ return false;
}
} // namespace Kernel
diff --git a/src/core/hle/kernel/object.h b/src/core/hle/kernel/object.h
index c9f4d0bb3..1541b6e3c 100644
--- a/src/core/hle/kernel/object.h
+++ b/src/core/hle/kernel/object.h
@@ -19,7 +19,8 @@ using Handle = u32;
enum class HandleType : u32 {
Unknown,
- Event,
+ WritableEvent,
+ ReadableEvent,
SharedMemory,
Thread,
Process,
@@ -33,9 +34,8 @@ enum class HandleType : u32 {
};
enum class ResetType {
- OneShot,
- Sticky,
- Pulse,
+ OneShot, ///< Reset automatically on object acquisition
+ Sticky, ///< Never reset automatically
};
class Object : NonCopyable {
diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp
index 7ca538401..c5aa19afa 100644
--- a/src/core/hle/kernel/process.cpp
+++ b/src/core/hle/kernel/process.cpp
@@ -9,6 +9,7 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/file_sys/program_metadata.h"
+#include "core/hle/kernel/errors.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/resource_limit.h"
@@ -19,6 +20,35 @@
#include "core/settings.h"
namespace Kernel {
+namespace {
+/**
+ * Sets up the primary application thread
+ *
+ * @param owner_process The parent process for the main thread
+ * @param kernel The kernel instance to create the main thread under.
+ * @param entry_point The address at which the thread should start execution
+ * @param priority The priority to give the main thread
+ */
+void SetupMainThread(Process& owner_process, KernelCore& kernel, VAddr entry_point, u32 priority) {
+ // Setup page table so we can write to memory
+ SetCurrentPageTable(&owner_process.VMManager().page_table);
+
+ // Initialize new "main" thread
+ const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
+ auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0,
+ owner_process.GetIdealCore(), stack_top, owner_process);
+
+ SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
+
+ // Register 1 must be a handle to the main thread
+ const Handle guest_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
+ thread->SetGuestHandle(guest_handle);
+ thread->GetContext().cpu_registers[1] = guest_handle;
+
+ // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
+ thread->ResumeFromWait();
+}
+} // Anonymous namespace
CodeSet::CodeSet() = default;
CodeSet::~CodeSet() = default;
@@ -27,13 +57,11 @@ SharedPtr<Process> Process::Create(KernelCore& kernel, std::string&& name) {
SharedPtr<Process> process(new Process(kernel));
process->name = std::move(name);
- process->flags.raw = 0;
- process->flags.memory_region.Assign(MemoryRegion::APPLICATION);
process->resource_limit = kernel.GetSystemResourceLimit();
process->status = ProcessStatus::Created;
process->program_id = 0;
process->process_id = kernel.CreateNewProcessID();
- process->svc_access_mask.set();
+ process->capabilities.InitializeForMetadatalessProcess();
std::mt19937 rng(Settings::values.rng_seed.value_or(0));
std::uniform_int_distribution<u64> distribution;
@@ -44,82 +72,34 @@ SharedPtr<Process> Process::Create(KernelCore& kernel, std::string&& name) {
return process;
}
-void Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata) {
- program_id = metadata.GetTitleID();
- is_64bit_process = metadata.Is64BitProgram();
- vm_manager.Reset(metadata.GetAddressSpaceType());
+SharedPtr<ResourceLimit> Process::GetResourceLimit() const {
+ return resource_limit;
}
-void Process::ParseKernelCaps(const u32* kernel_caps, std::size_t len) {
- for (std::size_t i = 0; i < len; ++i) {
- u32 descriptor = kernel_caps[i];
- u32 type = descriptor >> 20;
-
- if (descriptor == 0xFFFFFFFF) {
- // Unused descriptor entry
- continue;
- } else if ((type & 0xF00) == 0xE00) { // 0x0FFF
- // Allowed interrupts list
- LOG_WARNING(Loader, "ExHeader allowed interrupts list ignored");
- } else if ((type & 0xF80) == 0xF00) { // 0x07FF
- // Allowed syscalls mask
- unsigned int index = ((descriptor >> 24) & 7) * 24;
- u32 bits = descriptor & 0xFFFFFF;
-
- while (bits && index < svc_access_mask.size()) {
- svc_access_mask.set(index, bits & 1);
- ++index;
- bits >>= 1;
- }
- } else if ((type & 0xFF0) == 0xFE0) { // 0x00FF
- // Handle table size
- handle_table_size = descriptor & 0x3FF;
- } else if ((type & 0xFF8) == 0xFF0) { // 0x007F
- // Misc. flags
- flags.raw = descriptor & 0xFFFF;
- } else if ((type & 0xFFE) == 0xFF8) { // 0x001F
- // Mapped memory range
- if (i + 1 >= len || ((kernel_caps[i + 1] >> 20) & 0xFFE) != 0xFF8) {
- LOG_WARNING(Loader, "Incomplete exheader memory range descriptor ignored.");
- continue;
- }
- u32 end_desc = kernel_caps[i + 1];
- ++i; // Skip over the second descriptor on the next iteration
+ResultCode Process::ClearSignalState() {
+ if (status == ProcessStatus::Exited) {
+ LOG_ERROR(Kernel, "called on a terminated process instance.");
+ return ERR_INVALID_STATE;
+ }
- AddressMapping mapping;
- mapping.address = descriptor << 12;
- VAddr end_address = end_desc << 12;
+ if (!is_signaled) {
+ LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
+ return ERR_INVALID_STATE;
+ }
- if (mapping.address < end_address) {
- mapping.size = end_address - mapping.address;
- } else {
- mapping.size = 0;
- }
+ is_signaled = false;
+ return RESULT_SUCCESS;
+}
- mapping.read_only = (descriptor & (1 << 20)) != 0;
- mapping.unk_flag = (end_desc & (1 << 20)) != 0;
-
- address_mappings.push_back(mapping);
- } else if ((type & 0xFFF) == 0xFFE) { // 0x000F
- // Mapped memory page
- AddressMapping mapping;
- mapping.address = descriptor << 12;
- mapping.size = Memory::PAGE_SIZE;
- mapping.read_only = false;
- mapping.unk_flag = false;
-
- address_mappings.push_back(mapping);
- } else if ((type & 0xFE0) == 0xFC0) { // 0x01FF
- // Kernel version
- kernel_version = descriptor & 0xFFFF;
-
- int minor = kernel_version & 0xFF;
- int major = (kernel_version >> 8) & 0xFF;
- LOG_INFO(Loader, "ExHeader kernel version: {}.{}", major, minor);
- } else {
- LOG_ERROR(Loader, "Unhandled kernel caps descriptor: 0x{:08X}", descriptor);
- }
- }
+ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata) {
+ program_id = metadata.GetTitleID();
+ ideal_core = metadata.GetMainThreadCore();
+ is_64bit_process = metadata.Is64BitProgram();
+
+ vm_manager.Reset(metadata.GetAddressSpaceType());
+
+ const auto& caps = metadata.GetKernelCapabilities();
+ return capabilities.InitializeForUserProcess(caps.data(), caps.size(), vm_manager);
}
void Process::Run(VAddr entry_point, s32 main_thread_priority, u32 stack_size) {
@@ -129,17 +109,17 @@ void Process::Run(VAddr entry_point, s32 main_thread_priority, u32 stack_size) {
vm_manager
.MapMemoryBlock(vm_manager.GetTLSIORegionEndAddress() - stack_size,
std::make_shared<std::vector<u8>>(stack_size, 0), 0, stack_size,
- MemoryState::Mapped)
+ MemoryState::Stack)
.Unwrap();
vm_manager.LogLayout();
- status = ProcessStatus::Running;
+ ChangeStatus(ProcessStatus::Running);
- Kernel::SetupMainThread(kernel, entry_point, main_thread_priority, *this);
+ SetupMainThread(*this, kernel, entry_point, main_thread_priority);
}
void Process::PrepareForTermination() {
- status = ProcessStatus::Exited;
+ ChangeStatus(ProcessStatus::Exiting);
const auto stop_threads = [this](const std::vector<SharedPtr<Thread>>& thread_list) {
for (auto& thread : thread_list) {
@@ -163,6 +143,8 @@ void Process::PrepareForTermination() {
stop_threads(system.Scheduler(1).GetThreadList());
stop_threads(system.Scheduler(2).GetThreadList());
stop_threads(system.Scheduler(3).GetThreadList());
+
+ ChangeStatus(ProcessStatus::Exited);
}
/**
@@ -245,23 +227,25 @@ void Process::LoadModule(CodeSet module_, VAddr base_addr) {
Core::System::GetInstance().ArmInterface(3).ClearInstructionCache();
}
-ResultVal<VAddr> Process::HeapAllocate(VAddr target, u64 size, VMAPermission perms) {
- return vm_manager.HeapAllocate(target, size, perms);
-}
+Kernel::Process::Process(KernelCore& kernel) : WaitObject{kernel} {}
+Kernel::Process::~Process() {}
-ResultCode Process::HeapFree(VAddr target, u32 size) {
- return vm_manager.HeapFree(target, size);
+void Process::Acquire(Thread* thread) {
+ ASSERT_MSG(!ShouldWait(thread), "Object unavailable!");
}
-ResultCode Process::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state) {
- return vm_manager.MirrorMemory(dst_addr, src_addr, size, state);
+bool Process::ShouldWait(Thread* thread) const {
+ return !is_signaled;
}
-ResultCode Process::UnmapMemory(VAddr dst_addr, VAddr /*src_addr*/, u64 size) {
- return vm_manager.UnmapRange(dst_addr, size);
-}
+void Process::ChangeStatus(ProcessStatus new_status) {
+ if (status == new_status) {
+ return;
+ }
-Kernel::Process::Process(KernelCore& kernel) : Object{kernel} {}
-Kernel::Process::~Process() {}
+ status = new_status;
+ is_signaled = true;
+ WakeupAllWaitingThreads();
+}
} // namespace Kernel
diff --git a/src/core/hle/kernel/process.h b/src/core/hle/kernel/process.h
index ada845c7f..dcc57ae9f 100644
--- a/src/core/hle/kernel/process.h
+++ b/src/core/hle/kernel/process.h
@@ -11,12 +11,12 @@
#include <string>
#include <vector>
#include <boost/container/static_vector.hpp>
-#include "common/bit_field.h"
#include "common/common_types.h"
#include "core/hle/kernel/handle_table.h"
-#include "core/hle/kernel/object.h"
-#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/process_capability.h"
#include "core/hle/kernel/vm_manager.h"
+#include "core/hle/kernel/wait_object.h"
+#include "core/hle/result.h"
namespace FileSys {
class ProgramMetadata;
@@ -26,6 +26,7 @@ namespace Kernel {
class KernelCore;
class ResourceLimit;
+class Thread;
struct AddressMapping {
// Address and size must be page-aligned
@@ -41,24 +42,6 @@ enum class MemoryRegion : u16 {
BASE = 3,
};
-union ProcessFlags {
- u16 raw;
-
- BitField<0, 1, u16>
- allow_debug; ///< Allows other processes to attach to and debug this process.
- BitField<1, 1, u16> force_debug; ///< Allows this process to attach to processes even if they
- /// don't have allow_debug set.
- BitField<2, 1, u16> allow_nonalphanum;
- BitField<3, 1, u16> shared_page_writable; ///< Shared page is mapped with write permissions.
- BitField<4, 1, u16> privileged_priority; ///< Can use priority levels higher than 24.
- BitField<5, 1, u16> allow_main_args;
- BitField<6, 1, u16> shared_device_mem;
- BitField<7, 1, u16> runnable_on_sleep;
- BitField<8, 4, MemoryRegion>
- memory_region; ///< Default region for memory allocations for this process
- BitField<12, 1, u16> loaded_high; ///< Application loaded high (not at 0x00100000).
-};
-
/**
* Indicates the status of a Process instance.
*
@@ -117,8 +100,20 @@ struct CodeSet final {
VAddr entrypoint = 0;
};
-class Process final : public Object {
+class Process final : public WaitObject {
public:
+ enum : u64 {
+ /// Lowest allowed process ID for a kernel initial process.
+ InitialKIPIDMin = 1,
+ /// Highest allowed process ID for a kernel initial process.
+ InitialKIPIDMax = 80,
+
+ /// Lowest allowed process ID for a userland process.
+ ProcessIDMin = 81,
+ /// Highest allowed process ID for a userland process.
+ ProcessIDMax = 0xFFFFFFFFFFFFFFFF,
+ };
+
static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
static SharedPtr<Process> Create(KernelCore& kernel, std::string&& name);
@@ -161,7 +156,7 @@ public:
}
/// Gets the unique ID that identifies this particular process.
- u32 GetProcessID() const {
+ u64 GetProcessID() const {
return process_id;
}
@@ -171,28 +166,21 @@ public:
}
/// Gets the resource limit descriptor for this process
- ResourceLimit& GetResourceLimit() {
- return *resource_limit;
- }
+ SharedPtr<ResourceLimit> GetResourceLimit() const;
- /// Gets the resource limit descriptor for this process
- const ResourceLimit& GetResourceLimit() const {
- return *resource_limit;
+ /// Gets the ideal CPU core ID for this process
+ u8 GetIdealCore() const {
+ return ideal_core;
}
- /// Gets the default CPU ID for this process
- u8 GetDefaultProcessorID() const {
- return ideal_processor;
- }
-
- /// Gets the bitmask of allowed CPUs that this process' threads can run on.
- u32 GetAllowedProcessorMask() const {
- return allowed_processor_mask;
+ /// Gets the bitmask of allowed cores that this process' threads can run on.
+ u64 GetCoreMask() const {
+ return capabilities.GetCoreMask();
}
/// Gets the bitmask of allowed thread priorities.
- u32 GetAllowedThreadPriorityMask() const {
- return allowed_thread_priority_mask;
+ u64 GetPriorityMask() const {
+ return capabilities.GetPriorityMask();
}
u32 IsVirtualMemoryEnabled() const {
@@ -219,19 +207,26 @@ public:
return random_entropy.at(index);
}
+ /// Clears the signaled state of the process if and only if it's signaled.
+ ///
+ /// @pre The process must not be already terminated. If this is called on a
+ /// terminated process, then ERR_INVALID_STATE will be returned.
+ ///
+ /// @pre The process must be in a signaled state. If this is called on a
+ /// process instance that is not signaled, ERR_INVALID_STATE will be
+ /// returned.
+ ResultCode ClearSignalState();
+
/**
* Loads process-specifics configuration info with metadata provided
* by an executable.
*
- * @param metadata The provided metadata to load process specific info.
- */
- void LoadFromMetadata(const FileSys::ProgramMetadata& metadata);
-
- /**
- * Parses a list of kernel capability descriptors (as found in the ExHeader) and applies them
- * to this process.
+ * @param metadata The provided metadata to load process specific info from.
+ *
+ * @returns RESULT_SUCCESS if all relevant metadata was able to be
+ * loaded and parsed. Otherwise, an error code is returned.
*/
- void ParseKernelCaps(const u32* kernel_caps, std::size_t len);
+ ResultCode LoadFromMetadata(const FileSys::ProgramMetadata& metadata);
/**
* Applies address space changes and launches the process main thread.
@@ -247,7 +242,7 @@ public:
void LoadModule(CodeSet module_, VAddr base_addr);
///////////////////////////////////////////////////////////////////////////////////////////////
- // Memory Management
+ // Thread-local storage management
// Marks the next available region as used and returns the address of the slot.
VAddr MarkNextAvailableTLSSlotAsUsed(Thread& thread);
@@ -255,18 +250,21 @@ public:
// Frees a used TLS slot identified by the given address
void FreeTLSSlot(VAddr tls_address);
- ResultVal<VAddr> HeapAllocate(VAddr target, u64 size, VMAPermission perms);
- ResultCode HeapFree(VAddr target, u32 size);
-
- ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size,
- MemoryState state = MemoryState::Mapped);
-
- ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size);
-
private:
explicit Process(KernelCore& kernel);
~Process() override;
+ /// Checks if the specified thread should wait until this process is available.
+ bool ShouldWait(Thread* thread) const override;
+
+ /// Acquires/locks this process for the specified thread if it's available.
+ void Acquire(Thread* thread) override;
+
+ /// Changes the process status. If the status is different
+ /// from the current process status, then this will trigger
+ /// a process signal.
+ void ChangeStatus(ProcessStatus new_status);
+
/// Memory manager for this process.
Kernel::VMManager vm_manager;
@@ -274,30 +272,16 @@ private:
ProcessStatus status;
/// The ID of this process
- u32 process_id = 0;
+ u64 process_id = 0;
/// Title ID corresponding to the process
- u64 program_id;
+ u64 program_id = 0;
/// Resource limit descriptor for this process
SharedPtr<ResourceLimit> resource_limit;
- /// The process may only call SVCs which have the corresponding bit set.
- std::bitset<0x80> svc_access_mask;
- /// Maximum size of the handle table for the process.
- u32 handle_table_size = 0x200;
- /// Special memory ranges mapped into this processes address space. This is used to give
- /// processes access to specific I/O regions and device memory.
- boost::container::static_vector<AddressMapping, 8> address_mappings;
- ProcessFlags flags;
- /// Kernel compatibility version for this process
- u16 kernel_version = 0;
- /// The default CPU for this process, threads are scheduled on this cpu by default.
- u8 ideal_processor = 0;
- /// Bitmask of allowed CPUs that this process' threads can run on. TODO(Subv): Actually parse
- /// this value from the process header.
- u32 allowed_processor_mask = THREADPROCESSORID_DEFAULT_MASK;
- u32 allowed_thread_priority_mask = 0xFFFFFFFF;
+ /// The ideal CPU core for this process, threads are scheduled on this core by default.
+ u8 ideal_core = 0;
u32 is_virtual_address_memory_enabled = 0;
/// The Thread Local Storage area is allocated as processes create threads,
@@ -307,11 +291,18 @@ private:
/// This vector will grow as more pages are allocated for new threads.
std::vector<std::bitset<8>> tls_slots;
+ /// Contains the parsed process capability descriptors.
+ ProcessCapabilities capabilities;
+
/// Whether or not this process is AArch64, or AArch32.
/// By default, we currently assume this is true, unless otherwise
/// specified by metadata provided to the process during loading.
bool is_64bit_process = true;
+ /// Whether or not this process is signaled. This occurs
+ /// upon the process changing to a different state.
+ bool is_signaled = false;
+
/// Total running time for the process in ticks.
u64 total_process_running_time_ticks = 0;
diff --git a/src/core/hle/kernel/process_capability.cpp b/src/core/hle/kernel/process_capability.cpp
new file mode 100644
index 000000000..3a2164b25
--- /dev/null
+++ b/src/core/hle/kernel/process_capability.cpp
@@ -0,0 +1,355 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/bit_util.h"
+#include "core/hle/kernel/errors.h"
+#include "core/hle/kernel/handle_table.h"
+#include "core/hle/kernel/process_capability.h"
+#include "core/hle/kernel/vm_manager.h"
+
+namespace Kernel {
+namespace {
+
+// clang-format off
+
+// Shift offsets for kernel capability types.
+enum : u32 {
+ CapabilityOffset_PriorityAndCoreNum = 3,
+ CapabilityOffset_Syscall = 4,
+ CapabilityOffset_MapPhysical = 6,
+ CapabilityOffset_MapIO = 7,
+ CapabilityOffset_Interrupt = 11,
+ CapabilityOffset_ProgramType = 13,
+ CapabilityOffset_KernelVersion = 14,
+ CapabilityOffset_HandleTableSize = 15,
+ CapabilityOffset_Debug = 16,
+};
+
+// Combined mask of all parameters that may be initialized only once.
+constexpr u32 InitializeOnceMask = (1U << CapabilityOffset_PriorityAndCoreNum) |
+ (1U << CapabilityOffset_ProgramType) |
+ (1U << CapabilityOffset_KernelVersion) |
+ (1U << CapabilityOffset_HandleTableSize) |
+ (1U << CapabilityOffset_Debug);
+
+// Packed kernel version indicating 10.4.0
+constexpr u32 PackedKernelVersion = 0x520000;
+
+// Indicates possible types of capabilities that can be specified.
+enum class CapabilityType : u32 {
+ Unset = 0U,
+ PriorityAndCoreNum = (1U << CapabilityOffset_PriorityAndCoreNum) - 1,
+ Syscall = (1U << CapabilityOffset_Syscall) - 1,
+ MapPhysical = (1U << CapabilityOffset_MapPhysical) - 1,
+ MapIO = (1U << CapabilityOffset_MapIO) - 1,
+ Interrupt = (1U << CapabilityOffset_Interrupt) - 1,
+ ProgramType = (1U << CapabilityOffset_ProgramType) - 1,
+ KernelVersion = (1U << CapabilityOffset_KernelVersion) - 1,
+ HandleTableSize = (1U << CapabilityOffset_HandleTableSize) - 1,
+ Debug = (1U << CapabilityOffset_Debug) - 1,
+ Ignorable = 0xFFFFFFFFU,
+};
+
+// clang-format on
+
+constexpr CapabilityType GetCapabilityType(u32 value) {
+ return static_cast<CapabilityType>((~value & (value + 1)) - 1);
+}
+
+u32 GetFlagBitOffset(CapabilityType type) {
+ const auto value = static_cast<u32>(type);
+ return static_cast<u32>(Common::BitSize<u32>() - Common::CountLeadingZeroes32(value));
+}
+
+} // Anonymous namespace
+
+ResultCode ProcessCapabilities::InitializeForKernelProcess(const u32* capabilities,
+ std::size_t num_capabilities,
+ VMManager& vm_manager) {
+ Clear();
+
+ // Allow all cores and priorities.
+ core_mask = 0xF;
+ priority_mask = 0xFFFFFFFFFFFFFFFF;
+ kernel_version = PackedKernelVersion;
+
+ return ParseCapabilities(capabilities, num_capabilities, vm_manager);
+}
+
+ResultCode ProcessCapabilities::InitializeForUserProcess(const u32* capabilities,
+ std::size_t num_capabilities,
+ VMManager& vm_manager) {
+ Clear();
+
+ return ParseCapabilities(capabilities, num_capabilities, vm_manager);
+}
+
+void ProcessCapabilities::InitializeForMetadatalessProcess() {
+ // Allow all cores and priorities
+ core_mask = 0xF;
+ priority_mask = 0xFFFFFFFFFFFFFFFF;
+ kernel_version = PackedKernelVersion;
+
+ // Allow all system calls and interrupts.
+ svc_capabilities.set();
+ interrupt_capabilities.set();
+
+ // Allow using the maximum possible amount of handles
+ handle_table_size = static_cast<u32>(HandleTable::MAX_COUNT);
+
+ // Allow all debugging capabilities.
+ is_debuggable = true;
+ can_force_debug = true;
+}
+
+ResultCode ProcessCapabilities::ParseCapabilities(const u32* capabilities,
+ std::size_t num_capabilities,
+ VMManager& vm_manager) {
+ u32 set_flags = 0;
+ u32 set_svc_bits = 0;
+
+ for (std::size_t i = 0; i < num_capabilities; ++i) {
+ const u32 descriptor = capabilities[i];
+ const auto type = GetCapabilityType(descriptor);
+
+ if (type == CapabilityType::MapPhysical) {
+ i++;
+
+ // The MapPhysical type uses two descriptor flags for its parameters.
+ // If there's only one, then there's a problem.
+ if (i >= num_capabilities) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ const auto size_flags = capabilities[i];
+ if (GetCapabilityType(size_flags) != CapabilityType::MapPhysical) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ const auto result = HandleMapPhysicalFlags(descriptor, size_flags, vm_manager);
+ if (result.IsError()) {
+ return result;
+ }
+ } else {
+ const auto result =
+ ParseSingleFlagCapability(set_flags, set_svc_bits, descriptor, vm_manager);
+ if (result.IsError()) {
+ return result;
+ }
+ }
+ }
+
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits,
+ u32 flag, VMManager& vm_manager) {
+ const auto type = GetCapabilityType(flag);
+
+ if (type == CapabilityType::Unset) {
+ return ERR_INVALID_CAPABILITY_DESCRIPTOR;
+ }
+
+ // Bail early on ignorable entries, as one would expect,
+ // ignorable descriptors can be ignored.
+ if (type == CapabilityType::Ignorable) {
+ return RESULT_SUCCESS;
+ }
+
+ // Ensure that the give flag hasn't already been initialized before.
+ // If it has been, then bail.
+ const u32 flag_length = GetFlagBitOffset(type);
+ const u32 set_flag = 1U << flag_length;
+ if ((set_flag & set_flags & InitializeOnceMask) != 0) {
+ return ERR_INVALID_COMBINATION;
+ }
+ set_flags |= set_flag;
+
+ switch (type) {
+ case CapabilityType::PriorityAndCoreNum:
+ return HandlePriorityCoreNumFlags(flag);
+ case CapabilityType::Syscall:
+ return HandleSyscallFlags(set_svc_bits, flag);
+ case CapabilityType::MapIO:
+ return HandleMapIOFlags(flag, vm_manager);
+ case CapabilityType::Interrupt:
+ return HandleInterruptFlags(flag);
+ case CapabilityType::ProgramType:
+ return HandleProgramTypeFlags(flag);
+ case CapabilityType::KernelVersion:
+ return HandleKernelVersionFlags(flag);
+ case CapabilityType::HandleTableSize:
+ return HandleHandleTableFlags(flag);
+ case CapabilityType::Debug:
+ return HandleDebugFlags(flag);
+ default:
+ break;
+ }
+
+ return ERR_INVALID_CAPABILITY_DESCRIPTOR;
+}
+
+void ProcessCapabilities::Clear() {
+ svc_capabilities.reset();
+ interrupt_capabilities.reset();
+
+ core_mask = 0;
+ priority_mask = 0;
+
+ handle_table_size = 0;
+ kernel_version = 0;
+
+ program_type = ProgramType::SysModule;
+
+ is_debuggable = false;
+ can_force_debug = false;
+}
+
+ResultCode ProcessCapabilities::HandlePriorityCoreNumFlags(u32 flags) {
+ if (priority_mask != 0 || core_mask != 0) {
+ return ERR_INVALID_CAPABILITY_DESCRIPTOR;
+ }
+
+ const u32 core_num_min = (flags >> 16) & 0xFF;
+ const u32 core_num_max = (flags >> 24) & 0xFF;
+ if (core_num_min > core_num_max) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ const u32 priority_min = (flags >> 10) & 0x3F;
+ const u32 priority_max = (flags >> 4) & 0x3F;
+ if (priority_min > priority_max) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ // The switch only has 4 usable cores.
+ if (core_num_max >= 4) {
+ return ERR_INVALID_PROCESSOR_ID;
+ }
+
+ const auto make_mask = [](u64 min, u64 max) {
+ const u64 range = max - min + 1;
+ const u64 mask = (1ULL << range) - 1;
+
+ return mask << min;
+ };
+
+ core_mask = make_mask(core_num_min, core_num_max);
+ priority_mask = make_mask(priority_min, priority_max);
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleSyscallFlags(u32& set_svc_bits, u32 flags) {
+ const u32 index = flags >> 29;
+ const u32 svc_bit = 1U << index;
+
+ // If we've already set this svc before, bail.
+ if ((set_svc_bits & svc_bit) != 0) {
+ return ERR_INVALID_COMBINATION;
+ }
+ set_svc_bits |= svc_bit;
+
+ const u32 svc_mask = (flags >> 5) & 0xFFFFFF;
+ for (u32 i = 0; i < 24; ++i) {
+ const u32 svc_number = index * 24 + i;
+
+ if ((svc_mask & (1U << i)) == 0) {
+ continue;
+ }
+
+ if (svc_number >= svc_capabilities.size()) {
+ return ERR_OUT_OF_RANGE;
+ }
+
+ svc_capabilities[svc_number] = true;
+ }
+
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleMapPhysicalFlags(u32 flags, u32 size_flags,
+ VMManager& vm_manager) {
+ // TODO(Lioncache): Implement once the memory manager can handle this.
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleMapIOFlags(u32 flags, VMManager& vm_manager) {
+ // TODO(Lioncache): Implement once the memory manager can handle this.
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleInterruptFlags(u32 flags) {
+ constexpr u32 interrupt_ignore_value = 0x3FF;
+ const u32 interrupt0 = (flags >> 12) & 0x3FF;
+ const u32 interrupt1 = (flags >> 22) & 0x3FF;
+
+ for (u32 interrupt : {interrupt0, interrupt1}) {
+ if (interrupt == interrupt_ignore_value) {
+ continue;
+ }
+
+ // NOTE:
+ // This should be checking a generic interrupt controller value
+ // as part of the calculation, however, given we don't currently
+ // emulate that, it's sufficient to mark every interrupt as defined.
+
+ if (interrupt >= interrupt_capabilities.size()) {
+ return ERR_OUT_OF_RANGE;
+ }
+
+ interrupt_capabilities[interrupt] = true;
+ }
+
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleProgramTypeFlags(u32 flags) {
+ const u32 reserved = flags >> 17;
+ if (reserved != 0) {
+ return ERR_RESERVED_VALUE;
+ }
+
+ program_type = static_cast<ProgramType>((flags >> 14) & 0b111);
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleKernelVersionFlags(u32 flags) {
+ // Yes, the internal member variable is checked in the actual kernel here.
+ // This might look odd for options that are only allowed to be initialized
+ // just once, however the kernel has a separate initialization function for
+ // kernel processes and userland processes. The kernel variant sets this
+ // member variable ahead of time.
+
+ const u32 major_version = kernel_version >> 19;
+
+ if (major_version != 0 || flags < 0x80000) {
+ return ERR_INVALID_CAPABILITY_DESCRIPTOR;
+ }
+
+ kernel_version = flags;
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleHandleTableFlags(u32 flags) {
+ const u32 reserved = flags >> 26;
+ if (reserved != 0) {
+ return ERR_RESERVED_VALUE;
+ }
+
+ handle_table_size = (flags >> 16) & 0x3FF;
+ return RESULT_SUCCESS;
+}
+
+ResultCode ProcessCapabilities::HandleDebugFlags(u32 flags) {
+ const u32 reserved = flags >> 19;
+ if (reserved != 0) {
+ return ERR_RESERVED_VALUE;
+ }
+
+ is_debuggable = (flags & 0x20000) != 0;
+ can_force_debug = (flags & 0x40000) != 0;
+ return RESULT_SUCCESS;
+}
+
+} // namespace Kernel
diff --git a/src/core/hle/kernel/process_capability.h b/src/core/hle/kernel/process_capability.h
new file mode 100644
index 000000000..fbc8812a3
--- /dev/null
+++ b/src/core/hle/kernel/process_capability.h
@@ -0,0 +1,264 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <bitset>
+
+#include "common/common_types.h"
+
+union ResultCode;
+
+namespace Kernel {
+
+class VMManager;
+
+/// The possible types of programs that may be indicated
+/// by the program type capability descriptor.
+enum class ProgramType {
+ SysModule,
+ Application,
+ Applet,
+};
+
+/// Handles kernel capability descriptors that are provided by
+/// application metadata. These descriptors provide information
+/// that alters certain parameters for kernel process instance
+/// that will run said application (or applet).
+///
+/// Capabilities are a sequence of flag descriptors, that indicate various
+/// configurations and constraints for a particular process.
+///
+/// Flag types are indicated by a sequence of set low bits. E.g. the
+/// types are indicated with the low bits as follows (where x indicates "don't care"):
+///
+/// - Priority and core mask : 0bxxxxxxxxxxxx0111
+/// - Allowed service call mask: 0bxxxxxxxxxxx01111
+/// - Map physical memory : 0bxxxxxxxxx0111111
+/// - Map IO memory : 0bxxxxxxxx01111111
+/// - Interrupts : 0bxxxx011111111111
+/// - Application type : 0bxx01111111111111
+/// - Kernel version : 0bx011111111111111
+/// - Handle table size : 0b0111111111111111
+/// - Debugger flags : 0b1111111111111111
+///
+/// These are essentially a bit offset subtracted by 1 to create a mask.
+/// e.g. The first entry in the above list is simply bit 3 (value 8 -> 0b1000)
+/// subtracted by one (7 -> 0b0111)
+///
+/// An example of a bit layout (using the map physical layout):
+/// <example>
+/// The MapPhysical type indicates a sequence entry pair of:
+///
+/// [initial, memory_flags], where:
+///
+/// initial:
+/// bits:
+/// 7-24: Starting page to map memory at.
+/// 25 : Indicates if the memory should be mapped as read only.
+///
+/// memory_flags:
+/// bits:
+/// 7-20 : Number of pages to map
+/// 21-25: Seems to be reserved (still checked against though)
+/// 26 : Whether or not the memory being mapped is IO memory, or physical memory
+/// </example>
+///
+class ProcessCapabilities {
+public:
+ using InterruptCapabilities = std::bitset<1024>;
+ using SyscallCapabilities = std::bitset<128>;
+
+ ProcessCapabilities() = default;
+ ProcessCapabilities(const ProcessCapabilities&) = delete;
+ ProcessCapabilities(ProcessCapabilities&&) = default;
+
+ ProcessCapabilities& operator=(const ProcessCapabilities&) = delete;
+ ProcessCapabilities& operator=(ProcessCapabilities&&) = default;
+
+ /// Initializes this process capabilities instance for a kernel process.
+ ///
+ /// @param capabilities The capabilities to parse
+ /// @param num_capabilities The number of capabilities to parse.
+ /// @param vm_manager The memory manager to use for handling any mapping-related
+ /// operations (such as mapping IO memory, etc).
+ ///
+ /// @returns RESULT_SUCCESS if this capabilities instance was able to be initialized,
+ /// otherwise, an error code upon failure.
+ ///
+ ResultCode InitializeForKernelProcess(const u32* capabilities, std::size_t num_capabilities,
+ VMManager& vm_manager);
+
+ /// Initializes this process capabilities instance for a userland process.
+ ///
+ /// @param capabilities The capabilities to parse.
+ /// @param num_capabilities The total number of capabilities to parse.
+ /// @param vm_manager The memory manager to use for handling any mapping-related
+ /// operations (such as mapping IO memory, etc).
+ ///
+ /// @returns RESULT_SUCCESS if this capabilities instance was able to be initialized,
+ /// otherwise, an error code upon failure.
+ ///
+ ResultCode InitializeForUserProcess(const u32* capabilities, std::size_t num_capabilities,
+ VMManager& vm_manager);
+
+ /// Initializes this process capabilities instance for a process that does not
+ /// have any metadata to parse.
+ ///
+ /// This is necessary, as we allow running raw executables, and the internal
+ /// kernel process capabilities also determine what CPU cores the process is
+ /// allowed to run on, and what priorities are allowed for threads. It also
+ /// determines the max handle table size, what the program type is, whether or
+ /// not the process can be debugged, or whether it's possible for a process to
+ /// forcibly debug another process.
+ ///
+ /// Given the above, this essentially enables all capabilities across the board
+ /// for the process. It allows the process to:
+ ///
+ /// - Run on any core
+ /// - Use any thread priority
+ /// - Use the maximum amount of handles a process is allowed to.
+ /// - Be debuggable
+ /// - Forcibly debug other processes.
+ ///
+ /// Note that this is not a behavior that the kernel allows a process to do via
+ /// a single function like this. This is yuzu-specific behavior to handle
+ /// executables with no capability descriptors whatsoever to derive behavior from.
+ /// It being yuzu-specific is why this is also not the default behavior and not
+ /// done by default in the constructor.
+ ///
+ void InitializeForMetadatalessProcess();
+
+ /// Gets the allowable core mask
+ u64 GetCoreMask() const {
+ return core_mask;
+ }
+
+ /// Gets the allowable priority mask
+ u64 GetPriorityMask() const {
+ return priority_mask;
+ }
+
+ /// Gets the SVC access permission bits
+ const SyscallCapabilities& GetServiceCapabilities() const {
+ return svc_capabilities;
+ }
+
+ /// Gets the valid interrupt bits.
+ const InterruptCapabilities& GetInterruptCapabilities() const {
+ return interrupt_capabilities;
+ }
+
+ /// Gets the program type for this process.
+ ProgramType GetProgramType() const {
+ return program_type;
+ }
+
+ /// Gets the number of total allowable handles for the process' handle table.
+ u32 GetHandleTableSize() const {
+ return handle_table_size;
+ }
+
+ /// Gets the kernel version value.
+ u32 GetKernelVersion() const {
+ return kernel_version;
+ }
+
+ /// Whether or not this process can be debugged.
+ bool IsDebuggable() const {
+ return is_debuggable;
+ }
+
+ /// Whether or not this process can forcibly debug another
+ /// process, even if that process is not considered debuggable.
+ bool CanForceDebug() const {
+ return can_force_debug;
+ }
+
+private:
+ /// Attempts to parse a given sequence of capability descriptors.
+ ///
+ /// @param capabilities The sequence of capability descriptors to parse.
+ /// @param num_capabilities The number of descriptors within the given sequence.
+ /// @param vm_manager The memory manager that will perform any memory
+ /// mapping if necessary.
+ ///
+ /// @return RESULT_SUCCESS if no errors occur, otherwise an error code.
+ ///
+ ResultCode ParseCapabilities(const u32* capabilities, std::size_t num_capabilities,
+ VMManager& vm_manager);
+
+ /// Attempts to parse a capability descriptor that is only represented by a
+ /// single flag set.
+ ///
+ /// @param set_flags Running set of flags that are used to catch
+ /// flags being initialized more than once when they shouldn't be.
+ /// @param set_svc_bits Running set of bits representing the allowed supervisor calls mask.
+ /// @param flag The flag to attempt to parse.
+ /// @param vm_manager The memory manager that will perform any memory
+ /// mapping if necessary.
+ ///
+ /// @return RESULT_SUCCESS if no errors occurred, otherwise an error code.
+ ///
+ ResultCode ParseSingleFlagCapability(u32& set_flags, u32& set_svc_bits, u32 flag,
+ VMManager& vm_manager);
+
+ /// Clears the internal state of this process capability instance. Necessary,
+ /// to have a sane starting point due to us allowing running executables without
+ /// configuration metadata. We assume a process is not going to have metadata,
+ /// and if it turns out that the process does, in fact, have metadata, then
+ /// we attempt to parse it. Thus, we need this to reset data members back to
+ /// a good state.
+ ///
+ /// DO NOT ever make this a public member function. This isn't an invariant
+ /// anything external should depend upon (and if anything comes to rely on it,
+ /// you should immediately be questioning the design of that thing, not this
+ /// class. If the kernel itself can run without depending on behavior like that,
+ /// then so can yuzu).
+ ///
+ void Clear();
+
+ /// Handles flags related to the priority and core number capability flags.
+ ResultCode HandlePriorityCoreNumFlags(u32 flags);
+
+ /// Handles flags related to determining the allowable SVC mask.
+ ResultCode HandleSyscallFlags(u32& set_svc_bits, u32 flags);
+
+ /// Handles flags related to mapping physical memory pages.
+ ResultCode HandleMapPhysicalFlags(u32 flags, u32 size_flags, VMManager& vm_manager);
+
+ /// Handles flags related to mapping IO pages.
+ ResultCode HandleMapIOFlags(u32 flags, VMManager& vm_manager);
+
+ /// Handles flags related to the interrupt capability flags.
+ ResultCode HandleInterruptFlags(u32 flags);
+
+ /// Handles flags related to the program type.
+ ResultCode HandleProgramTypeFlags(u32 flags);
+
+ /// Handles flags related to the handle table size.
+ ResultCode HandleHandleTableFlags(u32 flags);
+
+ /// Handles flags related to the kernel version capability flags.
+ ResultCode HandleKernelVersionFlags(u32 flags);
+
+ /// Handles flags related to debug-specific capabilities.
+ ResultCode HandleDebugFlags(u32 flags);
+
+ SyscallCapabilities svc_capabilities;
+ InterruptCapabilities interrupt_capabilities;
+
+ u64 core_mask = 0;
+ u64 priority_mask = 0;
+
+ u32 handle_table_size = 0;
+ u32 kernel_version = 0;
+
+ ProgramType program_type = ProgramType::SysModule;
+
+ bool is_debuggable = false;
+ bool can_force_debug = false;
+};
+
+} // namespace Kernel
diff --git a/src/core/hle/kernel/readable_event.cpp b/src/core/hle/kernel/readable_event.cpp
new file mode 100644
index 000000000..6973e580c
--- /dev/null
+++ b/src/core/hle/kernel/readable_event.cpp
@@ -0,0 +1,51 @@
+// Copyright 2014 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include "common/assert.h"
+#include "core/hle/kernel/errors.h"
+#include "core/hle/kernel/object.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/thread.h"
+
+namespace Kernel {
+
+ReadableEvent::ReadableEvent(KernelCore& kernel) : WaitObject{kernel} {}
+ReadableEvent::~ReadableEvent() = default;
+
+bool ReadableEvent::ShouldWait(Thread* thread) const {
+ return !signaled;
+}
+
+void ReadableEvent::Acquire(Thread* thread) {
+ ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
+
+ if (reset_type == ResetType::OneShot)
+ signaled = false;
+}
+
+void ReadableEvent::Signal() {
+ signaled = true;
+ WakeupAllWaitingThreads();
+}
+
+void ReadableEvent::Clear() {
+ signaled = false;
+}
+
+ResultCode ReadableEvent::Reset() {
+ if (!signaled) {
+ return ERR_INVALID_STATE;
+ }
+
+ Clear();
+
+ return RESULT_SUCCESS;
+}
+
+void ReadableEvent::WakeupAllWaitingThreads() {
+ WaitObject::WakeupAllWaitingThreads();
+}
+
+} // namespace Kernel
diff --git a/src/core/hle/kernel/event.h b/src/core/hle/kernel/readable_event.h
index 27d6126b0..80b3b0aba 100644
--- a/src/core/hle/kernel/event.h
+++ b/src/core/hle/kernel/readable_event.h
@@ -4,56 +4,62 @@
#pragma once
-#include "common/common_types.h"
#include "core/hle/kernel/object.h"
#include "core/hle/kernel/wait_object.h"
+union ResultCode;
+
namespace Kernel {
class KernelCore;
+class WritableEvent;
+
+class ReadableEvent final : public WaitObject {
+ friend class WritableEvent;
-class Event final : public WaitObject {
public:
- /**
- * Creates an event
- * @param kernel The kernel instance to create this event under.
- * @param reset_type ResetType describing how to create event
- * @param name Optional name of event
- */
- static SharedPtr<Event> Create(KernelCore& kernel, ResetType reset_type,
- std::string name = "Unknown");
+ ~ReadableEvent() override;
std::string GetTypeName() const override {
- return "Event";
+ return "ReadableEvent";
}
std::string GetName() const override {
return name;
}
- static const HandleType HANDLE_TYPE = HandleType::Event;
- HandleType GetHandleType() const override {
- return HANDLE_TYPE;
- }
-
ResetType GetResetType() const {
return reset_type;
}
+ static const HandleType HANDLE_TYPE = HandleType::ReadableEvent;
+ HandleType GetHandleType() const override {
+ return HANDLE_TYPE;
+ }
+
bool ShouldWait(Thread* thread) const override;
void Acquire(Thread* thread) override;
void WakeupAllWaitingThreads() override;
- void Signal();
+ /// Unconditionally clears the readable event's state.
void Clear();
+ /// Clears the readable event's state if and only if it
+ /// has already been signaled.
+ ///
+ /// @pre The event must be in a signaled state. If this event
+ /// is in an unsignaled state and this function is called,
+ /// then ERR_INVALID_STATE will be returned.
+ ResultCode Reset();
+
private:
- explicit Event(KernelCore& kernel);
- ~Event() override;
+ explicit ReadableEvent(KernelCore& kernel);
+
+ void Signal();
- ResetType reset_type; ///< Current ResetType
+ ResetType reset_type;
+ bool signaled;
- bool signaled; ///< Whether the event has already been signaled
std::string name; ///< Name of event (optional)
};
diff --git a/src/core/hle/kernel/scheduler.cpp b/src/core/hle/kernel/scheduler.cpp
index 5a5f4cef1..df4d6cf0a 100644
--- a/src/core/hle/kernel/scheduler.cpp
+++ b/src/core/hle/kernel/scheduler.cpp
@@ -9,6 +9,7 @@
#include "common/logging/log.h"
#include "core/arm/arm_interface.h"
#include "core/core.h"
+#include "core/core_cpu.h"
#include "core/core_timing.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/process.h"
@@ -179,4 +180,69 @@ void Scheduler::SetThreadPriority(Thread* thread, u32 priority) {
ready_queue.prepare(priority);
}
+Thread* Scheduler::GetNextSuggestedThread(u32 core, u32 maximum_priority) const {
+ std::lock_guard<std::mutex> lock(scheduler_mutex);
+
+ const u32 mask = 1U << core;
+ return ready_queue.get_first_filter([mask, maximum_priority](Thread const* thread) {
+ return (thread->GetAffinityMask() & mask) != 0 && thread->GetPriority() < maximum_priority;
+ });
+}
+
+void Scheduler::YieldWithoutLoadBalancing(Thread* thread) {
+ ASSERT(thread != nullptr);
+ // Avoid yielding if the thread isn't even running.
+ ASSERT(thread->GetStatus() == ThreadStatus::Running);
+
+ // Sanity check that the priority is valid
+ ASSERT(thread->GetPriority() < THREADPRIO_COUNT);
+
+ // Yield this thread -- sleep for zero time and force reschedule to different thread
+ WaitCurrentThread_Sleep();
+ GetCurrentThread()->WakeAfterDelay(0);
+}
+
+void Scheduler::YieldWithLoadBalancing(Thread* thread) {
+ ASSERT(thread != nullptr);
+ const auto priority = thread->GetPriority();
+ const auto core = static_cast<u32>(thread->GetProcessorID());
+
+ // Avoid yielding if the thread isn't even running.
+ ASSERT(thread->GetStatus() == ThreadStatus::Running);
+
+ // Sanity check that the priority is valid
+ ASSERT(priority < THREADPRIO_COUNT);
+
+ // Sleep for zero time to be able to force reschedule to different thread
+ WaitCurrentThread_Sleep();
+ GetCurrentThread()->WakeAfterDelay(0);
+
+ Thread* suggested_thread = nullptr;
+
+ // Search through all of the cpu cores (except this one) for a suggested thread.
+ // Take the first non-nullptr one
+ for (unsigned cur_core = 0; cur_core < Core::NUM_CPU_CORES; ++cur_core) {
+ const auto res =
+ Core::System::GetInstance().CpuCore(cur_core).Scheduler().GetNextSuggestedThread(
+ core, priority);
+
+ // If scheduler provides a suggested thread
+ if (res != nullptr) {
+ // And its better than the current suggested thread (or is the first valid one)
+ if (suggested_thread == nullptr ||
+ suggested_thread->GetPriority() > res->GetPriority()) {
+ suggested_thread = res;
+ }
+ }
+ }
+
+ // If a suggested thread was found, queue that for this core
+ if (suggested_thread != nullptr)
+ suggested_thread->ChangeCore(core, suggested_thread->GetAffinityMask());
+}
+
+void Scheduler::YieldAndWaitForLoadBalancing(Thread* thread) {
+ UNIMPLEMENTED_MSG("Wait for load balancing thread yield type is not implemented!");
+}
+
} // namespace Kernel
diff --git a/src/core/hle/kernel/scheduler.h b/src/core/hle/kernel/scheduler.h
index c63032b7d..97ced4dfc 100644
--- a/src/core/hle/kernel/scheduler.h
+++ b/src/core/hle/kernel/scheduler.h
@@ -51,6 +51,75 @@ public:
/// Sets the priority of a thread in the scheduler
void SetThreadPriority(Thread* thread, u32 priority);
+ /// Gets the next suggested thread for load balancing
+ Thread* GetNextSuggestedThread(u32 core, u32 minimum_priority) const;
+
+ /**
+ * YieldWithoutLoadBalancing -- analogous to normal yield on a system
+ * Moves the thread to the end of the ready queue for its priority, and then reschedules the
+ * system to the new head of the queue.
+ *
+ * Example (Single Core -- but can be extrapolated to multi):
+ * ready_queue[prio=0]: ThreadA, ThreadB, ThreadC (->exec order->)
+ * Currently Running: ThreadR
+ *
+ * ThreadR calls YieldWithoutLoadBalancing
+ *
+ * ThreadR is moved to the end of ready_queue[prio=0]:
+ * ready_queue[prio=0]: ThreadA, ThreadB, ThreadC, ThreadR (->exec order->)
+ * Currently Running: Nothing
+ *
+ * System is rescheduled (ThreadA is popped off of queue):
+ * ready_queue[prio=0]: ThreadB, ThreadC, ThreadR (->exec order->)
+ * Currently Running: ThreadA
+ *
+ * If the queue is empty at time of call, no yielding occurs. This does not cross between cores
+ * or priorities at all.
+ */
+ void YieldWithoutLoadBalancing(Thread* thread);
+
+ /**
+ * YieldWithLoadBalancing -- yield but with better selection of the new running thread
+ * Moves the current thread to the end of the ready queue for its priority, then selects a
+ * 'suggested thread' (a thread on a different core that could run on this core) from the
+ * scheduler, changes its core, and reschedules the current core to that thread.
+ *
+ * Example (Dual Core -- can be extrapolated to Quad Core, this is just normal yield if it were
+ * single core):
+ * ready_queue[core=0][prio=0]: ThreadA, ThreadB (affinities not pictured as irrelevant
+ * ready_queue[core=1][prio=0]: ThreadC[affinity=both], ThreadD[affinity=core1only]
+ * Currently Running: ThreadQ on Core 0 || ThreadP on Core 1
+ *
+ * ThreadQ calls YieldWithLoadBalancing
+ *
+ * ThreadQ is moved to the end of ready_queue[core=0][prio=0]:
+ * ready_queue[core=0][prio=0]: ThreadA, ThreadB
+ * ready_queue[core=1][prio=0]: ThreadC[affinity=both], ThreadD[affinity=core1only]
+ * Currently Running: ThreadQ on Core 0 || ThreadP on Core 1
+ *
+ * A list of suggested threads for each core is compiled
+ * Suggested Threads: {ThreadC on Core 1}
+ * If this were quad core (as the switch is), there could be between 0 and 3 threads in this
+ * list. If there are more than one, the thread is selected by highest prio.
+ *
+ * ThreadC is core changed to Core 0:
+ * ready_queue[core=0][prio=0]: ThreadC, ThreadA, ThreadB, ThreadQ
+ * ready_queue[core=1][prio=0]: ThreadD
+ * Currently Running: None on Core 0 || ThreadP on Core 1
+ *
+ * System is rescheduled (ThreadC is popped off of queue):
+ * ready_queue[core=0][prio=0]: ThreadA, ThreadB, ThreadQ
+ * ready_queue[core=1][prio=0]: ThreadD
+ * Currently Running: ThreadC on Core 0 || ThreadP on Core 1
+ *
+ * If no suggested threads can be found this will behave just as normal yield. If there are
+ * multiple candidates for the suggested thread on a core, the highest prio is taken.
+ */
+ void YieldWithLoadBalancing(Thread* thread);
+
+ /// Currently unknown -- asserts as unimplemented on call
+ void YieldAndWaitForLoadBalancing(Thread* thread);
+
/// Returns a list of all threads managed by the scheduler
const std::vector<SharedPtr<Thread>>& GetThreadList() const {
return thread_list;
diff --git a/src/core/hle/kernel/server_session.cpp b/src/core/hle/kernel/server_session.cpp
index 80897f3a4..027434f92 100644
--- a/src/core/hle/kernel/server_session.cpp
+++ b/src/core/hle/kernel/server_session.cpp
@@ -6,6 +6,7 @@
#include <utility>
#include "common/assert.h"
+#include "common/common_types.h"
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
diff --git a/src/core/hle/kernel/server_session.h b/src/core/hle/kernel/server_session.h
index e068db2bf..e0e9d64c8 100644
--- a/src/core/hle/kernel/server_session.h
+++ b/src/core/hle/kernel/server_session.h
@@ -8,7 +8,6 @@
#include <string>
#include <vector>
-#include "common/common_types.h"
#include "core/hle/kernel/object.h"
#include "core/hle/kernel/wait_object.h"
#include "core/hle/result.h"
diff --git a/src/core/hle/kernel/shared_memory.cpp b/src/core/hle/kernel/shared_memory.cpp
index 0494581f5..22d0c1dd5 100644
--- a/src/core/hle/kernel/shared_memory.cpp
+++ b/src/core/hle/kernel/shared_memory.cpp
@@ -17,13 +17,13 @@ namespace Kernel {
SharedMemory::SharedMemory(KernelCore& kernel) : Object{kernel} {}
SharedMemory::~SharedMemory() = default;
-SharedPtr<SharedMemory> SharedMemory::Create(KernelCore& kernel, SharedPtr<Process> owner_process,
- u64 size, MemoryPermission permissions,
+SharedPtr<SharedMemory> SharedMemory::Create(KernelCore& kernel, Process* owner_process, u64 size,
+ MemoryPermission permissions,
MemoryPermission other_permissions, VAddr address,
MemoryRegion region, std::string name) {
SharedPtr<SharedMemory> shared_memory(new SharedMemory(kernel));
- shared_memory->owner_process = std::move(owner_process);
+ shared_memory->owner_process = owner_process;
shared_memory->name = std::move(name);
shared_memory->size = size;
shared_memory->permissions = permissions;
@@ -39,15 +39,15 @@ SharedPtr<SharedMemory> SharedMemory::Create(KernelCore& kernel, SharedPtr<Proce
shared_memory->backing_block.get());
}
} else {
- auto& vm_manager = shared_memory->owner_process->VMManager();
+ const auto& vm_manager = shared_memory->owner_process->VMManager();
// The memory is already available and mapped in the owner process.
- auto vma = vm_manager.FindVMA(address);
- ASSERT_MSG(vma != vm_manager.vma_map.end(), "Invalid memory address");
+ const auto vma = vm_manager.FindVMA(address);
+ ASSERT_MSG(vm_manager.IsValidHandle(vma), "Invalid memory address");
ASSERT_MSG(vma->second.backing_block, "Backing block doesn't exist for address");
// The returned VMA might be a bigger one encompassing the desired address.
- auto vma_offset = address - vma->first;
+ const auto vma_offset = address - vma->first;
ASSERT_MSG(vma_offset + size <= vma->second.size,
"Shared memory exceeds bounds of mapped block");
diff --git a/src/core/hle/kernel/shared_memory.h b/src/core/hle/kernel/shared_memory.h
index 0b48db699..dab2a6bea 100644
--- a/src/core/hle/kernel/shared_memory.h
+++ b/src/core/hle/kernel/shared_memory.h
@@ -45,8 +45,8 @@ public:
* linear heap.
* @param name Optional object name, used for debugging purposes.
*/
- static SharedPtr<SharedMemory> Create(KernelCore& kernel, SharedPtr<Process> owner_process,
- u64 size, MemoryPermission permissions,
+ static SharedPtr<SharedMemory> Create(KernelCore& kernel, Process* owner_process, u64 size,
+ MemoryPermission permissions,
MemoryPermission other_permissions, VAddr address = 0,
MemoryRegion region = MemoryRegion::BASE,
std::string name = "Unknown");
@@ -139,7 +139,7 @@ private:
/// Permission restrictions applied to other processes mapping the block.
MemoryPermission other_permissions{};
/// Process that created this shared memory block.
- SharedPtr<Process> owner_process;
+ Process* owner_process;
/// Address of shared memory block in the owner process if specified.
VAddr base_address = 0;
/// Name of shared memory object.
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index 1f19d5576..7cfecb68c 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -20,21 +20,22 @@
#include "core/hle/kernel/address_arbiter.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/mutex.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/readable_event.h"
#include "core/hle/kernel/resource_limit.h"
#include "core/hle/kernel/scheduler.h"
#include "core/hle/kernel/shared_memory.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/kernel/svc_wrap.h"
#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/lock.h"
#include "core/hle/result.h"
#include "core/hle/service/service.h"
-#include "core/settings.h"
+#include "core/memory.h"
namespace Kernel {
namespace {
@@ -63,43 +64,77 @@ bool IsInsideNewMapRegion(const VMManager& vm, VAddr address, u64 size) {
vm.GetNewMapRegionEndAddress());
}
+// 8 GiB
+constexpr u64 MAIN_MEMORY_SIZE = 0x200000000;
+
// Helper function that performs the common sanity checks for svcMapMemory
// and svcUnmapMemory. This is doable, as both functions perform their sanitizing
// in the same order.
ResultCode MapUnmapMemorySanityChecks(const VMManager& vm_manager, VAddr dst_addr, VAddr src_addr,
u64 size) {
- if (!Common::Is4KBAligned(dst_addr) || !Common::Is4KBAligned(src_addr)) {
+ if (!Common::Is4KBAligned(dst_addr)) {
+ LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
return ERR_INVALID_ADDRESS;
}
- if (size == 0 || !Common::Is4KBAligned(size)) {
+ if (!Common::Is4KBAligned(src_addr)) {
+ LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
+ return ERR_INVALID_SIZE;
+ }
+
+ if (size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size is 0");
+ return ERR_INVALID_SIZE;
+ }
+
+ if (!Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
return ERR_INVALID_SIZE;
}
if (!IsValidAddressRange(dst_addr, size)) {
+ LOG_ERROR(Kernel_SVC,
+ "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
+ dst_addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
if (!IsValidAddressRange(src_addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
+ src_addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
if (!IsInsideAddressSpace(vm_manager, src_addr, size)) {
+ LOG_ERROR(Kernel_SVC,
+ "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
+ src_addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
if (!IsInsideNewMapRegion(vm_manager, dst_addr, size)) {
+ LOG_ERROR(Kernel_SVC,
+ "Destination is not within the new map region, addr=0x{:016X}, size=0x{:016X}",
+ dst_addr, size);
return ERR_INVALID_MEMORY_RANGE;
}
const VAddr dst_end_address = dst_addr + size;
if (dst_end_address > vm_manager.GetHeapRegionBaseAddress() &&
vm_manager.GetHeapRegionEndAddress() > dst_addr) {
+ LOG_ERROR(Kernel_SVC,
+ "Destination does not fit within the heap region, addr=0x{:016X}, "
+ "size=0x{:016X}, end_addr=0x{:016X}",
+ dst_addr, size, dst_end_address);
return ERR_INVALID_MEMORY_RANGE;
}
if (dst_end_address > vm_manager.GetMapRegionBaseAddress() &&
vm_manager.GetMapRegionEndAddress() > dst_addr) {
+ LOG_ERROR(Kernel_SVC,
+ "Destination does not fit within the map region, addr=0x{:016X}, "
+ "size=0x{:016X}, end_addr=0x{:016X}",
+ dst_addr, size, dst_end_address);
return ERR_INVALID_MEMORY_RANGE;
}
@@ -143,15 +178,28 @@ ResultVal<s64> RetrieveResourceLimitValue(Handle resource_limit, u32 resource_ty
static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
- // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 4GB.
- if ((heap_size & 0xFFFFFFFE001FFFFF) != 0) {
+ // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 8GB.
+ if ((heap_size % 0x200000) != 0) {
+ LOG_ERROR(Kernel_SVC, "The heap size is not a multiple of 2MB, heap_size=0x{:016X}",
+ heap_size);
return ERR_INVALID_SIZE;
}
- auto& process = *Core::CurrentProcess();
- const VAddr heap_base = process.VMManager().GetHeapRegionBaseAddress();
- CASCADE_RESULT(*heap_addr,
- process.HeapAllocate(heap_base, heap_size, VMAPermission::ReadWrite));
+ if (heap_size >= 0x200000000) {
+ LOG_ERROR(Kernel_SVC, "The heap size is not less than 8GB, heap_size=0x{:016X}", heap_size);
+ return ERR_INVALID_SIZE;
+ }
+
+ auto& vm_manager = Core::CurrentProcess()->VMManager();
+ const VAddr heap_base = vm_manager.GetHeapRegionBaseAddress();
+ const auto alloc_result =
+ vm_manager.HeapAllocate(heap_base, heap_size, VMAPermission::ReadWrite);
+
+ if (alloc_result.Failed()) {
+ return alloc_result.Code();
+ }
+
+ *heap_addr = *alloc_result;
return RESULT_SUCCESS;
}
@@ -159,20 +207,31 @@ static ResultCode SetMemoryPermission(VAddr addr, u64 size, u32 prot) {
LOG_TRACE(Kernel_SVC, "called, addr=0x{:X}, size=0x{:X}, prot=0x{:X}", addr, size, prot);
if (!Common::Is4KBAligned(addr)) {
+ LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
return ERR_INVALID_ADDRESS;
}
- if (size == 0 || !Common::Is4KBAligned(size)) {
+ if (size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size is 0");
+ return ERR_INVALID_SIZE;
+ }
+
+ if (!Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
return ERR_INVALID_SIZE;
}
if (!IsValidAddressRange(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
+ addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
const auto permission = static_cast<MemoryPermission>(prot);
if (permission != MemoryPermission::None && permission != MemoryPermission::Read &&
permission != MemoryPermission::ReadWrite) {
+ LOG_ERROR(Kernel_SVC, "Invalid memory permission specified, Got memory permission=0x{:08X}",
+ static_cast<u32>(permission));
return ERR_INVALID_MEMORY_PERMISSIONS;
}
@@ -180,11 +239,15 @@ static ResultCode SetMemoryPermission(VAddr addr, u64 size, u32 prot) {
auto& vm_manager = current_process->VMManager();
if (!IsInsideAddressSpace(vm_manager, addr, size)) {
+ LOG_ERROR(Kernel_SVC,
+ "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
+ size);
return ERR_INVALID_ADDRESS_STATE;
}
const VMManager::VMAHandle iter = vm_manager.FindVMA(addr);
- if (iter == vm_manager.vma_map.end()) {
+ if (!vm_manager.IsValidHandle(iter)) {
+ LOG_ERROR(Kernel_SVC, "Unable to find VMA for address=0x{:016X}", addr);
return ERR_INVALID_ADDRESS_STATE;
}
@@ -197,11 +260,52 @@ static ResultCode SetMemoryPermission(VAddr addr, u64 size, u32 prot) {
return vm_manager.ReprotectRange(addr, size, converted_permissions);
}
-static ResultCode SetMemoryAttribute(VAddr addr, u64 size, u32 state0, u32 state1) {
- LOG_WARNING(Kernel_SVC,
- "(STUBBED) called, addr=0x{:X}, size=0x{:X}, state0=0x{:X}, state1=0x{:X}", addr,
- size, state0, state1);
- return RESULT_SUCCESS;
+static ResultCode SetMemoryAttribute(VAddr address, u64 size, u32 mask, u32 attribute) {
+ LOG_DEBUG(Kernel_SVC,
+ "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
+ size, mask, attribute);
+
+ if (!Common::Is4KBAligned(address)) {
+ LOG_ERROR(Kernel_SVC, "Address not page aligned (0x{:016X})", address);
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (size == 0 || !Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Invalid size (0x{:X}). Size must be non-zero and page aligned.",
+ size);
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (!IsValidAddressRange(address, size)) {
+ LOG_ERROR(Kernel_SVC, "Address range overflowed (Address: 0x{:016X}, Size: 0x{:016X})",
+ address, size);
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ const auto mem_attribute = static_cast<MemoryAttribute>(attribute);
+ const auto mem_mask = static_cast<MemoryAttribute>(mask);
+ const auto attribute_with_mask = mem_attribute | mem_mask;
+
+ if (attribute_with_mask != mem_mask) {
+ LOG_ERROR(Kernel_SVC,
+ "Memory attribute doesn't match the given mask (Attribute: 0x{:X}, Mask: {:X}",
+ attribute, mask);
+ return ERR_INVALID_COMBINATION;
+ }
+
+ if ((attribute_with_mask | MemoryAttribute::Uncached) != MemoryAttribute::Uncached) {
+ LOG_ERROR(Kernel_SVC, "Specified attribute isn't equal to MemoryAttributeUncached (8).");
+ return ERR_INVALID_COMBINATION;
+ }
+
+ auto& vm_manager = Core::CurrentProcess()->VMManager();
+ if (!IsInsideAddressSpace(vm_manager, address, size)) {
+ LOG_ERROR(Kernel_SVC,
+ "Given address (0x{:016X}) is outside the bounds of the address space.", address);
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ return vm_manager.SetMemoryAttribute(address, size, mem_mask, mem_attribute);
}
/// Maps a memory range into a different range.
@@ -209,15 +313,14 @@ static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
src_addr, size);
- auto* const current_process = Core::CurrentProcess();
- const auto& vm_manager = current_process->VMManager();
-
+ auto& vm_manager = Core::CurrentProcess()->VMManager();
const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
- if (result != RESULT_SUCCESS) {
+
+ if (result.IsError()) {
return result;
}
- return current_process->MirrorMemory(dst_addr, src_addr, size);
+ return vm_manager.MirrorMemory(dst_addr, src_addr, size, MemoryState::Stack);
}
/// Unmaps a region that was previously mapped with svcMapMemory
@@ -225,20 +328,22 @@ static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
src_addr, size);
- auto* const current_process = Core::CurrentProcess();
- const auto& vm_manager = current_process->VMManager();
-
+ auto& vm_manager = Core::CurrentProcess()->VMManager();
const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
- if (result != RESULT_SUCCESS) {
+
+ if (result.IsError()) {
return result;
}
- return current_process->UnmapMemory(dst_addr, src_addr, size);
+ return vm_manager.UnmapRange(dst_addr, size);
}
/// Connect to an OS service given the port name, returns the handle to the port to out
static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address) {
if (!Memory::IsValidVirtualAddress(port_name_address)) {
+ LOG_ERROR(Kernel_SVC,
+ "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
+ port_name_address);
return ERR_NOT_FOUND;
}
@@ -246,6 +351,8 @@ static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address
// Read 1 char beyond the max allowed port name to detect names that are too long.
std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
if (port_name.size() > PortNameMaxLength) {
+ LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
+ port_name.size());
return ERR_OUT_OF_RANGE;
}
@@ -288,12 +395,13 @@ static ResultCode SendSyncRequest(Handle handle) {
}
/// Get the ID for the specified thread.
-static ResultCode GetThreadId(u32* thread_id, Handle thread_handle) {
+static ResultCode GetThreadId(u64* thread_id, Handle thread_handle) {
LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", thread_handle);
return ERR_INVALID_HANDLE;
}
@@ -301,18 +409,33 @@ static ResultCode GetThreadId(u32* thread_id, Handle thread_handle) {
return RESULT_SUCCESS;
}
-/// Get the ID of the specified process
-static ResultCode GetProcessId(u32* process_id, Handle process_handle) {
- LOG_TRACE(Kernel_SVC, "called process=0x{:08X}", process_handle);
+/// Gets the ID of the specified process or a specified thread's owning process.
+static ResultCode GetProcessId(u64* process_id, Handle handle) {
+ LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
- const SharedPtr<Process> process = handle_table.Get<Process>(process_handle);
- if (!process) {
- return ERR_INVALID_HANDLE;
+ const SharedPtr<Process> process = handle_table.Get<Process>(handle);
+ if (process) {
+ *process_id = process->GetProcessID();
+ return RESULT_SUCCESS;
}
- *process_id = process->GetProcessID();
- return RESULT_SUCCESS;
+ const SharedPtr<Thread> thread = handle_table.Get<Thread>(handle);
+ if (thread) {
+ const Process* const owner_process = thread->GetOwnerProcess();
+ if (!owner_process) {
+ LOG_ERROR(Kernel_SVC, "Non-existent owning process encountered.");
+ return ERR_INVALID_HANDLE;
+ }
+
+ *process_id = owner_process->GetProcessID();
+ return RESULT_SUCCESS;
+ }
+
+ // NOTE: This should also handle debug objects before returning.
+
+ LOG_ERROR(Kernel_SVC, "Handle does not exist, handle=0x{:08X}", handle);
+ return ERR_INVALID_HANDLE;
}
/// Default thread wakeup callback for WaitSynchronization
@@ -337,12 +460,18 @@ static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64
LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
handles_address, handle_count, nano_seconds);
- if (!Memory::IsValidVirtualAddress(handles_address))
+ if (!Memory::IsValidVirtualAddress(handles_address)) {
+ LOG_ERROR(Kernel_SVC,
+ "Handle address is not a valid virtual address, handle_address=0x{:016X}",
+ handles_address);
return ERR_INVALID_POINTER;
+ }
static constexpr u64 MaxHandles = 0x40;
if (handle_count > MaxHandles) {
+ LOG_ERROR(Kernel_SVC, "Handle count specified is too large, expected {} but got {}",
+ MaxHandles, handle_count);
return ERR_OUT_OF_RANGE;
}
@@ -357,6 +486,7 @@ static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64
const auto object = handle_table.Get<WaitObject>(handle);
if (object == nullptr) {
+ LOG_ERROR(Kernel_SVC, "Object is a nullptr");
return ERR_INVALID_HANDLE;
}
@@ -380,11 +510,13 @@ static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64
// If a timeout value of 0 was provided, just return the Timeout error code instead of
// suspending the thread.
- if (nano_seconds == 0)
+ if (nano_seconds == 0) {
return RESULT_TIMEOUT;
+ }
- for (auto& object : objects)
+ for (auto& object : objects) {
object->AddWaitingThread(thread);
+ }
thread->SetWaitObjects(std::move(objects));
thread->SetStatus(ThreadStatus::WaitSynchAny);
@@ -405,6 +537,8 @@ static ResultCode CancelSynchronization(Handle thread_handle) {
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
+ thread_handle);
return ERR_INVALID_HANDLE;
}
@@ -423,10 +557,13 @@ static ResultCode ArbitrateLock(Handle holding_thread_handle, VAddr mutex_addr,
holding_thread_handle, mutex_addr, requesting_thread_handle);
if (Memory::IsKernelVirtualAddress(mutex_addr)) {
+ LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
+ mutex_addr);
return ERR_INVALID_ADDRESS_STATE;
}
if (!Common::IsWordAligned(mutex_addr)) {
+ LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
return ERR_INVALID_ADDRESS;
}
@@ -440,10 +577,13 @@ static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
if (Memory::IsKernelVirtualAddress(mutex_addr)) {
+ LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
+ mutex_addr);
return ERR_INVALID_ADDRESS_STATE;
}
if (!Common::IsWordAligned(mutex_addr)) {
+ LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
return ERR_INVALID_ADDRESS;
}
@@ -457,6 +597,7 @@ enum class BreakType : u32 {
PostNROLoad = 4,
PreNROUnload = 5,
PostNROUnload = 6,
+ CppException = 7,
};
struct BreakReason {
@@ -529,6 +670,9 @@ static void Break(u32 reason, u64 info1, u64 info2) {
"Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
info2);
break;
+ case BreakType::CppException:
+ LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
+ break;
default:
LOG_WARNING(
Debug_Emulated,
@@ -544,6 +688,9 @@ static void Break(u32 reason, u64 info1, u64 info2) {
"Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
reason, info1, info2);
handle_debug_buffer(info1, info2);
+ Core::System::GetInstance()
+ .ArmInterface(static_cast<std::size_t>(GetCurrentThread()->GetProcessorID()))
+ .LogBacktrace();
ASSERT(false);
Core::CurrentProcess()->PrepareForTermination();
@@ -572,8 +719,8 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
enum class GetInfoType : u64 {
// 1.0.0+
- AllowedCpuIdBitmask = 0,
- AllowedThreadPrioBitmask = 1,
+ AllowedCPUCoreMask = 0,
+ AllowedThreadPriorityMask = 1,
MapRegionBaseAddr = 2,
MapRegionSize = 3,
HeapRegionBaseAddr = 4,
@@ -581,7 +728,7 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
TotalMemoryUsage = 6,
TotalHeapUsage = 7,
IsCurrentProcessBeingDebugged = 8,
- ResourceHandleLimit = 9,
+ RegisterResourceLimit = 9,
IdleTickCount = 10,
RandomEntropy = 11,
PerformanceCounter = 0xF0000002,
@@ -601,86 +748,172 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
ThreadTickCount = 0xF0000002,
};
- const auto* current_process = Core::CurrentProcess();
- const auto& vm_manager = current_process->VMManager();
+ const auto info_id_type = static_cast<GetInfoType>(info_id);
- switch (static_cast<GetInfoType>(info_id)) {
- case GetInfoType::AllowedCpuIdBitmask:
- *result = current_process->GetAllowedProcessorMask();
- break;
- case GetInfoType::AllowedThreadPrioBitmask:
- *result = current_process->GetAllowedThreadPriorityMask();
- break;
+ switch (info_id_type) {
+ case GetInfoType::AllowedCPUCoreMask:
+ case GetInfoType::AllowedThreadPriorityMask:
case GetInfoType::MapRegionBaseAddr:
- *result = vm_manager.GetMapRegionBaseAddress();
- break;
case GetInfoType::MapRegionSize:
- *result = vm_manager.GetMapRegionSize();
- break;
case GetInfoType::HeapRegionBaseAddr:
- *result = vm_manager.GetHeapRegionBaseAddress();
- break;
case GetInfoType::HeapRegionSize:
- *result = vm_manager.GetHeapRegionSize();
- break;
+ case GetInfoType::ASLRRegionBaseAddr:
+ case GetInfoType::ASLRRegionSize:
+ case GetInfoType::NewMapRegionBaseAddr:
+ case GetInfoType::NewMapRegionSize:
case GetInfoType::TotalMemoryUsage:
- *result = vm_manager.GetTotalMemoryUsage();
- break;
case GetInfoType::TotalHeapUsage:
- *result = vm_manager.GetTotalHeapUsage();
- break;
+ case GetInfoType::IsVirtualAddressMemoryEnabled:
+ case GetInfoType::PersonalMmHeapUsage:
+ case GetInfoType::TitleId:
+ case GetInfoType::UserExceptionContextAddr: {
+ if (info_sub_id != 0) {
+ return ERR_INVALID_ENUM_VALUE;
+ }
+
+ const auto& current_process_handle_table = Core::CurrentProcess()->GetHandleTable();
+ const auto process = current_process_handle_table.Get<Process>(static_cast<Handle>(handle));
+ if (!process) {
+ return ERR_INVALID_HANDLE;
+ }
+
+ switch (info_id_type) {
+ case GetInfoType::AllowedCPUCoreMask:
+ *result = process->GetCoreMask();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::AllowedThreadPriorityMask:
+ *result = process->GetPriorityMask();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::MapRegionBaseAddr:
+ *result = process->VMManager().GetMapRegionBaseAddress();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::MapRegionSize:
+ *result = process->VMManager().GetMapRegionSize();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::HeapRegionBaseAddr:
+ *result = process->VMManager().GetHeapRegionBaseAddress();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::HeapRegionSize:
+ *result = process->VMManager().GetHeapRegionSize();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::ASLRRegionBaseAddr:
+ *result = process->VMManager().GetASLRRegionBaseAddress();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::ASLRRegionSize:
+ *result = process->VMManager().GetASLRRegionSize();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::NewMapRegionBaseAddr:
+ *result = process->VMManager().GetNewMapRegionBaseAddress();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::NewMapRegionSize:
+ *result = process->VMManager().GetNewMapRegionSize();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::TotalMemoryUsage:
+ *result = process->VMManager().GetTotalMemoryUsage();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::TotalHeapUsage:
+ *result = process->VMManager().GetTotalHeapUsage();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::IsVirtualAddressMemoryEnabled:
+ *result = process->IsVirtualMemoryEnabled();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::TitleId:
+ *result = process->GetTitleID();
+ return RESULT_SUCCESS;
+
+ case GetInfoType::UserExceptionContextAddr:
+ LOG_WARNING(Kernel_SVC,
+ "(STUBBED) Attempted to query user exception context address, returned 0");
+ *result = 0;
+ return RESULT_SUCCESS;
+
+ default:
+ break;
+ }
+
+ LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
+ return ERR_INVALID_ENUM_VALUE;
+ }
+
case GetInfoType::IsCurrentProcessBeingDebugged:
*result = 0;
- break;
+ return RESULT_SUCCESS;
+
+ case GetInfoType::RegisterResourceLimit: {
+ if (handle != 0) {
+ return ERR_INVALID_HANDLE;
+ }
+
+ if (info_sub_id != 0) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ Process* const current_process = Core::CurrentProcess();
+ HandleTable& handle_table = current_process->GetHandleTable();
+ const auto resource_limit = current_process->GetResourceLimit();
+ if (!resource_limit) {
+ *result = KernelHandle::InvalidHandle;
+ // Yes, the kernel considers this a successful operation.
+ return RESULT_SUCCESS;
+ }
+
+ const auto table_result = handle_table.Create(resource_limit);
+ if (table_result.Failed()) {
+ return table_result.Code();
+ }
+
+ *result = *table_result;
+ return RESULT_SUCCESS;
+ }
+
case GetInfoType::RandomEntropy:
if (handle != 0) {
+ LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
+ handle);
return ERR_INVALID_HANDLE;
}
if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
+ LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
+ Process::RANDOM_ENTROPY_SIZE, info_sub_id);
return ERR_INVALID_COMBINATION;
}
- *result = current_process->GetRandomEntropy(info_sub_id);
+ *result = Core::CurrentProcess()->GetRandomEntropy(info_sub_id);
return RESULT_SUCCESS;
- break;
- case GetInfoType::ASLRRegionBaseAddr:
- *result = vm_manager.GetASLRRegionBaseAddress();
- break;
- case GetInfoType::ASLRRegionSize:
- *result = vm_manager.GetASLRRegionSize();
- break;
- case GetInfoType::NewMapRegionBaseAddr:
- *result = vm_manager.GetNewMapRegionBaseAddress();
- break;
- case GetInfoType::NewMapRegionSize:
- *result = vm_manager.GetNewMapRegionSize();
- break;
- case GetInfoType::IsVirtualAddressMemoryEnabled:
- *result = current_process->IsVirtualMemoryEnabled();
- break;
- case GetInfoType::TitleId:
- *result = current_process->GetTitleID();
- break;
+
case GetInfoType::PrivilegedProcessId:
LOG_WARNING(Kernel_SVC,
"(STUBBED) Attempted to query privileged process id bounds, returned 0");
*result = 0;
- break;
- case GetInfoType::UserExceptionContextAddr:
- LOG_WARNING(Kernel_SVC,
- "(STUBBED) Attempted to query user exception context address, returned 0");
- *result = 0;
- break;
+ return RESULT_SUCCESS;
+
case GetInfoType::ThreadTickCount: {
constexpr u64 num_cpus = 4;
if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
+ LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
+ info_sub_id);
return ERR_INVALID_COMBINATION;
}
const auto thread =
- current_process->GetHandleTable().Get<Thread>(static_cast<Handle>(handle));
+ Core::CurrentProcess()->GetHandleTable().Get<Thread>(static_cast<Handle>(handle));
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
+ static_cast<Handle>(handle));
return ERR_INVALID_HANDLE;
}
@@ -700,19 +933,45 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
}
*result = out_ticks;
- break;
+ return RESULT_SUCCESS;
}
+
default:
LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
return ERR_INVALID_ENUM_VALUE;
}
-
- return RESULT_SUCCESS;
}
/// Sets the thread activity
-static ResultCode SetThreadActivity(Handle handle, u32 unknown) {
- LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, unknown=0x{:08X}", handle, unknown);
+static ResultCode SetThreadActivity(Handle handle, u32 activity) {
+ LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", handle, activity);
+ if (activity > static_cast<u32>(ThreadActivity::Paused)) {
+ return ERR_INVALID_ENUM_VALUE;
+ }
+
+ const auto* current_process = Core::CurrentProcess();
+ const SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
+ if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
+ return ERR_INVALID_HANDLE;
+ }
+
+ if (thread->GetOwnerProcess() != current_process) {
+ LOG_ERROR(Kernel_SVC,
+ "The current process does not own the current thread, thread_handle={:08X} "
+ "thread_pid={}, "
+ "current_process_pid={}",
+ handle, thread->GetOwnerProcess()->GetProcessID(),
+ current_process->GetProcessID());
+ return ERR_INVALID_HANDLE;
+ }
+
+ if (thread == GetCurrentThread()) {
+ LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
+ return ERR_BUSY;
+ }
+
+ thread->SetActivity(static_cast<ThreadActivity>(activity));
return RESULT_SUCCESS;
}
@@ -723,15 +982,23 @@ static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
const auto* current_process = Core::CurrentProcess();
const SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
return ERR_INVALID_HANDLE;
}
if (thread->GetOwnerProcess() != current_process) {
+ LOG_ERROR(Kernel_SVC,
+ "The current process does not own the current thread, thread_handle={:08X} "
+ "thread_pid={}, "
+ "current_process_pid={}",
+ handle, thread->GetOwnerProcess()->GetProcessID(),
+ current_process->GetProcessID());
return ERR_INVALID_HANDLE;
}
if (thread == GetCurrentThread()) {
- return ERR_ALREADY_REGISTERED;
+ LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
+ return ERR_BUSY;
}
Core::ARM_Interface::ThreadContext ctx = thread->GetContext();
@@ -751,9 +1018,12 @@ static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
/// Gets the priority for the specified thread
static ResultCode GetThreadPriority(u32* priority, Handle handle) {
+ LOG_TRACE(Kernel_SVC, "called");
+
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
return ERR_INVALID_HANDLE;
}
@@ -763,7 +1033,13 @@ static ResultCode GetThreadPriority(u32* priority, Handle handle) {
/// Sets the priority for the specified thread
static ResultCode SetThreadPriority(Handle handle, u32 priority) {
+ LOG_TRACE(Kernel_SVC, "called");
+
if (priority > THREADPRIO_LOWEST) {
+ LOG_ERROR(
+ Kernel_SVC,
+ "An invalid priority was specified, expected {} but got {} for thread_handle={:08X}",
+ THREADPRIO_LOWEST, priority, handle);
return ERR_INVALID_THREAD_PRIORITY;
}
@@ -771,6 +1047,7 @@ static ResultCode SetThreadPriority(Handle handle, u32 priority) {
SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
return ERR_INVALID_HANDLE;
}
@@ -793,32 +1070,46 @@ static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 s
shared_memory_handle, addr, size, permissions);
if (!Common::Is4KBAligned(addr)) {
+ LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
return ERR_INVALID_ADDRESS;
}
- if (size == 0 || !Common::Is4KBAligned(size)) {
+ if (size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size is 0");
+ return ERR_INVALID_SIZE;
+ }
+
+ if (!Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
return ERR_INVALID_SIZE;
}
if (!IsValidAddressRange(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
+ addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
const auto permissions_type = static_cast<MemoryPermission>(permissions);
if (permissions_type != MemoryPermission::Read &&
permissions_type != MemoryPermission::ReadWrite) {
- LOG_ERROR(Kernel_SVC, "Invalid permissions=0x{:08X}", permissions);
+ LOG_ERROR(Kernel_SVC, "Expected Read or ReadWrite permission but got permissions=0x{:08X}",
+ permissions);
return ERR_INVALID_MEMORY_PERMISSIONS;
}
auto* const current_process = Core::CurrentProcess();
auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
if (!shared_memory) {
+ LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
+ shared_memory_handle);
return ERR_INVALID_HANDLE;
}
const auto& vm_manager = current_process->VMManager();
if (!vm_manager.IsWithinASLRRegion(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
+ addr, size);
return ERR_INVALID_MEMORY_RANGE;
}
@@ -830,61 +1121,82 @@ static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64
shared_memory_handle, addr, size);
if (!Common::Is4KBAligned(addr)) {
+ LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
return ERR_INVALID_ADDRESS;
}
- if (size == 0 || !Common::Is4KBAligned(size)) {
+ if (size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size is 0");
+ return ERR_INVALID_SIZE;
+ }
+
+ if (!Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
return ERR_INVALID_SIZE;
}
if (!IsValidAddressRange(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
+ addr, size);
return ERR_INVALID_ADDRESS_STATE;
}
auto* const current_process = Core::CurrentProcess();
auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
if (!shared_memory) {
+ LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
+ shared_memory_handle);
return ERR_INVALID_HANDLE;
}
const auto& vm_manager = current_process->VMManager();
if (!vm_manager.IsWithinASLRRegion(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
+ addr, size);
return ERR_INVALID_MEMORY_RANGE;
}
return shared_memory->Unmap(*current_process, addr);
}
-/// Query process memory
-static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
- Handle process_handle, u64 addr) {
+static ResultCode QueryProcessMemory(VAddr memory_info_address, VAddr page_info_address,
+ Handle process_handle, VAddr address) {
+ LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
SharedPtr<Process> process = handle_table.Get<Process>(process_handle);
if (!process) {
+ LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
+ process_handle);
return ERR_INVALID_HANDLE;
}
- auto vma = process->VMManager().FindVMA(addr);
- memory_info->attributes = 0;
- if (vma == process->VMManager().vma_map.end()) {
- memory_info->base_address = 0;
- memory_info->permission = static_cast<u32>(VMAPermission::None);
- memory_info->size = 0;
- memory_info->type = static_cast<u32>(MemoryState::Unmapped);
- } else {
- memory_info->base_address = vma->second.base;
- memory_info->permission = static_cast<u32>(vma->second.permissions);
- memory_info->size = vma->second.size;
- memory_info->type = static_cast<u32>(vma->second.meminfo_state);
- }
- LOG_TRACE(Kernel_SVC, "called process=0x{:08X} addr={:X}", process_handle, addr);
+ const auto& vm_manager = process->VMManager();
+ const MemoryInfo memory_info = vm_manager.QueryMemory(address);
+
+ Memory::Write64(memory_info_address, memory_info.base_address);
+ Memory::Write64(memory_info_address + 8, memory_info.size);
+ Memory::Write32(memory_info_address + 16, memory_info.state);
+ Memory::Write32(memory_info_address + 20, memory_info.attributes);
+ Memory::Write32(memory_info_address + 24, memory_info.permission);
+ Memory::Write32(memory_info_address + 32, memory_info.ipc_ref_count);
+ Memory::Write32(memory_info_address + 28, memory_info.device_ref_count);
+ Memory::Write32(memory_info_address + 36, 0);
+
+ // Page info appears to be currently unused by the kernel and is always set to zero.
+ Memory::Write32(page_info_address, 0);
+
return RESULT_SUCCESS;
}
-/// Query memory
-static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
- LOG_TRACE(Kernel_SVC, "called, addr={:X}", addr);
- return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
+static ResultCode QueryMemory(VAddr memory_info_address, VAddr page_info_address,
+ VAddr query_address) {
+ LOG_TRACE(Kernel_SVC,
+ "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
+ "query_address=0x{:016X}",
+ memory_info_address, page_info_address, query_address);
+
+ return QueryProcessMemory(memory_info_address, page_info_address, CurrentProcess,
+ query_address);
}
/// Exits the current process
@@ -906,29 +1218,42 @@ static void ExitProcess() {
/// Creates a new thread
static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
u32 priority, s32 processor_id) {
- if (priority > THREADPRIO_LOWEST) {
- return ERR_INVALID_THREAD_PRIORITY;
- }
+ LOG_TRACE(Kernel_SVC,
+ "called entrypoint=0x{:08X}, arg=0x{:08X}, stacktop=0x{:08X}, "
+ "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
+ entry_point, arg, stack_top, priority, processor_id, *out_handle);
auto* const current_process = Core::CurrentProcess();
- if (processor_id == THREADPROCESSORID_DEFAULT) {
- // Set the target CPU to the one specified in the process' exheader.
- processor_id = current_process->GetDefaultProcessorID();
- ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
+ if (processor_id == THREADPROCESSORID_IDEAL) {
+ // Set the target CPU to the one specified by the process.
+ processor_id = current_process->GetIdealCore();
+ ASSERT(processor_id != THREADPROCESSORID_IDEAL);
}
- switch (processor_id) {
- case THREADPROCESSORID_0:
- case THREADPROCESSORID_1:
- case THREADPROCESSORID_2:
- case THREADPROCESSORID_3:
- break;
- default:
+ if (processor_id < THREADPROCESSORID_0 || processor_id > THREADPROCESSORID_3) {
LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
return ERR_INVALID_PROCESSOR_ID;
}
+ const u64 core_mask = current_process->GetCoreMask();
+ if ((core_mask | (1ULL << processor_id)) != core_mask) {
+ LOG_ERROR(Kernel_SVC, "Invalid thread core specified ({})", processor_id);
+ return ERR_INVALID_PROCESSOR_ID;
+ }
+
+ if (priority > THREADPRIO_LOWEST) {
+ LOG_ERROR(Kernel_SVC,
+ "Invalid thread priority specified ({}). Must be within the range 0-64",
+ priority);
+ return ERR_INVALID_THREAD_PRIORITY;
+ }
+
+ if (((1ULL << priority) & current_process->GetPriorityMask()) == 0) {
+ LOG_ERROR(Kernel_SVC, "Invalid thread priority specified ({})", priority);
+ return ERR_INVALID_THREAD_PRIORITY;
+ }
+
const std::string name = fmt::format("thread-{:X}", entry_point);
auto& kernel = Core::System::GetInstance().Kernel();
CASCADE_RESULT(SharedPtr<Thread> thread,
@@ -937,6 +1262,8 @@ static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, V
const auto new_guest_handle = current_process->GetHandleTable().Create(thread);
if (new_guest_handle.Failed()) {
+ LOG_ERROR(Kernel_SVC, "Failed to create handle with error=0x{:X}",
+ new_guest_handle.Code().raw);
return new_guest_handle.Code();
}
thread->SetGuestHandle(*new_guest_handle);
@@ -944,11 +1271,6 @@ static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, V
Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
- LOG_TRACE(Kernel_SVC,
- "called entrypoint=0x{:08X} ({}), arg=0x{:08X}, stacktop=0x{:08X}, "
- "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
- entry_point, name, arg, stack_top, priority, processor_id, *out_handle);
-
return RESULT_SUCCESS;
}
@@ -959,13 +1281,18 @@ static ResultCode StartThread(Handle thread_handle) {
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
+ thread_handle);
return ERR_INVALID_HANDLE;
}
ASSERT(thread->GetStatus() == ThreadStatus::Dormant);
thread->ResumeFromWait();
- Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
+
+ if (thread->GetStatus() == ThreadStatus::Ready) {
+ Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
+ }
return RESULT_SUCCESS;
}
@@ -982,18 +1309,38 @@ static void ExitThread() {
static void SleepThread(s64 nanoseconds) {
LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
- // Don't attempt to yield execution if there are no available threads to run,
- // this way we avoid a useless reschedule to the idle thread.
- if (nanoseconds == 0 && !Core::System::GetInstance().CurrentScheduler().HaveReadyThreads())
- return;
+ enum class SleepType : s64 {
+ YieldWithoutLoadBalancing = 0,
+ YieldWithLoadBalancing = -1,
+ YieldAndWaitForLoadBalancing = -2,
+ };
- // Sleep current thread and check for next thread to schedule
- WaitCurrentThread_Sleep();
+ if (nanoseconds <= 0) {
+ auto& scheduler{Core::System::GetInstance().CurrentScheduler()};
+ switch (static_cast<SleepType>(nanoseconds)) {
+ case SleepType::YieldWithoutLoadBalancing:
+ scheduler.YieldWithoutLoadBalancing(GetCurrentThread());
+ break;
+ case SleepType::YieldWithLoadBalancing:
+ scheduler.YieldWithLoadBalancing(GetCurrentThread());
+ break;
+ case SleepType::YieldAndWaitForLoadBalancing:
+ scheduler.YieldAndWaitForLoadBalancing(GetCurrentThread());
+ break;
+ default:
+ UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
+ }
+ } else {
+ // Sleep current thread and check for next thread to schedule
+ WaitCurrentThread_Sleep();
- // Create an event to wake the thread up after the specified nanosecond delay has passed
- GetCurrentThread()->WakeAfterDelay(nanoseconds);
+ // Create an event to wake the thread up after the specified nanosecond delay has passed
+ GetCurrentThread()->WakeAfterDelay(nanoseconds);
+ }
- Core::System::GetInstance().PrepareReschedule();
+ // Reschedule all CPU cores
+ for (std::size_t i = 0; i < Core::NUM_CPU_CORES; ++i)
+ Core::System::GetInstance().CpuCore(i).PrepareReschedule();
}
/// Wait process wide key atomic
@@ -1138,10 +1485,12 @@ static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout
address, type, value, timeout);
// If the passed address is a kernel virtual address, return invalid memory state.
if (Memory::IsKernelVirtualAddress(address)) {
+ LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
return ERR_INVALID_ADDRESS_STATE;
}
// If the address is not properly aligned to 4 bytes, return invalid address.
- if (address % sizeof(u32) != 0) {
+ if (!Common::IsWordAligned(address)) {
+ LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
return ERR_INVALID_ADDRESS;
}
@@ -1153,6 +1502,10 @@ static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout
case AddressArbiter::ArbitrationType::WaitIfEqual:
return AddressArbiter::WaitForAddressIfEqual(address, value, timeout);
default:
+ LOG_ERROR(Kernel_SVC,
+ "Invalid arbitration type, expected WaitIfLessThan, DecrementAndWaitIfLessThan "
+ "or WaitIfEqual but got {}",
+ type);
return ERR_INVALID_ENUM_VALUE;
}
}
@@ -1163,10 +1516,12 @@ static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to
address, type, value, num_to_wake);
// If the passed address is a kernel virtual address, return invalid memory state.
if (Memory::IsKernelVirtualAddress(address)) {
+ LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
return ERR_INVALID_ADDRESS_STATE;
}
// If the address is not properly aligned to 4 bytes, return invalid address.
- if (address % sizeof(u32) != 0) {
+ if (!Common::IsWordAligned(address)) {
+ LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
return ERR_INVALID_ADDRESS;
}
@@ -1179,12 +1534,18 @@ static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to
return AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(address, value,
num_to_wake);
default:
+ LOG_ERROR(Kernel_SVC,
+ "Invalid signal type, expected Signal, IncrementAndSignalIfEqual "
+ "or ModifyByWaitingCountAndSignalIfEqual but got {}",
+ type);
return ERR_INVALID_ENUM_VALUE;
}
}
/// This returns the total CPU ticks elapsed since the CPU was powered-on
static u64 GetSystemTick() {
+ LOG_TRACE(Kernel_SVC, "called");
+
const u64 result{CoreTiming::GetTicks()};
// Advance time to defeat dumb games that busy-wait for the frame to end.
@@ -1201,17 +1562,24 @@ static ResultCode CloseHandle(Handle handle) {
return handle_table.Close(handle);
}
-/// Reset an event
+/// Clears the signaled state of an event or process.
static ResultCode ResetSignal(Handle handle) {
LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
- auto event = handle_table.Get<Event>(handle);
- ASSERT(event != nullptr);
+ auto event = handle_table.Get<ReadableEvent>(handle);
+ if (event) {
+ return event->Reset();
+ }
+
+ auto process = handle_table.Get<Process>(handle);
+ if (process) {
+ return process->ClearSignalState();
+ }
- event->Clear();
- return RESULT_SUCCESS;
+ LOG_ERROR(Kernel_SVC, "Invalid handle (0x{:08X})", handle);
+ return ERR_INVALID_HANDLE;
}
/// Creates a TransferMemory object
@@ -1244,9 +1612,9 @@ static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32
}
auto& kernel = Core::System::GetInstance().Kernel();
- auto& handle_table = Core::CurrentProcess()->GetHandleTable();
- const auto shared_mem_handle = SharedMemory::Create(
- kernel, handle_table.Get<Process>(CurrentProcess), size, perms, perms, addr);
+ auto process = kernel.CurrentProcess();
+ auto& handle_table = process->GetHandleTable();
+ const auto shared_mem_handle = SharedMemory::Create(kernel, process, size, perms, perms, addr);
CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
return RESULT_SUCCESS;
@@ -1258,6 +1626,8 @@ static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask)
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
+ thread_handle);
return ERR_INVALID_HANDLE;
}
@@ -1268,26 +1638,29 @@ static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask)
}
static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
- LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:16X}, core=0x{:X}", thread_handle,
+ LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:016X}, core=0x{:X}", thread_handle,
mask, core);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
if (!thread) {
+ LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
+ thread_handle);
return ERR_INVALID_HANDLE;
}
- if (core == static_cast<u32>(THREADPROCESSORID_DEFAULT)) {
- const u8 default_processor_id = thread->GetOwnerProcess()->GetDefaultProcessorID();
+ if (core == static_cast<u32>(THREADPROCESSORID_IDEAL)) {
+ const u8 ideal_cpu_core = thread->GetOwnerProcess()->GetIdealCore();
- ASSERT(default_processor_id != static_cast<u8>(THREADPROCESSORID_DEFAULT));
+ ASSERT(ideal_cpu_core != static_cast<u8>(THREADPROCESSORID_IDEAL));
- // Set the target CPU to the one specified in the process' exheader.
- core = default_processor_id;
+ // Set the target CPU to the ideal core specified by the process.
+ core = ideal_cpu_core;
mask = 1ULL << core;
}
if (mask == 0) {
+ LOG_ERROR(Kernel_SVC, "Mask is 0");
return ERR_INVALID_COMBINATION;
}
@@ -1297,11 +1670,14 @@ static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
if (core == OnlyChangeMask) {
core = thread->GetIdealCore();
} else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
+ LOG_ERROR(Kernel_SVC, "Invalid core specified, got {}", core);
return ERR_INVALID_PROCESSOR_ID;
}
// Error out if the input core isn't enabled in the input mask.
if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
+ LOG_ERROR(Kernel_SVC, "Core is not enabled for the current mask, core={}, mask={:016X}",
+ core, mask);
return ERR_INVALID_COMBINATION;
}
@@ -1314,44 +1690,109 @@ static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permiss
u32 remote_permissions) {
LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
local_permissions, remote_permissions);
+ if (size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size is 0");
+ return ERR_INVALID_SIZE;
+ }
+ if (!Common::Is4KBAligned(size)) {
+ LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
+ return ERR_INVALID_SIZE;
+ }
- // Size must be a multiple of 4KB and be less than or equal to
- // approx. 8 GB (actually (1GB - 512B) * 8)
- if (size == 0 || (size & 0xFFFFFFFE00000FFF) != 0) {
+ if (size >= MAIN_MEMORY_SIZE) {
+ LOG_ERROR(Kernel_SVC, "Size is not less than 8GB, 0x{:016X}", size);
return ERR_INVALID_SIZE;
}
const auto local_perms = static_cast<MemoryPermission>(local_permissions);
if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
+ LOG_ERROR(Kernel_SVC,
+ "Invalid local memory permissions, expected Read or ReadWrite but got "
+ "local_permissions={}",
+ static_cast<u32>(local_permissions));
return ERR_INVALID_MEMORY_PERMISSIONS;
}
const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
remote_perms != MemoryPermission::DontCare) {
+ LOG_ERROR(Kernel_SVC,
+ "Invalid remote memory permissions, expected Read, ReadWrite or DontCare but got "
+ "remote_permissions={}",
+ static_cast<u32>(remote_permissions));
return ERR_INVALID_MEMORY_PERMISSIONS;
}
auto& kernel = Core::System::GetInstance().Kernel();
- auto& handle_table = Core::CurrentProcess()->GetHandleTable();
- auto shared_mem_handle =
- SharedMemory::Create(kernel, handle_table.Get<Process>(KernelHandle::CurrentProcess), size,
- local_perms, remote_perms);
+ auto process = kernel.CurrentProcess();
+ auto& handle_table = process->GetHandleTable();
+ auto shared_mem_handle = SharedMemory::Create(kernel, process, size, local_perms, remote_perms);
CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
return RESULT_SUCCESS;
}
+static ResultCode CreateEvent(Handle* write_handle, Handle* read_handle) {
+ LOG_DEBUG(Kernel_SVC, "called");
+
+ auto& kernel = Core::System::GetInstance().Kernel();
+ const auto [readable_event, writable_event] =
+ WritableEvent::CreateEventPair(kernel, ResetType::Sticky, "CreateEvent");
+
+ HandleTable& handle_table = kernel.CurrentProcess()->GetHandleTable();
+
+ const auto write_create_result = handle_table.Create(writable_event);
+ if (write_create_result.Failed()) {
+ return write_create_result.Code();
+ }
+ *write_handle = *write_create_result;
+
+ const auto read_create_result = handle_table.Create(readable_event);
+ if (read_create_result.Failed()) {
+ handle_table.Close(*write_create_result);
+ return read_create_result.Code();
+ }
+ *read_handle = *read_create_result;
+
+ LOG_DEBUG(Kernel_SVC,
+ "successful. Writable event handle=0x{:08X}, Readable event handle=0x{:08X}",
+ *write_create_result, *read_create_result);
+ return RESULT_SUCCESS;
+}
+
static ResultCode ClearEvent(Handle handle) {
LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
- SharedPtr<Event> evt = handle_table.Get<Event>(handle);
- if (evt == nullptr) {
+
+ auto writable_event = handle_table.Get<WritableEvent>(handle);
+ if (writable_event) {
+ writable_event->Clear();
+ return RESULT_SUCCESS;
+ }
+
+ auto readable_event = handle_table.Get<ReadableEvent>(handle);
+ if (readable_event) {
+ readable_event->Clear();
+ return RESULT_SUCCESS;
+ }
+
+ LOG_ERROR(Kernel_SVC, "Event handle does not exist, handle=0x{:08X}", handle);
+ return ERR_INVALID_HANDLE;
+}
+
+static ResultCode SignalEvent(Handle handle) {
+ LOG_DEBUG(Kernel_SVC, "called. Handle=0x{:08X}", handle);
+
+ HandleTable& handle_table = Core::CurrentProcess()->GetHandleTable();
+ auto writable_event = handle_table.Get<WritableEvent>(handle);
+
+ if (!writable_event) {
+ LOG_ERROR(Kernel_SVC, "Non-existent writable event handle used (0x{:08X})", handle);
return ERR_INVALID_HANDLE;
}
- evt->Clear();
+ writable_event->Signal();
return RESULT_SUCCESS;
}
@@ -1366,11 +1807,14 @@ static ResultCode GetProcessInfo(u64* out, Handle process_handle, u32 type) {
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
const auto process = handle_table.Get<Process>(process_handle);
if (!process) {
+ LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
+ process_handle);
return ERR_INVALID_HANDLE;
}
const auto info_type = static_cast<InfoType>(type);
if (info_type != InfoType::Status) {
+ LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
return ERR_INVALID_ENUM_VALUE;
}
@@ -1487,7 +1931,7 @@ static const FunctionDef SVC_Table[] = {
{0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
{0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
{0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
- {0x11, nullptr, "SignalEvent"},
+ {0x11, SvcWrap<SignalEvent>, "SignalEvent"},
{0x12, SvcWrap<ClearEvent>, "ClearEvent"},
{0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
{0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
@@ -1539,7 +1983,7 @@ static const FunctionDef SVC_Table[] = {
{0x42, nullptr, "ReplyAndReceiveLight"},
{0x43, nullptr, "ReplyAndReceive"},
{0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
- {0x45, nullptr, "CreateEvent"},
+ {0x45, SvcWrap<CreateEvent>, "CreateEvent"},
{0x46, nullptr, "Unknown"},
{0x47, nullptr, "Unknown"},
{0x48, nullptr, "MapPhysicalMemoryUnsafe"},
@@ -1588,7 +2032,7 @@ static const FunctionDef SVC_Table[] = {
{0x73, nullptr, "SetProcessMemoryPermission"},
{0x74, nullptr, "MapProcessMemory"},
{0x75, nullptr, "UnmapProcessMemory"},
- {0x76, nullptr, "QueryProcessMemory"},
+ {0x76, SvcWrap<QueryProcessMemory>, "QueryProcessMemory"},
{0x77, nullptr, "MapProcessCodeMemory"},
{0x78, nullptr, "UnmapProcessCodeMemory"},
{0x79, nullptr, "CreateProcess"},
diff --git a/src/core/hle/kernel/svc.h b/src/core/hle/kernel/svc.h
index b06aac4ec..c37ae0f98 100644
--- a/src/core/hle/kernel/svc.h
+++ b/src/core/hle/kernel/svc.h
@@ -8,22 +8,6 @@
namespace Kernel {
-struct MemoryInfo {
- u64 base_address;
- u64 size;
- u32 type;
- u32 attributes;
- u32 permission;
- u32 device_refcount;
- u32 ipc_refcount;
- INSERT_PADDING_WORDS(1);
-};
-static_assert(sizeof(MemoryInfo) == 0x28, "MemoryInfo has incorrect size.");
-
-struct PageInfo {
- u64 flags;
-};
-
void CallSVC(u32 immediate);
} // namespace Kernel
diff --git a/src/core/hle/kernel/svc_wrap.h b/src/core/hle/kernel/svc_wrap.h
index fa1116624..2a2c2c5ea 100644
--- a/src/core/hle/kernel/svc_wrap.h
+++ b/src/core/hle/kernel/svc_wrap.h
@@ -7,9 +7,7 @@
#include "common/common_types.h"
#include "core/arm/arm_interface.h"
#include "core/core.h"
-#include "core/hle/kernel/svc.h"
#include "core/hle/result.h"
-#include "core/memory.h"
namespace Kernel {
@@ -59,10 +57,31 @@ void SvcWrap() {
FuncReturn(retval);
}
+template <ResultCode func(u32*, u32*)>
+void SvcWrap() {
+ u32 param_1 = 0;
+ u32 param_2 = 0;
+ const u32 retval = func(&param_1, &param_2).raw;
+
+ auto& arm_interface = Core::CurrentArmInterface();
+ arm_interface.SetReg(1, param_1);
+ arm_interface.SetReg(2, param_2);
+
+ FuncReturn(retval);
+}
+
template <ResultCode func(u32*, u64)>
void SvcWrap() {
u32 param_1 = 0;
- u32 retval = func(&param_1, Param(1)).raw;
+ const u32 retval = func(&param_1, Param(1)).raw;
+ Core::CurrentArmInterface().SetReg(1, param_1);
+ FuncReturn(retval);
+}
+
+template <ResultCode func(u64*, u32)>
+void SvcWrap() {
+ u64 param_1 = 0;
+ const u32 retval = func(&param_1, static_cast<u32>(Param(1))).raw;
Core::CurrentArmInterface().SetReg(1, param_1);
FuncReturn(retval);
}
@@ -116,7 +135,12 @@ void SvcWrap() {
template <ResultCode func(u64, u64, u32, u32)>
void SvcWrap() {
FuncReturn(
- func(Param(0), Param(1), static_cast<u32>(Param(3)), static_cast<u32>(Param(3))).raw);
+ func(Param(0), Param(1), static_cast<u32>(Param(2)), static_cast<u32>(Param(3))).raw);
+}
+
+template <ResultCode func(u64, u64, u32, u64)>
+void SvcWrap() {
+ FuncReturn(func(Param(0), Param(1), static_cast<u32>(Param(2)), Param(3)).raw);
}
template <ResultCode func(u32, u64, u32)>
@@ -178,21 +202,6 @@ void SvcWrap() {
FuncReturn(retval);
}
-template <ResultCode func(MemoryInfo*, PageInfo*, u64)>
-void SvcWrap() {
- MemoryInfo memory_info = {};
- PageInfo page_info = {};
- u32 retval = func(&memory_info, &page_info, Param(2)).raw;
-
- Memory::Write64(Param(0), memory_info.base_address);
- Memory::Write64(Param(0) + 8, memory_info.size);
- Memory::Write32(Param(0) + 16, memory_info.type);
- Memory::Write32(Param(0) + 20, memory_info.attributes);
- Memory::Write32(Param(0) + 24, memory_info.permission);
-
- FuncReturn(retval);
-}
-
template <ResultCode func(u32*, u64, u64, u32)>
void SvcWrap() {
u32 param_1 = 0;
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index 4ffb76818..d3984dfc4 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -12,7 +12,6 @@
#include "common/assert.h"
#include "common/common_types.h"
#include "common/logging/log.h"
-#include "common/math_util.h"
#include "common/thread_queue_list.h"
#include "core/arm/arm_interface.h"
#include "core/core.h"
@@ -50,7 +49,7 @@ void Thread::Stop() {
// Clean up thread from ready queue
// This is only needed when the thread is terminated forcefully (SVC TerminateProcess)
- if (status == ThreadStatus::Ready) {
+ if (status == ThreadStatus::Ready || status == ThreadStatus::Paused) {
scheduler->UnscheduleThread(this, current_priority);
}
@@ -140,6 +139,11 @@ void Thread::ResumeFromWait() {
wakeup_callback = nullptr;
+ if (activity == ThreadActivity::Paused) {
+ status = ThreadStatus::Paused;
+ return;
+ }
+
status = ThreadStatus::Ready;
ChangeScheduler();
@@ -158,6 +162,9 @@ static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAdd
context.cpu_registers[0] = arg;
context.pc = entry_point;
context.sp = stack_top;
+ // TODO(merry): Perform a hardware test to determine the below value.
+ // AHP = 0, DN = 1, FTZ = 1, RMode = Round towards zero
+ context.fpcr = 0x03C00000;
}
ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
@@ -224,29 +231,6 @@ void Thread::BoostPriority(u32 priority) {
current_priority = priority;
}
-SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 priority,
- Process& owner_process) {
- // Setup page table so we can write to memory
- SetCurrentPageTable(&owner_process.VMManager().page_table);
-
- // Initialize new "main" thread
- const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
- auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0,
- stack_top, owner_process);
-
- SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
-
- // Register 1 must be a handle to the main thread
- const Handle guest_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
- thread->SetGuestHandle(guest_handle);
- thread->GetContext().cpu_registers[1] = guest_handle;
-
- // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
- thread->ResumeFromWait();
-
- return thread;
-}
-
void Thread::SetWaitSynchronizationResult(ResultCode result) {
context.cpu_registers[0] = result.raw;
}
@@ -388,6 +372,23 @@ bool Thread::InvokeWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> t
return wakeup_callback(reason, std::move(thread), std::move(object), index);
}
+void Thread::SetActivity(ThreadActivity value) {
+ activity = value;
+
+ if (value == ThreadActivity::Paused) {
+ // Set status if not waiting
+ if (status == ThreadStatus::Ready) {
+ status = ThreadStatus::Paused;
+ } else if (status == ThreadStatus::Running) {
+ status = ThreadStatus::Paused;
+ Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
+ }
+ } else if (status == ThreadStatus::Paused) {
+ // Ready to reschedule
+ ResumeFromWait();
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index d384d50db..c48b21aba 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -26,15 +26,16 @@ enum ThreadPriority : u32 {
THREADPRIO_USERLAND_MAX = 24, ///< Highest thread priority for userland apps
THREADPRIO_DEFAULT = 44, ///< Default thread priority for userland apps
THREADPRIO_LOWEST = 63, ///< Lowest thread priority
+ THREADPRIO_COUNT = 64, ///< Total number of possible thread priorities.
};
enum ThreadProcessorId : s32 {
- THREADPROCESSORID_DEFAULT = -2, ///< Run thread on default core specified by exheader
- THREADPROCESSORID_0 = 0, ///< Run thread on core 0
- THREADPROCESSORID_1 = 1, ///< Run thread on core 1
- THREADPROCESSORID_2 = 2, ///< Run thread on core 2
- THREADPROCESSORID_3 = 3, ///< Run thread on core 3
- THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
+ THREADPROCESSORID_IDEAL = -2, ///< Run thread on the ideal core specified by the process.
+ THREADPROCESSORID_0 = 0, ///< Run thread on core 0
+ THREADPROCESSORID_1 = 1, ///< Run thread on core 1
+ THREADPROCESSORID_2 = 2, ///< Run thread on core 2
+ THREADPROCESSORID_3 = 3, ///< Run thread on core 3
+ THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
/// Allowed CPU mask
THREADPROCESSORID_DEFAULT_MASK = (1 << THREADPROCESSORID_0) | (1 << THREADPROCESSORID_1) |
@@ -44,6 +45,7 @@ enum ThreadProcessorId : s32 {
enum class ThreadStatus {
Running, ///< Currently running
Ready, ///< Ready to run
+ Paused, ///< Paused by SetThreadActivity or debug
WaitHLEEvent, ///< Waiting for hle event to finish
WaitSleep, ///< Waiting due to a SleepThread SVC
WaitIPC, ///< Waiting for the reply from an IPC request
@@ -60,6 +62,11 @@ enum class ThreadWakeupReason {
Timeout // The thread was woken up due to a wait timeout.
};
+enum class ThreadActivity : u32 {
+ Normal = 0,
+ Paused = 1,
+};
+
class Thread final : public WaitObject {
public:
using TLSMemory = std::vector<u8>;
@@ -150,7 +157,7 @@ public:
* Gets the thread's thread ID
* @return The thread's ID
*/
- u32 GetThreadID() const {
+ u64 GetThreadID() const {
return thread_id;
}
@@ -370,6 +377,12 @@ public:
return affinity_mask;
}
+ ThreadActivity GetActivity() const {
+ return activity;
+ }
+
+ void SetActivity(ThreadActivity value);
+
private:
explicit Thread(KernelCore& kernel);
~Thread() override;
@@ -378,7 +391,7 @@ private:
Core::ARM_Interface::ThreadContext context{};
- u32 thread_id = 0;
+ u64 thread_id = 0;
ThreadStatus status = ThreadStatus::Dormant;
@@ -438,18 +451,9 @@ private:
TLSMemoryPtr tls_memory = std::make_shared<TLSMemory>();
std::string name;
-};
-/**
- * Sets up the primary application thread
- * @param kernel The kernel instance to create the main thread under.
- * @param entry_point The address at which the thread should start execution
- * @param priority The priority to give the main thread
- * @param owner_process The parent process for the main thread
- * @return A shared pointer to the main thread
- */
-SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 priority,
- Process& owner_process);
+ ThreadActivity activity = ThreadActivity::Normal;
+};
/**
* Gets the current thread
diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp
index 6957b16e0..2c4f50e2b 100644
--- a/src/core/hle/kernel/timer.cpp
+++ b/src/core/hle/kernel/timer.cpp
@@ -68,9 +68,6 @@ void Timer::Clear() {
void Timer::WakeupAllWaitingThreads() {
WaitObject::WakeupAllWaitingThreads();
-
- if (reset_type == ResetType::Pulse)
- signaled = false;
}
void Timer::Signal(int cycles_late) {
diff --git a/src/core/hle/kernel/vm_manager.cpp b/src/core/hle/kernel/vm_manager.cpp
index 100f8f6bf..10ad94aa6 100644
--- a/src/core/hle/kernel/vm_manager.cpp
+++ b/src/core/hle/kernel/vm_manager.cpp
@@ -25,19 +25,19 @@ static const char* GetMemoryStateName(MemoryState state) {
"CodeMutable", "Heap",
"Shared", "Unknown1",
"ModuleCodeStatic", "ModuleCodeMutable",
- "IpcBuffer0", "Mapped",
+ "IpcBuffer0", "Stack",
"ThreadLocal", "TransferMemoryIsolated",
"TransferMemory", "ProcessMemory",
- "Unknown2", "IpcBuffer1",
+ "Inaccessible", "IpcBuffer1",
"IpcBuffer3", "KernelStack",
};
- return names[static_cast<int>(state)];
+ return names[ToSvcMemoryState(state)];
}
bool VirtualMemoryArea::CanBeMergedWith(const VirtualMemoryArea& next) const {
ASSERT(base + size == next.base);
- if (permissions != next.permissions || meminfo_state != next.meminfo_state ||
+ if (permissions != next.permissions || state != next.state || attribute != next.attribute ||
type != next.type) {
return false;
}
@@ -87,6 +87,10 @@ VMManager::VMAHandle VMManager::FindVMA(VAddr target) const {
}
}
+bool VMManager::IsValidHandle(VMAHandle handle) const {
+ return handle != vma_map.cend();
+}
+
ResultVal<VMManager::VMAHandle> VMManager::MapMemoryBlock(VAddr target,
std::shared_ptr<std::vector<u8>> block,
std::size_t offset, u64 size,
@@ -111,7 +115,7 @@ ResultVal<VMManager::VMAHandle> VMManager::MapMemoryBlock(VAddr target,
final_vma.type = VMAType::AllocatedMemoryBlock;
final_vma.permissions = VMAPermission::ReadWrite;
- final_vma.meminfo_state = state;
+ final_vma.state = state;
final_vma.backing_block = std::move(block);
final_vma.offset = offset;
UpdatePageTableForVMA(final_vma);
@@ -136,7 +140,7 @@ ResultVal<VMManager::VMAHandle> VMManager::MapBackingMemory(VAddr target, u8* me
final_vma.type = VMAType::BackingMemory;
final_vma.permissions = VMAPermission::ReadWrite;
- final_vma.meminfo_state = state;
+ final_vma.state = state;
final_vma.backing_memory = memory;
UpdatePageTableForVMA(final_vma);
@@ -173,7 +177,7 @@ ResultVal<VMManager::VMAHandle> VMManager::MapMMIO(VAddr target, PAddr paddr, u6
final_vma.type = VMAType::MMIO;
final_vma.permissions = VMAPermission::ReadWrite;
- final_vma.meminfo_state = state;
+ final_vma.state = state;
final_vma.paddr = paddr;
final_vma.mmio_handler = std::move(mmio_handler);
UpdatePageTableForVMA(final_vma);
@@ -185,7 +189,8 @@ VMManager::VMAIter VMManager::Unmap(VMAIter vma_handle) {
VirtualMemoryArea& vma = vma_handle->second;
vma.type = VMAType::Free;
vma.permissions = VMAPermission::None;
- vma.meminfo_state = MemoryState::Unmapped;
+ vma.state = MemoryState::Unmapped;
+ vma.attribute = MemoryAttribute::None;
vma.backing_block = nullptr;
vma.offset = 0;
@@ -298,6 +303,54 @@ ResultCode VMManager::HeapFree(VAddr target, u64 size) {
return RESULT_SUCCESS;
}
+MemoryInfo VMManager::QueryMemory(VAddr address) const {
+ const auto vma = FindVMA(address);
+ MemoryInfo memory_info{};
+
+ if (IsValidHandle(vma)) {
+ memory_info.base_address = vma->second.base;
+ memory_info.attributes = ToSvcMemoryAttribute(vma->second.attribute);
+ memory_info.permission = static_cast<u32>(vma->second.permissions);
+ memory_info.size = vma->second.size;
+ memory_info.state = ToSvcMemoryState(vma->second.state);
+ } else {
+ memory_info.base_address = address_space_end;
+ memory_info.permission = static_cast<u32>(VMAPermission::None);
+ memory_info.size = 0 - address_space_end;
+ memory_info.state = static_cast<u32>(MemoryState::Inaccessible);
+ }
+
+ return memory_info;
+}
+
+ResultCode VMManager::SetMemoryAttribute(VAddr address, u64 size, MemoryAttribute mask,
+ MemoryAttribute attribute) {
+ constexpr auto ignore_mask = MemoryAttribute::Uncached | MemoryAttribute::DeviceMapped;
+ constexpr auto attribute_mask = ~ignore_mask;
+
+ const auto result = CheckRangeState(
+ address, size, MemoryState::FlagUncached, MemoryState::FlagUncached, VMAPermission::None,
+ VMAPermission::None, attribute_mask, MemoryAttribute::None, ignore_mask);
+
+ if (result.Failed()) {
+ return result.Code();
+ }
+
+ const auto [prev_state, prev_permissions, prev_attributes] = *result;
+ const auto new_attribute = (prev_attributes & ~mask) | (mask & attribute);
+
+ const auto carve_result = CarveVMARange(address, size);
+ if (carve_result.Failed()) {
+ return carve_result.Code();
+ }
+
+ auto vma_iter = *carve_result;
+ vma_iter->second.attribute = new_attribute;
+
+ MergeAdjacent(vma_iter);
+ return RESULT_SUCCESS;
+}
+
ResultCode VMManager::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state) {
const auto vma = FindVMA(src_addr);
@@ -341,7 +394,7 @@ void VMManager::LogLayout() const {
(u8)vma.permissions & (u8)VMAPermission::Read ? 'R' : '-',
(u8)vma.permissions & (u8)VMAPermission::Write ? 'W' : '-',
(u8)vma.permissions & (u8)VMAPermission::Execute ? 'X' : '-',
- GetMemoryStateName(vma.meminfo_state));
+ GetMemoryStateName(vma.state));
}
}
@@ -568,6 +621,66 @@ void VMManager::ClearPageTable() {
Memory::PageType::Unmapped);
}
+VMManager::CheckResults VMManager::CheckRangeState(VAddr address, u64 size, MemoryState state_mask,
+ MemoryState state, VMAPermission permission_mask,
+ VMAPermission permissions,
+ MemoryAttribute attribute_mask,
+ MemoryAttribute attribute,
+ MemoryAttribute ignore_mask) const {
+ auto iter = FindVMA(address);
+
+ // If we don't have a valid VMA handle at this point, then it means this is
+ // being called with an address outside of the address space, which is definitely
+ // indicative of a bug, as this function only operates on mapped memory regions.
+ DEBUG_ASSERT(IsValidHandle(iter));
+
+ const VAddr end_address = address + size - 1;
+ const MemoryAttribute initial_attributes = iter->second.attribute;
+ const VMAPermission initial_permissions = iter->second.permissions;
+ const MemoryState initial_state = iter->second.state;
+
+ while (true) {
+ // The iterator should be valid throughout the traversal. Hitting the end of
+ // the mapped VMA regions is unquestionably indicative of a bug.
+ DEBUG_ASSERT(IsValidHandle(iter));
+
+ const auto& vma = iter->second;
+
+ if (vma.state != initial_state) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if ((vma.state & state_mask) != state) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if (vma.permissions != initial_permissions) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if ((vma.permissions & permission_mask) != permissions) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if ((vma.attribute | ignore_mask) != (initial_attributes | ignore_mask)) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if ((vma.attribute & attribute_mask) != attribute) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ if (end_address <= vma.EndAddress()) {
+ break;
+ }
+
+ ++iter;
+ }
+
+ return MakeResult(
+ std::make_tuple(initial_state, initial_permissions, initial_attributes & ~ignore_mask));
+}
+
u64 VMManager::GetTotalMemoryUsage() const {
LOG_WARNING(Kernel, "(STUBBED) called");
return 0xF8000000;
diff --git a/src/core/hle/kernel/vm_manager.h b/src/core/hle/kernel/vm_manager.h
index d522404fe..6091533bc 100644
--- a/src/core/hle/kernel/vm_manager.h
+++ b/src/core/hle/kernel/vm_manager.h
@@ -6,6 +6,7 @@
#include <map>
#include <memory>
+#include <tuple>
#include <vector>
#include "common/common_types.h"
#include "core/hle/result.h"
@@ -43,26 +44,211 @@ enum class VMAPermission : u8 {
ReadWriteExecute = Read | Write | Execute,
};
-/// Set of values returned in MemoryInfo.state by svcQueryMemory.
+constexpr VMAPermission operator|(VMAPermission lhs, VMAPermission rhs) {
+ return static_cast<VMAPermission>(u32(lhs) | u32(rhs));
+}
+
+constexpr VMAPermission operator&(VMAPermission lhs, VMAPermission rhs) {
+ return static_cast<VMAPermission>(u32(lhs) & u32(rhs));
+}
+
+constexpr VMAPermission operator^(VMAPermission lhs, VMAPermission rhs) {
+ return static_cast<VMAPermission>(u32(lhs) ^ u32(rhs));
+}
+
+constexpr VMAPermission operator~(VMAPermission permission) {
+ return static_cast<VMAPermission>(~u32(permission));
+}
+
+constexpr VMAPermission& operator|=(VMAPermission& lhs, VMAPermission rhs) {
+ lhs = lhs | rhs;
+ return lhs;
+}
+
+constexpr VMAPermission& operator&=(VMAPermission& lhs, VMAPermission rhs) {
+ lhs = lhs & rhs;
+ return lhs;
+}
+
+constexpr VMAPermission& operator^=(VMAPermission& lhs, VMAPermission rhs) {
+ lhs = lhs ^ rhs;
+ return lhs;
+}
+
+/// Attribute flags that can be applied to a VMA
+enum class MemoryAttribute : u32 {
+ Mask = 0xFF,
+
+ /// No particular qualities
+ None = 0,
+ /// Memory locked/borrowed for use. e.g. This would be used by transfer memory.
+ Locked = 1,
+ /// Memory locked for use by IPC-related internals.
+ LockedForIPC = 2,
+ /// Mapped as part of the device address space.
+ DeviceMapped = 4,
+ /// Uncached memory
+ Uncached = 8,
+};
+
+constexpr MemoryAttribute operator|(MemoryAttribute lhs, MemoryAttribute rhs) {
+ return static_cast<MemoryAttribute>(u32(lhs) | u32(rhs));
+}
+
+constexpr MemoryAttribute operator&(MemoryAttribute lhs, MemoryAttribute rhs) {
+ return static_cast<MemoryAttribute>(u32(lhs) & u32(rhs));
+}
+
+constexpr MemoryAttribute operator^(MemoryAttribute lhs, MemoryAttribute rhs) {
+ return static_cast<MemoryAttribute>(u32(lhs) ^ u32(rhs));
+}
+
+constexpr MemoryAttribute operator~(MemoryAttribute attribute) {
+ return static_cast<MemoryAttribute>(~u32(attribute));
+}
+
+constexpr MemoryAttribute& operator|=(MemoryAttribute& lhs, MemoryAttribute rhs) {
+ lhs = lhs | rhs;
+ return lhs;
+}
+
+constexpr MemoryAttribute& operator&=(MemoryAttribute& lhs, MemoryAttribute rhs) {
+ lhs = lhs & rhs;
+ return lhs;
+}
+
+constexpr MemoryAttribute& operator^=(MemoryAttribute& lhs, MemoryAttribute rhs) {
+ lhs = lhs ^ rhs;
+ return lhs;
+}
+
+constexpr u32 ToSvcMemoryAttribute(MemoryAttribute attribute) {
+ return static_cast<u32>(attribute & MemoryAttribute::Mask);
+}
+
+// clang-format off
+/// Represents memory states and any relevant flags, as used by the kernel.
+/// svcQueryMemory interprets these by masking away all but the first eight
+/// bits when storing memory state into a MemoryInfo instance.
enum class MemoryState : u32 {
- Unmapped = 0x0,
- Io = 0x1,
- Normal = 0x2,
- CodeStatic = 0x3,
- CodeMutable = 0x4,
- Heap = 0x5,
- Shared = 0x6,
- ModuleCodeStatic = 0x8,
- ModuleCodeMutable = 0x9,
- IpcBuffer0 = 0xA,
- Mapped = 0xB,
- ThreadLocal = 0xC,
- TransferMemoryIsolated = 0xD,
- TransferMemory = 0xE,
- ProcessMemory = 0xF,
- IpcBuffer1 = 0x11,
- IpcBuffer3 = 0x12,
- KernelStack = 0x13,
+ Mask = 0xFF,
+ FlagProtect = 1U << 8,
+ FlagDebug = 1U << 9,
+ FlagIPC0 = 1U << 10,
+ FlagIPC3 = 1U << 11,
+ FlagIPC1 = 1U << 12,
+ FlagMapped = 1U << 13,
+ FlagCode = 1U << 14,
+ FlagAlias = 1U << 15,
+ FlagModule = 1U << 16,
+ FlagTransfer = 1U << 17,
+ FlagQueryPhysicalAddressAllowed = 1U << 18,
+ FlagSharedDevice = 1U << 19,
+ FlagSharedDeviceAligned = 1U << 20,
+ FlagIPCBuffer = 1U << 21,
+ FlagMemoryPoolAllocated = 1U << 22,
+ FlagMapProcess = 1U << 23,
+ FlagUncached = 1U << 24,
+ FlagCodeMemory = 1U << 25,
+
+ // Convenience flag sets to reduce repetition
+ IPCFlags = FlagIPC0 | FlagIPC3 | FlagIPC1,
+
+ CodeFlags = FlagDebug | IPCFlags | FlagMapped | FlagCode | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
+
+ DataFlags = FlagProtect | IPCFlags | FlagMapped | FlagAlias | FlagTransfer |
+ FlagQueryPhysicalAddressAllowed | FlagSharedDevice | FlagSharedDeviceAligned |
+ FlagMemoryPoolAllocated | FlagIPCBuffer | FlagUncached,
+
+ Unmapped = 0x00,
+ Io = 0x01 | FlagMapped,
+ Normal = 0x02 | FlagMapped | FlagQueryPhysicalAddressAllowed,
+ CodeStatic = 0x03 | CodeFlags | FlagMapProcess,
+ CodeMutable = 0x04 | CodeFlags | FlagMapProcess | FlagCodeMemory,
+ Heap = 0x05 | DataFlags | FlagCodeMemory,
+ Shared = 0x06 | FlagMapped | FlagMemoryPoolAllocated,
+ ModuleCodeStatic = 0x08 | CodeFlags | FlagModule | FlagMapProcess,
+ ModuleCodeMutable = 0x09 | DataFlags | FlagModule | FlagMapProcess | FlagCodeMemory,
+
+ IpcBuffer0 = 0x0A | FlagMapped | FlagQueryPhysicalAddressAllowed | FlagMemoryPoolAllocated |
+ IPCFlags | FlagSharedDevice | FlagSharedDeviceAligned,
+
+ Stack = 0x0B | FlagMapped | IPCFlags | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
+
+ ThreadLocal = 0x0C | FlagMapped | FlagMemoryPoolAllocated,
+
+ TransferMemoryIsolated = 0x0D | IPCFlags | FlagMapped | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated |
+ FlagUncached,
+
+ TransferMemory = 0x0E | FlagIPC3 | FlagIPC1 | FlagMapped | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
+
+ ProcessMemory = 0x0F | FlagIPC3 | FlagIPC1 | FlagMapped | FlagMemoryPoolAllocated,
+
+ // Used to signify an inaccessible or invalid memory region with memory queries
+ Inaccessible = 0x10,
+
+ IpcBuffer1 = 0x11 | FlagIPC3 | FlagIPC1 | FlagMapped | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
+
+ IpcBuffer3 = 0x12 | FlagIPC3 | FlagMapped | FlagQueryPhysicalAddressAllowed |
+ FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
+
+ KernelStack = 0x13 | FlagMapped,
+};
+// clang-format on
+
+constexpr MemoryState operator|(MemoryState lhs, MemoryState rhs) {
+ return static_cast<MemoryState>(u32(lhs) | u32(rhs));
+}
+
+constexpr MemoryState operator&(MemoryState lhs, MemoryState rhs) {
+ return static_cast<MemoryState>(u32(lhs) & u32(rhs));
+}
+
+constexpr MemoryState operator^(MemoryState lhs, MemoryState rhs) {
+ return static_cast<MemoryState>(u32(lhs) ^ u32(rhs));
+}
+
+constexpr MemoryState operator~(MemoryState lhs) {
+ return static_cast<MemoryState>(~u32(lhs));
+}
+
+constexpr MemoryState& operator|=(MemoryState& lhs, MemoryState rhs) {
+ lhs = lhs | rhs;
+ return lhs;
+}
+
+constexpr MemoryState& operator&=(MemoryState& lhs, MemoryState rhs) {
+ lhs = lhs & rhs;
+ return lhs;
+}
+
+constexpr MemoryState& operator^=(MemoryState& lhs, MemoryState rhs) {
+ lhs = lhs ^ rhs;
+ return lhs;
+}
+
+constexpr u32 ToSvcMemoryState(MemoryState state) {
+ return static_cast<u32>(state & MemoryState::Mask);
+}
+
+struct MemoryInfo {
+ u64 base_address;
+ u64 size;
+ u32 state;
+ u32 attributes;
+ u32 permission;
+ u32 ipc_ref_count;
+ u32 device_ref_count;
+};
+static_assert(sizeof(MemoryInfo) == 0x28, "MemoryInfo has incorrect size.");
+
+struct PageInfo {
+ u32 flags;
};
/**
@@ -71,6 +257,16 @@ enum class MemoryState : u32 {
* also backed by a single host memory allocation.
*/
struct VirtualMemoryArea {
+ /// Gets the starting (base) address of this VMA.
+ VAddr StartAddress() const {
+ return base;
+ }
+
+ /// Gets the ending address of this VMA.
+ VAddr EndAddress() const {
+ return base + size - 1;
+ }
+
/// Virtual base address of the region.
VAddr base = 0;
/// Size of the region.
@@ -78,8 +274,8 @@ struct VirtualMemoryArea {
VMAType type = VMAType::Free;
VMAPermission permissions = VMAPermission::None;
- /// Tag returned by svcQueryMemory. Not otherwise used.
- MemoryState meminfo_state = MemoryState::Unmapped;
+ MemoryState state = MemoryState::Unmapped;
+ MemoryAttribute attribute = MemoryAttribute::None;
// Settings for type = AllocatedMemoryBlock
/// Memory block backing this VMA.
@@ -113,16 +309,10 @@ struct VirtualMemoryArea {
* - http://duartes.org/gustavo/blog/post/page-cache-the-affair-between-memory-and-files/
*/
class VMManager final {
+ using VMAMap = std::map<VAddr, VirtualMemoryArea>;
+
public:
- /**
- * A map covering the entirety of the managed address space, keyed by the `base` field of each
- * VMA. It must always be modified by splitting or merging VMAs, so that the invariant
- * `elem.base + elem.size == next.base` is preserved, and mergeable regions must always be
- * merged when possible so that no two similar and adjacent regions exist that have not been
- * merged.
- */
- std::map<VAddr, VirtualMemoryArea> vma_map;
- using VMAHandle = decltype(vma_map)::const_iterator;
+ using VMAHandle = VMAMap::const_iterator;
VMManager();
~VMManager();
@@ -133,6 +323,9 @@ public:
/// Finds the VMA in which the given address is included in, or `vma_map.end()`.
VMAHandle FindVMA(VAddr target) const;
+ /// Indicates whether or not the given handle is within the VMA map.
+ bool IsValidHandle(VMAHandle handle) const;
+
// TODO(yuriks): Should these functions actually return the handle?
/**
@@ -189,8 +382,28 @@ public:
ResultVal<VAddr> HeapAllocate(VAddr target, u64 size, VMAPermission perms);
ResultCode HeapFree(VAddr target, u64 size);
- ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size,
- MemoryState state = MemoryState::Mapped);
+ ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state);
+
+ /// Queries the memory manager for information about the given address.
+ ///
+ /// @param address The address to query the memory manager about for information.
+ ///
+ /// @return A MemoryInfo instance containing information about the given address.
+ ///
+ MemoryInfo QueryMemory(VAddr address) const;
+
+ /// Sets an attribute across the given address range.
+ ///
+ /// @param address The starting address
+ /// @param size The size of the range to set the attribute on.
+ /// @param mask The attribute mask
+ /// @param attribute The attribute to set across the given address range
+ ///
+ /// @returns RESULT_SUCCESS if successful
+ /// @returns ERR_INVALID_ADDRESS_STATE if the attribute could not be set.
+ ///
+ ResultCode SetMemoryAttribute(VAddr address, u64 size, MemoryAttribute mask,
+ MemoryAttribute attribute);
/**
* Scans all VMAs and updates the page table range of any that use the given vector as backing
@@ -281,7 +494,7 @@ public:
Memory::PageTable page_table;
private:
- using VMAIter = decltype(vma_map)::iterator;
+ using VMAIter = VMAMap::iterator;
/// Converts a VMAHandle to a mutable VMAIter.
VMAIter StripIterConstness(const VMAHandle& iter);
@@ -328,6 +541,44 @@ private:
/// Clears out the page table
void ClearPageTable();
+ using CheckResults = ResultVal<std::tuple<MemoryState, VMAPermission, MemoryAttribute>>;
+
+ /// Checks if an address range adheres to the specified states provided.
+ ///
+ /// @param address The starting address of the address range.
+ /// @param size The size of the address range.
+ /// @param state_mask The memory state mask.
+ /// @param state The state to compare the individual VMA states against,
+ /// which is done in the form of: (vma.state & state_mask) != state.
+ /// @param permission_mask The memory permissions mask.
+ /// @param permissions The permission to compare the individual VMA permissions against,
+ /// which is done in the form of:
+ /// (vma.permission & permission_mask) != permission.
+ /// @param attribute_mask The memory attribute mask.
+ /// @param attribute The memory attributes to compare the individual VMA attributes
+ /// against, which is done in the form of:
+ /// (vma.attributes & attribute_mask) != attribute.
+ /// @param ignore_mask The memory attributes to ignore during the check.
+ ///
+ /// @returns If successful, returns a tuple containing the memory attributes
+ /// (with ignored bits specified by ignore_mask unset), memory permissions, and
+ /// memory state across the memory range.
+ /// @returns If not successful, returns ERR_INVALID_ADDRESS_STATE.
+ ///
+ CheckResults CheckRangeState(VAddr address, u64 size, MemoryState state_mask, MemoryState state,
+ VMAPermission permission_mask, VMAPermission permissions,
+ MemoryAttribute attribute_mask, MemoryAttribute attribute,
+ MemoryAttribute ignore_mask) const;
+
+ /**
+ * A map covering the entirety of the managed address space, keyed by the `base` field of each
+ * VMA. It must always be modified by splitting or merging VMAs, so that the invariant
+ * `elem.base + elem.size == next.base` is preserved, and mergeable regions must always be
+ * merged when possible so that no two similar and adjacent regions exist that have not been
+ * merged.
+ */
+ VMAMap vma_map;
+
u32 address_space_width = 0;
VAddr address_space_base = 0;
VAddr address_space_end = 0;
diff --git a/src/core/hle/kernel/wait_object.cpp b/src/core/hle/kernel/wait_object.cpp
index 530ee6af7..90580ed93 100644
--- a/src/core/hle/kernel/wait_object.cpp
+++ b/src/core/hle/kernel/wait_object.cpp
@@ -4,11 +4,11 @@
#include <algorithm>
#include "common/assert.h"
+#include "common/common_types.h"
#include "common/logging/log.h"
#include "core/hle/kernel/object.h"
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/thread.h"
-#include "core/hle/kernel/timer.h"
namespace Kernel {
diff --git a/src/core/hle/kernel/wait_object.h b/src/core/hle/kernel/wait_object.h
index f4367ee28..d70b67893 100644
--- a/src/core/hle/kernel/wait_object.h
+++ b/src/core/hle/kernel/wait_object.h
@@ -6,7 +6,6 @@
#include <vector>
#include <boost/smart_ptr/intrusive_ptr.hpp>
-#include "common/common_types.h"
#include "core/hle/kernel/object.h"
namespace Kernel {
diff --git a/src/core/hle/kernel/writable_event.cpp b/src/core/hle/kernel/writable_event.cpp
new file mode 100644
index 000000000..a58ea6ec8
--- /dev/null
+++ b/src/core/hle/kernel/writable_event.cpp
@@ -0,0 +1,52 @@
+// Copyright 2014 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include "common/assert.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/object.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/writable_event.h"
+
+namespace Kernel {
+
+WritableEvent::WritableEvent(KernelCore& kernel) : Object{kernel} {}
+WritableEvent::~WritableEvent() = default;
+
+EventPair WritableEvent::CreateEventPair(KernelCore& kernel, ResetType reset_type,
+ std::string name) {
+ SharedPtr<WritableEvent> writable_event(new WritableEvent(kernel));
+ SharedPtr<ReadableEvent> readable_event(new ReadableEvent(kernel));
+
+ writable_event->name = name + ":Writable";
+ writable_event->readable = readable_event;
+ readable_event->name = name + ":Readable";
+ readable_event->signaled = false;
+ readable_event->reset_type = reset_type;
+
+ return {std::move(readable_event), std::move(writable_event)};
+}
+
+SharedPtr<ReadableEvent> WritableEvent::GetReadableEvent() const {
+ return readable;
+}
+
+ResetType WritableEvent::GetResetType() const {
+ return readable->reset_type;
+}
+
+void WritableEvent::Signal() {
+ readable->Signal();
+}
+
+void WritableEvent::Clear() {
+ readable->Clear();
+}
+
+bool WritableEvent::IsSignaled() const {
+ return readable->signaled;
+}
+
+} // namespace Kernel
diff --git a/src/core/hle/kernel/writable_event.h b/src/core/hle/kernel/writable_event.h
new file mode 100644
index 000000000..c9068dd3d
--- /dev/null
+++ b/src/core/hle/kernel/writable_event.h
@@ -0,0 +1,61 @@
+// Copyright 2014 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "core/hle/kernel/object.h"
+
+namespace Kernel {
+
+class KernelCore;
+class ReadableEvent;
+class WritableEvent;
+
+struct EventPair {
+ SharedPtr<ReadableEvent> readable;
+ SharedPtr<WritableEvent> writable;
+};
+
+class WritableEvent final : public Object {
+public:
+ ~WritableEvent() override;
+
+ /**
+ * Creates an event
+ * @param kernel The kernel instance to create this event under.
+ * @param reset_type ResetType describing how to create event
+ * @param name Optional name of event
+ */
+ static EventPair CreateEventPair(KernelCore& kernel, ResetType reset_type,
+ std::string name = "Unknown");
+
+ std::string GetTypeName() const override {
+ return "WritableEvent";
+ }
+ std::string GetName() const override {
+ return name;
+ }
+
+ static const HandleType HANDLE_TYPE = HandleType::WritableEvent;
+ HandleType GetHandleType() const override {
+ return HANDLE_TYPE;
+ }
+
+ SharedPtr<ReadableEvent> GetReadableEvent() const;
+
+ ResetType GetResetType() const;
+
+ void Signal();
+ void Clear();
+ bool IsSignaled() const;
+
+private:
+ explicit WritableEvent(KernelCore& kernel);
+
+ SharedPtr<ReadableEvent> readable;
+
+ std::string name; ///< Name of event (optional)
+};
+
+} // namespace Kernel
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index 9521431bb..1f8ed265e 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -207,10 +207,11 @@ void Module::Interface::GetLastOpenedUser(Kernel::HLERequestContext& ctx) {
void Module::Interface::GetProfile(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
UUID user_id = rp.PopRaw<UUID>();
+ LOG_DEBUG(Service_ACC, "called user_id={}", user_id.Format());
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IProfile>(user_id, *profile_manager);
- LOG_DEBUG(Service_ACC, "called user_id={}", user_id.Format());
}
void Module::Interface::IsUserRegistrationRequestPermitted(Kernel::HLERequestContext& ctx) {
@@ -227,10 +228,10 @@ void Module::Interface::InitializeApplicationInfo(Kernel::HLERequestContext& ctx
}
void Module::Interface::GetBaasAccountManagerForApplication(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_ACC, "called");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IManagerForApplication>();
- LOG_DEBUG(Service_ACC, "called");
}
void Module::Interface::TrySelectUserWithoutInteraction(Kernel::HLERequestContext& ctx) {
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index 4f17b52f9..d1cbe0e44 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -8,17 +8,22 @@
#include <stack>
#include "audio_core/audio_renderer.h"
#include "core/core.h"
+#include "core/file_sys/savedata_factory.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/readable_event.h"
#include "core/hle/kernel/shared_memory.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/acc/profile_manager.h"
#include "core/hle/service/am/am.h"
#include "core/hle/service/am/applet_ae.h"
#include "core/hle/service/am/applet_oe.h"
#include "core/hle/service/am/applets/applets.h"
+#include "core/hle/service/am/applets/profile_select.h"
#include "core/hle/service/am/applets/software_keyboard.h"
#include "core/hle/service/am/applets/stub_applet.h"
+#include "core/hle/service/am/applets/web_browser.h"
#include "core/hle/service/am/idle.h"
#include "core/hle/service/am/omm.h"
#include "core/hle/service/am/spsm.h"
@@ -34,10 +39,13 @@
namespace Service::AM {
constexpr ResultCode ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 0x2};
+constexpr ResultCode ERR_NO_MESSAGES{ErrorModule::AM, 0x3};
constexpr ResultCode ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 0x1F7};
enum class AppletId : u32 {
+ ProfileSelect = 0x10,
SoftwareKeyboard = 0x11,
+ LibAppletOff = 0x17,
};
constexpr u32 POP_LAUNCH_PARAMETER_MAGIC = 0xC79497CA;
@@ -69,10 +77,13 @@ IWindowController::IWindowController() : ServiceFramework("IWindowController") {
IWindowController::~IWindowController() = default;
void IWindowController::GetAppletResourceUserId(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ const u64 process_id = Core::System::GetInstance().Kernel().CurrentProcess()->GetProcessID();
+
+ LOG_DEBUG(Service_AM, "called. Process ID=0x{:016X}", process_id);
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
- rb.Push<u64>(0);
+ rb.Push<u64>(process_id);
}
void IWindowController::AcquireForegroundRights(Kernel::HLERequestContext& ctx) {
@@ -208,8 +219,8 @@ ISelfController::ISelfController(std::shared_ptr<NVFlinger::NVFlinger> nvflinger
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- launchable_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::Sticky, "ISelfController:LaunchableEvent");
+ launchable_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "ISelfController:LaunchableEvent");
}
ISelfController::~ISelfController() = default;
@@ -217,6 +228,7 @@ ISelfController::~ISelfController() = default;
void ISelfController::SetFocusHandlingMode(Kernel::HLERequestContext& ctx) {
// Takes 3 input u8s with each field located immediately after the previous
// u8, these are bool flags. No output.
+ LOG_WARNING(Service_AM, "(STUBBED) called");
IPC::RequestParser rp{ctx};
@@ -229,44 +241,40 @@ void ISelfController::SetFocusHandlingMode(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::SetRestartMessageEnabled(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::SetPerformanceModeChangedNotification(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
bool flag = rp.Pop<bool>();
+ LOG_WARNING(Service_AM, "(STUBBED) called flag={}", flag);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called flag={}", flag);
}
void ISelfController::SetScreenShotPermission(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::SetOperationModeChangedNotification(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
bool flag = rp.Pop<bool>();
+ LOG_WARNING(Service_AM, "(STUBBED) called flag={}", flag);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called flag={}", flag);
}
void ISelfController::SetOutOfFocusSuspendingEnabled(Kernel::HLERequestContext& ctx) {
@@ -275,45 +283,45 @@ void ISelfController::SetOutOfFocusSuspendingEnabled(Kernel::HLERequestContext&
IPC::RequestParser rp{ctx};
bool enabled = rp.Pop<bool>();
+ LOG_WARNING(Service_AM, "(STUBBED) called enabled={}", enabled);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called enabled={}", enabled);
}
void ISelfController::LockExit(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::UnlockExit(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::GetLibraryAppletLaunchableEvent(Kernel::HLERequestContext& ctx) {
- launchable_event->Signal();
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
+ launchable_event.writable->Signal();
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(launchable_event);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ rb.PushCopyObjects(launchable_event.readable);
}
void ISelfController::SetScreenShotImageOrientation(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::CreateManagedDisplayLayer(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
// TODO(Subv): Find out how AM determines the display to use, for now just
// create the layer in the Default display.
u64 display_id = nvflinger->OpenDisplay("Default");
@@ -322,66 +330,67 @@ void ISelfController::CreateManagedDisplayLayer(Kernel::HLERequestContext& ctx)
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push(layer_id);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::SetHandlesRequestToDisplay(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::SetIdleTimeDetectionExtension(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
idle_time_detection_extension = rp.Pop<u32>();
+ LOG_WARNING(Service_AM, "(STUBBED) called idle_time_detection_extension={}",
+ idle_time_detection_extension);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ISelfController::GetIdleTimeDetectionExtension(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(idle_time_detection_extension);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
AppletMessageQueue::AppletMessageQueue() {
auto& kernel = Core::System::GetInstance().Kernel();
- on_new_message = Kernel::Event::Create(kernel, Kernel::ResetType::Sticky,
- "AMMessageQueue:OnMessageRecieved");
- on_operation_mode_changed = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "AMMessageQueue:OperationModeChanged");
+ on_new_message = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "AMMessageQueue:OnMessageRecieved");
+ on_operation_mode_changed = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "AMMessageQueue:OperationModeChanged");
}
AppletMessageQueue::~AppletMessageQueue() = default;
-const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetMesssageRecieveEvent() const {
- return on_new_message;
+const Kernel::SharedPtr<Kernel::ReadableEvent>& AppletMessageQueue::GetMesssageRecieveEvent()
+ const {
+ return on_new_message.readable;
}
-const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetOperationModeChangedEvent() const {
- return on_operation_mode_changed;
+const Kernel::SharedPtr<Kernel::ReadableEvent>& AppletMessageQueue::GetOperationModeChangedEvent()
+ const {
+ return on_operation_mode_changed.readable;
}
void AppletMessageQueue::PushMessage(AppletMessage msg) {
messages.push(msg);
- on_new_message->Signal();
+ on_new_message.writable->Signal();
}
AppletMessageQueue::AppletMessage AppletMessageQueue::PopMessage() {
if (messages.empty()) {
- on_new_message->Clear();
+ on_new_message.writable->Clear();
return AppletMessage::NoMessage;
}
auto msg = messages.front();
messages.pop();
if (messages.empty()) {
- on_new_message->Clear();
+ on_new_message.writable->Clear();
}
return msg;
}
@@ -393,7 +402,7 @@ std::size_t AppletMessageQueue::GetMessageCount() const {
void AppletMessageQueue::OperationModeChanged() {
PushMessage(AppletMessage::OperationModeChanged);
PushMessage(AppletMessage::PerformanceModeChanged);
- on_operation_mode_changed->Signal();
+ on_operation_mode_changed.writable->Signal();
}
ICommonStateGetter::ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_queue)
@@ -430,55 +439,62 @@ ICommonStateGetter::ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_q
// clang-format on
RegisterHandlers(functions);
-
- auto& kernel = Core::System::GetInstance().Kernel();
- event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "ICommonStateGetter:Event");
}
ICommonStateGetter::~ICommonStateGetter() = default;
void ICommonStateGetter::GetBootMode(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u8>(static_cast<u8>(Service::PM::SystemBootMode::Normal)); // Normal boot mode
-
- LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetEventHandle(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(msg_queue->GetMesssageRecieveEvent());
-
- LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::ReceiveMessage(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
+ const auto message = msg_queue->PopMessage();
IPC::ResponseBuilder rb{ctx, 3};
- rb.Push(RESULT_SUCCESS);
- rb.PushEnum<AppletMessageQueue::AppletMessage>(msg_queue->PopMessage());
- LOG_DEBUG(Service_AM, "called");
+ if (message == AppletMessageQueue::AppletMessage::NoMessage) {
+ LOG_ERROR(Service_AM, "Message queue is empty");
+ rb.Push(ERR_NO_MESSAGES);
+ rb.PushEnum<AppletMessageQueue::AppletMessage>(message);
+ return;
+ }
+ rb.Push(RESULT_SUCCESS);
+ rb.PushEnum<AppletMessageQueue::AppletMessage>(message);
}
void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u8>(FocusState::InFocus));
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void ICommonStateGetter::GetDefaultDisplayResolutionChangeEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(msg_queue->GetOperationModeChangedEvent());
-
- LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
@@ -493,8 +509,6 @@ void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext&
rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedHeight) *
static_cast<u32>(Settings::values.resolution_factor));
}
-
- LOG_DEBUG(Service_AM, "called");
}
IStorage::IStorage(std::vector<u8> buffer)
@@ -517,21 +531,21 @@ const std::vector<u8>& IStorage::GetData() const {
void ICommonStateGetter::GetOperationMode(Kernel::HLERequestContext& ctx) {
const bool use_docked_mode{Settings::values.use_docked_mode};
+ LOG_DEBUG(Service_AM, "called, use_docked_mode={}", use_docked_mode);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u8>(use_docked_mode ? OperationMode::Docked : OperationMode::Handheld));
-
- LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) {
const bool use_docked_mode{Settings::values.use_docked_mode};
+ LOG_DEBUG(Service_AM, "called, use_docked_mode={}", use_docked_mode);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u32>(use_docked_mode ? APM::PerformanceMode::Docked
: APM::PerformanceMode::Handheld));
-
- LOG_DEBUG(Service_AM, "called");
}
class ILibraryAppletAccessor final : public ServiceFramework<ILibraryAppletAccessor> {
@@ -566,32 +580,33 @@ public:
private:
void GetAppletStateChangedEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
const auto event = applet->GetBroker().GetStateChangedEvent();
- event->Signal();
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(event);
-
- LOG_DEBUG(Service_AM, "called");
}
void IsCompleted(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(applet->TransactionComplete());
-
- LOG_DEBUG(Service_AM, "called");
}
void GetResult(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(applet->GetStatus());
-
- LOG_DEBUG(Service_AM, "called");
}
void Start(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
ASSERT(applet != nullptr);
applet->Initialize();
@@ -599,36 +614,39 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_AM, "called");
}
void PushInData(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::RequestParser rp{ctx};
applet->GetBroker().PushNormalDataFromGame(*rp.PopIpcInterface<IStorage>());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_AM, "called");
}
void PopOutData(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
const auto storage = applet->GetBroker().PopNormalDataToGame();
if (storage == nullptr) {
+ LOG_ERROR(Service_AM,
+ "storage is a nullptr. There is no data in the current normal channel");
+
rb.Push(ERR_NO_DATA_IN_CHANNEL);
return;
}
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IStorage>(std::move(*storage));
-
- LOG_DEBUG(Service_AM, "called");
}
void PushInteractiveInData(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::RequestParser rp{ctx};
applet->GetBroker().PushInteractiveDataFromGame(*rp.PopIpcInterface<IStorage>());
@@ -638,51 +656,52 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_AM, "called");
}
void PopInteractiveOutData(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
const auto storage = applet->GetBroker().PopInteractiveDataToGame();
if (storage == nullptr) {
+ LOG_ERROR(Service_AM,
+ "storage is a nullptr. There is no data in the current interactive channel");
+
rb.Push(ERR_NO_DATA_IN_CHANNEL);
return;
}
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IStorage>(std::move(*storage));
-
- LOG_DEBUG(Service_AM, "called");
}
void GetPopOutDataEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(applet->GetBroker().GetNormalDataEvent());
-
- LOG_DEBUG(Service_AM, "called");
}
void GetPopInteractiveOutDataEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(applet->GetBroker().GetInteractiveDataEvent());
-
- LOG_DEBUG(Service_AM, "called");
}
std::shared_ptr<Applets::Applet> applet;
};
void IStorage::Open(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IStorageAccessor>(*this);
-
- LOG_DEBUG(Service_AM, "called");
}
IStorageAccessor::IStorageAccessor(IStorage& storage)
@@ -701,12 +720,12 @@ IStorageAccessor::IStorageAccessor(IStorage& storage)
IStorageAccessor::~IStorageAccessor() = default;
void IStorageAccessor::GetSize(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u64>(backing.buffer.size()));
-
- LOG_DEBUG(Service_AM, "called");
}
void IStorageAccessor::Write(Kernel::HLERequestContext& ctx) {
@@ -715,7 +734,13 @@ void IStorageAccessor::Write(Kernel::HLERequestContext& ctx) {
const u64 offset{rp.Pop<u64>()};
const std::vector<u8> data{ctx.ReadBuffer()};
+ LOG_DEBUG(Service_AM, "called, offset={}, size={}", offset, data.size());
+
if (data.size() > backing.buffer.size() - offset) {
+ LOG_ERROR(Service_AM,
+ "offset is out of bounds, backing_buffer_sz={}, data_size={}, offset={}",
+ backing.buffer.size(), data.size(), offset);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERR_SIZE_OUT_OF_BOUNDS);
}
@@ -724,8 +749,6 @@ void IStorageAccessor::Write(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_AM, "called, offset={}", offset);
}
void IStorageAccessor::Read(Kernel::HLERequestContext& ctx) {
@@ -734,7 +757,12 @@ void IStorageAccessor::Read(Kernel::HLERequestContext& ctx) {
const u64 offset{rp.Pop<u64>()};
const std::size_t size{ctx.GetWriteBufferSize()};
+ LOG_DEBUG(Service_AM, "called, offset={}, size={}", offset, size);
+
if (size > backing.buffer.size() - offset) {
+ LOG_ERROR(Service_AM, "offset is out of bounds, backing_buffer_sz={}, size={}, offset={}",
+ backing.buffer.size(), size, offset);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ERR_SIZE_OUT_OF_BOUNDS);
}
@@ -743,8 +771,6 @@ void IStorageAccessor::Read(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_AM, "called, offset={}", offset);
}
ILibraryAppletCreator::ILibraryAppletCreator() : ServiceFramework("ILibraryAppletCreator") {
@@ -763,8 +789,12 @@ ILibraryAppletCreator::~ILibraryAppletCreator() = default;
static std::shared_ptr<Applets::Applet> GetAppletFromId(AppletId id) {
switch (id) {
+ case AppletId::ProfileSelect:
+ return std::make_shared<Applets::ProfileSelect>();
case AppletId::SoftwareKeyboard:
return std::make_shared<Applets::SoftwareKeyboard>();
+ case AppletId::LibAppletOff:
+ return std::make_shared<Applets::WebBrowser>();
default:
LOG_ERROR(Service_AM, "Unimplemented AppletId [{:08X}]! -- Falling back to stub!",
static_cast<u32>(id));
@@ -783,6 +813,8 @@ void ILibraryAppletCreator::CreateLibraryApplet(Kernel::HLERequestContext& ctx)
const auto applet = GetAppletFromId(applet_id);
if (applet == nullptr) {
+ LOG_ERROR(Service_AM, "Applet doesn't exist! applet_id={}", static_cast<u32>(applet_id));
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultCode(-1));
return;
@@ -792,23 +824,23 @@ void ILibraryAppletCreator::CreateLibraryApplet(Kernel::HLERequestContext& ctx)
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<AM::ILibraryAppletAccessor>(applet);
-
- LOG_DEBUG(Service_AM, "called");
}
void ILibraryAppletCreator::CreateStorage(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 size{rp.Pop<u64>()};
+ LOG_DEBUG(Service_AM, "called, size={}", size);
+
std::vector<u8> buffer(size);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<AM::IStorage>(std::move(buffer));
-
- LOG_DEBUG(Service_AM, "called, size={}", size);
}
void ILibraryAppletCreator::CreateTransferMemoryStorage(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::RequestParser rp{ctx};
rp.SetCurrentOffset(3);
@@ -819,6 +851,7 @@ void ILibraryAppletCreator::CreateTransferMemoryStorage(Kernel::HLERequestContex
handle);
if (shared_mem == nullptr) {
+ LOG_ERROR(Service_AM, "shared_mem is a nullpr for handle={:08X}", handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultCode(-1));
return;
@@ -846,8 +879,8 @@ IApplicationFunctions::IApplicationFunctions() : ServiceFramework("IApplicationF
{22, &IApplicationFunctions::SetTerminateResult, "SetTerminateResult"},
{23, &IApplicationFunctions::GetDisplayVersion, "GetDisplayVersion"},
{24, nullptr, "GetLaunchStorageInfoForDebug"},
- {25, nullptr, "ExtendSaveData"},
- {26, nullptr, "GetSaveDataSize"},
+ {25, &IApplicationFunctions::ExtendSaveData, "ExtendSaveData"},
+ {26, &IApplicationFunctions::GetSaveDataSize, "GetSaveDataSize"},
{30, &IApplicationFunctions::BeginBlockingHomeButtonShortAndLongPressed, "BeginBlockingHomeButtonShortAndLongPressed"},
{31, &IApplicationFunctions::EndBlockingHomeButtonShortAndLongPressed, "EndBlockingHomeButtonShortAndLongPressed"},
{32, &IApplicationFunctions::BeginBlockingHomeButton, "BeginBlockingHomeButton"},
@@ -882,38 +915,45 @@ IApplicationFunctions::IApplicationFunctions() : ServiceFramework("IApplicationF
IApplicationFunctions::~IApplicationFunctions() = default;
void IApplicationFunctions::EnableApplicationCrashReport(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::BeginBlockingHomeButtonShortAndLongPressed(
Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::EndBlockingHomeButtonShortAndLongPressed(
Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::BeginBlockingHomeButton(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::EndBlockingHomeButton(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::PopLaunchParameter(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
LaunchParameters params{};
params.magic = POP_LAUNCH_PARAMETER_MAGIC;
@@ -932,21 +972,19 @@ void IApplicationFunctions::PopLaunchParameter(Kernel::HLERequestContext& ctx) {
std::memcpy(buffer.data(), &params, buffer.size());
rb.PushIpcInterface<AM::IStorage>(buffer);
-
- LOG_DEBUG(Service_AM, "called");
}
void IApplicationFunctions::CreateApplicationAndRequestToStartForQuest(
Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::EnsureSaveData(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
u128 uid = rp.PopRaw<u128>(); // What does this do?
-
LOG_WARNING(Service, "(STUBBED) called uid = {:016X}{:016X}", uid[1], uid[0]);
IPC::ResponseBuilder rb{ctx, 4};
@@ -961,60 +999,104 @@ void IApplicationFunctions::SetTerminateResult(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
u32 result = rp.Pop<u32>();
+ LOG_WARNING(Service_AM, "(STUBBED) called, result=0x{:08X}", result);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called, result=0x{:08X}", result);
}
void IApplicationFunctions::GetDisplayVersion(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(RESULT_SUCCESS);
rb.Push<u64>(1);
rb.Push<u64>(0);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::GetDesiredLanguage(Kernel::HLERequestContext& ctx) {
// TODO(bunnei): This should be configurable
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push(
static_cast<u64>(Service::Set::GetLanguageCodeFromIndex(Settings::values.language_index)));
- LOG_DEBUG(Service_AM, "called");
}
void IApplicationFunctions::InitializeGamePlayRecording(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::SetGamePlayRecordingState(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::NotifyRunning(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u8>(0); // Unknown, seems to be ignored by official processes
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
void IApplicationFunctions::GetPseudoDeviceId(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(RESULT_SUCCESS);
// Returns a 128-bit UUID
rb.Push<u64>(0);
rb.Push<u64>(0);
+}
- LOG_WARNING(Service_AM, "(STUBBED) called");
+void IApplicationFunctions::ExtendSaveData(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto type{rp.PopRaw<FileSys::SaveDataType>()};
+ rp.Skip(1, false);
+ const auto user_id{rp.PopRaw<u128>()};
+ const auto new_normal_size{rp.PopRaw<u64>()};
+ const auto new_journal_size{rp.PopRaw<u64>()};
+
+ LOG_DEBUG(Service_AM,
+ "called with type={:02X}, user_id={:016X}{:016X}, new_normal={:016X}, "
+ "new_journal={:016X}",
+ static_cast<u8>(type), user_id[1], user_id[0], new_normal_size, new_journal_size);
+
+ FileSystem::WriteSaveDataSize(type, Core::CurrentProcess()->GetTitleID(), user_id,
+ {new_normal_size, new_journal_size});
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+
+ // The following value is used upon failure to help the system recover.
+ // Since we always succeed, this should be 0.
+ rb.Push<u64>(0);
+}
+
+void IApplicationFunctions::GetSaveDataSize(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto type{rp.PopRaw<FileSys::SaveDataType>()};
+ rp.Skip(1, false);
+ const auto user_id{rp.PopRaw<u128>()};
+
+ LOG_DEBUG(Service_AM, "called with type={:02X}, user_id={:016X}{:016X}", static_cast<u8>(type),
+ user_id[1], user_id[0]);
+
+ const auto size =
+ FileSystem::ReadSaveDataSize(type, Core::CurrentProcess()->GetTitleID(), user_id);
+
+ IPC::ResponseBuilder rb{ctx, 6};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push(size.normal);
+ rb.Push(size.journal);
}
void InstallInterfaces(SM::ServiceManager& service_manager,
@@ -1051,9 +1133,10 @@ IHomeMenuFunctions::IHomeMenuFunctions() : ServiceFramework("IHomeMenuFunctions"
IHomeMenuFunctions::~IHomeMenuFunctions() = default;
void IHomeMenuFunctions::RequestToGetForeground(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_AM, "(STUBBED) called");
}
IGlobalStateController::IGlobalStateController() : ServiceFramework("IGlobalStateController") {
diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h
index 44c1bcde5..b6113cfdd 100644
--- a/src/core/hle/service/am/am.h
+++ b/src/core/hle/service/am/am.h
@@ -6,12 +6,9 @@
#include <memory>
#include <queue>
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/service.h"
-namespace Kernel {
-class Event;
-}
-
namespace Service {
namespace NVFlinger {
class NVFlinger;
@@ -52,8 +49,8 @@ public:
AppletMessageQueue();
~AppletMessageQueue();
- const Kernel::SharedPtr<Kernel::Event>& GetMesssageRecieveEvent() const;
- const Kernel::SharedPtr<Kernel::Event>& GetOperationModeChangedEvent() const;
+ const Kernel::SharedPtr<Kernel::ReadableEvent>& GetMesssageRecieveEvent() const;
+ const Kernel::SharedPtr<Kernel::ReadableEvent>& GetOperationModeChangedEvent() const;
void PushMessage(AppletMessage msg);
AppletMessage PopMessage();
std::size_t GetMessageCount() const;
@@ -61,8 +58,8 @@ public:
private:
std::queue<AppletMessage> messages;
- Kernel::SharedPtr<Kernel::Event> on_new_message;
- Kernel::SharedPtr<Kernel::Event> on_operation_mode_changed;
+ Kernel::EventPair on_new_message;
+ Kernel::EventPair on_operation_mode_changed;
};
class IWindowController final : public ServiceFramework<IWindowController> {
@@ -122,7 +119,7 @@ private:
void GetIdleTimeDetectionExtension(Kernel::HLERequestContext& ctx);
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
- Kernel::SharedPtr<Kernel::Event> launchable_event;
+ Kernel::EventPair launchable_event;
u32 idle_time_detection_extension = 0;
};
@@ -151,7 +148,6 @@ private:
void GetBootMode(Kernel::HLERequestContext& ctx);
void GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx);
- Kernel::SharedPtr<Kernel::Event> event;
std::shared_ptr<AppletMessageQueue> msg_queue;
};
@@ -210,6 +206,8 @@ private:
void SetGamePlayRecordingState(Kernel::HLERequestContext& ctx);
void NotifyRunning(Kernel::HLERequestContext& ctx);
void GetPseudoDeviceId(Kernel::HLERequestContext& ctx);
+ void ExtendSaveData(Kernel::HLERequestContext& ctx);
+ void GetSaveDataSize(Kernel::HLERequestContext& ctx);
void BeginBlockingHomeButtonShortAndLongPressed(Kernel::HLERequestContext& ctx);
void EndBlockingHomeButtonShortAndLongPressed(Kernel::HLERequestContext& ctx);
void BeginBlockingHomeButton(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/am/applet_ae.cpp b/src/core/hle/service/am/applet_ae.cpp
index ec93e3529..41a573a91 100644
--- a/src/core/hle/service/am/applet_ae.cpp
+++ b/src/core/hle/service/am/applet_ae.cpp
@@ -32,66 +32,75 @@ public:
private:
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
void GetSelfController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISelfController>(nvflinger);
- LOG_DEBUG(Service_AM, "called");
}
void GetWindowController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IWindowController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetAudioController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IAudioController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDisplayController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDisplayController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetProcessWindingController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IProcessWindingController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDebugFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDebugFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
void GetLibraryAppletCreator(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILibraryAppletCreator>();
- LOG_DEBUG(Service_AM, "called");
}
void GetApplicationFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IApplicationFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
@@ -122,97 +131,110 @@ public:
private:
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
void GetSelfController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISelfController>(nvflinger);
- LOG_DEBUG(Service_AM, "called");
}
void GetWindowController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IWindowController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetAudioController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IAudioController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDisplayController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDisplayController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDebugFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDebugFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
void GetLibraryAppletCreator(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILibraryAppletCreator>();
- LOG_DEBUG(Service_AM, "called");
}
void GetHomeMenuFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IHomeMenuFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
void GetGlobalStateController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IGlobalStateController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetApplicationCreator(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IApplicationCreator>();
- LOG_DEBUG(Service_AM, "called");
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
std::shared_ptr<AppletMessageQueue> msg_queue;
};
void AppletAE::OpenSystemAppletProxy(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystemAppletProxy>(nvflinger, msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
void AppletAE::OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
void AppletAE::OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
diff --git a/src/core/hle/service/am/applet_oe.cpp b/src/core/hle/service/am/applet_oe.cpp
index 20c8d5fff..d3a0a1568 100644
--- a/src/core/hle/service/am/applet_oe.cpp
+++ b/src/core/hle/service/am/applet_oe.cpp
@@ -35,59 +35,67 @@ public:
private:
void GetAudioController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IAudioController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDisplayController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDisplayController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetDebugFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IDebugFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
void GetWindowController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IWindowController>();
- LOG_DEBUG(Service_AM, "called");
}
void GetSelfController(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISelfController>(nvflinger);
- LOG_DEBUG(Service_AM, "called");
}
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
void GetLibraryAppletCreator(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILibraryAppletCreator>();
- LOG_DEBUG(Service_AM, "called");
}
void GetApplicationFunctions(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IApplicationFunctions>();
- LOG_DEBUG(Service_AM, "called");
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
@@ -95,10 +103,11 @@ private:
};
void AppletOE::OpenApplicationProxy(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IApplicationProxy>(nvflinger, msg_queue);
- LOG_DEBUG(Service_AM, "called");
}
AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
diff --git a/src/core/hle/service/am/applets/applets.cpp b/src/core/hle/service/am/applets/applets.cpp
index becbadd06..a6064c63f 100644
--- a/src/core/hle/service/am/applets/applets.cpp
+++ b/src/core/hle/service/am/applets/applets.cpp
@@ -5,8 +5,9 @@
#include <cstring>
#include "common/assert.h"
#include "core/core.h"
-#include "core/hle/kernel/event.h"
-#include "core/hle/kernel/server_port.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/server_session.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/am/am.h"
#include "core/hle/service/am/applets/applets.h"
@@ -14,12 +15,12 @@ namespace Service::AM::Applets {
AppletDataBroker::AppletDataBroker() {
auto& kernel = Core::System::GetInstance().Kernel();
- state_changed_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "ILibraryAppletAccessor:StateChangedEvent");
- pop_out_data_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "ILibraryAppletAccessor:PopDataOutEvent");
- pop_interactive_out_data_event = Kernel::Event::Create(
- kernel, Kernel::ResetType::OneShot, "ILibraryAppletAccessor:PopInteractiveDataOutEvent");
+ state_changed_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::Sticky, "ILibraryAppletAccessor:StateChangedEvent");
+ pop_out_data_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::Sticky, "ILibraryAppletAccessor:PopDataOutEvent");
+ pop_interactive_out_data_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::Sticky, "ILibraryAppletAccessor:PopInteractiveDataOutEvent");
}
AppletDataBroker::~AppletDataBroker() = default;
@@ -66,7 +67,7 @@ void AppletDataBroker::PushNormalDataFromGame(IStorage storage) {
void AppletDataBroker::PushNormalDataFromApplet(IStorage storage) {
out_channel.push(std::make_unique<IStorage>(storage));
- pop_out_data_event->Signal();
+ pop_out_data_event.writable->Signal();
}
void AppletDataBroker::PushInteractiveDataFromGame(IStorage storage) {
@@ -75,23 +76,23 @@ void AppletDataBroker::PushInteractiveDataFromGame(IStorage storage) {
void AppletDataBroker::PushInteractiveDataFromApplet(IStorage storage) {
out_interactive_channel.push(std::make_unique<IStorage>(storage));
- pop_interactive_out_data_event->Signal();
+ pop_interactive_out_data_event.writable->Signal();
}
void AppletDataBroker::SignalStateChanged() const {
- state_changed_event->Signal();
+ state_changed_event.writable->Signal();
}
-Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetNormalDataEvent() const {
- return pop_out_data_event;
+Kernel::SharedPtr<Kernel::ReadableEvent> AppletDataBroker::GetNormalDataEvent() const {
+ return pop_out_data_event.readable;
}
-Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetInteractiveDataEvent() const {
- return pop_interactive_out_data_event;
+Kernel::SharedPtr<Kernel::ReadableEvent> AppletDataBroker::GetInteractiveDataEvent() const {
+ return pop_interactive_out_data_event.readable;
}
-Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetStateChangedEvent() const {
- return state_changed_event;
+Kernel::SharedPtr<Kernel::ReadableEvent> AppletDataBroker::GetStateChangedEvent() const {
+ return state_changed_event.readable;
}
Applet::Applet() = default;
diff --git a/src/core/hle/service/am/applets/applets.h b/src/core/hle/service/am/applets/applets.h
index f65ea119c..37424c379 100644
--- a/src/core/hle/service/am/applets/applets.h
+++ b/src/core/hle/service/am/applets/applets.h
@@ -7,14 +7,11 @@
#include <memory>
#include <queue>
#include "common/swap.h"
-#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/object.h"
+#include "core/hle/kernel/writable_event.h"
union ResultCode;
-namespace Kernel {
-class Event;
-}
-
namespace Service::AM {
class IStorage;
@@ -40,9 +37,9 @@ public:
void SignalStateChanged() const;
- Kernel::SharedPtr<Kernel::Event> GetNormalDataEvent() const;
- Kernel::SharedPtr<Kernel::Event> GetInteractiveDataEvent() const;
- Kernel::SharedPtr<Kernel::Event> GetStateChangedEvent() const;
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetNormalDataEvent() const;
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetInteractiveDataEvent() const;
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetStateChangedEvent() const;
private:
// Queues are named from applet's perspective
@@ -59,13 +56,13 @@ private:
// PopInteractiveDataToGame and PushInteractiveDataFromApplet
std::queue<std::unique_ptr<IStorage>> out_interactive_channel;
- Kernel::SharedPtr<Kernel::Event> state_changed_event;
+ Kernel::EventPair state_changed_event;
// Signaled on PushNormalDataFromApplet
- Kernel::SharedPtr<Kernel::Event> pop_out_data_event;
+ Kernel::EventPair pop_out_data_event;
// Signaled on PushInteractiveDataFromApplet
- Kernel::SharedPtr<Kernel::Event> pop_interactive_out_data_event;
+ Kernel::EventPair pop_interactive_out_data_event;
};
class Applet {
diff --git a/src/core/hle/service/am/applets/profile_select.cpp b/src/core/hle/service/am/applets/profile_select.cpp
new file mode 100644
index 000000000..14e2a1fee
--- /dev/null
+++ b/src/core/hle/service/am/applets/profile_select.cpp
@@ -0,0 +1,77 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <cstring>
+
+#include "common/assert.h"
+#include "common/string_util.h"
+#include "core/core.h"
+#include "core/frontend/applets/profile_select.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/profile_select.h"
+
+namespace Service::AM::Applets {
+
+constexpr ResultCode ERR_USER_CANCELLED_SELECTION{ErrorModule::Account, 1};
+
+ProfileSelect::ProfileSelect() = default;
+ProfileSelect::~ProfileSelect() = default;
+
+void ProfileSelect::Initialize() {
+ complete = false;
+ status = RESULT_SUCCESS;
+ final_data.clear();
+
+ Applet::Initialize();
+
+ const auto user_config_storage = broker.PopNormalDataToApplet();
+ ASSERT(user_config_storage != nullptr);
+ const auto& user_config = user_config_storage->GetData();
+
+ ASSERT(user_config.size() >= sizeof(UserSelectionConfig));
+ std::memcpy(&config, user_config.data(), sizeof(UserSelectionConfig));
+}
+
+bool ProfileSelect::TransactionComplete() const {
+ return complete;
+}
+
+ResultCode ProfileSelect::GetStatus() const {
+ return status;
+}
+
+void ProfileSelect::ExecuteInteractive() {
+ UNREACHABLE_MSG("Attempted to call interactive execution on non-interactive applet.");
+}
+
+void ProfileSelect::Execute() {
+ if (complete) {
+ broker.PushNormalDataFromApplet(IStorage{final_data});
+ return;
+ }
+
+ const auto& frontend{Core::System::GetInstance().GetProfileSelector()};
+
+ frontend.SelectProfile([this](std::optional<Account::UUID> uuid) { SelectionComplete(uuid); });
+}
+
+void ProfileSelect::SelectionComplete(std::optional<Account::UUID> uuid) {
+ UserSelectionOutput output{};
+
+ if (uuid.has_value() && uuid->uuid != Account::INVALID_UUID) {
+ output.result = 0;
+ output.uuid_selected = uuid->uuid;
+ } else {
+ status = ERR_USER_CANCELLED_SELECTION;
+ output.result = ERR_USER_CANCELLED_SELECTION.raw;
+ output.uuid_selected = Account::INVALID_UUID;
+ }
+
+ final_data = std::vector<u8>(sizeof(UserSelectionOutput));
+ std::memcpy(final_data.data(), &output, final_data.size());
+ broker.PushNormalDataFromApplet(IStorage{final_data});
+ broker.SignalStateChanged();
+}
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/profile_select.h b/src/core/hle/service/am/applets/profile_select.h
new file mode 100644
index 000000000..787485f22
--- /dev/null
+++ b/src/core/hle/service/am/applets/profile_select.h
@@ -0,0 +1,50 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <vector>
+
+#include "common/common_funcs.h"
+#include "core/hle/service/acc/profile_manager.h"
+#include "core/hle/service/am/applets/applets.h"
+
+namespace Service::AM::Applets {
+
+struct UserSelectionConfig {
+ // TODO(DarkLordZach): RE this structure
+ // It seems to be flags and the like that determine the UI of the applet on the switch... from
+ // my research this is safe to ignore for now.
+ INSERT_PADDING_BYTES(0xA0);
+};
+static_assert(sizeof(UserSelectionConfig) == 0xA0, "UserSelectionConfig has incorrect size.");
+
+struct UserSelectionOutput {
+ u64 result;
+ u128 uuid_selected;
+};
+static_assert(sizeof(UserSelectionOutput) == 0x18, "UserSelectionOutput has incorrect size.");
+
+class ProfileSelect final : public Applet {
+public:
+ ProfileSelect();
+ ~ProfileSelect() override;
+
+ void Initialize() override;
+
+ bool TransactionComplete() const override;
+ ResultCode GetStatus() const override;
+ void ExecuteInteractive() override;
+ void Execute() override;
+
+ void SelectionComplete(std::optional<Account::UUID> uuid);
+
+private:
+ UserSelectionConfig config;
+ bool complete = false;
+ ResultCode status = RESULT_SUCCESS;
+ std::vector<u8> final_data;
+};
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/software_keyboard.cpp b/src/core/hle/service/am/applets/software_keyboard.cpp
index 981bdec51..f255f74b5 100644
--- a/src/core/hle/service/am/applets/software_keyboard.cpp
+++ b/src/core/hle/service/am/applets/software_keyboard.cpp
@@ -146,11 +146,10 @@ void SoftwareKeyboard::WriteText(std::optional<std::u16string> text) {
if (complete) {
broker.PushNormalDataFromApplet(IStorage{output_main});
+ broker.SignalStateChanged();
} else {
broker.PushInteractiveDataFromApplet(IStorage{output_sub});
}
-
- broker.SignalStateChanged();
} else {
output_main[0] = 1;
complete = true;
diff --git a/src/core/hle/service/am/applets/web_browser.cpp b/src/core/hle/service/am/applets/web_browser.cpp
new file mode 100644
index 000000000..9b0aa7f5f
--- /dev/null
+++ b/src/core/hle/service/am/applets/web_browser.cpp
@@ -0,0 +1,190 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <array>
+#include <cstring>
+#include <vector>
+
+#include "common/assert.h"
+#include "common/common_funcs.h"
+#include "common/common_paths.h"
+#include "common/file_util.h"
+#include "common/hex_util.h"
+#include "common/logging/log.h"
+#include "common/string_util.h"
+#include "core/core.h"
+#include "core/file_sys/content_archive.h"
+#include "core/file_sys/mode.h"
+#include "core/file_sys/nca_metadata.h"
+#include "core/file_sys/registered_cache.h"
+#include "core/file_sys/romfs.h"
+#include "core/file_sys/vfs_types.h"
+#include "core/frontend/applets/web_browser.h"
+#include "core/hle/kernel/process.h"
+#include "core/hle/service/am/applets/web_browser.h"
+#include "core/hle/service/filesystem/filesystem.h"
+#include "core/loader/loader.h"
+
+namespace Service::AM::Applets {
+
+// TODO(DarkLordZach): There are other arguments in the WebBuffer structure that are currently not
+// parsed, for example footer mode and left stick mode. Some of these are not particularly relevant,
+// but some may be worth an implementation.
+constexpr u16 WEB_ARGUMENT_URL_TYPE = 0x6;
+
+struct WebBufferHeader {
+ u16 count;
+ INSERT_PADDING_BYTES(6);
+};
+static_assert(sizeof(WebBufferHeader) == 0x8, "WebBufferHeader has incorrect size.");
+
+struct WebArgumentHeader {
+ u16 type;
+ u16 size;
+ u32 offset;
+};
+static_assert(sizeof(WebArgumentHeader) == 0x8, "WebArgumentHeader has incorrect size.");
+
+struct WebArgumentResult {
+ u32 result_code;
+ std::array<char, 0x1000> last_url;
+ u64 last_url_size;
+};
+static_assert(sizeof(WebArgumentResult) == 0x1010, "WebArgumentResult has incorrect size.");
+
+static std::vector<u8> GetArgumentDataForTagType(const std::vector<u8>& data, u16 type) {
+ WebBufferHeader header;
+ ASSERT(sizeof(WebBufferHeader) <= data.size());
+ std::memcpy(&header, data.data(), sizeof(WebBufferHeader));
+
+ u64 offset = sizeof(WebBufferHeader);
+ for (u16 i = 0; i < header.count; ++i) {
+ WebArgumentHeader arg;
+ ASSERT(offset + sizeof(WebArgumentHeader) <= data.size());
+ std::memcpy(&arg, data.data() + offset, sizeof(WebArgumentHeader));
+ offset += sizeof(WebArgumentHeader);
+
+ if (arg.type == type) {
+ std::vector<u8> out(arg.size);
+ offset += arg.offset;
+ ASSERT(offset + arg.size <= data.size());
+ std::memcpy(out.data(), data.data() + offset, out.size());
+ return out;
+ }
+
+ offset += arg.offset + arg.size;
+ }
+
+ return {};
+}
+
+static FileSys::VirtualFile GetManualRomFS() {
+ auto& loader{Core::System::GetInstance().GetAppLoader()};
+
+ FileSys::VirtualFile out;
+ if (loader.ReadManualRomFS(out) == Loader::ResultStatus::Success)
+ return out;
+
+ const auto& installed{FileSystem::GetUnionContents()};
+ const auto res = installed.GetEntry(Core::System::GetInstance().CurrentProcess()->GetTitleID(),
+ FileSys::ContentRecordType::Manual);
+
+ if (res != nullptr)
+ return res->GetRomFS();
+ return nullptr;
+}
+
+WebBrowser::WebBrowser() = default;
+
+WebBrowser::~WebBrowser() = default;
+
+void WebBrowser::Initialize() {
+ Applet::Initialize();
+
+ complete = false;
+ temporary_dir.clear();
+ filename.clear();
+ status = RESULT_SUCCESS;
+
+ const auto web_arg_storage = broker.PopNormalDataToApplet();
+ ASSERT(web_arg_storage != nullptr);
+ const auto& web_arg = web_arg_storage->GetData();
+
+ const auto url_data = GetArgumentDataForTagType(web_arg, WEB_ARGUMENT_URL_TYPE);
+ filename = Common::StringFromFixedZeroTerminatedBuffer(
+ reinterpret_cast<const char*>(url_data.data()), url_data.size());
+
+ temporary_dir = FileUtil::SanitizePath(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) +
+ "web_applet_manual",
+ FileUtil::DirectorySeparator::PlatformDefault);
+ FileUtil::DeleteDirRecursively(temporary_dir);
+
+ manual_romfs = GetManualRomFS();
+ if (manual_romfs == nullptr) {
+ status = ResultCode(-1);
+ LOG_ERROR(Service_AM, "Failed to find manual for current process!");
+ }
+
+ filename =
+ FileUtil::SanitizePath(temporary_dir + DIR_SEP + "html-document" + DIR_SEP + filename,
+ FileUtil::DirectorySeparator::PlatformDefault);
+}
+
+bool WebBrowser::TransactionComplete() const {
+ return complete;
+}
+
+ResultCode WebBrowser::GetStatus() const {
+ return status;
+}
+
+void WebBrowser::ExecuteInteractive() {
+ UNIMPLEMENTED_MSG("Unexpected interactive data recieved!");
+}
+
+void WebBrowser::Execute() {
+ if (complete)
+ return;
+
+ if (status != RESULT_SUCCESS) {
+ complete = true;
+ return;
+ }
+
+ auto& frontend{Core::System::GetInstance().GetWebBrowser()};
+
+ frontend.OpenPage(filename, [this] { UnpackRomFS(); }, [this] { Finalize(); });
+}
+
+void WebBrowser::UnpackRomFS() {
+ if (unpacked)
+ return;
+
+ ASSERT(manual_romfs != nullptr);
+ const auto dir =
+ FileSys::ExtractRomFS(manual_romfs, FileSys::RomFSExtractionType::SingleDiscard);
+ const auto& vfs{Core::System::GetInstance().GetFilesystem()};
+ const auto temp_dir = vfs->CreateDirectory(temporary_dir, FileSys::Mode::ReadWrite);
+ FileSys::VfsRawCopyD(dir, temp_dir);
+
+ unpacked = true;
+}
+
+void WebBrowser::Finalize() {
+ complete = true;
+
+ WebArgumentResult out{};
+ out.result_code = 0;
+ out.last_url_size = 0;
+
+ std::vector<u8> data(sizeof(WebArgumentResult));
+ std::memcpy(data.data(), &out, sizeof(WebArgumentResult));
+
+ broker.PushNormalDataFromApplet(IStorage{data});
+ broker.SignalStateChanged();
+
+ FileUtil::DeleteDirRecursively(temporary_dir);
+}
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/web_browser.h b/src/core/hle/service/am/applets/web_browser.h
new file mode 100644
index 000000000..b9e228fac
--- /dev/null
+++ b/src/core/hle/service/am/applets/web_browser.h
@@ -0,0 +1,44 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "core/file_sys/vfs_types.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/applets.h"
+
+namespace Service::AM::Applets {
+
+class WebBrowser final : public Applet {
+public:
+ WebBrowser();
+ ~WebBrowser() override;
+
+ void Initialize() override;
+
+ bool TransactionComplete() const override;
+ ResultCode GetStatus() const override;
+ void ExecuteInteractive() override;
+ void Execute() override;
+
+ // Callback to be fired when the frontend needs the manual RomFS unpacked to temporary
+ // directory. This is a blocking call and may take a while as some manuals can be up to 100MB in
+ // size. Attempting to access files at filename before invocation is likely to not work.
+ void UnpackRomFS();
+
+ // Callback to be fired when the frontend is finished browsing. This will delete the temporary
+ // manual RomFS extracted files, so ensure this is only called at actual finalization.
+ void Finalize();
+
+private:
+ bool complete = false;
+ bool unpacked = false;
+ ResultCode status = RESULT_SUCCESS;
+
+ FileSys::VirtualFile manual_romfs;
+ std::string temporary_dir;
+ std::string filename;
+};
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/aoc/aoc_u.cpp b/src/core/hle/service/aoc/aoc_u.cpp
index 54305cf05..b506bc3dd 100644
--- a/src/core/hle/service/aoc/aoc_u.cpp
+++ b/src/core/hle/service/aoc/aoc_u.cpp
@@ -13,11 +13,14 @@
#include "core/file_sys/patch_manager.h"
#include "core/file_sys/registered_cache.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/aoc/aoc_u.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/loader/loader.h"
+#include "core/settings.h"
namespace Service::AOC {
@@ -32,14 +35,14 @@ static std::vector<u64> AccumulateAOCTitleIDs() {
std::vector<u64> add_on_content;
const auto rcu = FileSystem::GetUnionContents();
const auto list =
- rcu->ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
+ rcu.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
std::transform(list.begin(), list.end(), std::back_inserter(add_on_content),
[](const FileSys::RegisteredCacheEntry& rce) { return rce.title_id; });
add_on_content.erase(
std::remove_if(
add_on_content.begin(), add_on_content.end(),
[&rcu](u64 tid) {
- return rcu->GetEntry(tid, FileSys::ContentRecordType::Data)->GetStatus() !=
+ return rcu.GetEntry(tid, FileSys::ContentRecordType::Data)->GetStatus() !=
Loader::ResultStatus::Success;
}),
add_on_content.end());
@@ -61,17 +64,26 @@ AOC_U::AOC_U() : ServiceFramework("aoc:u"), add_on_content(AccumulateAOCTitleIDs
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- aoc_change_event = Kernel::Event::Create(kernel, Kernel::ResetType::Sticky,
- "GetAddOnContentListChanged:Event");
+ aoc_change_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "GetAddOnContentListChanged:Event");
}
AOC_U::~AOC_U() = default;
void AOC_U::CountAddOnContent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AOC, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
const auto current = Core::System::GetInstance().CurrentProcess()->GetTitleID();
+
+ const auto& disabled = Settings::values.disabled_addons[current];
+ if (std::find(disabled.begin(), disabled.end(), "DLC") != disabled.end()) {
+ rb.Push<u32>(0);
+ return;
+ }
+
rb.Push<u32>(static_cast<u32>(
std::count_if(add_on_content.begin(), add_on_content.end(),
[current](u64 tid) { return CheckAOCTitleIDMatchesBase(tid, current); })));
@@ -82,6 +94,7 @@ void AOC_U::ListAddOnContent(Kernel::HLERequestContext& ctx) {
const auto offset = rp.PopRaw<u32>();
auto count = rp.PopRaw<u32>();
+ LOG_DEBUG(Service_AOC, "called with offset={}, count={}", offset, count);
const auto current = Core::System::GetInstance().CurrentProcess()->GetTitleID();
@@ -91,6 +104,10 @@ void AOC_U::ListAddOnContent(Kernel::HLERequestContext& ctx) {
out.push_back(static_cast<u32>(add_on_content[i] & 0x7FF));
}
+ const auto& disabled = Settings::values.disabled_addons[current];
+ if (std::find(disabled.begin(), disabled.end(), "DLC") != disabled.end())
+ out = {};
+
if (out.size() < offset) {
IPC::ResponseBuilder rb{ctx, 2};
// TODO(DarkLordZach): Find the correct error code.
@@ -110,6 +127,8 @@ void AOC_U::ListAddOnContent(Kernel::HLERequestContext& ctx) {
}
void AOC_U::GetAddOnContentBaseId(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_AOC, "called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
const auto title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
@@ -128,7 +147,6 @@ void AOC_U::PrepareAddOnContent(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto aoc_id = rp.PopRaw<u32>();
-
LOG_WARNING(Service_AOC, "(STUBBED) called with aoc_id={:08X}", aoc_id);
IPC::ResponseBuilder rb{ctx, 2};
@@ -140,7 +158,7 @@ void AOC_U::GetAddOnContentListChangedEvent(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(aoc_change_event);
+ rb.PushCopyObjects(aoc_change_event.readable);
}
void InstallInterfaces(SM::ServiceManager& service_manager) {
diff --git a/src/core/hle/service/aoc/aoc_u.h b/src/core/hle/service/aoc/aoc_u.h
index 68d94fdaa..5effea730 100644
--- a/src/core/hle/service/aoc/aoc_u.h
+++ b/src/core/hle/service/aoc/aoc_u.h
@@ -6,6 +6,10 @@
#include "core/hle/service/service.h"
+namespace Kernel {
+class WritableEvent;
+}
+
namespace Service::AOC {
class AOC_U final : public ServiceFramework<AOC_U> {
@@ -21,7 +25,7 @@ private:
void GetAddOnContentListChangedEvent(Kernel::HLERequestContext& ctx);
std::vector<u64> add_on_content;
- Kernel::SharedPtr<Kernel::Event> aoc_change_event;
+ Kernel::EventPair aoc_change_event;
};
/// Registers all AOC services with the specified service manager.
diff --git a/src/core/hle/service/apm/interface.cpp b/src/core/hle/service/apm/interface.cpp
index c22bd3859..fcacbab72 100644
--- a/src/core/hle/service/apm/interface.cpp
+++ b/src/core/hle/service/apm/interface.cpp
@@ -40,24 +40,22 @@ private:
auto mode = static_cast<PerformanceMode>(rp.Pop<u32>());
u32 config = rp.Pop<u32>();
+ LOG_WARNING(Service_APM, "(STUBBED) called mode={} config={}", static_cast<u32>(mode),
+ config);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_APM, "(STUBBED) called mode={} config={}", static_cast<u32>(mode),
- config);
}
void GetPerformanceConfiguration(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
auto mode = static_cast<PerformanceMode>(rp.Pop<u32>());
+ LOG_WARNING(Service_APM, "(STUBBED) called mode={}", static_cast<u32>(mode));
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(static_cast<u32>(PerformanceConfiguration::Config1));
-
- LOG_WARNING(Service_APM, "(STUBBED) called mode={}", static_cast<u32>(mode));
}
};
@@ -73,11 +71,11 @@ APM::APM(std::shared_ptr<Module> apm, const char* name)
APM::~APM() = default;
void APM::OpenSession(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_APM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISession>();
-
- LOG_DEBUG(Service_APM, "called");
}
APM_Sys::APM_Sys() : ServiceFramework{"apm:sys"} {
@@ -98,11 +96,11 @@ APM_Sys::APM_Sys() : ServiceFramework{"apm:sys"} {
APM_Sys::~APM_Sys() = default;
void APM_Sys::GetPerformanceEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_APM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISession>();
-
- LOG_DEBUG(Service_APM, "called");
}
} // namespace Service::APM
diff --git a/src/core/hle/service/arp/arp.cpp b/src/core/hle/service/arp/arp.cpp
index 358ef2576..e675b0188 100644
--- a/src/core/hle/service/arp/arp.cpp
+++ b/src/core/hle/service/arp/arp.cpp
@@ -59,11 +59,11 @@ public:
private:
void AcquireRegistrar(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_ARP, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IRegistrar>();
-
- LOG_DEBUG(Service_ARP, "called");
}
};
diff --git a/src/core/hle/service/audio/audout_u.cpp b/src/core/hle/service/audio/audout_u.cpp
index 23e1f1165..dc6a6b188 100644
--- a/src/core/hle/service/audio/audout_u.cpp
+++ b/src/core/hle/service/audio/audout_u.cpp
@@ -13,8 +13,10 @@
#include "common/swap.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/hle_ipc.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/audio/audout_u.h"
#include "core/memory.h"
@@ -46,8 +48,8 @@ class IAudioOut final : public ServiceFramework<IAudioOut> {
public:
IAudioOut(AudoutParams audio_params, AudioCore::AudioOut& audio_core, std::string&& device_name,
std::string&& unique_name)
- : ServiceFramework("IAudioOut"), audio_core(audio_core), audio_params(audio_params),
- device_name(std::move(device_name)) {
+ : ServiceFramework("IAudioOut"), audio_core(audio_core),
+ device_name(std::move(device_name)), audio_params(audio_params) {
static const FunctionInfo functions[] = {
{0, &IAudioOut::GetAudioOutState, "GetAudioOutState"},
@@ -67,11 +69,12 @@ public:
// This is the event handle used to check if the audio buffer was released
auto& kernel = Core::System::GetInstance().Kernel();
- buffer_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::Sticky, "IAudioOutBufferReleased");
+ buffer_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "IAudioOutBufferReleased");
stream = audio_core.OpenStream(audio_params.sample_rate, audio_params.channel_count,
- std::move(unique_name), [=]() { buffer_event->Signal(); });
+ std::move(unique_name),
+ [=]() { buffer_event.writable->Signal(); });
}
private:
@@ -86,6 +89,7 @@ private:
void GetAudioOutState(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u32>(stream->IsPlaying() ? AudioState::Started : AudioState::Stopped));
@@ -120,7 +124,7 @@ private:
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(buffer_event);
+ rb.PushCopyObjects(buffer_event.readable);
}
void AppendAudioOutBufferImpl(Kernel::HLERequestContext& ctx) {
@@ -148,6 +152,7 @@ private:
void GetReleasedAudioOutBufferImpl(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called {}", ctx.Description());
+
IPC::RequestParser rp{ctx};
const u64 max_count{ctx.GetWriteBufferSize() / sizeof(u64)};
const auto released_buffers{audio_core.GetTagsAndReleaseBuffers(stream, max_count)};
@@ -163,6 +168,7 @@ private:
void ContainsAudioOutBuffer(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
+
IPC::RequestParser rp{ctx};
const u64 tag{rp.Pop<u64>()};
IPC::ResponseBuilder rb{ctx, 3};
@@ -172,6 +178,7 @@ private:
void GetAudioOutBufferCount(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u32>(stream->GetQueueSize()));
@@ -183,12 +190,13 @@ private:
AudoutParams audio_params{};
- /// This is the evend handle used to check if the audio buffer was released
- Kernel::SharedPtr<Kernel::Event> buffer_event;
+ /// This is the event handle used to check if the audio buffer was released
+ Kernel::EventPair buffer_event;
};
void AudOutU::ListAudioOutsImpl(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
+
IPC::RequestParser rp{ctx};
ctx.WriteBuffer(DefaultDevice);
diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp
index d3ea57ea7..945259c7d 100644
--- a/src/core/hle/service/audio/audren_u.cpp
+++ b/src/core/hle/service/audio/audren_u.cpp
@@ -12,8 +12,10 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/hle_ipc.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/audio/audren_u.h"
namespace Service::Audio {
@@ -41,85 +43,90 @@ public:
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- system_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::Sticky, "IAudioRenderer:SystemEvent");
- renderer = std::make_unique<AudioCore::AudioRenderer>(audren_params, system_event);
+ system_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "IAudioRenderer:SystemEvent");
+ renderer = std::make_unique<AudioCore::AudioRenderer>(audren_params, system_event.writable);
}
private:
void UpdateAudioCallback() {
- system_event->Signal();
+ system_event.writable->Signal();
}
void GetSampleRate(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(renderer->GetSampleRate());
- LOG_DEBUG(Service_Audio, "called");
}
void GetSampleCount(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(renderer->GetSampleCount());
- LOG_DEBUG(Service_Audio, "called");
}
void GetState(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(static_cast<u32>(renderer->GetStreamState()));
- LOG_DEBUG(Service_Audio, "called");
}
void GetMixBufferCount(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(renderer->GetMixBufferCount());
- LOG_DEBUG(Service_Audio, "called");
}
void RequestUpdateImpl(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Audio, "(STUBBED) called");
+
ctx.WriteBuffer(renderer->UpdateAudioRenderer(ctx.ReadBuffer()));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_Audio, "(STUBBED) called");
}
void Start(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Audio, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_Audio, "(STUBBED) called");
}
void Stop(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Audio, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_Audio, "(STUBBED) called");
}
void QuerySystemEvent(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Audio, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(system_event);
-
- LOG_WARNING(Service_Audio, "(STUBBED) called");
+ rb.PushCopyObjects(system_event.readable);
}
void SetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
rendering_time_limit_percent = rp.Pop<u32>();
+ LOG_DEBUG(Service_Audio, "called. rendering_time_limit_percent={}",
+ rendering_time_limit_percent);
+
ASSERT(rendering_time_limit_percent >= 0 && rendering_time_limit_percent <= 100);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_Audio, "called. rendering_time_limit_percent={}",
- rendering_time_limit_percent);
}
void GetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
@@ -130,7 +137,7 @@ private:
rb.Push(rendering_time_limit_percent);
}
- Kernel::SharedPtr<Kernel::Event> system_event;
+ Kernel::EventPair system_event;
std::unique_ptr<AudioCore::AudioRenderer> renderer;
u32 rendering_time_limit_percent = 100;
};
@@ -157,8 +164,8 @@ public:
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- buffer_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "IAudioOutBufferReleasedEvent");
+ buffer_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IAudioOutBufferReleasedEvent");
}
private:
@@ -202,21 +209,22 @@ private:
void QueryAudioDeviceSystemEvent(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_Audio, "(STUBBED) called");
- buffer_event->Signal();
+ buffer_event.writable->Signal();
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(buffer_event);
+ rb.PushCopyObjects(buffer_event.readable);
}
void GetActiveChannelCount(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_Audio, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(1);
}
- Kernel::SharedPtr<Kernel::Event> buffer_event;
+ Kernel::EventPair buffer_event;
}; // namespace Audio
@@ -235,19 +243,20 @@ AudRenU::AudRenU() : ServiceFramework("audren:u") {
AudRenU::~AudRenU() = default;
void AudRenU::OpenAudioRenderer(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<AudioCore::AudioRendererParameter>();
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<Audio::IAudioRenderer>(std::move(params));
-
- LOG_DEBUG(Service_Audio, "called");
}
void AudRenU::GetAudioRendererWorkBufferSize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
auto params = rp.PopRaw<AudioCore::AudioRendererParameter>();
+ LOG_DEBUG(Service_Audio, "called");
u64 buffer_sz = Common::AlignUp(4 * params.mix_buffer_count, 0x40);
buffer_sz += params.unknown_c * 1024;
@@ -301,26 +310,26 @@ void AudRenU::GetAudioRendererWorkBufferSize(Kernel::HLERequestContext& ctx) {
rb.Push(RESULT_SUCCESS);
rb.Push<u64>(output_sz);
- LOG_DEBUG(Service_Audio, "called, buffer_size=0x{:X}", output_sz);
+ LOG_DEBUG(Service_Audio, "buffer_size=0x{:X}", output_sz);
}
void AudRenU::GetAudioDevice(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<Audio::IAudioDevice>();
-
- LOG_DEBUG(Service_Audio, "called");
}
void AudRenU::GetAudioDeviceServiceWithRevisionInfo(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Audio, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<Audio::IAudioDevice>();
-
- LOG_WARNING(Service_Audio, "(STUBBED) called"); // TODO(ogniK): Figure out what is different
- // based on the current revision
+ rb.PushIpcInterface<Audio::IAudioDevice>(); // TODO(ogniK): Figure out what is different
+ // based on the current revision
}
bool AudRenU::IsFeatureSupported(AudioFeatures feature, u32_le revision) const {
diff --git a/src/core/hle/service/audio/hwopus.cpp b/src/core/hle/service/audio/hwopus.cpp
index 763e619a4..a850cadc8 100644
--- a/src/core/hle/service/audio/hwopus.cpp
+++ b/src/core/hle/service/audio/hwopus.cpp
@@ -46,10 +46,13 @@ public:
private:
void DecodeInterleaved(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Audio, "called");
+
u32 consumed = 0;
u32 sample_count = 0;
std::vector<opus_int16> samples(ctx.GetWriteBufferSize() / sizeof(opus_int16));
if (!Decoder_DecodeInterleaved(consumed, sample_count, ctx.ReadBuffer(), samples)) {
+ LOG_ERROR(Audio, "Failed to decode opus data");
IPC::ResponseBuilder rb{ctx, 2};
// TODO(ogniK): Use correct error code
rb.Push(ResultCode(-1));
@@ -63,12 +66,15 @@ private:
}
void DecodeInterleavedWithPerformance(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Audio, "called");
+
u32 consumed = 0;
u32 sample_count = 0;
u64 performance = 0;
std::vector<opus_int16> samples(ctx.GetWriteBufferSize() / sizeof(opus_int16));
if (!Decoder_DecodeInterleaved(consumed, sample_count, ctx.ReadBuffer(), samples,
performance)) {
+ LOG_ERROR(Audio, "Failed to decode opus data");
IPC::ResponseBuilder rb{ctx, 2};
// TODO(ogniK): Use correct error code
rb.Push(ResultCode(-1));
@@ -88,24 +94,39 @@ private:
std::optional<std::reference_wrapper<u64>> performance_time = std::nullopt) {
const auto start_time = std::chrono::high_resolution_clock::now();
std::size_t raw_output_sz = output.size() * sizeof(opus_int16);
- if (sizeof(OpusHeader) > input.size())
+ if (sizeof(OpusHeader) > input.size()) {
+ LOG_ERROR(Audio, "Input is smaller than the header size, header_sz={}, input_sz={}",
+ sizeof(OpusHeader), input.size());
return false;
+ }
OpusHeader hdr{};
std::memcpy(&hdr, input.data(), sizeof(OpusHeader));
if (sizeof(OpusHeader) + static_cast<u32>(hdr.sz) > input.size()) {
+ LOG_ERROR(Audio, "Input does not fit in the opus header size. data_sz={}, input_sz={}",
+ sizeof(OpusHeader) + static_cast<u32>(hdr.sz), input.size());
return false;
}
auto frame = input.data() + sizeof(OpusHeader);
auto decoded_sample_count = opus_packet_get_nb_samples(
frame, static_cast<opus_int32>(input.size() - sizeof(OpusHeader)),
static_cast<opus_int32>(sample_rate));
- if (decoded_sample_count * channel_count * sizeof(u16) > raw_output_sz)
+ if (decoded_sample_count * channel_count * sizeof(u16) > raw_output_sz) {
+ LOG_ERROR(
+ Audio,
+ "Decoded data does not fit into the output data, decoded_sz={}, raw_output_sz={}",
+ decoded_sample_count * channel_count * sizeof(u16), raw_output_sz);
return false;
+ }
+ const int frame_size = (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count));
auto out_sample_count =
- opus_decode(decoder.get(), frame, hdr.sz, output.data(),
- (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count)), 0);
- if (out_sample_count < 0)
+ opus_decode(decoder.get(), frame, hdr.sz, output.data(), frame_size, 0);
+ if (out_sample_count < 0) {
+ LOG_ERROR(Audio,
+ "Incorrect sample count received from opus_decode, "
+ "output_sample_count={}, frame_size={}, data_sz_from_hdr={}",
+ out_sample_count, frame_size, static_cast<u32>(hdr.sz));
return false;
+ }
const auto end_time = std::chrono::high_resolution_clock::now() - start_time;
sample_count = out_sample_count;
consumed = static_cast<u32>(sizeof(OpusHeader) + hdr.sz);
@@ -134,14 +155,17 @@ static std::size_t WorkerBufferSize(u32 channel_count) {
void HwOpus::GetWorkBufferSize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- auto sample_rate = rp.Pop<u32>();
- auto channel_count = rp.Pop<u32>();
+ const auto sample_rate = rp.Pop<u32>();
+ const auto channel_count = rp.Pop<u32>();
+ LOG_DEBUG(Audio, "called with sample_rate={}, channel_count={}", sample_rate, channel_count);
+
ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
sample_rate == 12000 || sample_rate == 8000,
"Invalid sample rate");
ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
- u32 worker_buffer_sz = static_cast<u32>(WorkerBufferSize(channel_count));
- LOG_DEBUG(Audio, "called worker_buffer_sz={}", worker_buffer_sz);
+
+ const u32 worker_buffer_sz = static_cast<u32>(WorkerBufferSize(channel_count));
+ LOG_DEBUG(Audio, "worker_buffer_sz={}", worker_buffer_sz);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
@@ -155,6 +179,7 @@ void HwOpus::OpenOpusDecoder(Kernel::HLERequestContext& ctx) {
auto buffer_sz = rp.Pop<u32>();
LOG_DEBUG(Audio, "called sample_rate={}, channel_count={}, buffer_size={}", sample_rate,
channel_count, buffer_sz);
+
ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
sample_rate == 12000 || sample_rate == 8000,
"Invalid sample rate");
@@ -164,7 +189,8 @@ void HwOpus::OpenOpusDecoder(Kernel::HLERequestContext& ctx) {
ASSERT_MSG(buffer_sz >= worker_sz, "Worker buffer too large");
std::unique_ptr<OpusDecoder, OpusDeleter> decoder{
static_cast<OpusDecoder*>(operator new(worker_sz))};
- if (opus_decoder_init(decoder.get(), sample_rate, channel_count)) {
+ if (const int err = opus_decoder_init(decoder.get(), sample_rate, channel_count)) {
+ LOG_ERROR(Audio, "Failed to init opus decoder with error={}", err);
IPC::ResponseBuilder rb{ctx, 2};
// TODO(ogniK): Use correct error code
rb.Push(ResultCode(-1));
diff --git a/src/core/hle/service/bcat/module.cpp b/src/core/hle/service/bcat/module.cpp
index 6e7b795fb..b7bd738fc 100644
--- a/src/core/hle/service/bcat/module.cpp
+++ b/src/core/hle/service/bcat/module.cpp
@@ -33,10 +33,11 @@ public:
};
void Module::Interface::CreateBcatService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_BCAT, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IBcatService>();
- LOG_DEBUG(Service_BCAT, "called");
}
Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
diff --git a/src/core/hle/service/btdrv/btdrv.cpp b/src/core/hle/service/btdrv/btdrv.cpp
index f3bde6d0d..5704ca0ab 100644
--- a/src/core/hle/service/btdrv/btdrv.cpp
+++ b/src/core/hle/service/btdrv/btdrv.cpp
@@ -4,8 +4,10 @@
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/hle_ipc.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/btdrv/btdrv.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
@@ -30,19 +32,22 @@ public:
};
// clang-format on
RegisterHandlers(functions);
+
+ auto& kernel = Core::System::GetInstance().Kernel();
+ register_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "BT:RegisterEvent");
}
private:
void RegisterEvent(Kernel::HLERequestContext& ctx) {
- auto& kernel = Core::System::GetInstance().Kernel();
- register_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "BT:RegisterEvent");
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(register_event);
- LOG_WARNING(Service_BTM, "(STUBBED) called");
+ rb.PushCopyObjects(register_event.readable);
}
- Kernel::SharedPtr<Kernel::Event> register_event;
+
+ Kernel::EventPair register_event;
};
class BtDrv final : public ServiceFramework<BtDrv> {
diff --git a/src/core/hle/service/btm/btm.cpp b/src/core/hle/service/btm/btm.cpp
index a02f6b53a..ef7398a23 100644
--- a/src/core/hle/service/btm/btm.cpp
+++ b/src/core/hle/service/btm/btm.cpp
@@ -6,8 +6,10 @@
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/hle_ipc.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/btm/btm.h"
#include "core/hle/service/service.h"
@@ -53,49 +55,55 @@ public:
};
// clang-format on
RegisterHandlers(functions);
+
+ auto& kernel = Core::System::GetInstance().Kernel();
+ scan_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IBtmUserCore:ScanEvent");
+ connection_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "IBtmUserCore:ConnectionEvent");
+ service_discovery = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "IBtmUserCore:Discovery");
+ config_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IBtmUserCore:ConfigEvent");
}
private:
void GetScanEvent(Kernel::HLERequestContext& ctx) {
- auto& kernel = Core::System::GetInstance().Kernel();
- scan_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:ScanEvent");
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(scan_event);
- LOG_WARNING(Service_BTM, "(STUBBED) called");
+ rb.PushCopyObjects(scan_event.readable);
}
+
void GetConnectionEvent(Kernel::HLERequestContext& ctx) {
- auto& kernel = Core::System::GetInstance().Kernel();
- connection_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "IBtmUserCore:ConnectionEvent");
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(connection_event);
- LOG_WARNING(Service_BTM, "(STUBBED) called");
+ rb.PushCopyObjects(connection_event.readable);
}
+
void GetDiscoveryEvent(Kernel::HLERequestContext& ctx) {
- auto& kernel = Core::System::GetInstance().Kernel();
- service_discovery =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:Discovery");
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(service_discovery);
- LOG_WARNING(Service_BTM, "(STUBBED) called");
+ rb.PushCopyObjects(service_discovery.readable);
}
+
void GetConfigEvent(Kernel::HLERequestContext& ctx) {
- auto& kernel = Core::System::GetInstance().Kernel();
- config_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:ConfigEvent");
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(config_event);
- LOG_WARNING(Service_BTM, "(STUBBED) called");
+ rb.PushCopyObjects(config_event.readable);
}
- Kernel::SharedPtr<Kernel::Event> scan_event;
- Kernel::SharedPtr<Kernel::Event> connection_event;
- Kernel::SharedPtr<Kernel::Event> service_discovery;
- Kernel::SharedPtr<Kernel::Event> config_event;
+
+ Kernel::EventPair scan_event;
+ Kernel::EventPair connection_event;
+ Kernel::EventPair service_discovery;
+ Kernel::EventPair config_event;
};
class BTM_USR final : public ServiceFramework<BTM_USR> {
@@ -111,10 +119,11 @@ public:
private:
void GetCoreImpl(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_BTM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IBtmUserCore>();
- LOG_DEBUG(Service_BTM, "called");
}
};
@@ -209,11 +218,11 @@ public:
private:
void GetCoreImpl(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_BTM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IBtmSystemCore>();
-
- LOG_DEBUG(Service_BTM, "called");
}
};
diff --git a/src/core/hle/service/erpt/erpt.cpp b/src/core/hle/service/erpt/erpt.cpp
index ee11cd78e..d9b32954e 100644
--- a/src/core/hle/service/erpt/erpt.cpp
+++ b/src/core/hle/service/erpt/erpt.cpp
@@ -17,11 +17,13 @@ public:
static const FunctionInfo functions[] = {
{0, nullptr, "SubmitContext"},
{1, nullptr, "CreateReport"},
- {2, nullptr, "Unknown1"},
- {3, nullptr, "Unknown2"},
- {4, nullptr, "Unknown3"},
- {5, nullptr, "Unknown4"},
- {6, nullptr, "Unknown5"},
+ {2, nullptr, "SetInitialLaunchSettingsCompletionTime"},
+ {3, nullptr, "ClearInitialLaunchSettingsCompletionTime"},
+ {4, nullptr, "UpdatePowerOnTime"},
+ {5, nullptr, "UpdateAwakeTime"},
+ {6, nullptr, "SubmitMultipleCategoryContext"},
+ {7, nullptr, "UpdateApplicationLaunchTime"},
+ {8, nullptr, "ClearApplicationLaunchTime"},
};
// clang-format on
diff --git a/src/core/hle/service/fatal/fatal.cpp b/src/core/hle/service/fatal/fatal.cpp
index 2f15ac2a6..770590d0b 100644
--- a/src/core/hle/service/fatal/fatal.cpp
+++ b/src/core/hle/service/fatal/fatal.cpp
@@ -111,7 +111,8 @@ static void GenerateErrorReport(ResultCode error_code, const FatalInfo& info) {
}
static void ThrowFatalError(ResultCode error_code, FatalType fatal_type, const FatalInfo& info) {
- LOG_ERROR(Service_Fatal, "Threw fatal error type {}", static_cast<u32>(fatal_type));
+ LOG_ERROR(Service_Fatal, "Threw fatal error type {} with error code 0x{:X}",
+ static_cast<u32>(fatal_type), error_code.raw);
switch (fatal_type) {
case FatalType::ErrorReportAndScreen:
GenerateErrorReport(error_code, info);
diff --git a/src/core/hle/service/fgm/fgm.cpp b/src/core/hle/service/fgm/fgm.cpp
index 566fbf924..e461274c1 100644
--- a/src/core/hle/service/fgm/fgm.cpp
+++ b/src/core/hle/service/fgm/fgm.cpp
@@ -42,11 +42,11 @@ public:
private:
void Initialize(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_FGM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IRequest>();
-
- LOG_DEBUG(Service_FGM, "called");
}
};
diff --git a/src/core/hle/service/filesystem/filesystem.cpp b/src/core/hle/service/filesystem/filesystem.cpp
index 2aa77f68d..c6da2df43 100644
--- a/src/core/hle/service/filesystem/filesystem.cpp
+++ b/src/core/hle/service/filesystem/filesystem.cpp
@@ -8,18 +8,23 @@
#include "common/file_util.h"
#include "core/core.h"
#include "core/file_sys/bis_factory.h"
+#include "core/file_sys/control_metadata.h"
#include "core/file_sys/errors.h"
#include "core/file_sys/mode.h"
+#include "core/file_sys/partition_filesystem.h"
+#include "core/file_sys/patch_manager.h"
#include "core/file_sys/registered_cache.h"
#include "core/file_sys/romfs_factory.h"
#include "core/file_sys/savedata_factory.h"
#include "core/file_sys/sdmc_factory.h"
#include "core/file_sys/vfs.h"
#include "core/file_sys/vfs_offset.h"
+#include "core/hle/kernel/process.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/filesystem/fsp_ldr.h"
#include "core/hle/service/filesystem/fsp_pr.h"
#include "core/hle/service/filesystem/fsp_srv.h"
+#include "core/loader/loader.h"
namespace Service::FileSystem {
@@ -28,6 +33,10 @@ namespace Service::FileSystem {
// TODO(DarkLordZach): Eventually make this configurable in settings.
constexpr u64 EMULATED_SD_REPORTED_SIZE = 32000000000;
+// A default size for normal/journal save data size if application control metadata cannot be found.
+// This should be large enough to satisfy even the most extreme requirements (~4.2GB)
+constexpr u64 SUFFICIENT_SAVE_DATA_SIZE = 0xF0000000;
+
static FileSys::VirtualDir GetDirectoryRelativeWrapped(FileSys::VirtualDir base,
std::string_view dir_name_) {
std::string dir_name(FileUtil::SanitizePath(dir_name_));
@@ -113,6 +122,18 @@ ResultCode VfsDirectoryServiceWrapper::DeleteDirectoryRecursively(const std::str
return RESULT_SUCCESS;
}
+ResultCode VfsDirectoryServiceWrapper::CleanDirectoryRecursively(const std::string& path) const {
+ const std::string sanitized_path(FileUtil::SanitizePath(path));
+ auto dir = GetDirectoryRelativeWrapped(backing, FileUtil::GetParentPath(sanitized_path));
+
+ if (!dir->CleanSubdirectoryRecursive(FileUtil::GetFilename(sanitized_path))) {
+ // TODO(DarkLordZach): Find a better error code for this
+ return ResultCode(-1);
+ }
+
+ return RESULT_SUCCESS;
+}
+
ResultCode VfsDirectoryServiceWrapper::RenameFile(const std::string& src_path_,
const std::string& dest_path_) const {
std::string src_path(FileUtil::SanitizePath(src_path_));
@@ -329,20 +350,47 @@ ResultVal<FileSys::VirtualDir> OpenSDMC() {
return sdmc_factory->Open();
}
-std::shared_ptr<FileSys::RegisteredCacheUnion> registered_cache_union;
+FileSys::SaveDataSize ReadSaveDataSize(FileSys::SaveDataType type, u64 title_id, u128 user_id) {
+ if (save_data_factory == nullptr) {
+ return {0, 0};
+ }
+
+ const auto value = save_data_factory->ReadSaveDataSize(type, title_id, user_id);
+
+ if (value.normal == 0 && value.journal == 0) {
+ FileSys::SaveDataSize new_size{SUFFICIENT_SAVE_DATA_SIZE, SUFFICIENT_SAVE_DATA_SIZE};
+
+ FileSys::NACP nacp;
+ const auto res = Core::System::GetInstance().GetAppLoader().ReadControlData(nacp);
+
+ if (res != Loader::ResultStatus::Success) {
+ FileSys::PatchManager pm{Core::CurrentProcess()->GetTitleID()};
+ auto [nacp_unique, discard] = pm.GetControlMetadata();
-std::shared_ptr<FileSys::RegisteredCacheUnion> GetUnionContents() {
- if (registered_cache_union == nullptr) {
- registered_cache_union =
- std::make_shared<FileSys::RegisteredCacheUnion>(std::vector<FileSys::RegisteredCache*>{
- GetSystemNANDContents(), GetUserNANDContents(), GetSDMCContents()});
+ if (nacp_unique != nullptr) {
+ new_size = {nacp_unique->GetDefaultNormalSaveSize(),
+ nacp_unique->GetDefaultJournalSaveSize()};
+ }
+ } else {
+ new_size = {nacp.GetDefaultNormalSaveSize(), nacp.GetDefaultJournalSaveSize()};
+ }
+
+ WriteSaveDataSize(type, title_id, user_id, new_size);
+ return new_size;
}
- return registered_cache_union;
+ return value;
+}
+
+void WriteSaveDataSize(FileSys::SaveDataType type, u64 title_id, u128 user_id,
+ FileSys::SaveDataSize new_value) {
+ if (save_data_factory != nullptr)
+ save_data_factory->WriteSaveDataSize(type, title_id, user_id, new_value);
}
-void ClearUnionContents() {
- registered_cache_union = nullptr;
+FileSys::RegisteredCacheUnion GetUnionContents() {
+ return FileSys::RegisteredCacheUnion{
+ {GetSystemNANDContents(), GetUserNANDContents(), GetSDMCContents()}};
}
FileSys::RegisteredCache* GetSystemNANDContents() {
@@ -395,7 +443,6 @@ void CreateFactories(FileSys::VfsFilesystem& vfs, bool overwrite) {
bis_factory = nullptr;
save_data_factory = nullptr;
sdmc_factory = nullptr;
- ClearUnionContents();
}
auto nand_directory = vfs.OpenDirectory(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir),
diff --git a/src/core/hle/service/filesystem/filesystem.h b/src/core/hle/service/filesystem/filesystem.h
index 0a6cb6635..6fd5e7b23 100644
--- a/src/core/hle/service/filesystem/filesystem.h
+++ b/src/core/hle/service/filesystem/filesystem.h
@@ -21,9 +21,11 @@ class SDMCFactory;
enum class ContentRecordType : u8;
enum class Mode : u32;
enum class SaveDataSpaceId : u8;
+enum class SaveDataType : u8;
enum class StorageId : u8;
struct SaveDataDescriptor;
+struct SaveDataSize;
} // namespace FileSys
namespace Service {
@@ -48,8 +50,11 @@ ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space,
ResultVal<FileSys::VirtualDir> OpenSaveDataSpace(FileSys::SaveDataSpaceId space);
ResultVal<FileSys::VirtualDir> OpenSDMC();
-std::shared_ptr<FileSys::RegisteredCacheUnion> GetUnionContents();
-void ClearUnionContents();
+FileSys::SaveDataSize ReadSaveDataSize(FileSys::SaveDataType type, u64 title_id, u128 user_id);
+void WriteSaveDataSize(FileSys::SaveDataType type, u64 title_id, u128 user_id,
+ FileSys::SaveDataSize new_value);
+
+FileSys::RegisteredCacheUnion GetUnionContents();
FileSys::RegisteredCache* GetSystemNANDContents();
FileSys::RegisteredCache* GetUserNANDContents();
@@ -114,6 +119,18 @@ public:
ResultCode DeleteDirectoryRecursively(const std::string& path) const;
/**
+ * Cleans the specified directory. This is similar to DeleteDirectoryRecursively,
+ * in that it deletes all the contents of the specified directory, however, this
+ * function does *not* delete the directory itself. It only deletes everything
+ * within it.
+ *
+ * @param path Path relative to the archive.
+ *
+ * @return Result of the operation.
+ */
+ ResultCode CleanDirectoryRecursively(const std::string& path) const;
+
+ /**
* Rename a File specified by its path
* @param src_path Source path relative to the archive
* @param dest_path Destination path relative to the archive
diff --git a/src/core/hle/service/filesystem/fsp_srv.cpp b/src/core/hle/service/filesystem/fsp_srv.cpp
index 038dc80b1..74c4e583b 100644
--- a/src/core/hle/service/filesystem/fsp_srv.cpp
+++ b/src/core/hle/service/filesystem/fsp_srv.cpp
@@ -20,6 +20,7 @@
#include "core/file_sys/nca_metadata.h"
#include "core/file_sys/patch_manager.h"
#include "core/file_sys/savedata_factory.h"
+#include "core/file_sys/system_archive/system_archive.h"
#include "core/file_sys/vfs.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/process.h"
@@ -44,8 +45,12 @@ public:
explicit IStorage(FileSys::VirtualFile backend_)
: ServiceFramework("IStorage"), backend(std::move(backend_)) {
static const FunctionInfo functions[] = {
- {0, &IStorage::Read, "Read"}, {1, nullptr, "Write"}, {2, nullptr, "Flush"},
- {3, nullptr, "SetSize"}, {4, nullptr, "GetSize"}, {5, nullptr, "OperateRange"},
+ {0, &IStorage::Read, "Read"},
+ {1, nullptr, "Write"},
+ {2, nullptr, "Flush"},
+ {3, nullptr, "SetSize"},
+ {4, &IStorage::GetSize, "GetSize"},
+ {5, nullptr, "OperateRange"},
};
RegisterHandlers(functions);
}
@@ -62,11 +67,13 @@ private:
// Error checking
if (length < 0) {
+ LOG_ERROR(Service_FS, "Length is less than 0, length={}", length);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
+ LOG_ERROR(Service_FS, "Offset is less than 0, offset={}", offset);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
@@ -80,6 +87,15 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
+
+ void GetSize(Kernel::HLERequestContext& ctx) {
+ const u64 size = backend->GetSize();
+ LOG_DEBUG(Service_FS, "called, size={}", size);
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u64>(size);
+ }
};
class IFile final : public ServiceFramework<IFile> {
@@ -107,11 +123,13 @@ private:
// Error checking
if (length < 0) {
+ LOG_ERROR(Service_FS, "Length is less than 0, length={}", length);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
+ LOG_ERROR(Service_FS, "Offset is less than 0, offset={}", offset);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
@@ -138,11 +156,13 @@ private:
// Error checking
if (length < 0) {
+ LOG_ERROR(Service_FS, "Length is less than 0, length={}", length);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
+ LOG_ERROR(Service_FS, "Offset is less than 0, offset={}", offset);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
@@ -180,9 +200,10 @@ private:
void SetSize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 size = rp.Pop<u64>();
- backend->Resize(size);
LOG_DEBUG(Service_FS, "called, size={}", size);
+ backend->Resize(size);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -284,7 +305,7 @@ public:
{10, &IFileSystem::Commit, "Commit"},
{11, nullptr, "GetFreeSpaceSize"},
{12, nullptr, "GetTotalSpaceSize"},
- {13, nullptr, "CleanDirectoryRecursively"},
+ {13, &IFileSystem::CleanDirectoryRecursively, "CleanDirectoryRecursively"},
{14, nullptr, "GetFileTimeStampRaw"},
{15, nullptr, "QueryEntry"},
};
@@ -354,6 +375,16 @@ public:
rb.Push(backend.DeleteDirectoryRecursively(name));
}
+ void CleanDirectoryRecursively(Kernel::HLERequestContext& ctx) {
+ const auto file_buffer = ctx.ReadBuffer();
+ const std::string name = Common::StringFromBuffer(file_buffer);
+
+ LOG_DEBUG(Service_FS, "called. Directory: {}", name);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(backend.CleanDirectoryRecursively(name));
+ }
+
void RenameFile(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
@@ -465,6 +496,8 @@ public:
}
void ReadSaveDataInfo(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_FS, "called");
+
// Calculate how many entries we can fit in the output buffer
const u64 count_entries = ctx.GetWriteBufferSize() / sizeof(SaveDataInfo);
@@ -703,6 +736,8 @@ void FSP_SRV::OpenFileSystemWithPatch(Kernel::HLERequestContext& ctx) {
const auto type = rp.PopRaw<FileSystemType>();
const auto title_id = rp.PopRaw<u64>();
+ LOG_WARNING(Service_FS, "(STUBBED) called with type={}, title_id={:016X}",
+ static_cast<u8>(type), title_id);
IPC::ResponseBuilder rb{ctx, 2, 0, 0};
rb.Push(ResultCode(-1));
@@ -738,6 +773,7 @@ void FSP_SRV::MountSaveData(Kernel::HLERequestContext& ctx) {
auto space_id = rp.PopRaw<FileSys::SaveDataSpaceId>();
auto unk = rp.Pop<u32>();
LOG_INFO(Service_FS, "called with unknown={:08X}", unk);
+
auto save_struct = rp.PopRaw<FileSys::SaveDataDescriptor>();
auto dir = OpenSaveData(space_id, save_struct);
@@ -763,6 +799,7 @@ void FSP_SRV::OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx) {
void FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto space = rp.PopRaw<FileSys::SaveDataSpaceId>();
+ LOG_INFO(Service_FS, "called, space={}", static_cast<u8>(space));
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
@@ -772,9 +809,18 @@ void FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext&
void FSP_SRV::GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_FS, "(STUBBED) called");
+ enum class LogMode : u32 {
+ Off,
+ Log,
+ RedirectToSdCard,
+ LogToSdCard = Log | RedirectToSdCard,
+ };
+
+ // Given we always want to receive logging information,
+ // we always specify logging as enabled.
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
- rb.Push<u32>(5);
+ rb.PushEnum(LogMode::Log);
}
void FSP_SRV::OpenDataStorageByCurrentProcess(Kernel::HLERequestContext& ctx) {
@@ -808,6 +854,15 @@ void FSP_SRV::OpenDataStorageByDataId(Kernel::HLERequestContext& ctx) {
auto data = OpenRomFS(title_id, storage_id, FileSys::ContentRecordType::Data);
if (data.Failed()) {
+ const auto archive = FileSys::SystemArchive::SynthesizeSystemArchive(title_id);
+
+ if (archive != nullptr) {
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface(std::make_shared<IStorage>(archive));
+ return;
+ }
+
// TODO(DarkLordZach): Find the right error code to use here
LOG_ERROR(Service_FS,
"could not open data storage with title_id={:016X}, storage_id={:02X}", title_id,
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index 46604887c..04c8c35a8 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -12,7 +12,9 @@
#include "core/core.h"
#include "core/core_timing.h"
#include "core/frontend/input.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/hid/controllers/npad.h"
#include "core/settings.h"
@@ -167,8 +169,8 @@ void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) {
void Controller_NPad::OnInit() {
auto& kernel = Core::System::GetInstance().Kernel();
- styleset_changed_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "npad:NpadStyleSetChanged");
+ styleset_changed_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "npad:NpadStyleSetChanged");
if (!IsControllerActivated()) {
return;
@@ -337,52 +339,6 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
npad.pokeball_states.npad[npad.pokeball_states.common.last_entry_index];
auto& libnx_entry = npad.libnx.npad[npad.libnx.common.last_entry_index];
- if (hold_type == NpadHoldType::Horizontal) {
- ControllerPadState state{};
- AnalogPosition temp_lstick_entry{};
- AnalogPosition temp_rstick_entry{};
- if (controller_type == NPadControllerType::JoyLeft) {
- state.d_down.Assign(pad_state.pad_states.d_left.Value());
- state.d_left.Assign(pad_state.pad_states.d_up.Value());
- state.d_right.Assign(pad_state.pad_states.d_down.Value());
- state.d_up.Assign(pad_state.pad_states.d_right.Value());
- state.l.Assign(pad_state.pad_states.l.Value() |
- pad_state.pad_states.left_sl.Value());
- state.r.Assign(pad_state.pad_states.r.Value() |
- pad_state.pad_states.left_sr.Value());
-
- state.zl.Assign(pad_state.pad_states.zl.Value());
- state.plus.Assign(pad_state.pad_states.minus.Value());
-
- temp_lstick_entry = pad_state.l_stick;
- temp_rstick_entry = pad_state.r_stick;
- std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
- std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
- temp_lstick_entry.y *= -1;
- } else if (controller_type == NPadControllerType::JoyRight) {
- state.x.Assign(pad_state.pad_states.a.Value());
- state.a.Assign(pad_state.pad_states.b.Value());
- state.b.Assign(pad_state.pad_states.y.Value());
- state.y.Assign(pad_state.pad_states.b.Value());
-
- state.l.Assign(pad_state.pad_states.l.Value() |
- pad_state.pad_states.right_sl.Value());
- state.r.Assign(pad_state.pad_states.r.Value() |
- pad_state.pad_states.right_sr.Value());
- state.zr.Assign(pad_state.pad_states.zr.Value());
- state.plus.Assign(pad_state.pad_states.plus.Value());
-
- temp_lstick_entry = pad_state.l_stick;
- temp_rstick_entry = pad_state.r_stick;
- std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
- std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
- temp_rstick_entry.x *= -1;
- }
- pad_state.pad_states.raw = state.raw;
- pad_state.l_stick = temp_lstick_entry;
- pad_state.r_stick = temp_rstick_entry;
- }
-
libnx_entry.connection_status.raw = 0;
switch (controller_type) {
@@ -454,6 +410,8 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
libnx_entry.pad.pad_states.raw = pad_state.pad_states.raw;
libnx_entry.pad.l_stick = pad_state.l_stick;
libnx_entry.pad.r_stick = pad_state.r_stick;
+
+ press_state |= static_cast<u32>(pad_state.pad_states.raw);
}
std::memcpy(data + NPAD_OFFSET, shared_memory_entries.data(),
shared_memory_entries.size() * sizeof(NPadEntry));
@@ -494,7 +452,7 @@ void Controller_NPad::SetSupportedNPadIdTypes(u8* data, std::size_t length) {
had_controller_update = true;
}
if (had_controller_update) {
- styleset_changed_event->Signal();
+ styleset_changed_event.writable->Signal();
}
}
}
@@ -509,7 +467,7 @@ std::size_t Controller_NPad::GetSupportedNPadIdTypesSize() const {
}
void Controller_NPad::SetHoldType(NpadHoldType joy_hold_type) {
- styleset_changed_event->Signal();
+ styleset_changed_event.writable->Signal();
hold_type = joy_hold_type;
}
@@ -518,12 +476,15 @@ Controller_NPad::NpadHoldType Controller_NPad::GetHoldType() const {
}
void Controller_NPad::SetNpadMode(u32 npad_id, NPadAssignments assignment_mode) {
- ASSERT(npad_id < shared_memory_entries.size());
- shared_memory_entries[npad_id].pad_assignment = assignment_mode;
+ const std::size_t npad_index = NPadIdToIndex(npad_id);
+ ASSERT(npad_index < shared_memory_entries.size());
+ shared_memory_entries[npad_index].pad_assignment = assignment_mode;
}
void Controller_NPad::VibrateController(const std::vector<u32>& controller_ids,
const std::vector<Vibration>& vibrations) {
+ LOG_WARNING(Service_HID, "(STUBBED) called");
+
if (!can_controllers_vibrate) {
return;
}
@@ -533,15 +494,14 @@ void Controller_NPad::VibrateController(const std::vector<u32>& controller_ids,
// TODO(ogniK): Vibrate the physical controller
}
}
- LOG_WARNING(Service_HID, "(STUBBED) called");
last_processed_vibration = vibrations.back();
}
-Kernel::SharedPtr<Kernel::Event> Controller_NPad::GetStyleSetChangedEvent() const {
+Kernel::SharedPtr<Kernel::ReadableEvent> Controller_NPad::GetStyleSetChangedEvent() const {
// TODO(ogniK): Figure out the best time to signal this event. This event seems that it should
// be signalled at least once, and signaled after a new controller is connected?
- styleset_changed_event->Signal();
- return styleset_changed_event;
+ styleset_changed_event.writable->Signal();
+ return styleset_changed_event.readable;
}
Controller_NPad::Vibration Controller_NPad::GetLastVibration() const {
@@ -575,8 +535,8 @@ void Controller_NPad::AddNewControllerAt(NPadControllerType controller, u32 npad
return;
}
- connected_controllers[npad_id] = {controller, true};
- InitNewlyAddedControler(npad_id);
+ connected_controllers[NPadIdToIndex(npad_id)] = {controller, true};
+ InitNewlyAddedControler(NPadIdToIndex(npad_id));
}
void Controller_NPad::ConnectNPad(u32 npad_id) {
@@ -678,6 +638,10 @@ void Controller_NPad::ClearAllControllers() {
});
}
+u32 Controller_NPad::GetAndResetPressState() {
+ return std::exchange(press_state, 0);
+}
+
bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const {
const bool support_handheld =
std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(), NPAD_HANDHELD) !=
diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h
index abff6544d..106cf58c8 100644
--- a/src/core/hle/service/hid/controllers/npad.h
+++ b/src/core/hle/service/hid/controllers/npad.h
@@ -8,7 +8,8 @@
#include "common/bit_field.h"
#include "common/common_types.h"
#include "core/frontend/input.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/object.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/hid/controllers/controller_base.h"
#include "core/settings.h"
@@ -108,7 +109,7 @@ public:
void VibrateController(const std::vector<u32>& controller_ids,
const std::vector<Vibration>& vibrations);
- Kernel::SharedPtr<Kernel::Event> GetStyleSetChangedEvent() const;
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetStyleSetChangedEvent() const;
Vibration GetLastVibration() const;
void AddNewController(NPadControllerType controller);
@@ -123,6 +124,10 @@ public:
void ConnectAllDisconnectedControllers();
void ClearAllControllers();
+ // Logical OR for all buttons presses on all controllers
+ // Specifically for cheat engine and other features.
+ u32 GetAndResetPressState();
+
static std::size_t NPadIdToIndex(u32 npad_id);
static u32 IndexToNPad(std::size_t index);
@@ -291,6 +296,8 @@ private:
bool is_connected;
};
+ u32 press_state{};
+
NPadType style{};
std::array<NPadEntry, 10> shared_memory_entries{};
std::array<
@@ -303,7 +310,7 @@ private:
sticks;
std::vector<u32> supported_npad_id_types{};
NpadHoldType hold_type{NpadHoldType::Vertical};
- Kernel::SharedPtr<Kernel::Event> styleset_changed_event;
+ Kernel::EventPair styleset_changed_event;
Vibration last_processed_vibration{};
std::array<ControllerHolder, 10> connected_controllers{};
bool can_controllers_vibrate{true};
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index 7c0dac5dc..008bf3f02 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -13,8 +13,9 @@
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/readable_event.h"
#include "core/hle/kernel/shared_memory.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/hid/hid.h"
#include "core/hle/service/hid/irs.h"
#include "core/hle/service/hid/xcd.h"
@@ -39,118 +40,82 @@ constexpr u64 pad_update_ticks = CoreTiming::BASE_CLOCK_RATE / 66;
constexpr u64 accelerometer_update_ticks = CoreTiming::BASE_CLOCK_RATE / 100;
constexpr u64 gyroscope_update_ticks = CoreTiming::BASE_CLOCK_RATE / 100;
constexpr std::size_t SHARED_MEMORY_SIZE = 0x40000;
-enum class HidController : std::size_t {
- DebugPad,
- Touchscreen,
- Mouse,
- Keyboard,
- XPad,
- Unknown1,
- Unknown2,
- Unknown3,
- SixAxisSensor,
- NPad,
- Gesture,
-
- MaxControllers,
-};
-
-class IAppletResource final : public ServiceFramework<IAppletResource> {
-public:
- IAppletResource() : ServiceFramework("IAppletResource") {
- static const FunctionInfo functions[] = {
- {0, &IAppletResource::GetSharedMemoryHandle, "GetSharedMemoryHandle"},
- };
- RegisterHandlers(functions);
-
- auto& kernel = Core::System::GetInstance().Kernel();
- shared_mem = Kernel::SharedMemory::Create(
- kernel, nullptr, SHARED_MEMORY_SIZE, Kernel::MemoryPermission::ReadWrite,
- Kernel::MemoryPermission::Read, 0, Kernel::MemoryRegion::BASE, "HID:SharedMemory");
-
- MakeController<Controller_DebugPad>(HidController::DebugPad);
- MakeController<Controller_Touchscreen>(HidController::Touchscreen);
- MakeController<Controller_Mouse>(HidController::Mouse);
- MakeController<Controller_Keyboard>(HidController::Keyboard);
- MakeController<Controller_XPad>(HidController::XPad);
- MakeController<Controller_Stubbed>(HidController::Unknown1);
- MakeController<Controller_Stubbed>(HidController::Unknown2);
- MakeController<Controller_Stubbed>(HidController::Unknown3);
- MakeController<Controller_Stubbed>(HidController::SixAxisSensor);
- MakeController<Controller_NPad>(HidController::NPad);
- MakeController<Controller_Gesture>(HidController::Gesture);
-
- // Homebrew doesn't try to activate some controllers, so we activate them by default
- GetController<Controller_NPad>(HidController::NPad).ActivateController();
- GetController<Controller_Touchscreen>(HidController::Touchscreen).ActivateController();
-
- GetController<Controller_Stubbed>(HidController::Unknown1).SetCommonHeaderOffset(0x4c00);
- GetController<Controller_Stubbed>(HidController::Unknown2).SetCommonHeaderOffset(0x4e00);
- GetController<Controller_Stubbed>(HidController::Unknown3).SetCommonHeaderOffset(0x5000);
-
- // Register update callbacks
- pad_update_event = CoreTiming::RegisterEvent(
- "HID::UpdatePadCallback",
- [this](u64 userdata, int cycles_late) { UpdateControllers(userdata, cycles_late); });
-
- // TODO(shinyquagsire23): Other update callbacks? (accel, gyro?)
-
- CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event);
-
- ReloadInputDevices();
- }
- void ActivateController(HidController controller) {
- controllers[static_cast<size_t>(controller)]->ActivateController();
- }
+IAppletResource::IAppletResource() : ServiceFramework("IAppletResource") {
+ static const FunctionInfo functions[] = {
+ {0, &IAppletResource::GetSharedMemoryHandle, "GetSharedMemoryHandle"},
+ };
+ RegisterHandlers(functions);
+
+ auto& kernel = Core::System::GetInstance().Kernel();
+ shared_mem = Kernel::SharedMemory::Create(
+ kernel, nullptr, SHARED_MEMORY_SIZE, Kernel::MemoryPermission::ReadWrite,
+ Kernel::MemoryPermission::Read, 0, Kernel::MemoryRegion::BASE, "HID:SharedMemory");
+
+ MakeController<Controller_DebugPad>(HidController::DebugPad);
+ MakeController<Controller_Touchscreen>(HidController::Touchscreen);
+ MakeController<Controller_Mouse>(HidController::Mouse);
+ MakeController<Controller_Keyboard>(HidController::Keyboard);
+ MakeController<Controller_XPad>(HidController::XPad);
+ MakeController<Controller_Stubbed>(HidController::Unknown1);
+ MakeController<Controller_Stubbed>(HidController::Unknown2);
+ MakeController<Controller_Stubbed>(HidController::Unknown3);
+ MakeController<Controller_Stubbed>(HidController::SixAxisSensor);
+ MakeController<Controller_NPad>(HidController::NPad);
+ MakeController<Controller_Gesture>(HidController::Gesture);
+
+ // Homebrew doesn't try to activate some controllers, so we activate them by default
+ GetController<Controller_NPad>(HidController::NPad).ActivateController();
+ GetController<Controller_Touchscreen>(HidController::Touchscreen).ActivateController();
+
+ GetController<Controller_Stubbed>(HidController::Unknown1).SetCommonHeaderOffset(0x4c00);
+ GetController<Controller_Stubbed>(HidController::Unknown2).SetCommonHeaderOffset(0x4e00);
+ GetController<Controller_Stubbed>(HidController::Unknown3).SetCommonHeaderOffset(0x5000);
+
+ // Register update callbacks
+ pad_update_event =
+ CoreTiming::RegisterEvent("HID::UpdatePadCallback", [this](u64 userdata, int cycles_late) {
+ UpdateControllers(userdata, cycles_late);
+ });
+
+ // TODO(shinyquagsire23): Other update callbacks? (accel, gyro?)
+
+ CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event);
+
+ ReloadInputDevices();
+}
- void DeactivateController(HidController controller) {
- controllers[static_cast<size_t>(controller)]->DeactivateController();
- }
+void IAppletResource::ActivateController(HidController controller) {
+ controllers[static_cast<size_t>(controller)]->ActivateController();
+}
- template <typename T>
- void MakeController(HidController controller) {
- controllers[static_cast<std::size_t>(controller)] = std::make_unique<T>();
- }
+void IAppletResource::DeactivateController(HidController controller) {
+ controllers[static_cast<size_t>(controller)]->DeactivateController();
+}
- template <typename T>
- T& GetController(HidController controller) {
- return static_cast<T&>(*controllers[static_cast<size_t>(controller)]);
- }
+IAppletResource ::~IAppletResource() {
+ CoreTiming::UnscheduleEvent(pad_update_event, 0);
+}
- ~IAppletResource() {
- CoreTiming::UnscheduleEvent(pad_update_event, 0);
- }
+void IAppletResource::GetSharedMemoryHandle(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_HID, "called");
-private:
- void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(shared_mem);
- LOG_DEBUG(Service_HID, "called");
- }
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(shared_mem);
+}
- void UpdateControllers(u64 userdata, int cycles_late) {
- const bool should_reload = Settings::values.is_device_reload_pending.exchange(false);
- for (const auto& controller : controllers) {
- if (should_reload) {
- controller->OnLoadInputDevices();
- }
- controller->OnUpdate(shared_mem->GetPointer(), SHARED_MEMORY_SIZE);
+void IAppletResource::UpdateControllers(u64 userdata, int cycles_late) {
+ const bool should_reload = Settings::values.is_device_reload_pending.exchange(false);
+ for (const auto& controller : controllers) {
+ if (should_reload) {
+ controller->OnLoadInputDevices();
}
-
- CoreTiming::ScheduleEvent(pad_update_ticks - cycles_late, pad_update_event);
+ controller->OnUpdate(shared_mem->GetPointer(), SHARED_MEMORY_SIZE);
}
- // Handle to shared memory region designated to HID service
- Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;
-
- // CoreTiming update events
- CoreTiming::EventType* pad_update_event;
-
- std::array<std::unique_ptr<ControllerBase>, static_cast<size_t>(HidController::MaxControllers)>
- controllers{};
-};
+ CoreTiming::ScheduleEvent(pad_update_ticks - cycles_late, pad_update_event);
+}
class IActiveVibrationDeviceList final : public ServiceFramework<IActiveVibrationDeviceList> {
public:
@@ -163,452 +128,604 @@ public:
private:
void ActivateVibrationDevice(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_HID, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
}
};
-class Hid final : public ServiceFramework<Hid> {
-public:
- Hid() : ServiceFramework("hid") {
- // clang-format off
- static const FunctionInfo functions[] = {
- {0, &Hid::CreateAppletResource, "CreateAppletResource"},
- {1, &Hid::ActivateDebugPad, "ActivateDebugPad"},
- {11, &Hid::ActivateTouchScreen, "ActivateTouchScreen"},
- {21, &Hid::ActivateMouse, "ActivateMouse"},
- {31, &Hid::ActivateKeyboard, "ActivateKeyboard"},
- {32, nullptr, "SendKeyboardLockKeyEvent"},
- {40, nullptr, "AcquireXpadIdEventHandle"},
- {41, nullptr, "ReleaseXpadIdEventHandle"},
- {51, &Hid::ActivateXpad, "ActivateXpad"},
- {55, nullptr, "GetXpadIds"},
- {56, nullptr, "ActivateJoyXpad"},
- {58, nullptr, "GetJoyXpadLifoHandle"},
- {59, nullptr, "GetJoyXpadIds"},
- {60, nullptr, "ActivateSixAxisSensor"},
- {61, nullptr, "DeactivateSixAxisSensor"},
- {62, nullptr, "GetSixAxisSensorLifoHandle"},
- {63, nullptr, "ActivateJoySixAxisSensor"},
- {64, nullptr, "DeactivateJoySixAxisSensor"},
- {65, nullptr, "GetJoySixAxisSensorLifoHandle"},
- {66, &Hid::StartSixAxisSensor, "StartSixAxisSensor"},
- {67, &Hid::StopSixAxisSensor, "StopSixAxisSensor"},
- {68, nullptr, "IsSixAxisSensorFusionEnabled"},
- {69, nullptr, "EnableSixAxisSensorFusion"},
- {70, nullptr, "SetSixAxisSensorFusionParameters"},
- {71, nullptr, "GetSixAxisSensorFusionParameters"},
- {72, nullptr, "ResetSixAxisSensorFusionParameters"},
- {73, nullptr, "SetAccelerometerParameters"},
- {74, nullptr, "GetAccelerometerParameters"},
- {75, nullptr, "ResetAccelerometerParameters"},
- {76, nullptr, "SetAccelerometerPlayMode"},
- {77, nullptr, "GetAccelerometerPlayMode"},
- {78, nullptr, "ResetAccelerometerPlayMode"},
- {79, &Hid::SetGyroscopeZeroDriftMode, "SetGyroscopeZeroDriftMode"},
- {80, nullptr, "GetGyroscopeZeroDriftMode"},
- {81, nullptr, "ResetGyroscopeZeroDriftMode"},
- {82, &Hid::IsSixAxisSensorAtRest, "IsSixAxisSensorAtRest"},
- {83, nullptr, "IsFirmwareUpdateAvailableForSixAxisSensor"},
- {91, &Hid::ActivateGesture, "ActivateGesture"},
- {100, &Hid::SetSupportedNpadStyleSet, "SetSupportedNpadStyleSet"},
- {101, &Hid::GetSupportedNpadStyleSet, "GetSupportedNpadStyleSet"},
- {102, &Hid::SetSupportedNpadIdType, "SetSupportedNpadIdType"},
- {103, &Hid::ActivateNpad, "ActivateNpad"},
- {104, nullptr, "DeactivateNpad"},
- {106, &Hid::AcquireNpadStyleSetUpdateEventHandle, "AcquireNpadStyleSetUpdateEventHandle"},
- {107, &Hid::DisconnectNpad, "DisconnectNpad"},
- {108, &Hid::GetPlayerLedPattern, "GetPlayerLedPattern"},
- {109, &Hid::ActivateNpadWithRevision, "ActivateNpadWithRevision"},
- {120, &Hid::SetNpadJoyHoldType, "SetNpadJoyHoldType"},
- {121, &Hid::GetNpadJoyHoldType, "GetNpadJoyHoldType"},
- {122, &Hid::SetNpadJoyAssignmentModeSingleByDefault, "SetNpadJoyAssignmentModeSingleByDefault"},
- {123, nullptr, "SetNpadJoyAssignmentModeSingleByDefault"},
- {124, &Hid::SetNpadJoyAssignmentModeDual, "SetNpadJoyAssignmentModeDual"},
- {125, &Hid::MergeSingleJoyAsDualJoy, "MergeSingleJoyAsDualJoy"},
- {126, nullptr, "StartLrAssignmentMode"},
- {127, nullptr, "StopLrAssignmentMode"},
- {128, &Hid::SetNpadHandheldActivationMode, "SetNpadHandheldActivationMode"},
- {129, nullptr, "GetNpadHandheldActivationMode"},
- {130, nullptr, "SwapNpadAssignment"},
- {131, nullptr, "IsUnintendedHomeButtonInputProtectionEnabled"},
- {132, nullptr, "EnableUnintendedHomeButtonInputProtection"},
- {133, nullptr, "SetNpadJoyAssignmentModeSingleWithDestination"},
- {200, &Hid::GetVibrationDeviceInfo, "GetVibrationDeviceInfo"},
- {201, &Hid::SendVibrationValue, "SendVibrationValue"},
- {202, &Hid::GetActualVibrationValue, "GetActualVibrationValue"},
- {203, &Hid::CreateActiveVibrationDeviceList, "CreateActiveVibrationDeviceList"},
- {204, nullptr, "PermitVibration"},
- {205, nullptr, "IsVibrationPermitted"},
- {206, &Hid::SendVibrationValues, "SendVibrationValues"},
- {207, nullptr, "SendVibrationGcErmCommand"},
- {208, nullptr, "GetActualVibrationGcErmCommand"},
- {209, &Hid::BeginPermitVibrationSession, "BeginPermitVibrationSession"},
- {210, &Hid::EndPermitVibrationSession, "EndPermitVibrationSession"},
- {300, &Hid::ActivateConsoleSixAxisSensor, "ActivateConsoleSixAxisSensor"},
- {301, &Hid::StartConsoleSixAxisSensor, "StartConsoleSixAxisSensor"},
- {302, nullptr, "StopConsoleSixAxisSensor"},
- {303, nullptr, "ActivateSevenSixAxisSensor"},
- {304, nullptr, "StartSevenSixAxisSensor"},
- {305, nullptr, "StopSevenSixAxisSensor"},
- {306, nullptr, "InitializeSevenSixAxisSensor"},
- {307, nullptr, "FinalizeSevenSixAxisSensor"},
- {308, nullptr, "SetSevenSixAxisSensorFusionStrength"},
- {309, nullptr, "GetSevenSixAxisSensorFusionStrength"},
- {310, nullptr, "ResetSevenSixAxisSensorTimestamp"},
- {400, nullptr, "IsUsbFullKeyControllerEnabled"},
- {401, nullptr, "EnableUsbFullKeyController"},
- {402, nullptr, "IsUsbFullKeyControllerConnected"},
- {403, nullptr, "HasBattery"},
- {404, nullptr, "HasLeftRightBattery"},
- {405, nullptr, "GetNpadInterfaceType"},
- {406, nullptr, "GetNpadLeftRightInterfaceType"},
- {500, nullptr, "GetPalmaConnectionHandle"},
- {501, nullptr, "InitializePalma"},
- {502, nullptr, "AcquirePalmaOperationCompleteEvent"},
- {503, nullptr, "GetPalmaOperationInfo"},
- {504, nullptr, "PlayPalmaActivity"},
- {505, nullptr, "SetPalmaFrModeType"},
- {506, nullptr, "ReadPalmaStep"},
- {507, nullptr, "EnablePalmaStep"},
- {508, nullptr, "ResetPalmaStep"},
- {509, nullptr, "ReadPalmaApplicationSection"},
- {510, nullptr, "WritePalmaApplicationSection"},
- {511, nullptr, "ReadPalmaUniqueCode"},
- {512, nullptr, "SetPalmaUniqueCodeInvalid"},
- {513, nullptr, "WritePalmaActivityEntry"},
- {514, nullptr, "WritePalmaRgbLedPatternEntry"},
- {515, nullptr, "WritePalmaWaveEntry"},
- {516, nullptr, "SetPalmaDataBaseIdentificationVersion"},
- {517, nullptr, "GetPalmaDataBaseIdentificationVersion"},
- {518, nullptr, "SuspendPalmaFeature"},
- {519, nullptr, "GetPalmaOperationResult"},
- {520, nullptr, "ReadPalmaPlayLog"},
- {521, nullptr, "ResetPalmaPlayLog"},
- {522, &Hid::SetIsPalmaAllConnectable, "SetIsPalmaAllConnectable"},
- {523, nullptr, "SetIsPalmaPairedConnectable"},
- {524, nullptr, "PairPalma"},
- {525, &Hid::SetPalmaBoostMode, "SetPalmaBoostMode"},
- {1000, nullptr, "SetNpadCommunicationMode"},
- {1001, nullptr, "GetNpadCommunicationMode"},
- };
- // clang-format on
-
- RegisterHandlers(functions);
+std::shared_ptr<IAppletResource> Hid::GetAppletResource() {
+ if (applet_resource == nullptr) {
+ applet_resource = std::make_shared<IAppletResource>();
}
- ~Hid() = default;
-private:
- std::shared_ptr<IAppletResource> applet_resource;
+ return applet_resource;
+}
- void CreateAppletResource(Kernel::HLERequestContext& ctx) {
- if (applet_resource == nullptr) {
- applet_resource = std::make_shared<IAppletResource>();
- }
+Hid::Hid() : ServiceFramework("hid") {
+ // clang-format off
+ static const FunctionInfo functions[] = {
+ {0, &Hid::CreateAppletResource, "CreateAppletResource"},
+ {1, &Hid::ActivateDebugPad, "ActivateDebugPad"},
+ {11, &Hid::ActivateTouchScreen, "ActivateTouchScreen"},
+ {21, &Hid::ActivateMouse, "ActivateMouse"},
+ {31, &Hid::ActivateKeyboard, "ActivateKeyboard"},
+ {32, nullptr, "SendKeyboardLockKeyEvent"},
+ {40, nullptr, "AcquireXpadIdEventHandle"},
+ {41, nullptr, "ReleaseXpadIdEventHandle"},
+ {51, &Hid::ActivateXpad, "ActivateXpad"},
+ {55, nullptr, "GetXpadIds"},
+ {56, nullptr, "ActivateJoyXpad"},
+ {58, nullptr, "GetJoyXpadLifoHandle"},
+ {59, nullptr, "GetJoyXpadIds"},
+ {60, nullptr, "ActivateSixAxisSensor"},
+ {61, nullptr, "DeactivateSixAxisSensor"},
+ {62, nullptr, "GetSixAxisSensorLifoHandle"},
+ {63, nullptr, "ActivateJoySixAxisSensor"},
+ {64, nullptr, "DeactivateJoySixAxisSensor"},
+ {65, nullptr, "GetJoySixAxisSensorLifoHandle"},
+ {66, &Hid::StartSixAxisSensor, "StartSixAxisSensor"},
+ {67, &Hid::StopSixAxisSensor, "StopSixAxisSensor"},
+ {68, nullptr, "IsSixAxisSensorFusionEnabled"},
+ {69, nullptr, "EnableSixAxisSensorFusion"},
+ {70, nullptr, "SetSixAxisSensorFusionParameters"},
+ {71, nullptr, "GetSixAxisSensorFusionParameters"},
+ {72, nullptr, "ResetSixAxisSensorFusionParameters"},
+ {73, nullptr, "SetAccelerometerParameters"},
+ {74, nullptr, "GetAccelerometerParameters"},
+ {75, nullptr, "ResetAccelerometerParameters"},
+ {76, nullptr, "SetAccelerometerPlayMode"},
+ {77, nullptr, "GetAccelerometerPlayMode"},
+ {78, nullptr, "ResetAccelerometerPlayMode"},
+ {79, &Hid::SetGyroscopeZeroDriftMode, "SetGyroscopeZeroDriftMode"},
+ {80, nullptr, "GetGyroscopeZeroDriftMode"},
+ {81, nullptr, "ResetGyroscopeZeroDriftMode"},
+ {82, &Hid::IsSixAxisSensorAtRest, "IsSixAxisSensorAtRest"},
+ {83, nullptr, "IsFirmwareUpdateAvailableForSixAxisSensor"},
+ {91, &Hid::ActivateGesture, "ActivateGesture"},
+ {100, &Hid::SetSupportedNpadStyleSet, "SetSupportedNpadStyleSet"},
+ {101, &Hid::GetSupportedNpadStyleSet, "GetSupportedNpadStyleSet"},
+ {102, &Hid::SetSupportedNpadIdType, "SetSupportedNpadIdType"},
+ {103, &Hid::ActivateNpad, "ActivateNpad"},
+ {104, nullptr, "DeactivateNpad"},
+ {106, &Hid::AcquireNpadStyleSetUpdateEventHandle, "AcquireNpadStyleSetUpdateEventHandle"},
+ {107, &Hid::DisconnectNpad, "DisconnectNpad"},
+ {108, &Hid::GetPlayerLedPattern, "GetPlayerLedPattern"},
+ {109, &Hid::ActivateNpadWithRevision, "ActivateNpadWithRevision"},
+ {120, &Hid::SetNpadJoyHoldType, "SetNpadJoyHoldType"},
+ {121, &Hid::GetNpadJoyHoldType, "GetNpadJoyHoldType"},
+ {122, &Hid::SetNpadJoyAssignmentModeSingleByDefault, "SetNpadJoyAssignmentModeSingleByDefault"},
+ {123, nullptr, "SetNpadJoyAssignmentModeSingleByDefault"},
+ {124, &Hid::SetNpadJoyAssignmentModeDual, "SetNpadJoyAssignmentModeDual"},
+ {125, &Hid::MergeSingleJoyAsDualJoy, "MergeSingleJoyAsDualJoy"},
+ {126, nullptr, "StartLrAssignmentMode"},
+ {127, nullptr, "StopLrAssignmentMode"},
+ {128, &Hid::SetNpadHandheldActivationMode, "SetNpadHandheldActivationMode"},
+ {129, nullptr, "GetNpadHandheldActivationMode"},
+ {130, nullptr, "SwapNpadAssignment"},
+ {131, nullptr, "IsUnintendedHomeButtonInputProtectionEnabled"},
+ {132, nullptr, "EnableUnintendedHomeButtonInputProtection"},
+ {133, nullptr, "SetNpadJoyAssignmentModeSingleWithDestination"},
+ {200, &Hid::GetVibrationDeviceInfo, "GetVibrationDeviceInfo"},
+ {201, &Hid::SendVibrationValue, "SendVibrationValue"},
+ {202, &Hid::GetActualVibrationValue, "GetActualVibrationValue"},
+ {203, &Hid::CreateActiveVibrationDeviceList, "CreateActiveVibrationDeviceList"},
+ {204, nullptr, "PermitVibration"},
+ {205, nullptr, "IsVibrationPermitted"},
+ {206, &Hid::SendVibrationValues, "SendVibrationValues"},
+ {207, nullptr, "SendVibrationGcErmCommand"},
+ {208, nullptr, "GetActualVibrationGcErmCommand"},
+ {209, &Hid::BeginPermitVibrationSession, "BeginPermitVibrationSession"},
+ {210, &Hid::EndPermitVibrationSession, "EndPermitVibrationSession"},
+ {300, &Hid::ActivateConsoleSixAxisSensor, "ActivateConsoleSixAxisSensor"},
+ {301, &Hid::StartConsoleSixAxisSensor, "StartConsoleSixAxisSensor"},
+ {302, nullptr, "StopConsoleSixAxisSensor"},
+ {303, nullptr, "ActivateSevenSixAxisSensor"},
+ {304, nullptr, "StartSevenSixAxisSensor"},
+ {305, nullptr, "StopSevenSixAxisSensor"},
+ {306, nullptr, "InitializeSevenSixAxisSensor"},
+ {307, nullptr, "FinalizeSevenSixAxisSensor"},
+ {308, nullptr, "SetSevenSixAxisSensorFusionStrength"},
+ {309, nullptr, "GetSevenSixAxisSensorFusionStrength"},
+ {310, nullptr, "ResetSevenSixAxisSensorTimestamp"},
+ {400, nullptr, "IsUsbFullKeyControllerEnabled"},
+ {401, nullptr, "EnableUsbFullKeyController"},
+ {402, nullptr, "IsUsbFullKeyControllerConnected"},
+ {403, nullptr, "HasBattery"},
+ {404, nullptr, "HasLeftRightBattery"},
+ {405, nullptr, "GetNpadInterfaceType"},
+ {406, nullptr, "GetNpadLeftRightInterfaceType"},
+ {500, nullptr, "GetPalmaConnectionHandle"},
+ {501, nullptr, "InitializePalma"},
+ {502, nullptr, "AcquirePalmaOperationCompleteEvent"},
+ {503, nullptr, "GetPalmaOperationInfo"},
+ {504, nullptr, "PlayPalmaActivity"},
+ {505, nullptr, "SetPalmaFrModeType"},
+ {506, nullptr, "ReadPalmaStep"},
+ {507, nullptr, "EnablePalmaStep"},
+ {508, nullptr, "ResetPalmaStep"},
+ {509, nullptr, "ReadPalmaApplicationSection"},
+ {510, nullptr, "WritePalmaApplicationSection"},
+ {511, nullptr, "ReadPalmaUniqueCode"},
+ {512, nullptr, "SetPalmaUniqueCodeInvalid"},
+ {513, nullptr, "WritePalmaActivityEntry"},
+ {514, nullptr, "WritePalmaRgbLedPatternEntry"},
+ {515, nullptr, "WritePalmaWaveEntry"},
+ {516, nullptr, "SetPalmaDataBaseIdentificationVersion"},
+ {517, nullptr, "GetPalmaDataBaseIdentificationVersion"},
+ {518, nullptr, "SuspendPalmaFeature"},
+ {519, nullptr, "GetPalmaOperationResult"},
+ {520, nullptr, "ReadPalmaPlayLog"},
+ {521, nullptr, "ResetPalmaPlayLog"},
+ {522, &Hid::SetIsPalmaAllConnectable, "SetIsPalmaAllConnectable"},
+ {523, nullptr, "SetIsPalmaPairedConnectable"},
+ {524, nullptr, "PairPalma"},
+ {525, &Hid::SetPalmaBoostMode, "SetPalmaBoostMode"},
+ {1000, nullptr, "SetNpadCommunicationMode"},
+ {1001, nullptr, "GetNpadCommunicationMode"},
+ };
+ // clang-format on
+
+ RegisterHandlers(functions);
+}
- IPC::ResponseBuilder rb{ctx, 2, 0, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<IAppletResource>(applet_resource);
- LOG_DEBUG(Service_HID, "called");
- }
+Hid::~Hid() = default;
- void ActivateXpad(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::XPad);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::CreateAppletResource(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void ActivateDebugPad(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::DebugPad);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void ActivateTouchScreen(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::Touchscreen);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
+ if (applet_resource == nullptr) {
+ applet_resource = std::make_shared<IAppletResource>();
}
- void ActivateMouse(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::Mouse);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IAppletResource>(applet_resource);
+}
- void ActivateKeyboard(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::Keyboard);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::ActivateXpad(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto basic_xpad_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void ActivateGesture(Kernel::HLERequestContext& ctx) {
- applet_resource->ActivateController(HidController::Gesture);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ LOG_DEBUG(Service_HID, "called, basic_xpad_id={}, applet_resource_user_id={}", basic_xpad_id,
+ applet_resource_user_id);
- void ActivateNpadWithRevision(Kernel::HLERequestContext& ctx) {
- // Should have no effect with how our npad sets up the data
- applet_resource->ActivateController(HidController::NPad);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::XPad);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void StartSixAxisSensor(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto handle = rp.PopRaw<u32>();
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+void Hid::ActivateDebugPad(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 3};
- rb.Push(RESULT_SUCCESS);
- // TODO (Hexagon12): Properly implement reading gyroscope values from controllers.
- rb.Push(true);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ applet_resource->ActivateController(HidController::DebugPad);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void SetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto supported_styleset = rp.PopRaw<u32>();
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .SetSupportedStyleSet({supported_styleset});
+void Hid::ActivateTouchScreen(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::Touchscreen);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void GetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
- auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
+void Hid::ActivateMouse(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- IPC::ResponseBuilder rb{ctx, 3};
- rb.Push(RESULT_SUCCESS);
- rb.Push<u32>(controller.GetSupportedStyleSet().raw);
- LOG_DEBUG(Service_HID, "called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void SetSupportedNpadIdType(Kernel::HLERequestContext& ctx) {
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .SetSupportedNPadIdTypes(ctx.ReadBuffer().data(), ctx.GetReadBufferSize());
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::Mouse);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void ActivateNpad(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- applet_resource->ActivateController(HidController::NPad);
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::ActivateKeyboard(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto npad_id = rp.PopRaw<u32>();
- IPC::ResponseBuilder rb{ctx, 2, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .GetStyleSetChangedEvent());
- LOG_DEBUG(Service_HID, "called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void DisconnectNpad(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto npad_id = rp.PopRaw<u32>();
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .DisconnectNPad(npad_id);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::Keyboard);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void GetPlayerLedPattern(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto npad_id = rp.PopRaw<u32>();
- IPC::ResponseBuilder rb{ctx, 4};
- rb.Push(RESULT_SUCCESS);
- rb.PushRaw<u64>(applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .GetLedPattern(npad_id)
- .raw);
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::ActivateGesture(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto unknown{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void SetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
- auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
- IPC::RequestParser rp{ctx};
- const auto hold_type = rp.PopRaw<u64>();
- controller.SetHoldType(Controller_NPad::NpadHoldType{hold_type});
+ LOG_DEBUG(Service_HID, "called, unknown={}, applet_resource_user_id={}", unknown,
+ applet_resource_user_id);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::Gesture);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void GetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
- const auto& controller =
- applet_resource->GetController<Controller_NPad>(HidController::NPad);
- IPC::ResponseBuilder rb{ctx, 4};
- rb.Push(RESULT_SUCCESS);
- rb.Push<u64>(static_cast<u64>(controller.GetHoldType()));
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::ActivateNpadWithRevision(Kernel::HLERequestContext& ctx) {
+ // Should have no effect with how our npad sets up the data
+ IPC::RequestParser rp{ctx};
+ const auto unknown{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto npad_id = rp.PopRaw<u32>();
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ LOG_DEBUG(Service_HID, "called, unknown={}, applet_resource_user_id={}", unknown,
+ applet_resource_user_id);
- void BeginPermitVibrationSession(Kernel::HLERequestContext& ctx) {
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .SetVibrationEnabled(true);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->ActivateController(HidController::NPad);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void EndPermitVibrationSession(Kernel::HLERequestContext& ctx) {
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .SetVibrationEnabled(false);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::StartSixAxisSensor(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto handle{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void SendVibrationValue(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- const auto controller_id = rp.PopRaw<u32>();
- const auto vibration_values = rp.PopRaw<Controller_NPad::Vibration>();
+ LOG_WARNING(Service_HID, "(STUBBED) called, handle={}, applet_resource_user_id={}", handle,
+ applet_resource_user_id);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .VibrateController({controller_id}, {vibration_values});
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto handle{rp.Pop<u32>()};
+ const auto drift_mode{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void SendVibrationValues(Kernel::HLERequestContext& ctx) {
- const auto controllers = ctx.ReadBuffer(0);
- const auto vibrations = ctx.ReadBuffer(1);
+ LOG_WARNING(Service_HID,
+ "(STUBBED) called, handle={}, drift_mode={}, applet_resource_user_id={}", handle,
+ drift_mode, applet_resource_user_id);
- std::vector<u32> controller_list(controllers.size() / sizeof(u32));
- std::vector<Controller_NPad::Vibration> vibration_list(vibrations.size() /
- sizeof(Controller_NPad::Vibration));
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- std::memcpy(controller_list.data(), controllers.data(), controllers.size());
- std::memcpy(vibration_list.data(), vibrations.data(), vibrations.size());
- std::transform(controller_list.begin(), controller_list.end(), controller_list.begin(),
- [](u32 controller_id) { return controller_id - 3; });
+void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto handle{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .VibrateController(controller_list, vibration_list);
+ LOG_WARNING(Service_HID, "(STUBBED) called, handle={}, applet_resource_user_id={}", handle,
+ applet_resource_user_id);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ // TODO (Hexagon12): Properly implement reading gyroscope values from controllers.
+ rb.Push(true);
+}
- void GetActualVibrationValue(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 6};
- rb.Push(RESULT_SUCCESS);
- rb.PushRaw<Controller_NPad::Vibration>(
- applet_resource->GetController<Controller_NPad>(HidController::NPad)
- .GetLastVibration());
- LOG_DEBUG(Service_HID, "called");
- }
+void Hid::SetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto supported_styleset{rp.Pop<u32>()};
- void SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- const auto npad_id = rp.PopRaw<u32>();
- auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
- controller.SetNpadMode(npad_id, Controller_NPad::NPadAssignments::Dual);
+ LOG_DEBUG(Service_HID, "called, supported_styleset={}", supported_styleset);
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_HID, "called");
- }
+ applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .SetSupportedStyleSet({supported_styleset});
- void MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void SetNpadHandheldActivationMode(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- auto mode = rp.PopRaw<u32>();
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+void Hid::GetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 4};
- rb.Push(RESULT_SUCCESS);
- rb.Push<u32>(1);
- rb.Push<u32>(0);
- LOG_DEBUG(Service_HID, "called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void CreateActiveVibrationDeviceList(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2, 0, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<IActiveVibrationDeviceList>();
- LOG_DEBUG(Service_HID, "called");
- }
+ auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
- void ActivateConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u32>(controller.GetSupportedStyleSet().raw);
+}
- void StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+void Hid::SetSupportedNpadIdType(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
- void StopSixAxisSensor(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
- void SetIsPalmaAllConnectable(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
+ applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .SetSupportedNPadIdTypes(ctx.ReadBuffer().data(), ctx.GetReadBufferSize());
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
- void SetPalmaBoostMode(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_HID, "(STUBBED) called");
- }
-};
+void Hid::ActivateNpad(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ applet_resource->ActivateController(HidController::NPad);
+}
+
+void Hid::AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto npad_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+ const auto unknown{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, npad_id={}, applet_resource_user_id={}, unknown={}", npad_id,
+ applet_resource_user_id, unknown);
+
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .GetStyleSetChangedEvent());
+}
+
+void Hid::DisconnectNpad(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto npad_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, npad_id={}, applet_resource_user_id={}", npad_id,
+ applet_resource_user_id);
+
+ applet_resource->GetController<Controller_NPad>(HidController::NPad).DisconnectNPad(npad_id);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::GetPlayerLedPattern(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto npad_id{rp.Pop<u32>()};
+
+ LOG_DEBUG(Service_HID, "called, npad_id={}", npad_id);
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u64>(applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .GetLedPattern(npad_id)
+ .raw);
+}
+
+void Hid::SetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+ const auto hold_type{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}, hold_type={}",
+ applet_resource_user_id, hold_type);
+
+ auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
+ controller.SetHoldType(Controller_NPad::NpadHoldType{hold_type});
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::GetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
+
+ const auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u64>(static_cast<u64>(controller.GetHoldType()));
+}
+
+void Hid::SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto npad_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, npad_id={}, applet_resource_user_id={}", npad_id,
+ applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::BeginPermitVibrationSession(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
+
+ applet_resource->GetController<Controller_NPad>(HidController::NPad).SetVibrationEnabled(true);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::EndPermitVibrationSession(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_HID, "called");
+
+ applet_resource->GetController<Controller_NPad>(HidController::NPad).SetVibrationEnabled(false);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::SendVibrationValue(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto controller_id{rp.Pop<u32>()};
+ const auto vibration_values{rp.PopRaw<Controller_NPad::Vibration>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, controller_id={}, applet_resource_user_id={}", controller_id,
+ applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+
+ applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .VibrateController({controller_id}, {vibration_values});
+}
+
+void Hid::SendVibrationValues(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, applet_resource_user_id={}", applet_resource_user_id);
+
+ const auto controllers = ctx.ReadBuffer(0);
+ const auto vibrations = ctx.ReadBuffer(1);
+
+ std::vector<u32> controller_list(controllers.size() / sizeof(u32));
+ std::vector<Controller_NPad::Vibration> vibration_list(vibrations.size() /
+ sizeof(Controller_NPad::Vibration));
+
+ std::memcpy(controller_list.data(), controllers.data(), controllers.size());
+ std::memcpy(vibration_list.data(), vibrations.data(), vibrations.size());
+ std::transform(controller_list.begin(), controller_list.end(), controller_list.begin(),
+ [](u32 controller_id) { return controller_id - 3; });
+
+ applet_resource->GetController<Controller_NPad>(HidController::NPad)
+ .VibrateController(controller_list, vibration_list);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::GetActualVibrationValue(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto controller_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, controller_id={}, applet_resource_user_id={}", controller_id,
+ applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 6};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<Controller_NPad::Vibration>(
+ applet_resource->GetController<Controller_NPad>(HidController::NPad).GetLastVibration());
+}
+
+void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto npad_id{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_DEBUG(Service_HID, "called, npad_id={}, applet_resource_user_id={}", npad_id,
+ applet_resource_user_id);
+
+ auto& controller = applet_resource->GetController<Controller_NPad>(HidController::NPad);
+ controller.SetNpadMode(npad_id, Controller_NPad::NPadAssignments::Dual);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto unknown_1{rp.Pop<u32>()};
+ const auto unknown_2{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_WARNING(Service_HID,
+ "(STUBBED) called, unknown_1={}, unknown_2={}, applet_resource_user_id={}",
+ unknown_1, unknown_2, applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::SetNpadHandheldActivationMode(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+ const auto mode{rp.Pop<u64>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, applet_resource_user_id={}, mode={}",
+ applet_resource_user_id, mode);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_HID, "called");
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u32>(1);
+ rb.Push<u32>(0);
+}
+
+void Hid::CreateActiveVibrationDeviceList(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_HID, "called");
+
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IActiveVibrationDeviceList>();
+}
+
+void Hid::ActivateConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, applet_resource_user_id={}",
+ applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto handle{rp.Pop<u32>()};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, handle={}, applet_resource_user_id={}", handle,
+ applet_resource_user_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::StopSixAxisSensor(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto handle{rp.Pop<u32>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, handle={}", handle);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::SetIsPalmaAllConnectable(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_resource_user_id{rp.Pop<u64>()};
+ const auto unknown{rp.Pop<u32>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, applet_resource_user_id={}, unknown={}",
+ applet_resource_user_id, unknown);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
+
+void Hid::SetPalmaBoostMode(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto unknown{rp.Pop<u32>()};
+
+ LOG_WARNING(Service_HID, "(STUBBED) called, unknown={}", unknown);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+}
class HidDbg final : public ServiceFramework<HidDbg> {
public:
diff --git a/src/core/hle/service/hid/hid.h b/src/core/hle/service/hid/hid.h
index 773035460..eca27c056 100644
--- a/src/core/hle/service/hid/hid.h
+++ b/src/core/hle/service/hid/hid.h
@@ -4,12 +4,122 @@
#pragma once
+#include "controllers/controller_base.h"
+#include "core/hle/service/service.h"
+
+namespace CoreTiming {
+struct EventType;
+}
+
+namespace Kernel {
+class SharedMemory;
+}
+
namespace SM {
class ServiceManager;
}
namespace Service::HID {
+enum class HidController : std::size_t {
+ DebugPad,
+ Touchscreen,
+ Mouse,
+ Keyboard,
+ XPad,
+ Unknown1,
+ Unknown2,
+ Unknown3,
+ SixAxisSensor,
+ NPad,
+ Gesture,
+
+ MaxControllers,
+};
+
+class IAppletResource final : public ServiceFramework<IAppletResource> {
+public:
+ IAppletResource();
+ ~IAppletResource() override;
+
+ void ActivateController(HidController controller);
+ void DeactivateController(HidController controller);
+
+ template <typename T>
+ T& GetController(HidController controller) {
+ return static_cast<T&>(*controllers[static_cast<size_t>(controller)]);
+ }
+
+ template <typename T>
+ const T& GetController(HidController controller) const {
+ return static_cast<T&>(*controllers[static_cast<size_t>(controller)]);
+ }
+
+private:
+ template <typename T>
+ void MakeController(HidController controller) {
+ controllers[static_cast<std::size_t>(controller)] = std::make_unique<T>();
+ }
+
+ void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx);
+ void UpdateControllers(u64 userdata, int cycles_late);
+
+ Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;
+
+ CoreTiming::EventType* pad_update_event;
+
+ std::array<std::unique_ptr<ControllerBase>, static_cast<size_t>(HidController::MaxControllers)>
+ controllers{};
+};
+
+class Hid final : public ServiceFramework<Hid> {
+public:
+ Hid();
+ ~Hid() override;
+
+ std::shared_ptr<IAppletResource> GetAppletResource();
+
+private:
+ void CreateAppletResource(Kernel::HLERequestContext& ctx);
+ void ActivateXpad(Kernel::HLERequestContext& ctx);
+ void ActivateDebugPad(Kernel::HLERequestContext& ctx);
+ void ActivateTouchScreen(Kernel::HLERequestContext& ctx);
+ void ActivateMouse(Kernel::HLERequestContext& ctx);
+ void ActivateKeyboard(Kernel::HLERequestContext& ctx);
+ void ActivateGesture(Kernel::HLERequestContext& ctx);
+ void ActivateNpadWithRevision(Kernel::HLERequestContext& ctx);
+ void StartSixAxisSensor(Kernel::HLERequestContext& ctx);
+ void SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx);
+ void IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx);
+ void SetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx);
+ void GetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx);
+ void SetSupportedNpadIdType(Kernel::HLERequestContext& ctx);
+ void ActivateNpad(Kernel::HLERequestContext& ctx);
+ void AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx);
+ void DisconnectNpad(Kernel::HLERequestContext& ctx);
+ void GetPlayerLedPattern(Kernel::HLERequestContext& ctx);
+ void SetNpadJoyHoldType(Kernel::HLERequestContext& ctx);
+ void GetNpadJoyHoldType(Kernel::HLERequestContext& ctx);
+ void SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx);
+ void BeginPermitVibrationSession(Kernel::HLERequestContext& ctx);
+ void EndPermitVibrationSession(Kernel::HLERequestContext& ctx);
+ void SendVibrationValue(Kernel::HLERequestContext& ctx);
+ void SendVibrationValues(Kernel::HLERequestContext& ctx);
+ void GetActualVibrationValue(Kernel::HLERequestContext& ctx);
+ void SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx);
+ void MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx);
+ void SetNpadHandheldActivationMode(Kernel::HLERequestContext& ctx);
+ void GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx);
+ void CreateActiveVibrationDeviceList(Kernel::HLERequestContext& ctx);
+ void ActivateConsoleSixAxisSensor(Kernel::HLERequestContext& ctx);
+ void StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx);
+ void StopSixAxisSensor(Kernel::HLERequestContext& ctx);
+ void SetIsPalmaAllConnectable(Kernel::HLERequestContext& ctx);
+ void SetPalmaBoostMode(Kernel::HLERequestContext& ctx);
+
+ std::shared_ptr<IAppletResource> applet_resource;
+};
+
/// Reload input devices. Used when input configuration changed
void ReloadInputDevices();
diff --git a/src/core/hle/service/hid/irs.cpp b/src/core/hle/service/hid/irs.cpp
index 872e3c344..3c7f8b1ee 100644
--- a/src/core/hle/service/hid/irs.cpp
+++ b/src/core/hle/service/hid/irs.cpp
@@ -44,115 +44,133 @@ IRS::IRS() : ServiceFramework{"irs"} {
}
void IRS::ActivateIrsensor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::DeactivateIrsensor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::GetIrsensorSharedMemoryHandle(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_IRS, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(shared_mem);
- LOG_DEBUG(Service_IRS, "called");
}
void IRS::StopImageProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunMomentProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunClusteringProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunImageTransferProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::GetImageTransferProcessorState(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 5};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u64>(CoreTiming::GetTicks());
rb.PushRaw<u32>(0);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunTeraPluginProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::GetNpadIrCameraHandle(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u32>(device_handle);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunPointingProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::SuspendImageProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::CheckFirmwareVersion(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::SetFunctionLevel(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunImageTransferExProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::RunIrLedProcessor(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::StopImageProcessorAsync(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
void IRS::ActivateIrsensorWithFunctionLevel(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_IRS, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_IRS, "(STUBBED) called");
}
IRS::~IRS() = default;
diff --git a/src/core/hle/service/lbl/lbl.cpp b/src/core/hle/service/lbl/lbl.cpp
index 164c57e18..e8f9f2d29 100644
--- a/src/core/hle/service/lbl/lbl.cpp
+++ b/src/core/hle/service/lbl/lbl.cpp
@@ -55,29 +55,29 @@ public:
private:
void EnableVrMode(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LBL, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
vr_mode_enabled = true;
-
- LOG_DEBUG(Service_LBL, "called");
}
void DisableVrMode(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LBL, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
vr_mode_enabled = false;
-
- LOG_DEBUG(Service_LBL, "called");
}
void IsVrModeEnabled(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LBL, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(vr_mode_enabled);
-
- LOG_DEBUG(Service_LBL, "called");
}
bool vr_mode_enabled = false;
diff --git a/src/core/hle/service/ldn/ldn.cpp b/src/core/hle/service/ldn/ldn.cpp
index 167f2c66a..e250595e3 100644
--- a/src/core/hle/service/ldn/ldn.cpp
+++ b/src/core/hle/service/ldn/ldn.cpp
@@ -44,11 +44,11 @@ public:
}
void CreateMonitorService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LDN, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IMonitorService>();
-
- LOG_DEBUG(Service_LDN, "called");
}
};
@@ -104,11 +104,11 @@ public:
}
void CreateSystemLocalCommunicationService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LDN, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILocalCommunicationService>("ISystemLocalCommunicationService");
-
- LOG_DEBUG(Service_LDN, "called");
}
};
@@ -125,11 +125,11 @@ public:
}
void CreateUserLocalCommunicationService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LDN, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILocalCommunicationService>("IUserLocalCommunicationService");
-
- LOG_DEBUG(Service_LDN, "called");
}
};
diff --git a/src/core/hle/service/ldr/ldr.cpp b/src/core/hle/service/ldr/ldr.cpp
index 7a9d0d0dd..9df7ac50f 100644
--- a/src/core/hle/service/ldr/ldr.cpp
+++ b/src/core/hle/service/ldr/ldr.cpp
@@ -97,6 +97,8 @@ public:
rp.Skip(2, false);
const VAddr nrr_addr{rp.Pop<VAddr>()};
const u64 nrr_size{rp.Pop<u64>()};
+ LOG_DEBUG(Service_LDR, "called with nrr_addr={:016X}, nrr_size={:016X}", nrr_addr,
+ nrr_size);
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
@@ -189,6 +191,7 @@ public:
IPC::RequestParser rp{ctx};
rp.Skip(2, false);
const auto nrr_addr{rp.Pop<VAddr>()};
+ LOG_DEBUG(Service_LDR, "called with nrr_addr={:016X}", nrr_addr);
if (!Common::Is4KBAligned(nrr_addr)) {
LOG_ERROR(Service_LDR, "NRR Address has invalid alignment (actual {:016X})!", nrr_addr);
@@ -219,6 +222,10 @@ public:
const u64 nro_size{rp.Pop<u64>()};
const VAddr bss_addr{rp.Pop<VAddr>()};
const u64 bss_size{rp.Pop<u64>()};
+ LOG_DEBUG(
+ Service_LDR,
+ "called with nro_addr={:016X}, nro_size={:016X}, bss_addr={:016X}, bss_size={:016X}",
+ nro_addr, nro_size, bss_addr, bss_size);
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
@@ -311,14 +318,18 @@ public:
return;
}
- ASSERT(process->MirrorMemory(*map_address, nro_addr, nro_size,
- Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
- ASSERT(process->UnmapMemory(nro_addr, 0, nro_size) == RESULT_SUCCESS);
+ ASSERT(vm_manager
+ .MirrorMemory(*map_address, nro_addr, nro_size,
+ Kernel::MemoryState::ModuleCodeStatic)
+ .IsSuccess());
+ ASSERT(vm_manager.UnmapRange(nro_addr, nro_size).IsSuccess());
if (bss_size > 0) {
- ASSERT(process->MirrorMemory(*map_address + nro_size, bss_addr, bss_size,
- Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
- ASSERT(process->UnmapMemory(bss_addr, 0, bss_size) == RESULT_SUCCESS);
+ ASSERT(vm_manager
+ .MirrorMemory(*map_address + nro_size, bss_addr, bss_size,
+ Kernel::MemoryState::ModuleCodeStatic)
+ .IsSuccess());
+ ASSERT(vm_manager.UnmapRange(bss_addr, bss_size).IsSuccess());
}
vm_manager.ReprotectRange(*map_address, header.text_size,
@@ -328,10 +339,7 @@ public:
vm_manager.ReprotectRange(*map_address + header.rw_offset, header.rw_size,
Kernel::VMAPermission::ReadWrite);
- Core::System::GetInstance().ArmInterface(0).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(1).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(2).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(3).ClearInstructionCache();
+ Core::System::GetInstance().InvalidateCpuInstructionCaches();
nro.insert_or_assign(*map_address, NROInfo{hash, nro_size + bss_size});
@@ -345,6 +353,8 @@ public:
rp.Skip(2, false);
const VAddr mapped_addr{rp.PopRaw<VAddr>()};
const VAddr heap_addr{rp.PopRaw<VAddr>()};
+ LOG_DEBUG(Service_LDR, "called with mapped_addr={:016X}, heap_addr={:016X}", mapped_addr,
+ heap_addr);
if (!initialized) {
LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
@@ -374,18 +384,16 @@ public:
return;
}
- auto* process = Core::CurrentProcess();
- auto& vm_manager = process->VMManager();
+ auto& vm_manager = Core::CurrentProcess()->VMManager();
const auto& nro_size = iter->second.size;
- ASSERT(process->MirrorMemory(heap_addr, mapped_addr, nro_size,
- Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
- ASSERT(process->UnmapMemory(mapped_addr, 0, nro_size) == RESULT_SUCCESS);
+ ASSERT(vm_manager
+ .MirrorMemory(heap_addr, mapped_addr, nro_size,
+ Kernel::MemoryState::ModuleCodeStatic)
+ .IsSuccess());
+ ASSERT(vm_manager.UnmapRange(mapped_addr, nro_size).IsSuccess());
- Core::System::GetInstance().ArmInterface(0).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(1).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(2).ClearInstructionCache();
- Core::System::GetInstance().ArmInterface(3).ClearInstructionCache();
+ Core::System::GetInstance().InvalidateCpuInstructionCaches();
nro.erase(iter);
IPC::ResponseBuilder rb{ctx, 2};
@@ -393,24 +401,25 @@ public:
}
void Initialize(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_LDR, "(STUBBED) called");
+
initialized = true;
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_LDR, "(STUBBED) called");
}
private:
using SHA256Hash = std::array<u8, 0x20>;
struct NROHeader {
- u32_le entrypoint_insn;
+ INSERT_PADDING_WORDS(1);
u32_le mod_offset;
INSERT_PADDING_WORDS(2);
u32_le magic;
- INSERT_PADDING_WORDS(1);
+ u32_le version;
u32_le nro_size;
- INSERT_PADDING_WORDS(1);
+ u32_le flags;
u32_le text_offset;
u32_le text_size;
u32_le ro_offset;
@@ -426,9 +435,10 @@ private:
struct NRRHeader {
u32_le magic;
- INSERT_PADDING_BYTES(0x1C);
+ INSERT_PADDING_BYTES(12);
u64_le title_id_mask;
u64_le title_id_pattern;
+ INSERT_PADDING_BYTES(16);
std::array<u8, 0x100> modulus;
std::array<u8, 0x100> signature_1;
std::array<u8, 0x100> signature_2;
diff --git a/src/core/hle/service/lm/lm.cpp b/src/core/hle/service/lm/lm.cpp
index 4e5fdb16e..1f462e087 100644
--- a/src/core/hle/service/lm/lm.cpp
+++ b/src/core/hle/service/lm/lm.cpp
@@ -209,11 +209,11 @@ public:
* 0: ResultCode
*/
void OpenLogger(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ILogger>();
-
- LOG_DEBUG(Service_LM, "called");
}
};
diff --git a/src/core/hle/service/mm/mm_u.cpp b/src/core/hle/service/mm/mm_u.cpp
index e1f17a926..def63dc8a 100644
--- a/src/core/hle/service/mm/mm_u.cpp
+++ b/src/core/hle/service/mm/mm_u.cpp
@@ -31,12 +31,14 @@ public:
private:
void Initialize(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void Finalize(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -45,15 +47,16 @@ private:
IPC::RequestParser rp{ctx};
min = rp.Pop<u32>();
max = rp.Pop<u32>();
- current = min;
-
LOG_WARNING(Service_MM, "(STUBBED) called, min=0x{:X}, max=0x{:X}", min, max);
+
+ current = min;
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void Get(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(current);
@@ -61,6 +64,7 @@ private:
void InitializeWithId(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(id); // Any non zero value
@@ -68,6 +72,7 @@ private:
void FinalizeWithId(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -77,16 +82,17 @@ private:
u32 input_id = rp.Pop<u32>();
min = rp.Pop<u32>();
max = rp.Pop<u32>();
- current = min;
-
LOG_WARNING(Service_MM, "(STUBBED) called, input_id=0x{:X}, min=0x{:X}, max=0x{:X}",
input_id, min, max);
+
+ current = min;
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetWithId(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_MM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(current);
diff --git a/src/core/hle/service/nfc/nfc.cpp b/src/core/hle/service/nfc/nfc.cpp
index 30e542542..5c62d42ba 100644
--- a/src/core/hle/service/nfc/nfc.cpp
+++ b/src/core/hle/service/nfc/nfc.cpp
@@ -43,11 +43,11 @@ public:
private:
void CreateAmInterface(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IAm>();
-
- LOG_DEBUG(Service_NFC, "called");
}
};
@@ -91,11 +91,11 @@ public:
private:
void CreateUserInterface(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<MFIUser>();
-
- LOG_DEBUG(Service_NFC, "called");
}
};
@@ -138,19 +138,19 @@ private:
};
void InitializeOld(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0};
rb.Push(RESULT_SUCCESS);
-
// We don't deal with hardware initialization so we can just stub this.
- LOG_DEBUG(Service_NFC, "called");
}
void IsNfcEnabledOld(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "IsNfcEnabledOld");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u8>(Settings::values.enable_nfc);
-
- LOG_DEBUG(Service_NFC, "IsNfcEnabledOld");
}
void GetStateOld(Kernel::HLERequestContext& ctx) {
@@ -183,11 +183,11 @@ public:
private:
void CreateUserInterface(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IUser>();
-
- LOG_DEBUG(Service_NFC, "called");
}
};
@@ -241,11 +241,11 @@ public:
private:
void CreateSystemInterface(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystem>();
-
- LOG_DEBUG(Service_NFC, "called");
}
};
diff --git a/src/core/hle/service/nfp/nfp.cpp b/src/core/hle/service/nfp/nfp.cpp
index 1d6e7756f..1c4482e47 100644
--- a/src/core/hle/service/nfp/nfp.cpp
+++ b/src/core/hle/service/nfp/nfp.cpp
@@ -7,9 +7,11 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/lock.h"
-#include "core/hle/service/hid/hid.h"
#include "core/hle/service/nfp/nfp.h"
#include "core/hle/service/nfp/nfp_user.h"
@@ -18,13 +20,14 @@ namespace Service::NFP {
namespace ErrCodes {
constexpr ResultCode ERR_TAG_FAILED(ErrorModule::NFP,
-1); // TODO(ogniK): Find the actual error code
-}
+constexpr ResultCode ERR_NO_APPLICATION_AREA(ErrorModule::NFP, 152);
+} // namespace ErrCodes
Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
: ServiceFramework(name), module(std::move(module)) {
auto& kernel = Core::System::GetInstance().Kernel();
- nfc_tag_load =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IUser:NFCTagDetected");
+ nfc_tag_load = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IUser:NFCTagDetected");
}
Module::Interface::~Interface() = default;
@@ -63,10 +66,10 @@ public:
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- deactivate_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IUser:DeactivateEvent");
- availability_change_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "IUser:AvailabilityChangeEvent");
+ deactivate_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "IUser:DeactivateEvent");
+ availability_change_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot, "IUser:AvailabilityChangeEvent");
}
private:
@@ -108,30 +111,29 @@ private:
static_assert(sizeof(CommonInfo) == 0x40, "CommonInfo is an invalid size");
void Initialize(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0};
rb.Push(RESULT_SUCCESS);
state = State::Initialized;
-
- LOG_DEBUG(Service_NFC, "called");
}
void GetState(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
IPC::ResponseBuilder rb{ctx, 3, 0};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u32>(static_cast<u32>(state));
-
- LOG_DEBUG(Service_NFC, "called");
}
void ListDevices(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u32 array_size = rp.Pop<u32>();
+ LOG_DEBUG(Service_NFP, "called, array_size={}", array_size);
ctx.WriteBuffer(&device_handle, sizeof(device_handle));
- LOG_DEBUG(Service_NFP, "called, array_size={}", array_size);
-
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(1);
@@ -141,6 +143,7 @@ private:
IPC::RequestParser rp{ctx};
const u64 dev_handle = rp.Pop<u64>();
LOG_DEBUG(Service_NFP, "called, dev_handle=0x{:X}", dev_handle);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(npad_id);
@@ -150,6 +153,7 @@ private:
IPC::RequestParser rp{ctx};
const u64 dev_handle = rp.Pop<u64>();
LOG_DEBUG(Service_NFP, "called, dev_handle=0x{:X}", dev_handle);
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(nfp_interface.GetNFCEvent());
@@ -163,15 +167,16 @@ private:
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(deactivate_event);
+ rb.PushCopyObjects(deactivate_event.readable);
}
void StopDetection(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_NFP, "called");
+
switch (device_state) {
case DeviceState::TagFound:
case DeviceState::TagNearby:
- deactivate_event->Signal();
+ deactivate_event.writable->Signal();
device_state = DeviceState::Initialized;
break;
case DeviceState::SearchingForTag:
@@ -185,6 +190,7 @@ private:
void GetDeviceState(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_NFP, "called");
+
auto nfc_event = nfp_interface.GetNFCEvent();
if (!nfc_event->ShouldWait(Kernel::GetCurrentThread()) && !has_attached_handle) {
device_state = DeviceState::TagFound;
@@ -261,7 +267,7 @@ private:
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(availability_change_event);
+ rb.PushCopyObjects(availability_change_event.readable);
}
void GetRegisterInfo(Kernel::HLERequestContext& ctx) {
@@ -287,10 +293,9 @@ private:
}
void OpenApplicationArea(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_NFP, "called");
- // We don't need to worry about this since we can just open the file
+ LOG_WARNING(Service_NFP, "(STUBBED) called");
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+ rb.Push(ErrCodes::ERR_NO_APPLICATION_AREA);
}
void GetApplicationAreaSize(Kernel::HLERequestContext& ctx) {
@@ -312,17 +317,18 @@ private:
}
bool has_attached_handle{};
- const u64 device_handle{Common::MakeMagic('Y', 'U', 'Z', 'U')};
- const u32 npad_id{0}; // Player 1 controller
+ const u64 device_handle{0}; // Npad device 1
+ const u32 npad_id{0}; // Player 1 controller
State state{State::NonInitialized};
DeviceState device_state{DeviceState::Initialized};
- Kernel::SharedPtr<Kernel::Event> deactivate_event;
- Kernel::SharedPtr<Kernel::Event> availability_change_event;
+ Kernel::EventPair deactivate_event;
+ Kernel::EventPair availability_change_event;
const Module::Interface& nfp_interface;
};
void Module::Interface::CreateUserInterface(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_NFP, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IUser>(*this);
@@ -335,12 +341,14 @@ bool Module::Interface::LoadAmiibo(const std::vector<u8>& buffer) {
}
std::memcpy(&amiibo, buffer.data(), sizeof(amiibo));
- nfc_tag_load->Signal();
+ nfc_tag_load.writable->Signal();
return true;
}
-const Kernel::SharedPtr<Kernel::Event>& Module::Interface::GetNFCEvent() const {
- return nfc_tag_load;
+
+const Kernel::SharedPtr<Kernel::ReadableEvent>& Module::Interface::GetNFCEvent() const {
+ return nfc_tag_load.readable;
}
+
const Module::Interface::AmiiboFile& Module::Interface::GetAmiiboBuffer() const {
return amiibo;
}
diff --git a/src/core/hle/service/nfp/nfp.h b/src/core/hle/service/nfp/nfp.h
index 5c0ae8a54..a1817e991 100644
--- a/src/core/hle/service/nfp/nfp.h
+++ b/src/core/hle/service/nfp/nfp.h
@@ -6,7 +6,8 @@
#include <array>
#include <vector>
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/service.h"
namespace Service::NFP {
@@ -33,11 +34,11 @@ public:
void CreateUserInterface(Kernel::HLERequestContext& ctx);
bool LoadAmiibo(const std::vector<u8>& buffer);
- const Kernel::SharedPtr<Kernel::Event>& GetNFCEvent() const;
+ const Kernel::SharedPtr<Kernel::ReadableEvent>& GetNFCEvent() const;
const AmiiboFile& GetAmiiboBuffer() const;
private:
- Kernel::SharedPtr<Kernel::Event> nfc_tag_load{};
+ Kernel::EventPair nfc_tag_load{};
AmiiboFile amiibo{};
protected:
diff --git a/src/core/hle/service/nifm/nifm.cpp b/src/core/hle/service/nifm/nifm.cpp
index 75dcd94a3..60479bb45 100644
--- a/src/core/hle/service/nifm/nifm.cpp
+++ b/src/core/hle/service/nifm/nifm.cpp
@@ -4,7 +4,9 @@
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nifm/nifm.h"
#include "core/hle/service/service.h"
@@ -56,19 +58,23 @@ public:
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- event1 = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IRequest:Event1");
- event2 = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IRequest:Event2");
+ event1 = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IRequest:Event1");
+ event2 = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "IRequest:Event2");
}
private:
void Submit(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetRequestState(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0);
@@ -76,30 +82,34 @@ private:
void GetResult(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetSystemEventReadableHandles(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 2};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(event1, event2);
+ rb.PushCopyObjects(event1.readable, event2.readable);
}
void Cancel(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void SetConnectionConfirmationOption(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
- Kernel::SharedPtr<Kernel::Event> event1, event2;
+ Kernel::EventPair event1, event2;
};
class INetworkProfile final : public ServiceFramework<INetworkProfile> {
@@ -122,32 +132,36 @@ private:
void GetClientId(Kernel::HLERequestContext& ctx) {
static constexpr u32 client_id = 1;
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u64>(client_id); // Client ID needs to be non zero otherwise it's considered invalid
}
void CreateScanRequest(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIFM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IScanRequest>();
-
- LOG_DEBUG(Service_NIFM, "called");
}
void CreateRequest(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIFM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IRequest>();
-
- LOG_DEBUG(Service_NIFM, "called");
}
void RemoveNetworkProfile(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void CreateTemporaryNetworkProfile(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIFM, "called");
+
ASSERT_MSG(ctx.GetReadBufferSize() == 0x17c, "NetworkProfileData is not the correct size");
u128 uuid{};
auto buffer = ctx.ReadBuffer();
@@ -158,23 +172,24 @@ private:
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<INetworkProfile>();
rb.PushRaw<u128>(uuid);
-
- LOG_DEBUG(Service_NIFM, "called");
}
void IsWirelessCommunicationEnabled(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u8>(0);
}
void IsEthernetCommunicationEnabled(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u8>(0);
}
void IsAnyInternetRequestAccepted(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u8>(0);
@@ -235,17 +250,19 @@ public:
}
void CreateGeneralServiceOld(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIFM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IGeneralService>();
- LOG_DEBUG(Service_NIFM, "called");
}
void CreateGeneralService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIFM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IGeneralService>();
- LOG_DEBUG(Service_NIFM, "called");
}
};
diff --git a/src/core/hle/service/nim/nim.cpp b/src/core/hle/service/nim/nim.cpp
index 18091c9bb..0dabcd23b 100644
--- a/src/core/hle/service/nim/nim.cpp
+++ b/src/core/hle/service/nim/nim.cpp
@@ -6,7 +6,9 @@
#include <ctime>
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nim/nim.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
@@ -138,57 +140,61 @@ public:
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- finished_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "IEnsureNetworkClockAvailabilityService:FinishEvent");
+ finished_event = Kernel::WritableEvent::CreateEventPair(
+ kernel, Kernel::ResetType::OneShot,
+ "IEnsureNetworkClockAvailabilityService:FinishEvent");
}
private:
- Kernel::SharedPtr<Kernel::Event> finished_event;
+ Kernel::EventPair finished_event;
void StartTask(Kernel::HLERequestContext& ctx) {
// No need to connect to the internet, just finish the task straight away.
- finished_event->Signal();
+ LOG_DEBUG(Service_NIM, "called");
+ finished_event.writable->Signal();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_NIM, "called");
}
void GetFinishNotificationEvent(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(finished_event);
- LOG_DEBUG(Service_NIM, "called");
+ rb.PushCopyObjects(finished_event.readable);
}
void GetResult(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIM, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_NIM, "called");
}
void Cancel(Kernel::HLERequestContext& ctx) {
- finished_event->Clear();
+ LOG_DEBUG(Service_NIM, "called");
+ finished_event.writable->Clear();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_NIM, "called");
}
void IsProcessing(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIM, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u32>(0); // We instantly process the request
- LOG_DEBUG(Service_NIM, "called");
}
void GetServerTime(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIM, "called");
+
const s64 server_time{std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count()};
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<s64>(server_time);
- LOG_DEBUG(Service_NIM, "called");
}
};
@@ -208,23 +214,26 @@ public:
private:
void OpenEnsureNetworkClockAvailabilityService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NIM, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IEnsureNetworkClockAvailabilityService>();
- LOG_DEBUG(Service_NIM, "called");
}
// TODO(ogniK): Do we need these?
void SuspendAutonomicTimeCorrection(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_NIM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_NIM, "(STUBBED) called");
}
void ResumeAutonomicTimeCorrection(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_NIM, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_NIM, "(STUBBED) called");
}
};
diff --git a/src/core/hle/service/ns/ns.cpp b/src/core/hle/service/ns/ns.cpp
index 1d2978f24..2663f56b1 100644
--- a/src/core/hle/service/ns/ns.cpp
+++ b/src/core/hle/service/ns/ns.cpp
@@ -433,11 +433,11 @@ public:
private:
template <typename T>
void PushInterface(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NS, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<T>();
-
- LOG_DEBUG(Service_NS, "called");
}
};
@@ -526,11 +526,11 @@ public:
private:
void OpenSystemUpdateControl(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NS, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystemUpdateControl>();
-
- LOG_DEBUG(Service_NS, "called");
}
};
diff --git a/src/core/hle/service/ns/pl_u.cpp b/src/core/hle/service/ns/pl_u.cpp
index 1066bf505..ad176f89d 100644
--- a/src/core/hle/service/ns/pl_u.cpp
+++ b/src/core/hle/service/ns/pl_u.cpp
@@ -281,6 +281,7 @@ void PL_U::RequestLoad(Kernel::HLERequestContext& ctx) {
const u32 shared_font_type{rp.Pop<u32>()};
// Games don't call this so all fonts should be loaded
LOG_DEBUG(Service_NS, "called, shared_font_type={}", shared_font_type);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -288,8 +289,8 @@ void PL_U::RequestLoad(Kernel::HLERequestContext& ctx) {
void PL_U::GetLoadState(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u32 font_id{rp.Pop<u32>()};
-
LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(static_cast<u32>(LoadState::Done));
@@ -298,8 +299,8 @@ void PL_U::GetLoadState(Kernel::HLERequestContext& ctx) {
void PL_U::GetSize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u32 font_id{rp.Pop<u32>()};
-
LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(impl->GetSharedFontRegion(font_id).size);
@@ -308,8 +309,8 @@ void PL_U::GetSize(Kernel::HLERequestContext& ctx) {
void PL_U::GetSharedMemoryAddressOffset(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u32 font_id{rp.Pop<u32>()};
-
LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(impl->GetSharedFontRegion(font_id).offset);
@@ -317,6 +318,7 @@ void PL_U::GetSharedMemoryAddressOffset(Kernel::HLERequestContext& ctx) {
void PL_U::GetSharedMemoryNativeHandle(Kernel::HLERequestContext& ctx) {
// Map backing memory for the font data
+ LOG_DEBUG(Service_NS, "called");
Core::CurrentProcess()->VMManager().MapMemoryBlock(SHARED_FONT_MEM_VADDR, impl->shared_font, 0,
SHARED_FONT_MEM_SIZE,
Kernel::MemoryState::Shared);
@@ -328,7 +330,6 @@ void PL_U::GetSharedMemoryNativeHandle(Kernel::HLERequestContext& ctx) {
Kernel::MemoryPermission::Read, SHARED_FONT_MEM_VADDR, Kernel::MemoryRegion::BASE,
"PL_U:shared_font_mem");
- LOG_DEBUG(Service_NS, "called");
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(impl->shared_font_mem);
@@ -338,6 +339,7 @@ void PL_U::GetSharedFontInOrderOfPriority(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 language_code{rp.Pop<u64>()}; // TODO(ogniK): Find out what this is used for
LOG_DEBUG(Service_NS, "called, language_code={:X}", language_code);
+
IPC::ResponseBuilder rb{ctx, 4};
std::vector<u32> font_codes;
std::vector<u32> font_offsets;
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
index c41ef7058..466db7ccd 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_as_gpu.cpp
@@ -54,6 +54,7 @@ u32 nvhost_as_gpu::InitalizeEx(const std::vector<u8>& input, std::vector<u8>& ou
IoctlInitalizeEx params{};
std::memcpy(&params, input.data(), input.size());
LOG_WARNING(Service_NVDRV, "(STUBBED) called, big_page_size=0x{:X}", params.big_page_size);
+
return 0;
}
@@ -191,6 +192,7 @@ u32 nvhost_as_gpu::BindChannel(const std::vector<u8>& input, std::vector<u8>& ou
IoctlBindChannel params{};
std::memcpy(&params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, fd={:X}", params.fd);
+
channel = params.fd;
return 0;
}
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
index 792d26e52..d57a54ee8 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
@@ -103,6 +103,7 @@ u32 nvhost_ctrl_gpu::GetTPCMasks(const std::vector<u8>& input, std::vector<u8>&
u32 nvhost_ctrl_gpu::GetActiveSlotMask(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlActiveSlotMask params{};
if (input.size() > 0) {
std::memcpy(&params, input.data(), input.size());
@@ -115,6 +116,7 @@ u32 nvhost_ctrl_gpu::GetActiveSlotMask(const std::vector<u8>& input, std::vector
u32 nvhost_ctrl_gpu::ZCullGetCtxSize(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlZcullGetCtxSize params{};
if (input.size() > 0) {
std::memcpy(&params, input.data(), input.size());
@@ -126,6 +128,7 @@ u32 nvhost_ctrl_gpu::ZCullGetCtxSize(const std::vector<u8>& input, std::vector<u
u32 nvhost_ctrl_gpu::ZCullGetInfo(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlNvgpuGpuZcullGetInfoArgs params{};
if (input.size() > 0) {
@@ -148,6 +151,7 @@ u32 nvhost_ctrl_gpu::ZCullGetInfo(const std::vector<u8>& input, std::vector<u8>&
u32 nvhost_ctrl_gpu::ZBCSetTable(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IoctlZbcSetTable params{};
std::memcpy(&params, input.data(), input.size());
// TODO(ogniK): What does this even actually do?
@@ -157,6 +161,7 @@ u32 nvhost_ctrl_gpu::ZBCSetTable(const std::vector<u8>& input, std::vector<u8>&
u32 nvhost_ctrl_gpu::ZBCQueryTable(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IoctlZbcQueryTable params{};
std::memcpy(&params, input.data(), input.size());
// TODO : To implement properly
@@ -166,6 +171,7 @@ u32 nvhost_ctrl_gpu::ZBCQueryTable(const std::vector<u8>& input, std::vector<u8>
u32 nvhost_ctrl_gpu::FlushL2(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IoctlFlushL2 params{};
std::memcpy(&params, input.data(), input.size());
// TODO : To implement properly
@@ -175,6 +181,7 @@ u32 nvhost_ctrl_gpu::FlushL2(const std::vector<u8>& input, std::vector<u8>& outp
u32 nvhost_ctrl_gpu::GetGpuTime(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlGetGpuTime params{};
std::memcpy(&params, input.data(), input.size());
params.gpu_time = CoreTiming::cyclesToNs(CoreTiming::GetTicks());
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
index 874d5e1c3..0a650f36c 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
@@ -8,7 +8,6 @@
#include "core/core.h"
#include "core/hle/service/nvdrv/devices/nvhost_gpu.h"
#include "core/memory.h"
-#include "video_core/command_processor.h"
#include "video_core/gpu.h"
#include "video_core/memory_manager.h"
@@ -61,12 +60,14 @@ u32 nvhost_gpu::SetNVMAPfd(const std::vector<u8>& input, std::vector<u8>& output
IoctlSetNvmapFD params{};
std::memcpy(&params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, fd={}", params.nvmap_fd);
+
nvmap_fd = params.nvmap_fd;
return 0;
}
u32 nvhost_gpu::SetClientData(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlClientData params{};
std::memcpy(&params, input.data(), input.size());
user_data = params.data;
@@ -75,6 +76,7 @@ u32 nvhost_gpu::SetClientData(const std::vector<u8>& input, std::vector<u8>& out
u32 nvhost_gpu::GetClientData(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called");
+
IoctlClientData params{};
std::memcpy(&params, input.data(), input.size());
params.data = user_data;
@@ -86,6 +88,7 @@ u32 nvhost_gpu::ZCullBind(const std::vector<u8>& input, std::vector<u8>& output)
std::memcpy(&zcull_params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, gpu_va={:X}, mode={:X}", zcull_params.gpu_va,
zcull_params.mode);
+
std::memcpy(output.data(), &zcull_params, output.size());
return 0;
}
@@ -95,6 +98,7 @@ u32 nvhost_gpu::SetErrorNotifier(const std::vector<u8>& input, std::vector<u8>&
std::memcpy(&params, input.data(), input.size());
LOG_WARNING(Service_NVDRV, "(STUBBED) called, offset={:X}, size={:X}, mem={:X}", params.offset,
params.size, params.mem);
+
std::memcpy(output.data(), &params, output.size());
return 0;
}
@@ -102,6 +106,7 @@ u32 nvhost_gpu::SetErrorNotifier(const std::vector<u8>& input, std::vector<u8>&
u32 nvhost_gpu::SetChannelPriority(const std::vector<u8>& input, std::vector<u8>& output) {
std::memcpy(&channel_priority, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "(STUBBED) called, priority={:X}", channel_priority);
+
return 0;
}
@@ -113,6 +118,7 @@ u32 nvhost_gpu::AllocGPFIFOEx2(const std::vector<u8>& input, std::vector<u8>& ou
"unk1={:X}, unk2={:X}, unk3={:X}",
params.num_entries, params.flags, params.unk0, params.unk1, params.unk2,
params.unk3);
+
params.fence_out.id = 0;
params.fence_out.value = 0;
std::memcpy(output.data(), &params, output.size());
@@ -124,11 +130,22 @@ u32 nvhost_gpu::AllocateObjectContext(const std::vector<u8>& input, std::vector<
std::memcpy(&params, input.data(), input.size());
LOG_WARNING(Service_NVDRV, "(STUBBED) called, class_num={:X}, flags={:X}", params.class_num,
params.flags);
+
params.obj_id = 0x0;
std::memcpy(output.data(), &params, output.size());
return 0;
}
+static void PushGPUEntries(Tegra::CommandList&& entries) {
+ if (entries.empty()) {
+ return;
+ }
+
+ auto& dma_pusher{Core::System::GetInstance().GPU().DmaPusher()};
+ dma_pusher.Push(std::move(entries));
+ dma_pusher.DispatchCalls();
+}
+
u32 nvhost_gpu::SubmitGPFIFO(const std::vector<u8>& input, std::vector<u8>& output) {
if (input.size() < sizeof(IoctlSubmitGpfifo)) {
UNIMPLEMENTED();
@@ -142,11 +159,11 @@ u32 nvhost_gpu::SubmitGPFIFO(const std::vector<u8>& input, std::vector<u8>& outp
params.num_entries * sizeof(Tegra::CommandListHeader),
"Incorrect input size");
- std::vector<Tegra::CommandListHeader> entries(params.num_entries);
+ Tegra::CommandList entries(params.num_entries);
std::memcpy(entries.data(), &input[sizeof(IoctlSubmitGpfifo)],
params.num_entries * sizeof(Tegra::CommandListHeader));
- Core::System::GetInstance().GPU().ProcessCommandLists(entries);
+ PushGPUEntries(std::move(entries));
params.fence_out.id = 0;
params.fence_out.value = 0;
@@ -163,11 +180,11 @@ u32 nvhost_gpu::KickoffPB(const std::vector<u8>& input, std::vector<u8>& output)
LOG_WARNING(Service_NVDRV, "(STUBBED) called, gpfifo={:X}, num_entries={:X}, flags={:X}",
params.address, params.num_entries, params.flags);
- std::vector<Tegra::CommandListHeader> entries(params.num_entries);
+ Tegra::CommandList entries(params.num_entries);
Memory::ReadBlock(params.address, entries.data(),
params.num_entries * sizeof(Tegra::CommandListHeader));
- Core::System::GetInstance().GPU().ProcessCommandLists(entries);
+ PushGPUEntries(std::move(entries));
params.fence_out.id = 0;
params.fence_out.value = 0;
@@ -179,6 +196,7 @@ u32 nvhost_gpu::GetWaitbase(const std::vector<u8>& input, std::vector<u8>& outpu
IoctlGetWaitbase params{};
std::memcpy(&params, input.data(), sizeof(IoctlGetWaitbase));
LOG_INFO(Service_NVDRV, "called, unknown=0x{:X}", params.unknown);
+
params.value = 0; // Seems to be hard coded at 0
std::memcpy(output.data(), &params, output.size());
return 0;
@@ -188,6 +206,7 @@ u32 nvhost_gpu::ChannelSetTimeout(const std::vector<u8>& input, std::vector<u8>&
IoctlChannelSetTimeout params{};
std::memcpy(&params, input.data(), sizeof(IoctlChannelSetTimeout));
LOG_INFO(Service_NVDRV, "called, timeout=0x{:X}", params.timeout);
+
return 0;
}
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_nvdec.cpp b/src/core/hle/service/nvdrv/devices/nvhost_nvdec.cpp
index 46dbbc37c..f5e8ea7c3 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_nvdec.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_nvdec.cpp
@@ -30,6 +30,7 @@ u32 nvhost_nvdec::SetNVMAPfd(const std::vector<u8>& input, std::vector<u8>& outp
IoctlSetNvmapFD params{};
std::memcpy(&params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, fd={}", params.nvmap_fd);
+
nvmap_fd = params.nvmap_fd;
return 0;
}
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_nvjpg.cpp b/src/core/hle/service/nvdrv/devices/nvhost_nvjpg.cpp
index c67f934f6..3e0951ab0 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_nvjpg.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_nvjpg.cpp
@@ -30,6 +30,7 @@ u32 nvhost_nvjpg::SetNVMAPfd(const std::vector<u8>& input, std::vector<u8>& outp
IoctlSetNvmapFD params{};
std::memcpy(&params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, fd={}", params.nvmap_fd);
+
nvmap_fd = params.nvmap_fd;
return 0;
}
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_vic.cpp b/src/core/hle/service/nvdrv/devices/nvhost_vic.cpp
index 727b9fee4..d544f0f31 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_vic.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_vic.cpp
@@ -30,6 +30,7 @@ u32 nvhost_vic::SetNVMAPfd(const std::vector<u8>& input, std::vector<u8>& output
IoctlSetNvmapFD params{};
std::memcpy(&params, input.data(), input.size());
LOG_DEBUG(Service_NVDRV, "called, fd={}", params.nvmap_fd);
+
nvmap_fd = params.nvmap_fd;
return 0;
}
diff --git a/src/core/hle/service/nvdrv/devices/nvmap.cpp b/src/core/hle/service/nvdrv/devices/nvmap.cpp
index 43651d8a6..1ec796fc6 100644
--- a/src/core/hle/service/nvdrv/devices/nvmap.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvmap.cpp
@@ -54,6 +54,7 @@ u32 nvmap::IocCreate(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "size=0x{:08X}", params.size);
if (!params.size) {
+ LOG_ERROR(Service_NVDRV, "Size is 0");
return static_cast<u32>(NvErrCodes::InvalidValue);
}
// Create a new nvmap object and obtain a handle to it.
@@ -78,10 +79,12 @@ u32 nvmap::IocAlloc(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_DEBUG(Service_NVDRV, "called, addr={:X}", params.addr);
if (!params.handle) {
+ LOG_ERROR(Service_NVDRV, "Handle is 0");
return static_cast<u32>(NvErrCodes::InvalidValue);
}
if ((params.align - 1) & params.align) {
+ LOG_ERROR(Service_NVDRV, "Incorrect alignment used, alignment={:08X}", params.align);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
@@ -92,10 +95,12 @@ u32 nvmap::IocAlloc(const std::vector<u8>& input, std::vector<u8>& output) {
auto object = GetObject(params.handle);
if (!object) {
+ LOG_ERROR(Service_NVDRV, "Object does not exist, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
if (object->status == Object::Status::Allocated) {
+ LOG_ERROR(Service_NVDRV, "Object is already allocated, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::OperationNotPermitted);
}
@@ -116,11 +121,13 @@ u32 nvmap::IocGetId(const std::vector<u8>& input, std::vector<u8>& output) {
LOG_WARNING(Service_NVDRV, "called");
if (!params.handle) {
+ LOG_ERROR(Service_NVDRV, "Handle is zero");
return static_cast<u32>(NvErrCodes::InvalidValue);
}
auto object = GetObject(params.handle);
if (!object) {
+ LOG_ERROR(Service_NVDRV, "Object does not exist, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::OperationNotPermitted);
}
@@ -139,11 +146,13 @@ u32 nvmap::IocFromId(const std::vector<u8>& input, std::vector<u8>& output) {
auto itr = std::find_if(handles.begin(), handles.end(),
[&](const auto& entry) { return entry.second->id == params.id; });
if (itr == handles.end()) {
+ LOG_ERROR(Service_NVDRV, "Object does not exist, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
auto& object = itr->second;
if (object->status != Object::Status::Allocated) {
+ LOG_ERROR(Service_NVDRV, "Object is not allocated, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
@@ -166,10 +175,12 @@ u32 nvmap::IocParam(const std::vector<u8>& input, std::vector<u8>& output) {
auto object = GetObject(params.handle);
if (!object) {
+ LOG_ERROR(Service_NVDRV, "Object does not exist, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
if (object->status != Object::Status::Allocated) {
+ LOG_ERROR(Service_NVDRV, "Object is not allocated, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::OperationNotPermitted);
}
@@ -209,9 +220,14 @@ u32 nvmap::IocFree(const std::vector<u8>& input, std::vector<u8>& output) {
auto itr = handles.find(params.handle);
if (itr == handles.end()) {
+ LOG_ERROR(Service_NVDRV, "Object does not exist, handle={:08X}", params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
if (!itr->second->refcount) {
+ LOG_ERROR(
+ Service_NVDRV,
+ "There is no references to this object. The object is already freed. handle={:08X}",
+ params.handle);
return static_cast<u32>(NvErrCodes::InvalidValue);
}
diff --git a/src/core/hle/service/nvdrv/interface.cpp b/src/core/hle/service/nvdrv/interface.cpp
index 602086eed..3b9ab4b14 100644
--- a/src/core/hle/service/nvdrv/interface.cpp
+++ b/src/core/hle/service/nvdrv/interface.cpp
@@ -6,7 +6,9 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nvdrv/interface.h"
#include "core/hle/service/nvdrv/nvdrv.h"
@@ -55,6 +57,7 @@ void NVDRV::Close(Kernel::HLERequestContext& ctx) {
void NVDRV::Initialize(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0);
@@ -68,15 +71,15 @@ void NVDRV::QueryEvent(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(query_event);
+ rb.PushCopyObjects(query_event.readable);
rb.Push<u32>(0);
}
void NVDRV::SetClientPID(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
pid = rp.Pop<u64>();
-
LOG_WARNING(Service_NVDRV, "(STUBBED) called, pid=0x{:X}", pid);
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0);
@@ -84,12 +87,14 @@ void NVDRV::SetClientPID(Kernel::HLERequestContext& ctx) {
void NVDRV::FinishInitialize(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void NVDRV::GetStatus(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NVDRV, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -98,6 +103,7 @@ void NVDRV::DumpGraphicsMemoryInfo(Kernel::HLERequestContext& ctx) {
// According to SwitchBrew, this has no inputs and no outputs, so effectively does nothing on
// retail hardware.
LOG_DEBUG(Service_NVDRV, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
@@ -123,7 +129,8 @@ NVDRV::NVDRV(std::shared_ptr<Module> nvdrv, const char* name)
RegisterHandlers(functions);
auto& kernel = Core::System::GetInstance().Kernel();
- query_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "NVDRV::query_event");
+ query_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::OneShot,
+ "NVDRV::query_event");
}
NVDRV::~NVDRV() = default;
diff --git a/src/core/hle/service/nvdrv/interface.h b/src/core/hle/service/nvdrv/interface.h
index 5a1e4baa7..fe311b069 100644
--- a/src/core/hle/service/nvdrv/interface.h
+++ b/src/core/hle/service/nvdrv/interface.h
@@ -5,10 +5,13 @@
#pragma once
#include <memory>
-#include "core/hle/kernel/event.h"
#include "core/hle/service/nvdrv/nvdrv.h"
#include "core/hle/service/service.h"
+namespace Kernel {
+class WritableEvent;
+}
+
namespace Service::Nvidia {
class NVDRV final : public ServiceFramework<NVDRV> {
@@ -31,7 +34,7 @@ private:
u64 pid{};
- Kernel::SharedPtr<Kernel::Event> query_event;
+ Kernel::EventPair query_event;
};
} // namespace Service::Nvidia
diff --git a/src/core/hle/service/nvflinger/buffer_queue.cpp b/src/core/hle/service/nvflinger/buffer_queue.cpp
index 630ebbfc7..fc07d9bb8 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue.cpp
@@ -7,28 +7,31 @@
#include "common/assert.h"
#include "common/logging/log.h"
#include "core/core.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nvflinger/buffer_queue.h"
namespace Service::NVFlinger {
BufferQueue::BufferQueue(u32 id, u64 layer_id) : id(id), layer_id(layer_id) {
auto& kernel = Core::System::GetInstance().Kernel();
- buffer_wait_event =
- Kernel::Event::Create(kernel, Kernel::ResetType::Sticky, "BufferQueue NativeHandle");
+ buffer_wait_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ "BufferQueue NativeHandle");
}
BufferQueue::~BufferQueue() = default;
void BufferQueue::SetPreallocatedBuffer(u32 slot, const IGBPBuffer& igbp_buffer) {
+ LOG_WARNING(Service, "Adding graphics buffer {}", slot);
+
Buffer buffer{};
buffer.slot = slot;
buffer.igbp_buffer = igbp_buffer;
buffer.status = Buffer::Status::Free;
- LOG_WARNING(Service, "Adding graphics buffer {}", slot);
-
queue.emplace_back(buffer);
- buffer_wait_event->Signal();
+ buffer_wait_event.writable->Signal();
}
std::optional<u32> BufferQueue::DequeueBuffer(u32 width, u32 height) {
@@ -87,11 +90,12 @@ void BufferQueue::ReleaseBuffer(u32 slot) {
ASSERT(itr->status == Buffer::Status::Acquired);
itr->status = Buffer::Status::Free;
- buffer_wait_event->Signal();
+ buffer_wait_event.writable->Signal();
}
u32 BufferQueue::Query(QueryType type) {
LOG_WARNING(Service, "(STUBBED) called type={}", static_cast<u32>(type));
+
switch (type) {
case QueryType::NativeWindowFormat:
// TODO(Subv): Use an enum for this
@@ -103,4 +107,12 @@ u32 BufferQueue::Query(QueryType type) {
return 0;
}
+Kernel::SharedPtr<Kernel::WritableEvent> BufferQueue::GetWritableBufferWaitEvent() const {
+ return buffer_wait_event.writable;
+}
+
+Kernel::SharedPtr<Kernel::ReadableEvent> BufferQueue::GetBufferWaitEvent() const {
+ return buffer_wait_event.readable;
+}
+
} // namespace Service::NVFlinger
diff --git a/src/core/hle/service/nvflinger/buffer_queue.h b/src/core/hle/service/nvflinger/buffer_queue.h
index 8cff5eb71..b171f256c 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.h
+++ b/src/core/hle/service/nvflinger/buffer_queue.h
@@ -10,7 +10,8 @@
#include "common/common_funcs.h"
#include "common/math_util.h"
#include "common/swap.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/object.h"
+#include "core/hle/kernel/writable_event.h"
namespace CoreTiming {
struct EventType;
@@ -86,16 +87,16 @@ public:
return id;
}
- Kernel::SharedPtr<Kernel::Event> GetBufferWaitEvent() const {
- return buffer_wait_event;
- }
+ Kernel::SharedPtr<Kernel::WritableEvent> GetWritableBufferWaitEvent() const;
+
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetBufferWaitEvent() const;
private:
u32 id;
u64 layer_id;
std::vector<Buffer> queue;
- Kernel::SharedPtr<Kernel::Event> buffer_wait_event;
+ Kernel::EventPair buffer_wait_event;
};
} // namespace Service::NVFlinger
diff --git a/src/core/hle/service/nvflinger/nvflinger.cpp b/src/core/hle/service/nvflinger/nvflinger.cpp
index 214e6d1b3..6db2cce41 100644
--- a/src/core/hle/service/nvflinger/nvflinger.cpp
+++ b/src/core/hle/service/nvflinger/nvflinger.cpp
@@ -5,7 +5,6 @@
#include <algorithm>
#include <optional>
-#include "common/alignment.h"
#include "common/assert.h"
#include "common/logging/log.h"
#include "common/microprofile.h"
@@ -13,13 +12,15 @@
#include "core/core.h"
#include "core/core_timing.h"
#include "core/core_timing_util.h"
+#include "core/hle/kernel/kernel.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nvdrv/devices/nvdisp_disp0.h"
#include "core/hle/service/nvdrv/nvdrv.h"
#include "core/hle/service/nvflinger/buffer_queue.h"
#include "core/hle/service/nvflinger/nvflinger.h"
#include "core/perf_stats.h"
#include "video_core/renderer_base.h"
-#include "video_core/video_core.h"
namespace Service::NVFlinger {
@@ -27,12 +28,6 @@ constexpr std::size_t SCREEN_REFRESH_RATE = 60;
constexpr u64 frame_ticks = static_cast<u64>(CoreTiming::BASE_CLOCK_RATE / SCREEN_REFRESH_RATE);
NVFlinger::NVFlinger() {
- // Add the different displays to the list of displays.
- displays.emplace_back(0, "Default");
- displays.emplace_back(1, "External");
- displays.emplace_back(2, "Edid");
- displays.emplace_back(3, "Internal");
-
// Schedule the screen composition events
composition_event =
CoreTiming::RegisterEvent("ScreenComposition", [this](u64 userdata, int cycles_late) {
@@ -52,13 +47,13 @@ void NVFlinger::SetNVDrvInstance(std::shared_ptr<Nvidia::Module> instance) {
}
u64 NVFlinger::OpenDisplay(std::string_view name) {
- LOG_WARNING(Service, "Opening display {}", name);
+ LOG_DEBUG(Service, "Opening \"{}\" display", name);
// TODO(Subv): Currently we only support the Default display.
ASSERT(name == "Default");
- auto itr = std::find_if(displays.begin(), displays.end(),
- [&](const Display& display) { return display.name == name; });
+ const auto itr = std::find_if(displays.begin(), displays.end(),
+ [&](const Display& display) { return display.name == name; });
ASSERT(itr != displays.end());
@@ -70,8 +65,8 @@ u64 NVFlinger::CreateLayer(u64 display_id) {
ASSERT_MSG(display.layers.empty(), "Only one layer is supported per display at the moment");
- u64 layer_id = next_layer_id++;
- u32 buffer_queue_id = next_buffer_queue_id++;
+ const u64 layer_id = next_layer_id++;
+ const u32 buffer_queue_id = next_buffer_queue_id++;
auto buffer_queue = std::make_shared<BufferQueue>(buffer_queue_id, layer_id);
display.layers.emplace_back(layer_id, buffer_queue);
buffer_queues.emplace_back(std::move(buffer_queue));
@@ -83,22 +78,21 @@ u32 NVFlinger::GetBufferQueueId(u64 display_id, u64 layer_id) {
return layer.buffer_queue->GetId();
}
-Kernel::SharedPtr<Kernel::Event> NVFlinger::GetVsyncEvent(u64 display_id) {
- const auto& display = GetDisplay(display_id);
- return display.vsync_event;
+Kernel::SharedPtr<Kernel::ReadableEvent> NVFlinger::GetVsyncEvent(u64 display_id) {
+ return GetDisplay(display_id).vsync_event.readable;
}
std::shared_ptr<BufferQueue> NVFlinger::GetBufferQueue(u32 id) const {
- auto itr = std::find_if(buffer_queues.begin(), buffer_queues.end(),
- [&](const auto& queue) { return queue->GetId() == id; });
+ const auto itr = std::find_if(buffer_queues.begin(), buffer_queues.end(),
+ [&](const auto& queue) { return queue->GetId() == id; });
ASSERT(itr != buffer_queues.end());
return *itr;
}
Display& NVFlinger::GetDisplay(u64 display_id) {
- auto itr = std::find_if(displays.begin(), displays.end(),
- [&](const Display& display) { return display.id == display_id; });
+ const auto itr = std::find_if(displays.begin(), displays.end(),
+ [&](const Display& display) { return display.id == display_id; });
ASSERT(itr != displays.end());
return *itr;
@@ -107,8 +101,8 @@ Display& NVFlinger::GetDisplay(u64 display_id) {
Layer& NVFlinger::GetLayer(u64 display_id, u64 layer_id) {
auto& display = GetDisplay(display_id);
- auto itr = std::find_if(display.layers.begin(), display.layers.end(),
- [&](const Layer& layer) { return layer.id == layer_id; });
+ const auto itr = std::find_if(display.layers.begin(), display.layers.end(),
+ [&](const Layer& layer) { return layer.id == layer_id; });
ASSERT(itr != display.layers.end());
return *itr;
@@ -117,7 +111,7 @@ Layer& NVFlinger::GetLayer(u64 display_id, u64 layer_id) {
void NVFlinger::Compose() {
for (auto& display : displays) {
// Trigger vsync for this display at the end of drawing
- SCOPE_EXIT({ display.vsync_event->Signal(); });
+ SCOPE_EXIT({ display.vsync_event.writable->Signal(); });
// Don't do anything for displays without layers.
if (display.layers.empty())
@@ -143,7 +137,7 @@ void NVFlinger::Compose() {
continue;
}
- auto& igbp_buffer = buffer->get().igbp_buffer;
+ const auto& igbp_buffer = buffer->get().igbp_buffer;
// Now send the buffer to the GPU for drawing.
// TODO(Subv): Support more than just disp0. The display device selection is probably based
@@ -164,7 +158,8 @@ Layer::~Layer() = default;
Display::Display(u64 id, std::string name) : id(id), name(std::move(name)) {
auto& kernel = Core::System::GetInstance().Kernel();
- vsync_event = Kernel::Event::Create(kernel, Kernel::ResetType::Pulse, "Display VSync Event");
+ vsync_event = Kernel::WritableEvent::CreateEventPair(kernel, Kernel::ResetType::Sticky,
+ fmt::format("Display VSync Event {}", id));
}
Display::~Display() = default;
diff --git a/src/core/hle/service/nvflinger/nvflinger.h b/src/core/hle/service/nvflinger/nvflinger.h
index 3dc69e69b..8f9a0a7f8 100644
--- a/src/core/hle/service/nvflinger/nvflinger.h
+++ b/src/core/hle/service/nvflinger/nvflinger.h
@@ -4,18 +4,24 @@
#pragma once
+#include <array>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "common/common_types.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/object.h"
namespace CoreTiming {
struct EventType;
}
+namespace Kernel {
+class ReadableEvent;
+class WritableEvent;
+} // namespace Kernel
+
namespace Service::Nvidia {
class Module;
}
@@ -40,7 +46,7 @@ struct Display {
std::string name;
std::vector<Layer> layers;
- Kernel::SharedPtr<Kernel::Event> vsync_event;
+ Kernel::EventPair vsync_event;
};
class NVFlinger final {
@@ -61,7 +67,7 @@ public:
u32 GetBufferQueueId(u64 display_id, u64 layer_id);
/// Gets the vsync event for the specified display.
- Kernel::SharedPtr<Kernel::Event> GetVsyncEvent(u64 display_id);
+ Kernel::SharedPtr<Kernel::ReadableEvent> GetVsyncEvent(u64 display_id);
/// Obtains a buffer queue identified by the id.
std::shared_ptr<BufferQueue> GetBufferQueue(u32 id) const;
@@ -79,7 +85,13 @@ private:
std::shared_ptr<Nvidia::Module> nvdrv;
- std::vector<Display> displays;
+ std::array<Display, 5> displays{{
+ {0, "Default"},
+ {1, "External"},
+ {2, "Edid"},
+ {3, "Internal"},
+ {4, "Null"},
+ }};
std::vector<std::shared_ptr<BufferQueue>> buffer_queues;
/// Id to use for the next layer that is created, this counter is shared among all displays.
diff --git a/src/core/hle/service/pctl/module.cpp b/src/core/hle/service/pctl/module.cpp
index 4fd185f69..6081f41e1 100644
--- a/src/core/hle/service/pctl/module.cpp
+++ b/src/core/hle/service/pctl/module.cpp
@@ -114,29 +114,33 @@ public:
private:
void Initialize(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_PCTL, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 0};
rb.Push(RESULT_SUCCESS);
}
void CheckFreeCommunicationPermission(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_PCTL, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
};
void Module::Interface::CreateService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_PCTL, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IParentalControlService>();
- LOG_DEBUG(Service_PCTL, "called");
}
void Module::Interface::CreateServiceWithoutInitialize(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_PCTL, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IParentalControlService>();
- LOG_DEBUG(Service_PCTL, "called");
}
Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
diff --git a/src/core/hle/service/pm/pm.cpp b/src/core/hle/service/pm/pm.cpp
index 6ec35ca60..6b27dc4a3 100644
--- a/src/core/hle/service/pm/pm.cpp
+++ b/src/core/hle/service/pm/pm.cpp
@@ -13,19 +13,30 @@ public:
explicit BootMode() : ServiceFramework{"pm:bm"} {
static const FunctionInfo functions[] = {
{0, &BootMode::GetBootMode, "GetBootMode"},
- {1, nullptr, "SetMaintenanceBoot"},
+ {1, &BootMode::SetMaintenanceBoot, "SetMaintenanceBoot"},
};
RegisterHandlers(functions);
}
private:
void GetBootMode(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_PM, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
- rb.Push<u32>(static_cast<u32>(SystemBootMode::Normal)); // Normal boot mode
+ rb.PushEnum(boot_mode);
+ }
+ void SetMaintenanceBoot(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_PM, "called");
+
+ boot_mode = SystemBootMode::Maintenance;
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
}
+
+ SystemBootMode boot_mode = SystemBootMode::Normal;
};
class DebugMonitor final : public ServiceFramework<DebugMonitor> {
diff --git a/src/core/hle/service/pm/pm.h b/src/core/hle/service/pm/pm.h
index 370f2ed72..cc8d3f215 100644
--- a/src/core/hle/service/pm/pm.h
+++ b/src/core/hle/service/pm/pm.h
@@ -9,7 +9,12 @@ class ServiceManager;
}
namespace Service::PM {
-enum class SystemBootMode : u32 { Normal = 0, Maintenance = 1 };
+
+enum class SystemBootMode {
+ Normal,
+ Maintenance,
+};
+
/// Registers all PM services with the specified service manager.
void InstallInterfaces(SM::ServiceManager& service_manager);
diff --git a/src/core/hle/service/psc/psc.cpp b/src/core/hle/service/psc/psc.cpp
index bbad870a2..0ba0a4076 100644
--- a/src/core/hle/service/psc/psc.cpp
+++ b/src/core/hle/service/psc/psc.cpp
@@ -61,11 +61,11 @@ public:
private:
void GetPmModule(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_PSC, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IPmModule>();
-
- LOG_DEBUG(Service_PSC, "called");
}
};
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index 1ec340466..d25b80ab0 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -70,10 +70,6 @@
#include "core/hle/service/vi/vi.h"
#include "core/hle/service/wlan/wlan.h"
-using Kernel::ClientPort;
-using Kernel::ServerPort;
-using Kernel::SharedPtr;
-
namespace Service {
/**
@@ -101,33 +97,33 @@ ServiceFrameworkBase::ServiceFrameworkBase(const char* service_name, u32 max_ses
ServiceFrameworkBase::~ServiceFrameworkBase() = default;
void ServiceFrameworkBase::InstallAsService(SM::ServiceManager& service_manager) {
- ASSERT(port == nullptr);
- port = service_manager.RegisterService(service_name, max_sessions).Unwrap();
+ ASSERT(!port_installed);
+
+ auto port = service_manager.RegisterService(service_name, max_sessions).Unwrap();
port->SetHleHandler(shared_from_this());
+ port_installed = true;
}
void ServiceFrameworkBase::InstallAsNamedPort() {
- ASSERT(port == nullptr);
+ ASSERT(!port_installed);
auto& kernel = Core::System::GetInstance().Kernel();
- SharedPtr<ServerPort> server_port;
- SharedPtr<ClientPort> client_port;
- std::tie(server_port, client_port) =
- ServerPort::CreatePortPair(kernel, max_sessions, service_name);
+ auto [server_port, client_port] =
+ Kernel::ServerPort::CreatePortPair(kernel, max_sessions, service_name);
server_port->SetHleHandler(shared_from_this());
kernel.AddNamedPort(service_name, std::move(client_port));
+ port_installed = true;
}
Kernel::SharedPtr<Kernel::ClientPort> ServiceFrameworkBase::CreatePort() {
- ASSERT(port == nullptr);
+ ASSERT(!port_installed);
auto& kernel = Core::System::GetInstance().Kernel();
- Kernel::SharedPtr<Kernel::ServerPort> server_port;
- Kernel::SharedPtr<Kernel::ClientPort> client_port;
- std::tie(server_port, client_port) =
+ auto [server_port, client_port] =
Kernel::ServerPort::CreatePortPair(kernel, max_sessions, service_name);
- port = MakeResult<Kernel::SharedPtr<Kernel::ServerPort>>(std::move(server_port)).Unwrap();
+ auto port = MakeResult(std::move(server_port)).Unwrap();
port->SetHleHandler(shared_from_this());
+ port_installed = true;
return client_port;
}
@@ -152,8 +148,7 @@ void ServiceFrameworkBase::ReportUnimplementedFunction(Kernel::HLERequestContext
}
buf.push_back('}');
- LOG_ERROR(Service, "unknown / unimplemented {}", fmt::to_string(buf));
- UNIMPLEMENTED();
+ UNIMPLEMENTED_MSG("Unknown / unimplemented {}", fmt::to_string(buf));
}
void ServiceFrameworkBase::InvokeRequest(Kernel::HLERequestContext& ctx) {
diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h
index 98483ecf1..029533628 100644
--- a/src/core/hle/service/service.h
+++ b/src/core/hle/service/service.h
@@ -96,11 +96,9 @@ private:
/// Maximum number of concurrent sessions that this service can handle.
u32 max_sessions;
- /**
- * Port where incoming connections will be received. Only created when InstallAsService() or
- * InstallAsNamedPort() are called.
- */
- Kernel::SharedPtr<Kernel::ServerPort> port;
+ /// Flag to store if a port was already create/installed to detect multiple install attempts,
+ /// which is not supported.
+ bool port_installed = false;
/// Function used to safely up-cast pointers to the derived class before invoking a handler.
InvokerFn* handler_invoker;
diff --git a/src/core/hle/service/set/set.cpp b/src/core/hle/service/set/set.cpp
index 9e5af7839..1afc43f75 100644
--- a/src/core/hle/service/set/set.cpp
+++ b/src/core/hle/service/set/set.cpp
@@ -35,6 +35,8 @@ constexpr std::array<LanguageCode, 17> available_language_codes = {{
constexpr std::size_t pre4_0_0_max_entries = 0xF;
constexpr std::size_t post4_0_0_max_entries = 0x40;
+constexpr ResultCode ERR_INVALID_LANGUAGE{ErrorModule::Settings, 625};
+
LanguageCode GetLanguageCodeFromIndex(std::size_t index) {
return available_language_codes.at(index);
}
@@ -49,38 +51,54 @@ static std::array<LanguageCode, size> MakeLanguageCodeSubset() {
static void PushResponseLanguageCode(Kernel::HLERequestContext& ctx, std::size_t max_size) {
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
- if (available_language_codes.size() > max_size)
+ if (available_language_codes.size() > max_size) {
rb.Push(static_cast<u32>(max_size));
- else
+ } else {
rb.Push(static_cast<u32>(available_language_codes.size()));
+ }
}
void SET::GetAvailableLanguageCodes(Kernel::HLERequestContext& ctx) {
- if (available_language_codes.size() > pre4_0_0_max_entries)
+ LOG_DEBUG(Service_SET, "called");
+
+ if (available_language_codes.size() > pre4_0_0_max_entries) {
ctx.WriteBuffer(MakeLanguageCodeSubset<pre4_0_0_max_entries>());
- else
+ } else {
ctx.WriteBuffer(available_language_codes);
-
+ }
PushResponseLanguageCode(ctx, pre4_0_0_max_entries);
+}
- LOG_DEBUG(Service_SET, "called");
+void SET::MakeLanguageCode(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto index = rp.Pop<u32>();
+
+ if (index >= available_language_codes.size()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERR_INVALID_LANGUAGE);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushEnum(available_language_codes[index]);
}
void SET::GetAvailableLanguageCodes2(Kernel::HLERequestContext& ctx) {
- if (available_language_codes.size() > post4_0_0_max_entries)
+ LOG_DEBUG(Service_SET, "called");
+
+ if (available_language_codes.size() > post4_0_0_max_entries) {
ctx.WriteBuffer(MakeLanguageCodeSubset<post4_0_0_max_entries>());
- else
+ } else {
ctx.WriteBuffer(available_language_codes);
-
+ }
PushResponseLanguageCode(ctx, post4_0_0_max_entries);
-
- LOG_DEBUG(Service_SET, "called");
}
void SET::GetAvailableLanguageCodeCount(Kernel::HLERequestContext& ctx) {
- PushResponseLanguageCode(ctx, pre4_0_0_max_entries);
-
LOG_DEBUG(Service_SET, "called");
+
+ PushResponseLanguageCode(ctx, pre4_0_0_max_entries);
}
void SET::GetAvailableLanguageCodeCount2(Kernel::HLERequestContext& ctx) {
@@ -90,18 +108,18 @@ void SET::GetAvailableLanguageCodeCount2(Kernel::HLERequestContext& ctx) {
}
void SET::GetLanguageCode(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_SET, "called {}", Settings::values.language_index);
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
- rb.Push(static_cast<u64>(available_language_codes[Settings::values.language_index]));
-
- LOG_DEBUG(Service_SET, "called {}", Settings::values.language_index);
+ rb.PushEnum(available_language_codes[Settings::values.language_index]);
}
SET::SET() : ServiceFramework("set") {
static const FunctionInfo functions[] = {
{0, &SET::GetLanguageCode, "GetLanguageCode"},
{1, &SET::GetAvailableLanguageCodes, "GetAvailableLanguageCodes"},
- {2, nullptr, "MakeLanguageCode"},
+ {2, &SET::MakeLanguageCode, "MakeLanguageCode"},
{3, &SET::GetAvailableLanguageCodeCount, "GetAvailableLanguageCodeCount"},
{4, nullptr, "GetRegionCode"},
{5, &SET::GetAvailableLanguageCodes2, "GetAvailableLanguageCodes2"},
diff --git a/src/core/hle/service/set/set.h b/src/core/hle/service/set/set.h
index 266f13e46..31f9cb296 100644
--- a/src/core/hle/service/set/set.h
+++ b/src/core/hle/service/set/set.h
@@ -38,6 +38,7 @@ public:
private:
void GetLanguageCode(Kernel::HLERequestContext& ctx);
void GetAvailableLanguageCodes(Kernel::HLERequestContext& ctx);
+ void MakeLanguageCode(Kernel::HLERequestContext& ctx);
void GetAvailableLanguageCodes2(Kernel::HLERequestContext& ctx);
void GetAvailableLanguageCodeCount(Kernel::HLERequestContext& ctx);
void GetAvailableLanguageCodeCount2(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/set/set_sys.cpp b/src/core/hle/service/set/set_sys.cpp
index 41efca31c..c9b4da5b0 100644
--- a/src/core/hle/service/set/set_sys.cpp
+++ b/src/core/hle/service/set/set_sys.cpp
@@ -10,22 +10,22 @@
namespace Service::Set {
void SET_SYS::GetColorSetId(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_SET, "called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushEnum(color_set);
-
- LOG_DEBUG(Service_SET, "called");
}
void SET_SYS::SetColorSetId(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_SET, "called");
+
IPC::RequestParser rp{ctx};
color_set = rp.PopEnum<ColorSet>();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
-
- LOG_DEBUG(Service_SET, "called");
}
SET_SYS::SET_SYS() : ServiceFramework("set:sys") {
diff --git a/src/core/hle/service/sm/controller.cpp b/src/core/hle/service/sm/controller.cpp
index 98f6e4111..74da4d5e6 100644
--- a/src/core/hle/service/sm/controller.cpp
+++ b/src/core/hle/service/sm/controller.cpp
@@ -14,25 +14,26 @@ namespace Service::SM {
void Controller::ConvertSessionToDomain(Kernel::HLERequestContext& ctx) {
ASSERT_MSG(ctx.Session()->IsSession(), "Session is already a domain");
+ LOG_DEBUG(Service, "called, server_session={}", ctx.Session()->GetObjectId());
ctx.Session()->ConvertToDomain();
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(1); // Converted sessions start with 1 request handler
-
- LOG_DEBUG(Service, "called, server_session={}", ctx.Session()->GetObjectId());
}
void Controller::DuplicateSession(Kernel::HLERequestContext& ctx) {
// TODO(bunnei): This is just creating a new handle to the same Session. I assume this is wrong
// and that we probably want to actually make an entirely new Session, but we still need to
// verify this on hardware.
+ LOG_DEBUG(Service, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles};
rb.Push(RESULT_SUCCESS);
Kernel::SharedPtr<Kernel::ClientSession> session{ctx.Session()->parent->client};
rb.PushMoveObjects(session);
- LOG_DEBUG(Service, "called, session={}", session->GetObjectId());
+ LOG_DEBUG(Service, "session={}", session->GetObjectId());
}
void Controller::DuplicateSessionEx(Kernel::HLERequestContext& ctx) {
@@ -42,11 +43,11 @@ void Controller::DuplicateSessionEx(Kernel::HLERequestContext& ctx) {
}
void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u16>(0x500);
-
- LOG_WARNING(Service, "(STUBBED) called");
}
Controller::Controller() : ServiceFramework("IpcController") {
diff --git a/src/core/hle/service/sm/sm.cpp b/src/core/hle/service/sm/sm.cpp
index 9ca8483a5..142929124 100644
--- a/src/core/hle/service/sm/sm.cpp
+++ b/src/core/hle/service/sm/sm.cpp
@@ -54,13 +54,11 @@ ResultVal<Kernel::SharedPtr<Kernel::ServerPort>> ServiceManager::RegisterService
return ERR_ALREADY_REGISTERED;
auto& kernel = Core::System::GetInstance().Kernel();
- Kernel::SharedPtr<Kernel::ServerPort> server_port;
- Kernel::SharedPtr<Kernel::ClientPort> client_port;
- std::tie(server_port, client_port) =
+ auto [server_port, client_port] =
Kernel::ServerPort::CreatePortPair(kernel, max_sessions, name);
registered_services.emplace(std::move(name), std::move(client_port));
- return MakeResult<Kernel::SharedPtr<Kernel::ServerPort>>(std::move(server_port));
+ return MakeResult(std::move(server_port));
}
ResultCode ServiceManager::UnregisterService(const std::string& name) {
@@ -83,7 +81,7 @@ ResultVal<Kernel::SharedPtr<Kernel::ClientPort>> ServiceManager::GetServicePort(
return ERR_SERVICE_NOT_REGISTERED;
}
- return MakeResult<Kernel::SharedPtr<Kernel::ClientPort>>(it->second);
+ return MakeResult(it->second);
}
ResultVal<Kernel::SharedPtr<Kernel::ClientSession>> ServiceManager::ConnectToService(
@@ -103,9 +101,10 @@ SM::~SM() = default;
* 0: ResultCode
*/
void SM::Initialize(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_SM, "called");
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_SM, "called");
}
void SM::GetService(Kernel::HLERequestContext& ctx) {
@@ -146,12 +145,13 @@ void SM::RegisterService(Kernel::HLERequestContext& ctx) {
const std::string name(name_buf.begin(), end);
- const auto unk_bool = static_cast<bool>(rp.PopRaw<u32>());
- const auto session_count = rp.PopRaw<u32>();
+ const auto is_light = static_cast<bool>(rp.PopRaw<u32>());
+ const auto max_session_count = rp.PopRaw<u32>();
- LOG_DEBUG(Service_SM, "called with unk_bool={}", unk_bool);
+ LOG_DEBUG(Service_SM, "called with name={}, max_session_count={}, is_light={}", name,
+ max_session_count, is_light);
- auto handle = service_manager->RegisterService(name, session_count);
+ auto handle = service_manager->RegisterService(name, max_session_count);
if (handle.Failed()) {
LOG_ERROR(Service_SM, "failed to register service with error_code={:08X}",
handle.Code().raw);
@@ -172,6 +172,7 @@ void SM::UnregisterService(Kernel::HLERequestContext& ctx) {
const auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
const std::string name(name_buf.begin(), end);
+ LOG_DEBUG(Service_SM, "called with name={}", name);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(service_manager->UnregisterService(name));
diff --git a/src/core/hle/service/spl/module.cpp b/src/core/hle/service/spl/module.cpp
index b2de2a818..8db0c2f13 100644
--- a/src/core/hle/service/spl/module.cpp
+++ b/src/core/hle/service/spl/module.cpp
@@ -24,6 +24,8 @@ Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
Module::Interface::~Interface() = default;
void Module::Interface::GetRandomBytes(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_SPL, "called");
+
IPC::RequestParser rp{ctx};
std::size_t size = ctx.GetWriteBufferSize();
@@ -36,7 +38,6 @@ void Module::Interface::GetRandomBytes(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_SPL, "called");
}
void InstallInterfaces(SM::ServiceManager& service_manager) {
diff --git a/src/core/hle/service/ssl/ssl.cpp b/src/core/hle/service/ssl/ssl.cpp
index bc4f7a437..af40a1815 100644
--- a/src/core/hle/service/ssl/ssl.cpp
+++ b/src/core/hle/service/ssl/ssl.cpp
@@ -69,6 +69,7 @@ public:
private:
void SetOption(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_SSL, "(STUBBED) called");
+
IPC::RequestParser rp{ctx};
IPC::ResponseBuilder rb{ctx, 2};
@@ -114,6 +115,7 @@ private:
void SetInterfaceVersion(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_SSL, "called");
+
IPC::RequestParser rp{ctx};
ssl_version = rp.Pop<u32>();
diff --git a/src/core/hle/service/time/time.cpp b/src/core/hle/service/time/time.cpp
index e561a0c52..c13640ad8 100644
--- a/src/core/hle/service/time/time.cpp
+++ b/src/core/hle/service/time/time.cpp
@@ -12,9 +12,16 @@
#include "core/hle/kernel/client_session.h"
#include "core/hle/service/time/interface.h"
#include "core/hle/service/time/time.h"
+#include "core/settings.h"
namespace Service::Time {
+static std::chrono::seconds GetSecondsSinceEpoch() {
+ return std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()) +
+ Settings::values.custom_rtc_differential;
+}
+
static void PosixToCalendar(u64 posix_time, CalendarTime& calendar_time,
CalendarAdditionalInfo& additional_info,
[[maybe_unused]] const TimeZoneRule& /*rule*/) {
@@ -68,10 +75,9 @@ public:
private:
void GetCurrentTime(Kernel::HLERequestContext& ctx) {
- const s64 time_since_epoch{std::chrono::duration_cast<std::chrono::seconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count()};
+ const s64 time_since_epoch{GetSecondsSinceEpoch().count()};
LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u64>(time_since_epoch);
@@ -79,6 +85,7 @@ private:
void GetSystemClockContext(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_Time, "(STUBBED) called");
+
SystemClockContext system_clock_ontext{};
IPC::ResponseBuilder rb{ctx, (sizeof(SystemClockContext) / 4) + 2};
rb.Push(RESULT_SUCCESS);
@@ -98,6 +105,7 @@ public:
private:
void GetCurrentTimePoint(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called");
+
SteadyClockTimePoint steady_clock_time_point{
CoreTiming::cyclesToMs(CoreTiming::GetTicks()) / 1000};
IPC::ResponseBuilder rb{ctx, (sizeof(SteadyClockTimePoint) / 4) + 2};
@@ -130,6 +138,7 @@ private:
void GetDeviceLocationName(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, (sizeof(LocationName) / 4) + 2};
rb.Push(RESULT_SUCCESS);
rb.PushRaw(location_name);
@@ -137,6 +146,7 @@ private:
void GetTotalLocationNameCount(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_Time, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0);
@@ -154,7 +164,6 @@ private:
void ToCalendarTime(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 posix_time = rp.Pop<u64>();
-
LOG_WARNING(Service_Time, "(STUBBED) called, posix_time=0x{:016X}", posix_time);
TimeZoneRule time_zone_rule{};
@@ -175,7 +184,6 @@ private:
void ToCalendarTimeWithMyRule(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 posix_time = rp.Pop<u64>();
-
LOG_WARNING(Service_Time, "(STUBBED) called, posix_time=0x{:016X}", posix_time);
CalendarTime calendar_time{2018, 1, 1, 0, 0, 0};
@@ -192,6 +200,7 @@ private:
void ToPosixTime(Kernel::HLERequestContext& ctx) {
// TODO(ogniK): Figure out how to handle multiple times
LOG_WARNING(Service_Time, "(STUBBED) called");
+
IPC::RequestParser rp{ctx};
auto calendar_time = rp.PopRaw<CalendarTime>();
auto posix_time = CalendarToPosix(calendar_time, {});
@@ -204,6 +213,7 @@ private:
void ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_Time, "(STUBBED) called");
+
IPC::RequestParser rp{ctx};
auto calendar_time = rp.PopRaw<CalendarTime>();
auto posix_time = CalendarToPosix(calendar_time, {});
@@ -216,69 +226,73 @@ private:
};
void Module::Interface::GetStandardUserSystemClock(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystemClock>();
- LOG_DEBUG(Service_Time, "called");
}
void Module::Interface::GetStandardNetworkSystemClock(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystemClock>();
- LOG_DEBUG(Service_Time, "called");
}
void Module::Interface::GetStandardSteadyClock(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISteadyClock>();
- LOG_DEBUG(Service_Time, "called");
}
void Module::Interface::GetTimeZoneService(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ITimeZoneService>();
- LOG_DEBUG(Service_Time, "called");
}
void Module::Interface::GetStandardLocalSystemClock(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<ISystemClock>();
- LOG_DEBUG(Service_Time, "called");
}
void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called");
IPC::RequestParser rp{ctx};
- auto unknown_u8 = rp.PopRaw<u8>();
+ const auto initial_type = rp.PopRaw<u8>();
- ClockSnapshot clock_snapshot{};
-
- const s64 time_since_epoch{std::chrono::duration_cast<std::chrono::seconds>(
- std::chrono::system_clock::now().time_since_epoch())
- .count()};
- CalendarTime calendar_time{};
+ const s64 time_since_epoch{GetSecondsSinceEpoch().count()};
const std::time_t time(time_since_epoch);
const std::tm* tm = std::localtime(&time);
if (tm == nullptr) {
+ LOG_ERROR(Service_Time, "tm is a nullptr");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultCode(-1)); // TODO(ogniK): Find appropriate error code
return;
}
- SteadyClockTimePoint steady_clock_time_point{CoreTiming::cyclesToMs(CoreTiming::GetTicks()) /
- 1000};
- LocationName location_name{"UTC"};
+ const SteadyClockTimePoint steady_clock_time_point{
+ CoreTiming::cyclesToMs(CoreTiming::GetTicks()) / 1000, {}};
+
+ CalendarTime calendar_time{};
calendar_time.year = tm->tm_year + 1900;
calendar_time.month = tm->tm_mon + 1;
calendar_time.day = tm->tm_mday;
calendar_time.hour = tm->tm_hour;
calendar_time.minute = tm->tm_min;
calendar_time.second = tm->tm_sec;
+
+ ClockSnapshot clock_snapshot{};
clock_snapshot.system_posix_time = time_since_epoch;
clock_snapshot.network_posix_time = time_since_epoch;
clock_snapshot.system_calendar_time = calendar_time;
@@ -291,9 +305,10 @@ void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
clock_snapshot.network_calendar_info = additional_info;
clock_snapshot.steady_clock_timepoint = steady_clock_time_point;
- clock_snapshot.location_name = location_name;
+ clock_snapshot.location_name = LocationName{"UTC"};
clock_snapshot.clock_auto_adjustment_enabled = 1;
- clock_snapshot.ipc_u8 = unknown_u8;
+ clock_snapshot.type = initial_type;
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
ctx.WriteBuffer(&clock_snapshot, sizeof(ClockSnapshot));
diff --git a/src/core/hle/service/time/time.h b/src/core/hle/service/time/time.h
index ea43fbea7..f11affe95 100644
--- a/src/core/hle/service/time/time.h
+++ b/src/core/hle/service/time/time.h
@@ -22,7 +22,6 @@ struct CalendarTime {
u8 hour;
u8 minute;
u8 second;
- INSERT_PADDING_BYTES(1);
};
static_assert(sizeof(CalendarTime) == 0x8, "CalendarTime structure has incorrect size");
@@ -30,7 +29,7 @@ struct CalendarAdditionalInfo {
u32_le day_of_week;
u32_le day_of_year;
std::array<u8, 8> name;
- INSERT_PADDING_BYTES(1);
+ u8 is_dst;
s32_le utc_offset;
};
static_assert(sizeof(CalendarAdditionalInfo) == 0x18,
@@ -42,8 +41,10 @@ struct TimeZoneRule {
};
struct SteadyClockTimePoint {
+ using SourceID = std::array<u8, 16>;
+
u64_le value;
- INSERT_PADDING_WORDS(4);
+ SourceID source_id;
};
static_assert(sizeof(SteadyClockTimePoint) == 0x18, "SteadyClockTimePoint is incorrect size");
@@ -66,8 +67,9 @@ struct ClockSnapshot {
SteadyClockTimePoint steady_clock_timepoint;
LocationName location_name;
u8 clock_auto_adjustment_enabled;
- u8 ipc_u8;
- INSERT_PADDING_BYTES(2);
+ u8 type;
+ u8 version;
+ INSERT_PADDING_BYTES(1);
};
static_assert(sizeof(ClockSnapshot) == 0xd0, "ClockSnapshot is an invalid size");
diff --git a/src/core/hle/service/usb/usb.cpp b/src/core/hle/service/usb/usb.cpp
index f0a831d45..58a9845fc 100644
--- a/src/core/hle/service/usb/usb.cpp
+++ b/src/core/hle/service/usb/usb.cpp
@@ -73,7 +73,7 @@ public:
{3, nullptr, "Populate"},
{4, nullptr, "PostBufferAsync"},
{5, nullptr, "GetXferReport"},
- {6, nullptr, "Unknown2"},
+ {6, nullptr, "PostBufferMultiAsync"},
{7, nullptr, "Unknown3"},
{8, nullptr, "Unknown4"},
};
@@ -159,11 +159,11 @@ public:
private:
void GetPdSession(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_USB, "called");
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
rb.PushIpcInterface<IPdSession>();
-
- LOG_DEBUG(Service_USB, "called");
}
};
diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp
index a72416084..0f2c25182 100644
--- a/src/core/hle/service/vi/vi.cpp
+++ b/src/core/hle/service/vi/vi.cpp
@@ -18,7 +18,9 @@
#include "common/swap.h"
#include "core/core_timing.h"
#include "core/hle/ipc_helpers.h"
-#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/readable_event.h"
+#include "core/hle/kernel/thread.h"
+#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nvdrv/nvdrv.h"
#include "core/hle/service/nvflinger/buffer_queue.h"
#include "core/hle/service/nvflinger/nvflinger.h"
@@ -30,12 +32,26 @@
namespace Service::VI {
+constexpr ResultCode ERR_OPERATION_FAILED{ErrorModule::VI, 1};
+constexpr ResultCode ERR_UNSUPPORTED{ErrorModule::VI, 6};
+
struct DisplayInfo {
+ /// The name of this particular display.
char display_name[0x40]{"Default"};
- u64 unknown_1{1};
- u64 unknown_2{1};
- u64 width{1280};
- u64 height{720};
+
+ /// Whether or not the display has a limited number of layers.
+ u8 has_limited_layers{1};
+ INSERT_PADDING_BYTES(7){};
+
+ /// Indicates the total amount of layers supported by the display.
+ /// @note This is only valid if has_limited_layers is set.
+ u64 max_layers{1};
+
+ /// Maximum width in pixels.
+ u64 width{1920};
+
+ /// Maximum height in pixels.
+ u64 height{1080};
};
static_assert(sizeof(DisplayInfo) == 0x60, "DisplayInfo has wrong size");
@@ -501,12 +517,14 @@ private:
void TransactParcel(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- u32 id = rp.Pop<u32>();
- auto transaction = static_cast<TransactionId>(rp.Pop<u32>());
- u32 flags = rp.Pop<u32>();
- auto buffer_queue = nv_flinger->GetBufferQueue(id);
+ const u32 id = rp.Pop<u32>();
+ const auto transaction = static_cast<TransactionId>(rp.Pop<u32>());
+ const u32 flags = rp.Pop<u32>();
+
+ LOG_DEBUG(Service_VI, "called. id=0x{:08X} transaction={:X}, flags=0x{:08X}", id,
+ static_cast<u32>(transaction), flags);
- LOG_DEBUG(Service_VI, "called, transaction={:X}", static_cast<u32>(transaction));
+ auto buffer_queue = nv_flinger->GetBufferQueue(id);
if (transaction == TransactionId::Connect) {
IGBPConnectRequestParcel request{ctx.ReadBuffer()};
@@ -542,12 +560,14 @@ private:
// Repeat TransactParcel DequeueBuffer when a buffer is available
auto buffer_queue = nv_flinger->GetBufferQueue(id);
std::optional<u32> slot = buffer_queue->DequeueBuffer(width, height);
+ ASSERT_MSG(slot != std::nullopt, "Could not dequeue buffer.");
+
IGBPDequeueBufferResponseParcel response{*slot};
ctx.WriteBuffer(response.Serialize());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
},
- buffer_queue->GetBufferWaitEvent());
+ buffer_queue->GetWritableBufferWaitEvent());
}
} else if (transaction == TransactionId::RequestBuffer) {
IGBPRequestBufferRequestParcel request{ctx.ReadBuffer()};
@@ -590,26 +610,27 @@ private:
void AdjustRefcount(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- u32 id = rp.Pop<u32>();
- s32 addval = rp.PopRaw<s32>();
- u32 type = rp.Pop<u32>();
+ const u32 id = rp.Pop<u32>();
+ const s32 addval = rp.PopRaw<s32>();
+ const u32 type = rp.Pop<u32>();
LOG_WARNING(Service_VI, "(STUBBED) called id={}, addval={:08X}, type={:08X}", id, addval,
type);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetNativeHandle(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- u32 id = rp.Pop<u32>();
- u32 unknown = rp.Pop<u32>();
+ const u32 id = rp.Pop<u32>();
+ const u32 unknown = rp.Pop<u32>();
- auto buffer_queue = nv_flinger->GetBufferQueue(id);
+ LOG_WARNING(Service_VI, "(STUBBED) called id={}, unknown={:08X}", id, unknown);
- // TODO(Subv): Find out what this actually is.
+ const auto buffer_queue = nv_flinger->GetBufferQueue(id);
- LOG_WARNING(Service_VI, "(STUBBED) called id={}, unknown={:08X}", id, unknown);
+ // TODO(Subv): Find out what this actually is.
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(buffer_queue->GetBufferWaitEvent());
@@ -672,26 +693,33 @@ public:
private:
void SetLayerZ(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u64 layer_id = rp.Pop<u64>();
- u64 z_value = rp.Pop<u64>();
+ const u64 layer_id = rp.Pop<u64>();
+ const u64 z_value = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. layer_id=0x{:016X}, z_value=0x{:016X}", layer_id,
+ z_value);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
+ // This function currently does nothing but return a success error code in
+ // the vi library itself, so do the same thing, but log out the passed in values.
void SetLayerVisibility(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- u64 layer_id = rp.Pop<u64>();
- bool visibility = rp.Pop<bool>();
+ const u64 layer_id = rp.Pop<u64>();
+ const bool visibility = rp.Pop<bool>();
+
+ LOG_DEBUG(Service_VI, "called, layer_id=0x{:08X}, visibility={}", layer_id, visibility);
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_VI, "(STUBBED) called, layer_id=0x{:08X}, visibility={}", layer_id,
- visibility);
}
void GetDisplayMode(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_VI, "(STUBBED) called");
+
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(RESULT_SUCCESS);
@@ -707,10 +735,8 @@ private:
static_cast<u32>(Settings::values.resolution_factor));
}
- rb.PushRaw<float>(60.0f);
+ rb.PushRaw<float>(60.0f); // This wouldn't seem to be correct for 30 fps games.
rb.Push<u32>(0);
-
- LOG_DEBUG(Service_VI, "called");
}
};
@@ -792,23 +818,27 @@ public:
private:
void CloseDisplay(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u64 display = rp.Pop<u64>();
+ const u64 display = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. display=0x{:016X}", display);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void CreateManagedLayer(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u32 unknown = rp.Pop<u32>();
+ const u32 unknown = rp.Pop<u32>();
rp.Skip(1, false);
- u64 display = rp.Pop<u64>();
- u64 aruid = rp.Pop<u64>();
+ const u64 display = rp.Pop<u64>();
+ const u64 aruid = rp.Pop<u64>();
- u64 layer_id = nv_flinger->CreateLayer(display);
+ LOG_WARNING(Service_VI,
+ "(STUBBED) called. unknown=0x{:08X}, display=0x{:016X}, aruid=0x{:016X}",
+ unknown, display, aruid);
+
+ const u64 layer_id = nv_flinger->CreateLayer(display);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
@@ -816,10 +846,12 @@ private:
}
void AddToLayerStack(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u32 stack = rp.Pop<u32>();
- u64 layer_id = rp.Pop<u64>();
+ const u32 stack = rp.Pop<u32>();
+ const u64 layer_id = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. stack=0x{:08X}, layer_id=0x{:016X}", stack,
+ layer_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
@@ -827,12 +859,14 @@ private:
void SetLayerVisibility(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- u64 layer_id = rp.Pop<u64>();
- bool visibility = rp.Pop<bool>();
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+ const u64 layer_id = rp.Pop<u64>();
+ const bool visibility = rp.Pop<bool>();
+
LOG_WARNING(Service_VI, "(STUBBED) called, layer_id=0x{:X}, visibility={}", layer_id,
visibility);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
}
std::shared_ptr<NVFlinger::NVFlinger> nv_flinger;
@@ -844,6 +878,22 @@ public:
~IApplicationDisplayService() = default;
private:
+ enum class ConvertedScaleMode : u64 {
+ Freeze = 0,
+ ScaleToWindow = 1,
+ ScaleAndCrop = 2,
+ None = 3,
+ PreserveAspectRatio = 4,
+ };
+
+ enum class NintendoScaleMode : u32 {
+ None = 0,
+ Freeze = 1,
+ ScaleToWindow = 2,
+ ScaleAndCrop = 3,
+ PreserveAspectRatio = 4,
+ };
+
void GetRelayService(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_VI, "(STUBBED) called");
@@ -878,11 +928,25 @@ private:
void OpenDisplay(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_VI, "(STUBBED) called");
+
IPC::RequestParser rp{ctx};
- auto name_buf = rp.PopRaw<std::array<u8, 0x40>>();
- auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
+ const auto name_buf = rp.PopRaw<std::array<char, 0x40>>();
+
+ OpenDisplayImpl(ctx, std::string_view{name_buf.data(), name_buf.size()});
+ }
- std::string name(name_buf.begin(), end);
+ void OpenDefaultDisplay(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_VI, "called");
+
+ OpenDisplayImpl(ctx, "Default");
+ }
+
+ void OpenDisplayImpl(Kernel::HLERequestContext& ctx, std::string_view name) {
+ const auto trim_pos = name.find('\0');
+
+ if (trim_pos != std::string_view::npos) {
+ name.remove_suffix(name.size() - trim_pos);
+ }
ASSERT_MSG(name == "Default", "Non-default displays aren't supported yet");
@@ -892,46 +956,71 @@ private:
}
void CloseDisplay(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u64 display_id = rp.Pop<u64>();
+ const u64 display_id = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. display_id=0x{:016X}", display_id);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ }
+
+ // This literally does nothing internally in the actual service itself,
+ // and just returns a successful result code regardless of the input.
+ void SetDisplayEnabled(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_VI, "called.");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetDisplayResolution(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u64 display_id = rp.Pop<u64>();
+ const u64 display_id = rp.Pop<u64>();
+
+ LOG_DEBUG(Service_VI, "called. display_id=0x{:016X}", display_id);
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(RESULT_SUCCESS);
- if (Settings::values.use_docked_mode) {
- rb.Push(static_cast<u64>(DisplayResolution::DockedWidth) *
- static_cast<u32>(Settings::values.resolution_factor));
- rb.Push(static_cast<u64>(DisplayResolution::DockedHeight) *
- static_cast<u32>(Settings::values.resolution_factor));
- } else {
- rb.Push(static_cast<u64>(DisplayResolution::UndockedWidth) *
- static_cast<u32>(Settings::values.resolution_factor));
- rb.Push(static_cast<u64>(DisplayResolution::UndockedHeight) *
- static_cast<u32>(Settings::values.resolution_factor));
- }
+ // This only returns the fixed values of 1280x720 and makes no distinguishing
+ // between docked and undocked dimensions. We take the liberty of applying
+ // the resolution scaling factor here.
+ rb.Push(static_cast<u64>(DisplayResolution::UndockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u64>(DisplayResolution::UndockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
}
void SetLayerScalingMode(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u32 scaling_mode = rp.Pop<u32>();
- u64 unknown = rp.Pop<u64>();
+ const auto scaling_mode = rp.PopEnum<NintendoScaleMode>();
+ const u64 unknown = rp.Pop<u64>();
+
+ LOG_DEBUG(Service_VI, "called. scaling_mode=0x{:08X}, unknown=0x{:016X}",
+ static_cast<u32>(scaling_mode), unknown);
IPC::ResponseBuilder rb{ctx, 2};
+
+ if (scaling_mode > NintendoScaleMode::PreserveAspectRatio) {
+ LOG_ERROR(Service_VI, "Invalid scaling mode provided.");
+ rb.Push(ERR_OPERATION_FAILED);
+ return;
+ }
+
+ if (scaling_mode != NintendoScaleMode::ScaleToWindow &&
+ scaling_mode != NintendoScaleMode::PreserveAspectRatio) {
+ LOG_ERROR(Service_VI, "Unsupported scaling mode supplied.");
+ rb.Push(ERR_UNSUPPORTED);
+ return;
+ }
+
rb.Push(RESULT_SUCCESS);
}
void ListDisplays(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_VI, "(STUBBED) called");
+
IPC::RequestParser rp{ctx};
DisplayInfo display_info;
display_info.width *= static_cast<u64>(Settings::values.resolution_factor);
@@ -940,22 +1029,22 @@ private:
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u64>(1);
- LOG_WARNING(Service_VI, "(STUBBED) called");
}
void OpenLayer(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_VI, "called");
IPC::RequestParser rp{ctx};
- auto name_buf = rp.PopRaw<std::array<u8, 0x40>>();
- auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
+ const auto name_buf = rp.PopRaw<std::array<u8, 0x40>>();
+ const auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
- std::string display_name(name_buf.begin(), end);
+ const std::string display_name(name_buf.begin(), end);
- u64 layer_id = rp.Pop<u64>();
- u64 aruid = rp.Pop<u64>();
+ const u64 layer_id = rp.Pop<u64>();
+ const u64 aruid = rp.Pop<u64>();
- u64 display_id = nv_flinger->OpenDisplay(display_name);
- u32 buffer_queue_id = nv_flinger->GetBufferQueueId(display_id, layer_id);
+ LOG_DEBUG(Service_VI, "called. layer_id=0x{:016X}, aruid=0x{:016X}", layer_id, aruid);
+
+ const u64 display_id = nv_flinger->OpenDisplay(display_name);
+ const u32 buffer_queue_id = nv_flinger->GetBufferQueueId(display_id, layer_id);
NativeWindow native_window{buffer_queue_id};
IPC::ResponseBuilder rb{ctx, 4};
@@ -964,17 +1053,17 @@ private:
}
void CreateStrayLayer(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_VI, "called");
-
IPC::RequestParser rp{ctx};
- u32 flags = rp.Pop<u32>();
+ const u32 flags = rp.Pop<u32>();
rp.Pop<u32>(); // padding
- u64 display_id = rp.Pop<u64>();
+ const u64 display_id = rp.Pop<u64>();
+
+ LOG_DEBUG(Service_VI, "called. flags=0x{:08X}, display_id=0x{:016X}", flags, display_id);
// TODO(Subv): What's the difference between a Stray and a Managed layer?
- u64 layer_id = nv_flinger->CreateLayer(display_id);
- u32 buffer_queue_id = nv_flinger->GetBufferQueueId(display_id, layer_id);
+ const u64 layer_id = nv_flinger->CreateLayer(display_id);
+ const u32 buffer_queue_id = nv_flinger->GetBufferQueueId(display_id, layer_id);
NativeWindow native_window{buffer_queue_id};
IPC::ResponseBuilder rb{ctx, 6};
@@ -984,72 +1073,59 @@ private:
}
void DestroyStrayLayer(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
-
IPC::RequestParser rp{ctx};
- u64 layer_id = rp.Pop<u64>();
+ const u64 layer_id = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. layer_id=0x{:016X}", layer_id);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetDisplayVsyncEvent(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_VI, "(STUBBED) called");
IPC::RequestParser rp{ctx};
- u64 display_id = rp.Pop<u64>();
+ const u64 display_id = rp.Pop<u64>();
+
+ LOG_WARNING(Service_VI, "(STUBBED) called. display_id=0x{:016X}", display_id);
- auto vsync_event = nv_flinger->GetVsyncEvent(display_id);
+ const auto vsync_event = nv_flinger->GetVsyncEvent(display_id);
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
rb.PushCopyObjects(vsync_event);
}
- enum class ConvertedScaleMode : u64 {
- None = 0, // VI seems to name this as "Unknown" but lots of games pass it, assume it's no
- // scaling/default
- Freeze = 1,
- ScaleToWindow = 2,
- Crop = 3,
- NoCrop = 4,
- };
-
- // This struct is different, currently it's 1:1 but this might change in the future.
- enum class NintendoScaleMode : u32 {
- None = 0,
- Freeze = 1,
- ScaleToWindow = 2,
- Crop = 3,
- NoCrop = 4,
- };
-
void ConvertScalingMode(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
- auto mode = rp.PopEnum<NintendoScaleMode>();
+ const auto mode = rp.PopEnum<NintendoScaleMode>();
LOG_DEBUG(Service_VI, "called mode={}", static_cast<u32>(mode));
- IPC::ResponseBuilder rb{ctx, 4};
- rb.Push(RESULT_SUCCESS);
+ const auto converted_mode = ConvertScalingModeImpl(mode);
+
+ if (converted_mode.Succeeded()) {
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushEnum(*converted_mode);
+ } else {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(converted_mode.Code());
+ }
+ }
+
+ static ResultVal<ConvertedScaleMode> ConvertScalingModeImpl(NintendoScaleMode mode) {
switch (mode) {
case NintendoScaleMode::None:
- rb.PushEnum(ConvertedScaleMode::None);
- break;
+ return MakeResult(ConvertedScaleMode::None);
case NintendoScaleMode::Freeze:
- rb.PushEnum(ConvertedScaleMode::Freeze);
- break;
+ return MakeResult(ConvertedScaleMode::Freeze);
case NintendoScaleMode::ScaleToWindow:
- rb.PushEnum(ConvertedScaleMode::ScaleToWindow);
- break;
- case NintendoScaleMode::Crop:
- rb.PushEnum(ConvertedScaleMode::Crop);
- break;
- case NintendoScaleMode::NoCrop:
- rb.PushEnum(ConvertedScaleMode::NoCrop);
- break;
+ return MakeResult(ConvertedScaleMode::ScaleToWindow);
+ case NintendoScaleMode::ScaleAndCrop:
+ return MakeResult(ConvertedScaleMode::ScaleAndCrop);
+ case NintendoScaleMode::PreserveAspectRatio:
+ return MakeResult(ConvertedScaleMode::PreserveAspectRatio);
default:
- UNIMPLEMENTED_MSG("Unknown scaling mode {}", static_cast<u32>(mode));
- rb.PushEnum(ConvertedScaleMode::None);
- break;
+ return ERR_OPERATION_FAILED;
}
}
@@ -1067,9 +1143,9 @@ IApplicationDisplayService::IApplicationDisplayService(
"GetIndirectDisplayTransactionService"},
{1000, &IApplicationDisplayService::ListDisplays, "ListDisplays"},
{1010, &IApplicationDisplayService::OpenDisplay, "OpenDisplay"},
- {1011, nullptr, "OpenDefaultDisplay"},
+ {1011, &IApplicationDisplayService::OpenDefaultDisplay, "OpenDefaultDisplay"},
{1020, &IApplicationDisplayService::CloseDisplay, "CloseDisplay"},
- {1101, nullptr, "SetDisplayEnabled"},
+ {1101, &IApplicationDisplayService::SetDisplayEnabled, "SetDisplayEnabled"},
{1102, &IApplicationDisplayService::GetDisplayResolution, "GetDisplayResolution"},
{2020, &IApplicationDisplayService::OpenLayer, "OpenLayer"},
{2021, nullptr, "CloseLayer"},
diff --git a/src/core/loader/deconstructed_rom_directory.cpp b/src/core/loader/deconstructed_rom_directory.cpp
index 8518dddcb..07aa7a1cd 100644
--- a/src/core/loader/deconstructed_rom_directory.cpp
+++ b/src/core/loader/deconstructed_rom_directory.cpp
@@ -7,7 +7,6 @@
#include "common/common_funcs.h"
#include "common/file_util.h"
#include "common/logging/log.h"
-#include "core/core.h"
#include "core/file_sys/content_archive.h"
#include "core/file_sys/control_metadata.h"
#include "core/file_sys/patch_manager.h"
@@ -130,7 +129,10 @@ ResultStatus AppLoader_DeconstructedRomDirectory::Load(Kernel::Process& process)
return ResultStatus::Error32BitISA;
}
- process.LoadFromMetadata(metadata);
+ if (process.LoadFromMetadata(metadata).IsError()) {
+ return ResultStatus::ErrorUnableToParseKernelMetadata;
+ }
+
const FileSys::PatchManager pm(metadata.GetTitleID());
// Load NSO modules
@@ -146,7 +148,7 @@ ResultStatus AppLoader_DeconstructedRomDirectory::Load(Kernel::Process& process)
const VAddr load_addr = next_load_addr;
const bool should_pass_arguments = std::strcmp(module, "rtld") == 0;
const auto tentative_next_load_addr =
- AppLoader_NSO::LoadModule(*module_file, load_addr, should_pass_arguments, pm);
+ AppLoader_NSO::LoadModule(process, *module_file, load_addr, should_pass_arguments, pm);
if (!tentative_next_load_addr) {
return ResultStatus::ErrorLoadingNSO;
}
diff --git a/src/core/loader/deconstructed_rom_directory.h b/src/core/loader/deconstructed_rom_directory.h
index d109ed2b5..1615cb5a8 100644
--- a/src/core/loader/deconstructed_rom_directory.h
+++ b/src/core/loader/deconstructed_rom_directory.h
@@ -33,7 +33,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
diff --git a/src/core/loader/elf.h b/src/core/loader/elf.h
index 6af76441c..a2d33021c 100644
--- a/src/core/loader/elf.h
+++ b/src/core/loader/elf.h
@@ -22,7 +22,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
diff --git a/src/core/loader/loader.cpp b/src/core/loader/loader.cpp
index 9cd0b0ccd..d8cc30959 100644
--- a/src/core/loader/loader.cpp
+++ b/src/core/loader/loader.cpp
@@ -93,7 +93,7 @@ std::string GetFileTypeString(FileType type) {
return "unknown";
}
-constexpr std::array<const char*, 60> RESULT_MESSAGES{
+constexpr std::array<const char*, 62> RESULT_MESSAGES{
"The operation completed successfully.",
"The loader requested to load is already loaded.",
"The operation is not implemented.",
@@ -103,6 +103,7 @@ constexpr std::array<const char*, 60> RESULT_MESSAGES{
"The NPDM has a bad ACI header,",
"The NPDM file has a bad file access control.",
"The NPDM has a bad file access header.",
+ "The NPDM has bad kernel capability descriptors.",
"The PFS/HFS partition has a bad header.",
"The PFS/HFS partition has incorrect size as determined by the header.",
"The NCA file has a bad header.",
@@ -125,6 +126,7 @@ constexpr std::array<const char*, 60> RESULT_MESSAGES{
"The file could not be found or does not exist.",
"The game is missing a program metadata file (main.npdm).",
"The game uses the currently-unimplemented 32-bit architecture.",
+ "Unable to completely parse the kernel metadata when loading the emulated process",
"The RomFS could not be found.",
"The ELF file has incorrect size as determined by the header.",
"There was a general error loading the NRO into emulated memory.",
diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h
index 7686634bf..bb925f4a6 100644
--- a/src/core/loader/loader.h
+++ b/src/core/loader/loader.h
@@ -12,8 +12,13 @@
#include <vector>
#include "common/common_types.h"
+#include "core/file_sys/control_metadata.h"
#include "core/file_sys/vfs.h"
+namespace FileSys {
+class NACP;
+} // namespace FileSys
+
namespace Kernel {
struct AddressMapping;
class Process;
@@ -66,6 +71,7 @@ enum class ResultStatus : u16 {
ErrorBadACIHeader,
ErrorBadFileAccessControl,
ErrorBadFileAccessHeader,
+ ErrorBadKernelCapabilityDescriptors,
ErrorBadPFSHeader,
ErrorIncorrectPFSFileSize,
ErrorBadNCAHeader,
@@ -88,6 +94,7 @@ enum class ResultStatus : u16 {
ErrorNullFile,
ErrorMissingNPDM,
Error32BitISA,
+ ErrorUnableToParseKernelMetadata,
ErrorNoRomFS,
ErrorIncorrectELFFileSize,
ErrorLoadingNRO,
@@ -131,7 +138,7 @@ public:
* Returns the type of this file
* @return FileType corresponding to the loaded file
*/
- virtual FileType GetFileType() = 0;
+ virtual FileType GetFileType() const = 0;
/**
* Load the application and return the created Process instance
@@ -171,6 +178,8 @@ public:
/**
* Get the banner (typically banner section) of the application
+ * In the context of NX, this is the animation that displays in the bottom right of the screen
+ * when a game boots. Stored in GIF format.
* @param buffer Reference to buffer to store data
* @return ResultStatus result of function
*/
@@ -180,6 +189,8 @@ public:
/**
* Get the logo (typically logo section) of the application
+ * In the context of NX, this is the static image that displays in the top left of the screen
+ * when a game boots. Stored in JPEG format.
* @param buffer Reference to buffer to store data
* @return ResultStatus result of function
*/
@@ -243,6 +254,24 @@ public:
return ResultStatus::ErrorNotImplemented;
}
+ /**
+ * Get the control data (CNMT) of the application
+ * @param control Reference to store the application control data into
+ * @return ResultStatus result of function
+ */
+ virtual ResultStatus ReadControlData(FileSys::NACP& control) {
+ return ResultStatus::ErrorNotImplemented;
+ }
+
+ /**
+ * Get the RomFS of the manual of the application
+ * @param file The raw manual RomFS of the game
+ * @return ResultStatus result of function
+ */
+ virtual ResultStatus ReadManualRomFS(FileSys::VirtualFile& file) {
+ return ResultStatus::ErrorNotImplemented;
+ }
+
protected:
FileSys::VirtualFile file;
bool is_loaded = false;
diff --git a/src/core/loader/nax.cpp b/src/core/loader/nax.cpp
index 42f4a777b..93a970d10 100644
--- a/src/core/loader/nax.cpp
+++ b/src/core/loader/nax.cpp
@@ -37,7 +37,7 @@ FileType AppLoader_NAX::IdentifyType(const FileSys::VirtualFile& file) {
return IdentifyTypeImpl(nax);
}
-FileType AppLoader_NAX::GetFileType() {
+FileType AppLoader_NAX::GetFileType() const {
return IdentifyTypeImpl(*nax);
}
@@ -79,4 +79,13 @@ u64 AppLoader_NAX::ReadRomFSIVFCOffset() const {
ResultStatus AppLoader_NAX::ReadProgramId(u64& out_program_id) {
return nca_loader->ReadProgramId(out_program_id);
}
+
+ResultStatus AppLoader_NAX::ReadBanner(std::vector<u8>& buffer) {
+ return nca_loader->ReadBanner(buffer);
+}
+
+ResultStatus AppLoader_NAX::ReadLogo(std::vector<u8>& buffer) {
+ return nca_loader->ReadLogo(buffer);
+}
+
} // namespace Loader
diff --git a/src/core/loader/nax.h b/src/core/loader/nax.h
index b4d93bd01..f40079574 100644
--- a/src/core/loader/nax.h
+++ b/src/core/loader/nax.h
@@ -31,7 +31,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override;
+ FileType GetFileType() const override;
ResultStatus Load(Kernel::Process& process) override;
@@ -39,6 +39,9 @@ public:
u64 ReadRomFSIVFCOffset() const override;
ResultStatus ReadProgramId(u64& out_program_id) override;
+ ResultStatus ReadBanner(std::vector<u8>& buffer) override;
+ ResultStatus ReadLogo(std::vector<u8>& buffer) override;
+
private:
std::unique_ptr<FileSys::NAX> nax;
std::unique_ptr<AppLoader_NCA> nca_loader;
diff --git a/src/core/loader/nca.cpp b/src/core/loader/nca.cpp
index 7e1b0d84f..ce8196fcf 100644
--- a/src/core/loader/nca.cpp
+++ b/src/core/loader/nca.cpp
@@ -84,4 +84,23 @@ ResultStatus AppLoader_NCA::ReadProgramId(u64& out_program_id) {
return ResultStatus::Success;
}
+ResultStatus AppLoader_NCA::ReadBanner(std::vector<u8>& buffer) {
+ if (nca == nullptr || nca->GetStatus() != ResultStatus::Success)
+ return ResultStatus::ErrorNotInitialized;
+ const auto logo = nca->GetLogoPartition();
+ if (logo == nullptr)
+ return ResultStatus::ErrorNoIcon;
+ buffer = logo->GetFile("StartupMovie.gif")->ReadAllBytes();
+ return ResultStatus::Success;
+}
+
+ResultStatus AppLoader_NCA::ReadLogo(std::vector<u8>& buffer) {
+ if (nca == nullptr || nca->GetStatus() != ResultStatus::Success)
+ return ResultStatus::ErrorNotInitialized;
+ const auto logo = nca->GetLogoPartition();
+ if (logo == nullptr)
+ return ResultStatus::ErrorNoIcon;
+ buffer = logo->GetFile("NintendoLogo.png")->ReadAllBytes();
+ return ResultStatus::Success;
+}
} // namespace Loader
diff --git a/src/core/loader/nca.h b/src/core/loader/nca.h
index 95d9b73a1..b9f077468 100644
--- a/src/core/loader/nca.h
+++ b/src/core/loader/nca.h
@@ -29,7 +29,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
@@ -39,6 +39,9 @@ public:
u64 ReadRomFSIVFCOffset() const override;
ResultStatus ReadProgramId(u64& out_program_id) override;
+ ResultStatus ReadBanner(std::vector<u8>& buffer) override;
+ ResultStatus ReadLogo(std::vector<u8>& buffer) override;
+
private:
std::unique_ptr<FileSys::NCA> nca;
std::unique_ptr<AppLoader_DeconstructedRomDirectory> directory_loader;
diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp
index fbbd6b0de..4fad0c0dd 100644
--- a/src/core/loader/nro.cpp
+++ b/src/core/loader/nro.cpp
@@ -10,7 +10,6 @@
#include "common/file_util.h"
#include "common/logging/log.h"
#include "common/swap.h"
-#include "core/core.h"
#include "core/file_sys/control_metadata.h"
#include "core/file_sys/romfs_factory.h"
#include "core/file_sys/vfs_offset.h"
@@ -129,9 +128,8 @@ static constexpr u32 PageAlignSize(u32 size) {
return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;
}
-/*static*/ bool AppLoader_NRO::LoadNro(const std::vector<u8>& data, const std::string& name,
- VAddr load_base) {
-
+static bool LoadNroImpl(Kernel::Process& process, const std::vector<u8>& data,
+ const std::string& name, VAddr load_base) {
if (data.size() < sizeof(NroHeader)) {
return {};
}
@@ -189,7 +187,7 @@ static constexpr u32 PageAlignSize(u32 size) {
// Load codeset for current process
codeset.memory = std::make_shared<std::vector<u8>>(std::move(program_image));
- Core::CurrentProcess()->LoadModule(std::move(codeset), load_base);
+ process.LoadModule(std::move(codeset), load_base);
// Register module with GDBStub
GDBStub::RegisterModule(name, load_base, load_base);
@@ -197,8 +195,9 @@ static constexpr u32 PageAlignSize(u32 size) {
return true;
}
-bool AppLoader_NRO::LoadNro(const FileSys::VfsFile& file, VAddr load_base) {
- return AppLoader_NRO::LoadNro(file.ReadAllBytes(), file.GetName(), load_base);
+bool AppLoader_NRO::LoadNro(Kernel::Process& process, const FileSys::VfsFile& file,
+ VAddr load_base) {
+ return LoadNroImpl(process, file.ReadAllBytes(), file.GetName(), load_base);
}
ResultStatus AppLoader_NRO::Load(Kernel::Process& process) {
@@ -209,7 +208,7 @@ ResultStatus AppLoader_NRO::Load(Kernel::Process& process) {
// Load NRO
const VAddr base_address = process.VMManager().GetCodeRegionBaseAddress();
- if (!LoadNro(*file, base_address)) {
+ if (!LoadNro(process, *file, base_address)) {
return ResultStatus::ErrorLoadingNRO;
}
diff --git a/src/core/loader/nro.h b/src/core/loader/nro.h
index 3e6959302..013d629c0 100644
--- a/src/core/loader/nro.h
+++ b/src/core/loader/nro.h
@@ -14,6 +14,10 @@ namespace FileSys {
class NACP;
}
+namespace Kernel {
+class Process;
+}
+
namespace Loader {
/// Loads an NRO file
@@ -29,7 +33,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
@@ -41,10 +45,8 @@ public:
ResultStatus ReadTitle(std::string& title) override;
bool IsRomFSUpdatable() const override;
- static bool LoadNro(const std::vector<u8>& data, const std::string& name, VAddr load_base);
-
private:
- bool LoadNro(const FileSys::VfsFile& file, VAddr load_base);
+ bool LoadNro(Kernel::Process& process, const FileSys::VfsFile& file, VAddr load_base);
std::vector<u8> icon_data;
std::unique_ptr<FileSys::NACP> nacp;
diff --git a/src/core/loader/nso.cpp b/src/core/loader/nso.cpp
index aaf006309..6ded0b707 100644
--- a/src/core/loader/nso.cpp
+++ b/src/core/loader/nso.cpp
@@ -9,7 +9,6 @@
#include "common/file_util.h"
#include "common/logging/log.h"
#include "common/swap.h"
-#include "core/core.h"
#include "core/file_sys/patch_manager.h"
#include "core/gdbstub/gdbstub.h"
#include "core/hle/kernel/process.h"
@@ -93,7 +92,8 @@ static constexpr u32 PageAlignSize(u32 size) {
return (size + Memory::PAGE_MASK) & ~Memory::PAGE_MASK;
}
-std::optional<VAddr> AppLoader_NSO::LoadModule(const FileSys::VfsFile& file, VAddr load_base,
+std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::Process& process,
+ const FileSys::VfsFile& file, VAddr load_base,
bool should_pass_arguments,
std::optional<FileSys::PatchManager> pm) {
if (file.GetSize() < sizeof(NsoHeader))
@@ -166,7 +166,7 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(const FileSys::VfsFile& file, VAd
// Load codeset for current process
codeset.memory = std::make_shared<std::vector<u8>>(std::move(program_image));
- Core::CurrentProcess()->LoadModule(std::move(codeset), load_base);
+ process.LoadModule(std::move(codeset), load_base);
// Register module with GDBStub
GDBStub::RegisterModule(file.GetName(), load_base, load_base);
@@ -181,7 +181,7 @@ ResultStatus AppLoader_NSO::Load(Kernel::Process& process) {
// Load module
const VAddr base_address = process.VMManager().GetCodeRegionBaseAddress();
- if (!LoadModule(*file, base_address, true)) {
+ if (!LoadModule(process, *file, base_address, true)) {
return ResultStatus::ErrorLoadingNSO;
}
LOG_DEBUG(Loader, "loaded module {} @ 0x{:X}", file->GetName(), base_address);
diff --git a/src/core/loader/nso.h b/src/core/loader/nso.h
index 433306139..135b6ea5a 100644
--- a/src/core/loader/nso.h
+++ b/src/core/loader/nso.h
@@ -10,6 +10,10 @@
#include "core/loader/linker.h"
#include "core/loader/loader.h"
+namespace Kernel {
+class Process;
+}
+
namespace Loader {
constexpr u64 NSO_ARGUMENT_DATA_ALLOCATION_SIZE = 0x9000;
@@ -33,12 +37,12 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
- static std::optional<VAddr> LoadModule(const FileSys::VfsFile& file, VAddr load_base,
- bool should_pass_arguments,
+ static std::optional<VAddr> LoadModule(Kernel::Process& process, const FileSys::VfsFile& file,
+ VAddr load_base, bool should_pass_arguments,
std::optional<FileSys::PatchManager> pm = {});
ResultStatus Load(Kernel::Process& process) override;
diff --git a/src/core/loader/nsp.cpp b/src/core/loader/nsp.cpp
index 080d89904..7da1f8960 100644
--- a/src/core/loader/nsp.cpp
+++ b/src/core/loader/nsp.cpp
@@ -151,4 +151,28 @@ ResultStatus AppLoader_NSP::ReadTitle(std::string& title) {
title = nacp_file->GetApplicationName();
return ResultStatus::Success;
}
+
+ResultStatus AppLoader_NSP::ReadControlData(FileSys::NACP& nacp) {
+ if (nacp_file == nullptr)
+ return ResultStatus::ErrorNoControl;
+ nacp = *nacp_file;
+ return ResultStatus::Success;
+}
+
+ResultStatus AppLoader_NSP::ReadManualRomFS(FileSys::VirtualFile& file) {
+ const auto nca = nsp->GetNCA(nsp->GetProgramTitleID(), FileSys::ContentRecordType::Manual);
+ if (nsp->GetStatus() != ResultStatus::Success || nca == nullptr)
+ return ResultStatus::ErrorNoRomFS;
+ file = nca->GetRomFS();
+ return file == nullptr ? ResultStatus::ErrorNoRomFS : ResultStatus::Success;
+}
+
+ResultStatus AppLoader_NSP::ReadBanner(std::vector<u8>& buffer) {
+ return secondary_loader->ReadBanner(buffer);
+}
+
+ResultStatus AppLoader_NSP::ReadLogo(std::vector<u8>& buffer) {
+ return secondary_loader->ReadLogo(buffer);
+}
+
} // namespace Loader
diff --git a/src/core/loader/nsp.h b/src/core/loader/nsp.h
index db91cd01e..953a1b508 100644
--- a/src/core/loader/nsp.h
+++ b/src/core/loader/nsp.h
@@ -31,7 +31,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
@@ -43,6 +43,11 @@ public:
ResultStatus ReadProgramId(u64& out_program_id) override;
ResultStatus ReadIcon(std::vector<u8>& buffer) override;
ResultStatus ReadTitle(std::string& title) override;
+ ResultStatus ReadControlData(FileSys::NACP& nacp) override;
+ ResultStatus ReadManualRomFS(FileSys::VirtualFile& file) override;
+
+ ResultStatus ReadBanner(std::vector<u8>& buffer) override;
+ ResultStatus ReadLogo(std::vector<u8>& buffer) override;
private:
std::unique_ptr<FileSys::NSP> nsp;
diff --git a/src/core/loader/xci.cpp b/src/core/loader/xci.cpp
index 461607c95..89f7bbf77 100644
--- a/src/core/loader/xci.cpp
+++ b/src/core/loader/xci.cpp
@@ -120,4 +120,29 @@ ResultStatus AppLoader_XCI::ReadTitle(std::string& title) {
title = nacp_file->GetApplicationName();
return ResultStatus::Success;
}
+
+ResultStatus AppLoader_XCI::ReadControlData(FileSys::NACP& control) {
+ if (nacp_file == nullptr)
+ return ResultStatus::ErrorNoControl;
+ control = *nacp_file;
+ return ResultStatus::Success;
+}
+
+ResultStatus AppLoader_XCI::ReadManualRomFS(FileSys::VirtualFile& file) {
+ const auto nca = xci->GetSecurePartitionNSP()->GetNCA(xci->GetProgramTitleID(),
+ FileSys::ContentRecordType::Manual);
+ if (xci->GetStatus() != ResultStatus::Success || nca == nullptr)
+ return ResultStatus::ErrorXCIMissingPartition;
+ file = nca->GetRomFS();
+ return file == nullptr ? ResultStatus::ErrorNoRomFS : ResultStatus::Success;
+}
+
+ResultStatus AppLoader_XCI::ReadBanner(std::vector<u8>& buffer) {
+ return nca_loader->ReadBanner(buffer);
+}
+
+ResultStatus AppLoader_XCI::ReadLogo(std::vector<u8>& buffer) {
+ return nca_loader->ReadLogo(buffer);
+}
+
} // namespace Loader
diff --git a/src/core/loader/xci.h b/src/core/loader/xci.h
index 46f8dfc9e..d6995b61e 100644
--- a/src/core/loader/xci.h
+++ b/src/core/loader/xci.h
@@ -31,7 +31,7 @@ public:
*/
static FileType IdentifyType(const FileSys::VirtualFile& file);
- FileType GetFileType() override {
+ FileType GetFileType() const override {
return IdentifyType(file);
}
@@ -43,6 +43,11 @@ public:
ResultStatus ReadProgramId(u64& out_program_id) override;
ResultStatus ReadIcon(std::vector<u8>& buffer) override;
ResultStatus ReadTitle(std::string& title) override;
+ ResultStatus ReadControlData(FileSys::NACP& control) override;
+ ResultStatus ReadManualRomFS(FileSys::VirtualFile& file) override;
+
+ ResultStatus ReadBanner(std::vector<u8>& buffer) override;
+ ResultStatus ReadLogo(std::vector<u8>& buffer) override;
private:
std::unique_ptr<FileSys::XCI> xci;
diff --git a/src/core/memory.cpp b/src/core/memory.cpp
index 70abd856a..e9166dbd9 100644
--- a/src/core/memory.cpp
+++ b/src/core/memory.cpp
@@ -53,6 +53,14 @@ void PageTable::Resize(std::size_t address_space_width_in_bits) {
pointers.resize(num_page_table_entries);
attributes.resize(num_page_table_entries);
+
+ // The default is a 39-bit address space, which causes an initial 1GB allocation size. If the
+ // vector size is subsequently decreased (via resize), the vector might not automatically
+ // actually reallocate/resize its underlying allocation, which wastes up to ~800 MB for
+ // 36-bit titles. Call shrink_to_fit to reduce capacity to what's actually in use.
+
+ pointers.shrink_to_fit();
+ attributes.shrink_to_fit();
}
static void MapPages(PageTable& page_table, VAddr base, u64 size, u8* memory, PageType type) {
@@ -117,14 +125,13 @@ void RemoveDebugHook(PageTable& page_table, VAddr base, u64 size, MemoryHookPoin
* using a VMA from the current process
*/
static u8* GetPointerFromVMA(const Kernel::Process& process, VAddr vaddr) {
- u8* direct_pointer = nullptr;
+ const auto& vm_manager = process.VMManager();
- auto& vm_manager = process.VMManager();
+ const auto it = vm_manager.FindVMA(vaddr);
+ DEBUG_ASSERT(vm_manager.IsValidHandle(it));
- auto it = vm_manager.FindVMA(vaddr);
- ASSERT(it != vm_manager.vma_map.end());
-
- auto& vma = it->second;
+ u8* direct_pointer = nullptr;
+ const auto& vma = it->second;
switch (vma.type) {
case Kernel::VMAType::AllocatedMemoryBlock:
direct_pointer = vma.backing_block->data() + vma.offset;
@@ -180,6 +187,7 @@ T Read(const VAddr vaddr) {
default:
UNREACHABLE();
}
+ return {};
}
template <typename T>
diff --git a/src/core/settings.cpp b/src/core/settings.cpp
index 26fcd3405..2e232e1e7 100644
--- a/src/core/settings.cpp
+++ b/src/core/settings.cpp
@@ -74,4 +74,33 @@ void Apply() {
Service::HID::ReloadInputDevices();
}
+template <typename T>
+void LogSetting(const std::string& name, const T& value) {
+ LOG_INFO(Config, "{}: {}", name, value);
+}
+
+void LogSettings() {
+ LOG_INFO(Config, "yuzu Configuration:");
+ LogSetting("System_UseDockedMode", Settings::values.use_docked_mode);
+ LogSetting("System_EnableNfc", Settings::values.enable_nfc);
+ LogSetting("System_RngSeed", Settings::values.rng_seed.value_or(0));
+ LogSetting("System_CurrentUser", Settings::values.current_user);
+ LogSetting("System_LanguageIndex", Settings::values.language_index);
+ LogSetting("Core_UseCpuJit", Settings::values.use_cpu_jit);
+ LogSetting("Core_UseMultiCore", Settings::values.use_multi_core);
+ LogSetting("Renderer_UseResolutionFactor", Settings::values.resolution_factor);
+ LogSetting("Renderer_UseFrameLimit", Settings::values.use_frame_limit);
+ LogSetting("Renderer_FrameLimit", Settings::values.frame_limit);
+ LogSetting("Renderer_UseAccurateGpuEmulation", Settings::values.use_accurate_gpu_emulation);
+ LogSetting("Audio_OutputEngine", Settings::values.sink_id);
+ LogSetting("Audio_EnableAudioStretching", Settings::values.enable_audio_stretching);
+ LogSetting("Audio_OutputDevice", Settings::values.audio_device_id);
+ LogSetting("DataStorage_UseVirtualSd", Settings::values.use_virtual_sd);
+ LogSetting("DataStorage_NandDir", Settings::values.nand_dir);
+ LogSetting("DataStorage_SdmcDir", Settings::values.sdmc_dir);
+ LogSetting("Debugging_UseGdbstub", Settings::values.use_gdbstub);
+ LogSetting("Debugging_GdbstubPort", Settings::values.gdbstub_port);
+ LogSetting("Debugging_ProgramArgs", Settings::values.program_args);
+}
+
} // namespace Settings
diff --git a/src/core/settings.h b/src/core/settings.h
index a0c5fd447..c97387fc7 100644
--- a/src/core/settings.h
+++ b/src/core/settings.h
@@ -6,8 +6,11 @@
#include <array>
#include <atomic>
+#include <chrono>
+#include <map>
#include <optional>
#include <string>
+#include <vector>
#include "common/common_types.h"
namespace Settings {
@@ -348,6 +351,11 @@ struct Values {
bool use_docked_mode;
bool enable_nfc;
std::optional<u32> rng_seed;
+ // Measured in seconds since epoch
+ std::optional<std::chrono::seconds> custom_rtc;
+ // Set on game boot, reset on stop. Seconds difference between current time and `custom_rtc`
+ std::chrono::seconds custom_rtc_differential;
+
s32 current_user;
s32 language_index;
@@ -411,7 +419,11 @@ struct Values {
std::string web_api_url;
std::string yuzu_username;
std::string yuzu_token;
+
+ // Add-Ons
+ std::map<u64, std::vector<std::string>> disabled_addons;
} extern values;
void Apply();
+void LogSettings();
} // namespace Settings
diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp
index a3b08c740..09ed74d78 100644
--- a/src/core/telemetry_session.cpp
+++ b/src/core/telemetry_session.cpp
@@ -103,13 +103,8 @@ bool VerifyLogin(const std::string& username, const std::string& token) {
TelemetrySession::TelemetrySession() {
#ifdef ENABLE_WEB_SERVICE
- if (Settings::values.enable_telemetry) {
- backend = std::make_unique<WebService::TelemetryJson>(Settings::values.web_api_url,
- Settings::values.yuzu_username,
- Settings::values.yuzu_token);
- } else {
- backend = std::make_unique<Telemetry::NullVisitor>();
- }
+ backend = std::make_unique<WebService::TelemetryJson>(
+ Settings::values.web_api_url, Settings::values.yuzu_username, Settings::values.yuzu_token);
#else
backend = std::make_unique<Telemetry::NullVisitor>();
#endif
@@ -180,7 +175,8 @@ TelemetrySession::~TelemetrySession() {
// This is just a placeholder to wrap up the session once the core completes and this is
// destroyed. This will be moved elsewhere once we are actually doing real I/O with the service.
field_collection.Accept(*backend);
- backend->Complete();
+ if (Settings::values.enable_telemetry)
+ backend->Complete();
backend = nullptr;
}
diff --git a/src/video_core/CMakeLists.txt b/src/video_core/CMakeLists.txt
index 3f906a517..6113e17ff 100644
--- a/src/video_core/CMakeLists.txt
+++ b/src/video_core/CMakeLists.txt
@@ -1,6 +1,6 @@
add_library(video_core STATIC
- command_processor.cpp
- command_processor.h
+ dma_pusher.cpp
+ dma_pusher.h
debug_utils/debug_utils.cpp
debug_utils/debug_utils.h
engines/fermi_2d.cpp
@@ -30,6 +30,8 @@ add_library(video_core STATIC
renderer_base.h
renderer_opengl/gl_buffer_cache.cpp
renderer_opengl/gl_buffer_cache.h
+ renderer_opengl/gl_global_cache.cpp
+ renderer_opengl/gl_global_cache.h
renderer_opengl/gl_primitive_assembler.cpp
renderer_opengl/gl_primitive_assembler.h
renderer_opengl/gl_rasterizer.cpp
@@ -57,6 +59,35 @@ add_library(video_core STATIC
renderer_opengl/renderer_opengl.h
renderer_opengl/utils.cpp
renderer_opengl/utils.h
+ shader/decode/arithmetic.cpp
+ shader/decode/arithmetic_immediate.cpp
+ shader/decode/bfe.cpp
+ shader/decode/bfi.cpp
+ shader/decode/shift.cpp
+ shader/decode/arithmetic_integer.cpp
+ shader/decode/arithmetic_integer_immediate.cpp
+ shader/decode/arithmetic_half.cpp
+ shader/decode/arithmetic_half_immediate.cpp
+ shader/decode/ffma.cpp
+ shader/decode/hfma2.cpp
+ shader/decode/conversion.cpp
+ shader/decode/memory.cpp
+ shader/decode/float_set_predicate.cpp
+ shader/decode/integer_set_predicate.cpp
+ shader/decode/half_set_predicate.cpp
+ shader/decode/predicate_set_register.cpp
+ shader/decode/predicate_set_predicate.cpp
+ shader/decode/register_set_predicate.cpp
+ shader/decode/float_set.cpp
+ shader/decode/integer_set.cpp
+ shader/decode/half_set.cpp
+ shader/decode/video.cpp
+ shader/decode/xmad.cpp
+ shader/decode/other.cpp
+ shader/decode.cpp
+ shader/shader_ir.cpp
+ shader/shader_ir.h
+ shader/track.cpp
surface.cpp
surface.h
textures/astc.cpp
diff --git a/src/video_core/command_processor.cpp b/src/video_core/command_processor.cpp
deleted file mode 100644
index 8b9c548cc..000000000
--- a/src/video_core/command_processor.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2018 yuzu Emulator Project
-// Licensed under GPLv2 or any later version
-// Refer to the license.txt file included.
-
-#include <array>
-#include <cstddef>
-#include <memory>
-#include <utility>
-#include "common/assert.h"
-#include "common/logging/log.h"
-#include "common/microprofile.h"
-#include "common/vector_math.h"
-#include "core/memory.h"
-#include "core/tracer/recorder.h"
-#include "video_core/command_processor.h"
-#include "video_core/engines/fermi_2d.h"
-#include "video_core/engines/kepler_memory.h"
-#include "video_core/engines/maxwell_3d.h"
-#include "video_core/engines/maxwell_compute.h"
-#include "video_core/engines/maxwell_dma.h"
-#include "video_core/gpu.h"
-#include "video_core/renderer_base.h"
-#include "video_core/video_core.h"
-
-namespace Tegra {
-
-enum class BufferMethods {
- BindObject = 0,
- CountBufferMethods = 0x40,
-};
-
-MICROPROFILE_DEFINE(ProcessCommandLists, "GPU", "Execute command buffer", MP_RGB(128, 128, 192));
-
-void GPU::ProcessCommandLists(const std::vector<CommandListHeader>& commands) {
- MICROPROFILE_SCOPE(ProcessCommandLists);
-
- // On entering GPU code, assume all memory may be touched by the ARM core.
- maxwell_3d->dirty_flags.OnMemoryWrite();
-
- auto WriteReg = [this](u32 method, u32 subchannel, u32 value, u32 remaining_params) {
- LOG_TRACE(HW_GPU,
- "Processing method {:08X} on subchannel {} value "
- "{:08X} remaining params {}",
- method, subchannel, value, remaining_params);
-
- ASSERT(subchannel < bound_engines.size());
-
- if (method == static_cast<u32>(BufferMethods::BindObject)) {
- // Bind the current subchannel to the desired engine id.
- LOG_DEBUG(HW_GPU, "Binding subchannel {} to engine {}", subchannel, value);
- bound_engines[subchannel] = static_cast<EngineID>(value);
- return;
- }
-
- if (method < static_cast<u32>(BufferMethods::CountBufferMethods)) {
- // TODO(Subv): Research and implement these methods.
- LOG_ERROR(HW_GPU, "Special buffer methods other than Bind are not implemented");
- return;
- }
-
- const EngineID engine = bound_engines[subchannel];
-
- switch (engine) {
- case EngineID::FERMI_TWOD_A:
- fermi_2d->WriteReg(method, value);
- break;
- case EngineID::MAXWELL_B:
- maxwell_3d->WriteReg(method, value, remaining_params);
- break;
- case EngineID::MAXWELL_COMPUTE_B:
- maxwell_compute->WriteReg(method, value);
- break;
- case EngineID::MAXWELL_DMA_COPY_A:
- maxwell_dma->WriteReg(method, value);
- break;
- case EngineID::KEPLER_INLINE_TO_MEMORY_B:
- kepler_memory->WriteReg(method, value);
- break;
- default:
- UNIMPLEMENTED_MSG("Unimplemented engine");
- }
- };
-
- for (auto entry : commands) {
- Tegra::GPUVAddr address = entry.Address();
- u32 size = entry.sz;
- const std::optional<VAddr> head_address = memory_manager->GpuToCpuAddress(address);
- VAddr current_addr = *head_address;
- while (current_addr < *head_address + size * sizeof(CommandHeader)) {
- const CommandHeader header = {Memory::Read32(current_addr)};
- current_addr += sizeof(u32);
-
- switch (header.mode.Value()) {
- case SubmissionMode::IncreasingOld:
- case SubmissionMode::Increasing: {
- // Increase the method value with each argument.
- for (unsigned i = 0; i < header.arg_count; ++i) {
- WriteReg(header.method + i, header.subchannel, Memory::Read32(current_addr),
- header.arg_count - i - 1);
- current_addr += sizeof(u32);
- }
- break;
- }
- case SubmissionMode::NonIncreasingOld:
- case SubmissionMode::NonIncreasing: {
- // Use the same method value for all arguments.
- for (unsigned i = 0; i < header.arg_count; ++i) {
- WriteReg(header.method, header.subchannel, Memory::Read32(current_addr),
- header.arg_count - i - 1);
- current_addr += sizeof(u32);
- }
- break;
- }
- case SubmissionMode::IncreaseOnce: {
- ASSERT(header.arg_count.Value() >= 1);
-
- // Use the original method for the first argument and then the next method for all
- // other arguments.
- WriteReg(header.method, header.subchannel, Memory::Read32(current_addr),
- header.arg_count - 1);
- current_addr += sizeof(u32);
-
- for (unsigned i = 1; i < header.arg_count; ++i) {
- WriteReg(header.method + 1, header.subchannel, Memory::Read32(current_addr),
- header.arg_count - i - 1);
- current_addr += sizeof(u32);
- }
- break;
- }
- case SubmissionMode::Inline: {
- // The register value is stored in the bits 16-28 as an immediate
- WriteReg(header.method, header.subchannel, header.inline_data, 0);
- break;
- }
- default:
- UNIMPLEMENTED();
- }
- }
- }
-}
-
-} // namespace Tegra
diff --git a/src/video_core/command_processor.h b/src/video_core/command_processor.h
deleted file mode 100644
index bd766e77a..000000000
--- a/src/video_core/command_processor.h
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2018 yuzu Emulator Project
-// Licensed under GPLv2 or any later version
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <type_traits>
-#include "common/bit_field.h"
-#include "common/common_types.h"
-#include "video_core/memory_manager.h"
-
-namespace Tegra {
-
-enum class SubmissionMode : u32 {
- IncreasingOld = 0,
- Increasing = 1,
- NonIncreasingOld = 2,
- NonIncreasing = 3,
- Inline = 4,
- IncreaseOnce = 5
-};
-
-struct CommandListHeader {
- u32 entry0; // gpu_va_lo
- union {
- u32 entry1; // gpu_va_hi | (unk_0x02 << 0x08) | (size << 0x0A) | (unk_0x01 << 0x1F)
- BitField<0, 8, u32> gpu_va_hi;
- BitField<8, 2, u32> unk1;
- BitField<10, 21, u32> sz;
- BitField<31, 1, u32> unk2;
- };
-
- GPUVAddr Address() const {
- return (static_cast<GPUVAddr>(gpu_va_hi) << 32) | entry0;
- }
-};
-static_assert(sizeof(CommandListHeader) == 8, "CommandListHeader is incorrect size");
-
-union CommandHeader {
- u32 hex;
-
- BitField<0, 13, u32> method;
- BitField<13, 3, u32> subchannel;
-
- BitField<16, 13, u32> arg_count;
- BitField<16, 13, u32> inline_data;
-
- BitField<29, 3, SubmissionMode> mode;
-};
-static_assert(std::is_standard_layout_v<CommandHeader>, "CommandHeader is not standard layout");
-static_assert(sizeof(CommandHeader) == sizeof(u32), "CommandHeader has incorrect size!");
-
-} // namespace Tegra
diff --git a/src/video_core/dma_pusher.cpp b/src/video_core/dma_pusher.cpp
new file mode 100644
index 000000000..63a958f11
--- /dev/null
+++ b/src/video_core/dma_pusher.cpp
@@ -0,0 +1,123 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/microprofile.h"
+#include "core/core.h"
+#include "core/memory.h"
+#include "video_core/dma_pusher.h"
+#include "video_core/engines/maxwell_3d.h"
+#include "video_core/gpu.h"
+
+namespace Tegra {
+
+DmaPusher::DmaPusher(GPU& gpu) : gpu(gpu) {}
+
+DmaPusher::~DmaPusher() = default;
+
+MICROPROFILE_DEFINE(DispatchCalls, "GPU", "Execute command buffer", MP_RGB(128, 128, 192));
+
+void DmaPusher::DispatchCalls() {
+ MICROPROFILE_SCOPE(DispatchCalls);
+
+ // On entering GPU code, assume all memory may be touched by the ARM core.
+ gpu.Maxwell3D().dirty_flags.OnMemoryWrite();
+
+ dma_pushbuffer_subindex = 0;
+
+ while (Core::System::GetInstance().IsPoweredOn()) {
+ if (!Step()) {
+ break;
+ }
+ }
+}
+
+bool DmaPusher::Step() {
+ if (dma_get != dma_put) {
+ // Push buffer non-empty, read a word
+ const CommandHeader command_header{
+ Memory::Read32(*gpu.MemoryManager().GpuToCpuAddress(dma_get))};
+
+ dma_get += sizeof(u32);
+
+ if (!non_main) {
+ dma_mget = dma_get;
+ }
+
+ // now, see if we're in the middle of a command
+ if (dma_state.length_pending) {
+ // Second word of long non-inc methods command - method count
+ dma_state.length_pending = 0;
+ dma_state.method_count = command_header.method_count_;
+ } else if (dma_state.method_count) {
+ // Data word of methods command
+ CallMethod(command_header.argument);
+
+ if (!dma_state.non_incrementing) {
+ dma_state.method++;
+ }
+
+ if (dma_increment_once) {
+ dma_state.non_incrementing = true;
+ }
+
+ dma_state.method_count--;
+ } else {
+ // No command active - this is the first word of a new one
+ switch (command_header.mode) {
+ case SubmissionMode::Increasing:
+ SetState(command_header);
+ dma_state.non_incrementing = false;
+ dma_increment_once = false;
+ break;
+ case SubmissionMode::NonIncreasing:
+ SetState(command_header);
+ dma_state.non_incrementing = true;
+ dma_increment_once = false;
+ break;
+ case SubmissionMode::Inline:
+ dma_state.method = command_header.method;
+ dma_state.subchannel = command_header.subchannel;
+ CallMethod(command_header.arg_count);
+ dma_state.non_incrementing = true;
+ dma_increment_once = false;
+ break;
+ case SubmissionMode::IncreaseOnce:
+ SetState(command_header);
+ dma_state.non_incrementing = false;
+ dma_increment_once = true;
+ break;
+ }
+ }
+ } else if (ib_enable && !dma_pushbuffer.empty()) {
+ // Current pushbuffer empty, but we have more IB entries to read
+ const CommandList& command_list{dma_pushbuffer.front()};
+ const CommandListHeader& command_list_header{command_list[dma_pushbuffer_subindex++]};
+ dma_get = command_list_header.addr;
+ dma_put = dma_get + command_list_header.size * sizeof(u32);
+ non_main = command_list_header.is_non_main;
+
+ if (dma_pushbuffer_subindex >= command_list.size()) {
+ // We've gone through the current list, remove it from the queue
+ dma_pushbuffer.pop();
+ dma_pushbuffer_subindex = 0;
+ }
+ } else {
+ // Otherwise, pushbuffer empty and IB empty or nonexistent - nothing to do
+ return {};
+ }
+
+ return true;
+}
+
+void DmaPusher::SetState(const CommandHeader& command_header) {
+ dma_state.method = command_header.method;
+ dma_state.subchannel = command_header.subchannel;
+ dma_state.method_count = command_header.method_count;
+}
+
+void DmaPusher::CallMethod(u32 argument) const {
+ gpu.CallMethod({dma_state.method, argument, dma_state.subchannel, dma_state.method_count});
+}
+
+} // namespace Tegra
diff --git a/src/video_core/dma_pusher.h b/src/video_core/dma_pusher.h
new file mode 100644
index 000000000..1097e5c49
--- /dev/null
+++ b/src/video_core/dma_pusher.h
@@ -0,0 +1,99 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <vector>
+#include <queue>
+
+#include "common/bit_field.h"
+#include "common/common_types.h"
+#include "video_core/memory_manager.h"
+
+namespace Tegra {
+
+enum class SubmissionMode : u32 {
+ IncreasingOld = 0,
+ Increasing = 1,
+ NonIncreasingOld = 2,
+ NonIncreasing = 3,
+ Inline = 4,
+ IncreaseOnce = 5
+};
+
+struct CommandListHeader {
+ union {
+ u64 raw;
+ BitField<0, 40, GPUVAddr> addr;
+ BitField<41, 1, u64> is_non_main;
+ BitField<42, 21, u64> size;
+ };
+};
+static_assert(sizeof(CommandListHeader) == sizeof(u64), "CommandListHeader is incorrect size");
+
+union CommandHeader {
+ u32 argument;
+ BitField<0, 13, u32> method;
+ BitField<0, 24, u32> method_count_;
+ BitField<13, 3, u32> subchannel;
+ BitField<16, 13, u32> arg_count;
+ BitField<16, 13, u32> method_count;
+ BitField<29, 3, SubmissionMode> mode;
+};
+static_assert(std::is_standard_layout_v<CommandHeader>, "CommandHeader is not standard layout");
+static_assert(sizeof(CommandHeader) == sizeof(u32), "CommandHeader has incorrect size!");
+
+class GPU;
+
+using CommandList = std::vector<Tegra::CommandListHeader>;
+
+/**
+ * The DmaPusher class implements DMA submission to FIFOs, providing an area of memory that the
+ * emulated app fills with commands and tells PFIFO to process. The pushbuffers are then assembled
+ * into a "command stream" consisting of 32-bit words that make up "commands".
+ * See https://envytools.readthedocs.io/en/latest/hw/fifo/dma-pusher.html#fifo-dma-pusher for
+ * details on this implementation.
+ */
+class DmaPusher {
+public:
+ explicit DmaPusher(GPU& gpu);
+ ~DmaPusher();
+
+ void Push(CommandList&& entries) {
+ dma_pushbuffer.push(std::move(entries));
+ }
+
+ void DispatchCalls();
+
+private:
+ bool Step();
+
+ void SetState(const CommandHeader& command_header);
+
+ void CallMethod(u32 argument) const;
+
+ GPU& gpu;
+
+ std::queue<CommandList> dma_pushbuffer; ///< Queue of command lists to be processed
+ std::size_t dma_pushbuffer_subindex{}; ///< Index within a command list within the pushbuffer
+
+ struct DmaState {
+ u32 method; ///< Current method
+ u32 subchannel; ///< Current subchannel
+ u32 method_count; ///< Current method count
+ u32 length_pending; ///< Large NI command length pending
+ bool non_incrementing; ///< Current command's NI flag
+ };
+
+ DmaState dma_state{};
+ bool dma_increment_once{};
+
+ GPUVAddr dma_put{}; ///< pushbuffer current end address
+ GPUVAddr dma_get{}; ///< pushbuffer current read address
+ GPUVAddr dma_mget{}; ///< main pushbuffer last read address
+ bool ib_enable{true}; ///< IB mode enabled
+ bool non_main{}; ///< non-main pushbuffer active
+};
+
+} // namespace Tegra
diff --git a/src/video_core/engines/fermi_2d.cpp b/src/video_core/engines/fermi_2d.cpp
index e7721a2be..80f70e332 100644
--- a/src/video_core/engines/fermi_2d.cpp
+++ b/src/video_core/engines/fermi_2d.cpp
@@ -14,13 +14,13 @@ namespace Tegra::Engines {
Fermi2D::Fermi2D(VideoCore::RasterizerInterface& rasterizer, MemoryManager& memory_manager)
: memory_manager(memory_manager), rasterizer{rasterizer} {}
-void Fermi2D::WriteReg(u32 method, u32 value) {
- ASSERT_MSG(method < Regs::NUM_REGS,
+void Fermi2D::CallMethod(const GPU::MethodCall& method_call) {
+ ASSERT_MSG(method_call.method < Regs::NUM_REGS,
"Invalid Fermi2D register, increase the size of the Regs structure");
- regs.reg_array[method] = value;
+ regs.reg_array[method_call.method] = method_call.argument;
- switch (method) {
+ switch (method_call.method) {
case FERMI2D_REG_INDEX(trigger): {
HandleSurfaceCopy();
break;
diff --git a/src/video_core/engines/fermi_2d.h b/src/video_core/engines/fermi_2d.h
index 2a6e8bbbb..50009bf75 100644
--- a/src/video_core/engines/fermi_2d.h
+++ b/src/video_core/engines/fermi_2d.h
@@ -27,7 +27,7 @@ public:
~Fermi2D() = default;
/// Write the value to the register identified by method.
- void WriteReg(u32 method, u32 value);
+ void CallMethod(const GPU::MethodCall& method_call);
struct Regs {
static constexpr std::size_t NUM_REGS = 0x258;
diff --git a/src/video_core/engines/kepler_memory.cpp b/src/video_core/engines/kepler_memory.cpp
index 2adbc9eaf..4880191fc 100644
--- a/src/video_core/engines/kepler_memory.cpp
+++ b/src/video_core/engines/kepler_memory.cpp
@@ -17,19 +17,19 @@ KeplerMemory::KeplerMemory(VideoCore::RasterizerInterface& rasterizer,
KeplerMemory::~KeplerMemory() = default;
-void KeplerMemory::WriteReg(u32 method, u32 value) {
- ASSERT_MSG(method < Regs::NUM_REGS,
+void KeplerMemory::CallMethod(const GPU::MethodCall& method_call) {
+ ASSERT_MSG(method_call.method < Regs::NUM_REGS,
"Invalid KeplerMemory register, increase the size of the Regs structure");
- regs.reg_array[method] = value;
+ regs.reg_array[method_call.method] = method_call.argument;
- switch (method) {
+ switch (method_call.method) {
case KEPLERMEMORY_REG_INDEX(exec): {
state.write_offset = 0;
break;
}
case KEPLERMEMORY_REG_INDEX(data): {
- ProcessData(value);
+ ProcessData(method_call.argument);
break;
}
}
diff --git a/src/video_core/engines/kepler_memory.h b/src/video_core/engines/kepler_memory.h
index bf4a13cff..fe9ebc5b9 100644
--- a/src/video_core/engines/kepler_memory.h
+++ b/src/video_core/engines/kepler_memory.h
@@ -9,6 +9,7 @@
#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
+#include "video_core/gpu.h"
#include "video_core/memory_manager.h"
namespace VideoCore {
@@ -26,7 +27,7 @@ public:
~KeplerMemory();
/// Write the value to the register identified by method.
- void WriteReg(u32 method, u32 value);
+ void CallMethod(const GPU::MethodCall& method_call);
struct Regs {
static constexpr size_t NUM_REGS = 0x7F;
diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index f0a5470b9..a388b3944 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -37,6 +37,7 @@ void Maxwell3D::InitializeRegisterDefaults() {
regs.viewports[viewport].depth_range_near = 0.0f;
regs.viewports[viewport].depth_range_far = 1.0f;
}
+
// Doom and Bomberman seems to use the uninitialized registers and just enable blend
// so initialize blend registers with sane values
regs.blend.equation_rgb = Regs::Blend::Equation::Add;
@@ -66,6 +67,7 @@ void Maxwell3D::InitializeRegisterDefaults() {
regs.stencil_back_func_func = Regs::ComparisonOp::Always;
regs.stencil_back_func_mask = 0xFFFFFFFF;
regs.stencil_back_mask = 0xFFFFFFFF;
+
// TODO(Rodrigo): Most games do not set a point size. I think this is a case of a
// register carrying a default value. Assume it's OpenGL's default (1).
regs.point_size = 1.0f;
@@ -78,6 +80,9 @@ void Maxwell3D::InitializeRegisterDefaults() {
regs.color_mask[color_mask].B.Assign(1);
regs.color_mask[color_mask].A.Assign(1);
}
+
+ // Commercial games seem to assume this value is enabled and nouveau sets this value manually.
+ regs.rt_separate_frag_data = 1;
}
void Maxwell3D::CallMacroMethod(u32 method, std::vector<u32> parameters) {
@@ -97,71 +102,101 @@ void Maxwell3D::CallMacroMethod(u32 method, std::vector<u32> parameters) {
macro_interpreter.Execute(search->second, std::move(parameters));
}
-void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
+void Maxwell3D::CallMethod(const GPU::MethodCall& method_call) {
auto debug_context = Core::System::GetInstance().GetGPUDebugContext();
// It is an error to write to a register other than the current macro's ARG register before it
// has finished execution.
if (executing_macro != 0) {
- ASSERT(method == executing_macro + 1);
+ ASSERT(method_call.method == executing_macro + 1);
}
// Methods after 0xE00 are special, they're actually triggers for some microcode that was
// uploaded to the GPU during initialization.
- if (method >= MacroRegistersStart) {
+ if (method_call.method >= MacroRegistersStart) {
// We're trying to execute a macro
if (executing_macro == 0) {
// A macro call must begin by writing the macro method's register, not its argument.
- ASSERT_MSG((method % 2) == 0,
+ ASSERT_MSG((method_call.method % 2) == 0,
"Can't start macro execution by writing to the ARGS register");
- executing_macro = method;
+ executing_macro = method_call.method;
}
- macro_params.push_back(value);
+ macro_params.push_back(method_call.argument);
// Call the macro when there are no more parameters in the command buffer
- if (remaining_params == 0) {
+ if (method_call.IsLastCall()) {
CallMacroMethod(executing_macro, std::move(macro_params));
}
return;
}
- ASSERT_MSG(method < Regs::NUM_REGS,
+ ASSERT_MSG(method_call.method < Regs::NUM_REGS,
"Invalid Maxwell3D register, increase the size of the Regs structure");
if (debug_context) {
debug_context->OnEvent(Tegra::DebugContext::Event::MaxwellCommandLoaded, nullptr);
}
- if (regs.reg_array[method] != value) {
- regs.reg_array[method] = value;
+ if (regs.reg_array[method_call.method] != method_call.argument) {
+ regs.reg_array[method_call.method] = method_call.argument;
+ // Color buffers
+ constexpr u32 first_rt_reg = MAXWELL3D_REG_INDEX(rt);
+ constexpr u32 registers_per_rt = sizeof(regs.rt[0]) / sizeof(u32);
+ if (method_call.method >= first_rt_reg &&
+ method_call.method < first_rt_reg + registers_per_rt * Regs::NumRenderTargets) {
+ const std::size_t rt_index = (method_call.method - first_rt_reg) / registers_per_rt;
+ dirty_flags.color_buffer |= 1u << static_cast<u32>(rt_index);
+ }
+
+ // Zeta buffer
+ constexpr u32 registers_in_zeta = sizeof(regs.zeta) / sizeof(u32);
+ if (method_call.method == MAXWELL3D_REG_INDEX(zeta_enable) ||
+ method_call.method == MAXWELL3D_REG_INDEX(zeta_width) ||
+ method_call.method == MAXWELL3D_REG_INDEX(zeta_height) ||
+ (method_call.method >= MAXWELL3D_REG_INDEX(zeta) &&
+ method_call.method < MAXWELL3D_REG_INDEX(zeta) + registers_in_zeta)) {
+ dirty_flags.zeta_buffer = true;
+ }
+
+ // Shader
+ constexpr u32 shader_registers_count =
+ sizeof(regs.shader_config[0]) * Regs::MaxShaderProgram / sizeof(u32);
+ if (method_call.method >= MAXWELL3D_REG_INDEX(shader_config[0]) &&
+ method_call.method < MAXWELL3D_REG_INDEX(shader_config[0]) + shader_registers_count) {
+ dirty_flags.shaders = true;
+ }
+
// Vertex format
- if (method >= MAXWELL3D_REG_INDEX(vertex_attrib_format) &&
- method < MAXWELL3D_REG_INDEX(vertex_attrib_format) + regs.vertex_attrib_format.size()) {
+ if (method_call.method >= MAXWELL3D_REG_INDEX(vertex_attrib_format) &&
+ method_call.method <
+ MAXWELL3D_REG_INDEX(vertex_attrib_format) + regs.vertex_attrib_format.size()) {
dirty_flags.vertex_attrib_format = true;
}
// Vertex buffer
- if (method >= MAXWELL3D_REG_INDEX(vertex_array) &&
- method < MAXWELL3D_REG_INDEX(vertex_array) + 4 * 32) {
- dirty_flags.vertex_array |= 1u << ((method - MAXWELL3D_REG_INDEX(vertex_array)) >> 2);
- } else if (method >= MAXWELL3D_REG_INDEX(vertex_array_limit) &&
- method < MAXWELL3D_REG_INDEX(vertex_array_limit) + 2 * 32) {
+ if (method_call.method >= MAXWELL3D_REG_INDEX(vertex_array) &&
+ method_call.method < MAXWELL3D_REG_INDEX(vertex_array) + 4 * 32) {
+ dirty_flags.vertex_array |=
+ 1u << ((method_call.method - MAXWELL3D_REG_INDEX(vertex_array)) >> 2);
+ } else if (method_call.method >= MAXWELL3D_REG_INDEX(vertex_array_limit) &&
+ method_call.method < MAXWELL3D_REG_INDEX(vertex_array_limit) + 2 * 32) {
+ dirty_flags.vertex_array |=
+ 1u << ((method_call.method - MAXWELL3D_REG_INDEX(vertex_array_limit)) >> 1);
+ } else if (method_call.method >= MAXWELL3D_REG_INDEX(instanced_arrays) &&
+ method_call.method < MAXWELL3D_REG_INDEX(instanced_arrays) + 32) {
dirty_flags.vertex_array |=
- 1u << ((method - MAXWELL3D_REG_INDEX(vertex_array_limit)) >> 1);
- } else if (method >= MAXWELL3D_REG_INDEX(instanced_arrays) &&
- method < MAXWELL3D_REG_INDEX(instanced_arrays) + 32) {
- dirty_flags.vertex_array |= 1u << (method - MAXWELL3D_REG_INDEX(instanced_arrays));
+ 1u << (method_call.method - MAXWELL3D_REG_INDEX(instanced_arrays));
}
}
- switch (method) {
+ switch (method_call.method) {
case MAXWELL3D_REG_INDEX(macros.data): {
- ProcessMacroUpload(value);
+ ProcessMacroUpload(method_call.argument);
break;
}
case MAXWELL3D_REG_INDEX(macros.bind): {
- ProcessMacroBind(value);
+ ProcessMacroBind(method_call.argument);
break;
}
case MAXWELL3D_REG_INDEX(const_buffer.cb_data[0]):
@@ -180,7 +215,7 @@ void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
case MAXWELL3D_REG_INDEX(const_buffer.cb_data[13]):
case MAXWELL3D_REG_INDEX(const_buffer.cb_data[14]):
case MAXWELL3D_REG_INDEX(const_buffer.cb_data[15]): {
- ProcessCBData(value);
+ ProcessCBData(method_call.argument);
break;
}
case MAXWELL3D_REG_INDEX(cb_bind[0].raw_config): {
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 9324d9710..1f76aa670 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -42,6 +42,7 @@ public:
static constexpr std::size_t NumVertexArrays = 32;
static constexpr std::size_t NumVertexAttributes = 32;
static constexpr std::size_t NumTextureSamplers = 32;
+ static constexpr std::size_t NumClipDistances = 8;
static constexpr std::size_t MaxShaderProgram = 6;
static constexpr std::size_t MaxShaderStage = 5;
// Maximum number of const buffers per shader stage.
@@ -163,6 +164,7 @@ public:
return 3;
default:
UNREACHABLE();
+ return 1;
}
}
@@ -744,7 +746,20 @@ public:
u32 vb_element_base;
- INSERT_PADDING_WORDS(0x38);
+ INSERT_PADDING_WORDS(0x36);
+
+ union {
+ BitField<0, 1, u32> c0;
+ BitField<1, 1, u32> c1;
+ BitField<2, 1, u32> c2;
+ BitField<3, 1, u32> c3;
+ BitField<4, 1, u32> c4;
+ BitField<5, 1, u32> c5;
+ BitField<6, 1, u32> c6;
+ BitField<7, 1, u32> c7;
+ } clip_distance_enabled;
+
+ INSERT_PADDING_WORDS(0x1);
float point_size;
@@ -857,6 +872,7 @@ public:
return 4;
}
UNREACHABLE();
+ return 1;
}
GPUVAddr StartAddress() const {
@@ -902,8 +918,15 @@ public:
u32 viewport_transform_enabled;
- INSERT_PADDING_WORDS(0x25);
+ INSERT_PADDING_WORDS(0x3);
+
+ union {
+ BitField<0, 1, u32> depth_range_0_1;
+ BitField<3, 1, u32> depth_clamp_near;
+ BitField<4, 1, u32> depth_clamp_far;
+ } view_volume_clip_control;
+ INSERT_PADDING_WORDS(0x21);
struct {
u32 enable;
LogicOperation operation;
@@ -1066,10 +1089,18 @@ public:
MemoryManager& memory_manager;
struct DirtyFlags {
+ u8 color_buffer = 0xFF;
+ bool zeta_buffer = true;
+
+ bool shaders = true;
+
bool vertex_attrib_format = true;
u32 vertex_array = 0xFFFFFFFF;
void OnMemoryWrite() {
+ color_buffer = 0xFF;
+ zeta_buffer = true;
+ shaders = true;
vertex_array = 0xFFFFFFFF;
}
};
@@ -1080,7 +1111,7 @@ public:
u32 GetRegisterValue(u32 method) const;
/// Write the value to the register identified by method.
- void WriteReg(u32 method, u32 value, u32 remaining_params);
+ void CallMethod(const GPU::MethodCall& method_call);
/// Returns a list of enabled textures for the specified shader stage.
std::vector<Texture::FullTextureInfo> GetStageTextures(Regs::ShaderStage stage) const;
@@ -1201,6 +1232,7 @@ ASSERT_REG_POSITION(stencil_front_mask, 0x4E7);
ASSERT_REG_POSITION(frag_color_clamp, 0x4EA);
ASSERT_REG_POSITION(screen_y_control, 0x4EB);
ASSERT_REG_POSITION(vb_element_base, 0x50D);
+ASSERT_REG_POSITION(clip_distance_enabled, 0x544);
ASSERT_REG_POSITION(point_size, 0x546);
ASSERT_REG_POSITION(zeta_enable, 0x54E);
ASSERT_REG_POSITION(multisample_control, 0x54F);
@@ -1224,6 +1256,7 @@ ASSERT_REG_POSITION(instanced_arrays, 0x620);
ASSERT_REG_POSITION(cull, 0x646);
ASSERT_REG_POSITION(pixel_center_integer, 0x649);
ASSERT_REG_POSITION(viewport_transform_enabled, 0x64B);
+ASSERT_REG_POSITION(view_volume_clip_control, 0x64F);
ASSERT_REG_POSITION(logic_op, 0x671);
ASSERT_REG_POSITION(clear_buffers, 0x674);
ASSERT_REG_POSITION(color_mask, 0x680);
diff --git a/src/video_core/engines/maxwell_compute.cpp b/src/video_core/engines/maxwell_compute.cpp
index 8b5f08351..656db6a61 100644
--- a/src/video_core/engines/maxwell_compute.cpp
+++ b/src/video_core/engines/maxwell_compute.cpp
@@ -8,13 +8,13 @@
namespace Tegra::Engines {
-void MaxwellCompute::WriteReg(u32 method, u32 value) {
- ASSERT_MSG(method < Regs::NUM_REGS,
+void MaxwellCompute::CallMethod(const GPU::MethodCall& method_call) {
+ ASSERT_MSG(method_call.method < Regs::NUM_REGS,
"Invalid MaxwellCompute register, increase the size of the Regs structure");
- regs.reg_array[method] = value;
+ regs.reg_array[method_call.method] = method_call.argument;
- switch (method) {
+ switch (method_call.method) {
case MAXWELL_COMPUTE_REG_INDEX(compute): {
LOG_CRITICAL(HW_GPU, "Compute shaders are not implemented");
UNREACHABLE();
diff --git a/src/video_core/engines/maxwell_compute.h b/src/video_core/engines/maxwell_compute.h
index 6ea934fb9..1d71f11bd 100644
--- a/src/video_core/engines/maxwell_compute.h
+++ b/src/video_core/engines/maxwell_compute.h
@@ -9,6 +9,7 @@
#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
+#include "video_core/gpu.h"
namespace Tegra::Engines {
@@ -42,7 +43,7 @@ public:
"MaxwellCompute Regs has wrong size");
/// Write the value to the register identified by method.
- void WriteReg(u32 method, u32 value);
+ void CallMethod(const GPU::MethodCall& method_call);
};
#define ASSERT_REG_POSITION(field_name, position) \
diff --git a/src/video_core/engines/maxwell_dma.cpp b/src/video_core/engines/maxwell_dma.cpp
index a34e884fe..06462f570 100644
--- a/src/video_core/engines/maxwell_dma.cpp
+++ b/src/video_core/engines/maxwell_dma.cpp
@@ -14,16 +14,16 @@ namespace Tegra::Engines {
MaxwellDMA::MaxwellDMA(VideoCore::RasterizerInterface& rasterizer, MemoryManager& memory_manager)
: memory_manager(memory_manager), rasterizer{rasterizer} {}
-void MaxwellDMA::WriteReg(u32 method, u32 value) {
- ASSERT_MSG(method < Regs::NUM_REGS,
+void MaxwellDMA::CallMethod(const GPU::MethodCall& method_call) {
+ ASSERT_MSG(method_call.method < Regs::NUM_REGS,
"Invalid MaxwellDMA register, increase the size of the Regs structure");
- regs.reg_array[method] = value;
+ regs.reg_array[method_call.method] = method_call.argument;
#define MAXWELLDMA_REG_INDEX(field_name) \
(offsetof(Tegra::Engines::MaxwellDMA::Regs, field_name) / sizeof(u32))
- switch (method) {
+ switch (method_call.method) {
case MAXWELLDMA_REG_INDEX(exec): {
HandleCopy();
break;
diff --git a/src/video_core/engines/maxwell_dma.h b/src/video_core/engines/maxwell_dma.h
index 5f3704f05..1f8cd65d2 100644
--- a/src/video_core/engines/maxwell_dma.h
+++ b/src/video_core/engines/maxwell_dma.h
@@ -24,7 +24,7 @@ public:
~MaxwellDMA() = default;
/// Write the value to the register identified by method.
- void WriteReg(u32 method, u32 value);
+ void CallMethod(const GPU::MethodCall& method_call);
struct Regs {
static constexpr std::size_t NUM_REGS = 0x1D6;
diff --git a/src/video_core/engines/shader_bytecode.h b/src/video_core/engines/shader_bytecode.h
index b9faaf8e0..9989825f8 100644
--- a/src/video_core/engines/shader_bytecode.h
+++ b/src/video_core/engines/shader_bytecode.h
@@ -208,6 +208,8 @@ enum class UniformType : u64 {
SignedShort = 3,
Single = 4,
Double = 5,
+ Quad = 6,
+ UnsignedQuad = 7,
};
enum class StoreType : u64 {
@@ -397,6 +399,10 @@ struct IpaMode {
bool operator!=(const IpaMode& a) const {
return !operator==(a);
}
+ bool operator<(const IpaMode& a) const {
+ return std::tie(interpolation_mode, sampling_mode) <
+ std::tie(a.interpolation_mode, a.sampling_mode);
+ }
};
enum class SystemVariable : u64 {
@@ -575,7 +581,7 @@ union Instruction {
union {
BitField<39, 2, u64> tab5cb8_2;
- BitField<41, 3, u64> tab5c68_1;
+ BitField<41, 3, u64> postfactor;
BitField<44, 2, u64> tab5c68_0;
BitField<48, 1, u64> negate_b;
} fmul;
@@ -609,7 +615,7 @@ union Instruction {
BitField<31, 1, u64> negate_b;
BitField<30, 1, u64> abs_b;
- BitField<47, 2, HalfType> type_b;
+ BitField<28, 2, HalfType> type_b;
BitField<35, 2, HalfType> type_c;
} alu_half;
@@ -644,6 +650,7 @@ union Instruction {
BitField<37, 2, HalfPrecision> precision;
BitField<32, 1, u64> saturate;
+ BitField<31, 1, u64> negate_b;
BitField<30, 1, u64> negate_c;
BitField<35, 2, HalfType> type_c;
} rr;
@@ -780,6 +787,12 @@ union Instruction {
} st_l;
union {
+ BitField<48, 3, UniformType> type;
+ BitField<46, 2, u64> cache_mode;
+ BitField<20, 24, s64> immediate_offset;
+ } ldg;
+
+ union {
BitField<0, 3, u64> pred0;
BitField<3, 3, u64> pred3;
BitField<7, 1, u64> abs_a;
@@ -1049,6 +1062,7 @@ union Instruction {
BitField<49, 1, u64> nodep_flag;
BitField<50, 3, u64> component_mask_selector;
BitField<53, 4, u64> texture_info;
+ BitField<59, 1, u64> fp32_flag;
TextureType GetTextureType() const {
// The TEXS instruction has a weird encoding for the texture type.
@@ -1064,6 +1078,7 @@ union Instruction {
LOG_CRITICAL(HW_GPU, "Unhandled texture_info: {}",
static_cast<u32>(texture_info.Value()));
UNREACHABLE();
+ return TextureType::Texture1D;
}
TextureProcessMode GetTextureProcessMode() const {
@@ -1144,6 +1159,7 @@ union Instruction {
LOG_CRITICAL(HW_GPU, "Unhandled texture_info: {}",
static_cast<u32>(texture_info.Value()));
UNREACHABLE();
+ return TextureType::Texture1D;
}
TextureProcessMode GetTextureProcessMode() const {
@@ -1428,6 +1444,7 @@ public:
PredicateSetRegister,
RegisterSetPredicate,
Conversion,
+ Video,
Xmad,
Unknown,
};
@@ -1549,7 +1566,7 @@ private:
INST("1110111011011---", Id::STG, Type::Memory, "STG"),
INST("110000----111---", Id::TEX, Type::Memory, "TEX"),
INST("1101111101001---", Id::TXQ, Type::Memory, "TXQ"),
- INST("1101100---------", Id::TEXS, Type::Memory, "TEXS"),
+ INST("1101-00---------", Id::TEXS, Type::Memory, "TEXS"),
INST("1101101---------", Id::TLDS, Type::Memory, "TLDS"),
INST("110010----111---", Id::TLD4, Type::Memory, "TLD4"),
INST("1101111100------", Id::TLD4S, Type::Memory, "TLD4S"),
@@ -1559,8 +1576,8 @@ private:
INST("11100000--------", Id::IPA, Type::Trivial, "IPA"),
INST("1111101111100---", Id::OUT_R, Type::Trivial, "OUT_R"),
INST("1110111111010---", Id::ISBERD, Type::Trivial, "ISBERD"),
- INST("01011111--------", Id::VMAD, Type::Trivial, "VMAD"),
- INST("0101000011110---", Id::VSETP, Type::Trivial, "VSETP"),
+ INST("01011111--------", Id::VMAD, Type::Video, "VMAD"),
+ INST("0101000011110---", Id::VSETP, Type::Video, "VSETP"),
INST("0011001-1-------", Id::FFMA_IMM, Type::Ffma, "FFMA_IMM"),
INST("010010011-------", Id::FFMA_CR, Type::Ffma, "FFMA_CR"),
INST("010100011-------", Id::FFMA_RC, Type::Ffma, "FFMA_RC"),
diff --git a/src/video_core/engines/shader_header.h b/src/video_core/engines/shader_header.h
index 99c34649f..cf2b76ff6 100644
--- a/src/video_core/engines/shader_header.h
+++ b/src/video_core/engines/shader_header.h
@@ -106,7 +106,7 @@ struct Header {
} ps;
};
- u64 GetLocalMemorySize() {
+ u64 GetLocalMemorySize() const {
return (common1.shader_local_memory_low_size |
(common2.shader_local_memory_high_size << 24));
}
diff --git a/src/video_core/gpu.cpp b/src/video_core/gpu.cpp
index 51b3904f6..d3d32a359 100644
--- a/src/video_core/gpu.cpp
+++ b/src/video_core/gpu.cpp
@@ -3,6 +3,8 @@
// Refer to the license.txt file included.
#include "common/assert.h"
+#include "core/core_timing.h"
+#include "core/memory.h"
#include "video_core/engines/fermi_2d.h"
#include "video_core/engines/kepler_memory.h"
#include "video_core/engines/maxwell_3d.h"
@@ -26,6 +28,7 @@ u32 FramebufferConfig::BytesPerPixel(PixelFormat format) {
GPU::GPU(VideoCore::RasterizerInterface& rasterizer) {
memory_manager = std::make_unique<Tegra::MemoryManager>();
+ dma_pusher = std::make_unique<Tegra::DmaPusher>(*this);
maxwell_3d = std::make_unique<Engines::Maxwell3D>(rasterizer, *memory_manager);
fermi_2d = std::make_unique<Engines::Fermi2D>(rasterizer, *memory_manager);
maxwell_compute = std::make_unique<Engines::MaxwellCompute>();
@@ -51,6 +54,14 @@ const MemoryManager& GPU::MemoryManager() const {
return *memory_manager;
}
+DmaPusher& GPU::DmaPusher() {
+ return *dma_pusher;
+}
+
+const DmaPusher& GPU::DmaPusher() const {
+ return *dma_pusher;
+}
+
u32 RenderTargetBytesPerPixel(RenderTargetFormat format) {
ASSERT(format != RenderTargetFormat::NONE);
@@ -93,6 +104,7 @@ u32 RenderTargetBytesPerPixel(RenderTargetFormat format) {
return 1;
default:
UNIMPLEMENTED_MSG("Unimplemented render target format {}", static_cast<u32>(format));
+ return 1;
}
}
@@ -110,6 +122,212 @@ u32 DepthFormatBytesPerPixel(DepthFormat format) {
return 2;
default:
UNIMPLEMENTED_MSG("Unimplemented Depth format {}", static_cast<u32>(format));
+ return 1;
+ }
+}
+
+// Note that, traditionally, methods are treated as 4-byte addressable locations, and hence
+// their numbers are written down multiplied by 4 in Docs. Here we are not multiply by 4.
+// So the values you see in docs might be multiplied by 4.
+enum class BufferMethods {
+ BindObject = 0x0,
+ Nop = 0x2,
+ SemaphoreAddressHigh = 0x4,
+ SemaphoreAddressLow = 0x5,
+ SemaphoreSequence = 0x6,
+ SemaphoreTrigger = 0x7,
+ NotifyIntr = 0x8,
+ WrcacheFlush = 0x9,
+ Unk28 = 0xA,
+ Unk2c = 0xB,
+ RefCnt = 0x14,
+ SemaphoreAcquire = 0x1A,
+ SemaphoreRelease = 0x1B,
+ Unk70 = 0x1C,
+ Unk74 = 0x1D,
+ Unk78 = 0x1E,
+ Unk7c = 0x1F,
+ Yield = 0x20,
+ NonPullerMethods = 0x40,
+};
+
+enum class GpuSemaphoreOperation {
+ AcquireEqual = 0x1,
+ WriteLong = 0x2,
+ AcquireGequal = 0x4,
+ AcquireMask = 0x8,
+};
+
+void GPU::CallMethod(const MethodCall& method_call) {
+ LOG_TRACE(HW_GPU, "Processing method {:08X} on subchannel {}", method_call.method,
+ method_call.subchannel);
+
+ ASSERT(method_call.subchannel < bound_engines.size());
+
+ if (ExecuteMethodOnEngine(method_call)) {
+ CallEngineMethod(method_call);
+ } else {
+ CallPullerMethod(method_call);
+ }
+}
+
+bool GPU::ExecuteMethodOnEngine(const MethodCall& method_call) {
+ const auto method = static_cast<BufferMethods>(method_call.method);
+ return method >= BufferMethods::NonPullerMethods;
+}
+
+void GPU::CallPullerMethod(const MethodCall& method_call) {
+ regs.reg_array[method_call.method] = method_call.argument;
+ const auto method = static_cast<BufferMethods>(method_call.method);
+
+ switch (method) {
+ case BufferMethods::BindObject: {
+ ProcessBindMethod(method_call);
+ break;
+ }
+ case BufferMethods::Nop:
+ case BufferMethods::SemaphoreAddressHigh:
+ case BufferMethods::SemaphoreAddressLow:
+ case BufferMethods::SemaphoreSequence:
+ case BufferMethods::RefCnt:
+ break;
+ case BufferMethods::SemaphoreTrigger: {
+ ProcessSemaphoreTriggerMethod();
+ break;
+ }
+ case BufferMethods::NotifyIntr: {
+ // TODO(Kmather73): Research and implement this method.
+ LOG_ERROR(HW_GPU, "Special puller engine method NotifyIntr not implemented");
+ break;
+ }
+ case BufferMethods::WrcacheFlush: {
+ // TODO(Kmather73): Research and implement this method.
+ LOG_ERROR(HW_GPU, "Special puller engine method WrcacheFlush not implemented");
+ break;
+ }
+ case BufferMethods::Unk28: {
+ // TODO(Kmather73): Research and implement this method.
+ LOG_ERROR(HW_GPU, "Special puller engine method Unk28 not implemented");
+ break;
+ }
+ case BufferMethods::Unk2c: {
+ // TODO(Kmather73): Research and implement this method.
+ LOG_ERROR(HW_GPU, "Special puller engine method Unk2c not implemented");
+ break;
+ }
+ case BufferMethods::SemaphoreAcquire: {
+ ProcessSemaphoreAcquire();
+ break;
+ }
+ case BufferMethods::SemaphoreRelease: {
+ ProcessSemaphoreRelease();
+ break;
+ }
+ case BufferMethods::Yield: {
+ // TODO(Kmather73): Research and implement this method.
+ LOG_ERROR(HW_GPU, "Special puller engine method Yield not implemented");
+ break;
+ }
+ default:
+ LOG_ERROR(HW_GPU, "Special puller engine method {:X} not implemented",
+ static_cast<u32>(method));
+ break;
+ }
+}
+
+void GPU::CallEngineMethod(const MethodCall& method_call) {
+ const EngineID engine = bound_engines[method_call.subchannel];
+
+ switch (engine) {
+ case EngineID::FERMI_TWOD_A:
+ fermi_2d->CallMethod(method_call);
+ break;
+ case EngineID::MAXWELL_B:
+ maxwell_3d->CallMethod(method_call);
+ break;
+ case EngineID::MAXWELL_COMPUTE_B:
+ maxwell_compute->CallMethod(method_call);
+ break;
+ case EngineID::MAXWELL_DMA_COPY_A:
+ maxwell_dma->CallMethod(method_call);
+ break;
+ case EngineID::KEPLER_INLINE_TO_MEMORY_B:
+ kepler_memory->CallMethod(method_call);
+ break;
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented engine");
+ }
+}
+
+void GPU::ProcessBindMethod(const MethodCall& method_call) {
+ // Bind the current subchannel to the desired engine id.
+ LOG_DEBUG(HW_GPU, "Binding subchannel {} to engine {}", method_call.subchannel,
+ method_call.argument);
+ bound_engines[method_call.subchannel] = static_cast<EngineID>(method_call.argument);
+}
+
+void GPU::ProcessSemaphoreTriggerMethod() {
+ const auto semaphoreOperationMask = 0xF;
+ const auto op =
+ static_cast<GpuSemaphoreOperation>(regs.semaphore_trigger & semaphoreOperationMask);
+ if (op == GpuSemaphoreOperation::WriteLong) {
+ auto address = memory_manager->GpuToCpuAddress(regs.smaphore_address.SmaphoreAddress());
+ struct Block {
+ u32 sequence;
+ u32 zeros = 0;
+ u64 timestamp;
+ };
+
+ Block block{};
+ block.sequence = regs.semaphore_sequence;
+ // TODO(Kmather73): Generate a real GPU timestamp and write it here instead of
+ // CoreTiming
+ block.timestamp = CoreTiming::GetTicks();
+ Memory::WriteBlock(*address, &block, sizeof(block));
+ } else {
+ const auto address =
+ memory_manager->GpuToCpuAddress(regs.smaphore_address.SmaphoreAddress());
+ const u32 word = Memory::Read32(*address);
+ if ((op == GpuSemaphoreOperation::AcquireEqual && word == regs.semaphore_sequence) ||
+ (op == GpuSemaphoreOperation::AcquireGequal &&
+ static_cast<s32>(word - regs.semaphore_sequence) > 0) ||
+ (op == GpuSemaphoreOperation::AcquireMask && (word & regs.semaphore_sequence))) {
+ // Nothing to do in this case
+ } else {
+ regs.acquire_source = true;
+ regs.acquire_value = regs.semaphore_sequence;
+ if (op == GpuSemaphoreOperation::AcquireEqual) {
+ regs.acquire_active = true;
+ regs.acquire_mode = false;
+ } else if (op == GpuSemaphoreOperation::AcquireGequal) {
+ regs.acquire_active = true;
+ regs.acquire_mode = true;
+ } else if (op == GpuSemaphoreOperation::AcquireMask) {
+ // TODO(kemathe) The acquire mask operation waits for a value that, ANDed with
+ // semaphore_sequence, gives a non-0 result
+ LOG_ERROR(HW_GPU, "Invalid semaphore operation AcquireMask not implemented");
+ } else {
+ LOG_ERROR(HW_GPU, "Invalid semaphore operation");
+ }
+ }
+ }
+}
+
+void GPU::ProcessSemaphoreRelease() {
+ const auto address = memory_manager->GpuToCpuAddress(regs.smaphore_address.SmaphoreAddress());
+ Memory::Write32(*address, regs.semaphore_release);
+}
+
+void GPU::ProcessSemaphoreAcquire() {
+ const auto address = memory_manager->GpuToCpuAddress(regs.smaphore_address.SmaphoreAddress());
+ const u32 word = Memory::Read32(*address);
+ const auto value = regs.semaphore_acquire;
+ if (word != value) {
+ regs.acquire_active = true;
+ regs.acquire_value = value;
+ // TODO(kemathe73) figure out how to do the acquire_timeout
+ regs.acquire_mode = false;
+ regs.acquire_source = false;
}
}
diff --git a/src/video_core/gpu.h b/src/video_core/gpu.h
index 5cc1e19ca..fb8975811 100644
--- a/src/video_core/gpu.h
+++ b/src/video_core/gpu.h
@@ -9,6 +9,7 @@
#include <vector>
#include "common/common_types.h"
#include "core/hle/service/nvflinger/buffer_queue.h"
+#include "video_core/dma_pusher.h"
#include "video_core/memory_manager.h"
namespace VideoCore {
@@ -119,8 +120,23 @@ public:
explicit GPU(VideoCore::RasterizerInterface& rasterizer);
~GPU();
- /// Processes a command list stored at the specified address in GPU memory.
- void ProcessCommandLists(const std::vector<CommandListHeader>& commands);
+ struct MethodCall {
+ u32 method{};
+ u32 argument{};
+ u32 subchannel{};
+ u32 method_count{};
+
+ bool IsLastCall() const {
+ return method_count <= 1;
+ }
+
+ MethodCall(u32 method, u32 argument, u32 subchannel = 0, u32 method_count = 0)
+ : method(method), argument(argument), subchannel(subchannel),
+ method_count(method_count) {}
+ };
+
+ /// Calls a GPU method.
+ void CallMethod(const MethodCall& method_call);
/// Returns a reference to the Maxwell3D GPU engine.
Engines::Maxwell3D& Maxwell3D();
@@ -134,7 +150,54 @@ public:
/// Returns a const reference to the GPU memory manager.
const Tegra::MemoryManager& MemoryManager() const;
+ /// Returns a reference to the GPU DMA pusher.
+ Tegra::DmaPusher& DmaPusher();
+
+ /// Returns a const reference to the GPU DMA pusher.
+ const Tegra::DmaPusher& DmaPusher() const;
+
+ struct Regs {
+ static constexpr size_t NUM_REGS = 0x100;
+
+ union {
+ struct {
+ INSERT_PADDING_WORDS(0x4);
+ struct {
+ u32 address_high;
+ u32 address_low;
+
+ GPUVAddr SmaphoreAddress() const {
+ return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
+ address_low);
+ }
+ } smaphore_address;
+
+ u32 semaphore_sequence;
+ u32 semaphore_trigger;
+ INSERT_PADDING_WORDS(0xC);
+
+ // The puser and the puller share the reference counter, the pusher only has read
+ // access
+ u32 reference_count;
+ INSERT_PADDING_WORDS(0x5);
+
+ u32 semaphore_acquire;
+ u32 semaphore_release;
+ INSERT_PADDING_WORDS(0xE4);
+
+ // Puller state
+ u32 acquire_mode;
+ u32 acquire_source;
+ u32 acquire_active;
+ u32 acquire_timeout;
+ u32 acquire_value;
+ };
+ std::array<u32, NUM_REGS> reg_array;
+ };
+ } regs{};
+
private:
+ std::unique_ptr<Tegra::DmaPusher> dma_pusher;
std::unique_ptr<Tegra::MemoryManager> memory_manager;
/// Mapping of command subchannels to their bound engine ids.
@@ -150,6 +213,37 @@ private:
std::unique_ptr<Engines::MaxwellDMA> maxwell_dma;
/// Inline memory engine
std::unique_ptr<Engines::KeplerMemory> kepler_memory;
+
+ void ProcessBindMethod(const MethodCall& method_call);
+ void ProcessSemaphoreTriggerMethod();
+ void ProcessSemaphoreRelease();
+ void ProcessSemaphoreAcquire();
+
+ // Calls a GPU puller method.
+ void CallPullerMethod(const MethodCall& method_call);
+ // Calls a GPU engine method.
+ void CallEngineMethod(const MethodCall& method_call);
+ // Determines where the method should be executed.
+ bool ExecuteMethodOnEngine(const MethodCall& method_call);
};
+#define ASSERT_REG_POSITION(field_name, position) \
+ static_assert(offsetof(GPU::Regs, field_name) == position * 4, \
+ "Field " #field_name " has invalid position")
+
+ASSERT_REG_POSITION(smaphore_address, 0x4);
+ASSERT_REG_POSITION(semaphore_sequence, 0x6);
+ASSERT_REG_POSITION(semaphore_trigger, 0x7);
+ASSERT_REG_POSITION(reference_count, 0x14);
+ASSERT_REG_POSITION(semaphore_acquire, 0x1A);
+ASSERT_REG_POSITION(semaphore_release, 0x1B);
+
+ASSERT_REG_POSITION(acquire_mode, 0x100);
+ASSERT_REG_POSITION(acquire_source, 0x101);
+ASSERT_REG_POSITION(acquire_active, 0x102);
+ASSERT_REG_POSITION(acquire_timeout, 0x103);
+ASSERT_REG_POSITION(acquire_value, 0x104);
+
+#undef ASSERT_REG_POSITION
+
} // namespace Tegra
diff --git a/src/video_core/macro_interpreter.cpp b/src/video_core/macro_interpreter.cpp
index 2b0dea5cd..64f75db43 100644
--- a/src/video_core/macro_interpreter.cpp
+++ b/src/video_core/macro_interpreter.cpp
@@ -171,6 +171,7 @@ u32 MacroInterpreter::GetALUResult(ALUOperation operation, u32 src_a, u32 src_b)
default:
UNIMPLEMENTED_MSG("Unimplemented ALU operation {}", static_cast<u32>(operation));
+ return 0;
}
}
@@ -250,7 +251,7 @@ void MacroInterpreter::SetMethodAddress(u32 address) {
}
void MacroInterpreter::Send(u32 value) {
- maxwell3d.WriteReg(method_address.address, value, 0);
+ maxwell3d.CallMethod({method_address.address, value});
// Increment the method address by the method increment.
method_address.address.Assign(method_address.address.Value() +
method_address.increment.Value());
@@ -268,6 +269,7 @@ bool MacroInterpreter::EvaluateBranchCondition(BranchCondition cond, u32 value)
return value != 0;
}
UNREACHABLE();
+ return true;
}
} // namespace Tegra
diff --git a/src/video_core/morton.cpp b/src/video_core/morton.cpp
index a310491a8..b68f4fb13 100644
--- a/src/video_core/morton.cpp
+++ b/src/video_core/morton.cpp
@@ -66,8 +66,6 @@ static constexpr ConversionArray morton_to_linear_fns = {
MortonCopy<true, PixelFormat::BC6H_UF16>,
MortonCopy<true, PixelFormat::BC6H_SF16>,
MortonCopy<true, PixelFormat::ASTC_2D_4X4>,
- MortonCopy<true, PixelFormat::G8R8U>,
- MortonCopy<true, PixelFormat::G8R8S>,
MortonCopy<true, PixelFormat::BGRA8>,
MortonCopy<true, PixelFormat::RGBA32F>,
MortonCopy<true, PixelFormat::RG32F>,
@@ -138,8 +136,6 @@ static constexpr ConversionArray linear_to_morton_fns = {
MortonCopy<false, PixelFormat::BC6H_SF16>,
// TODO(Subv): Swizzling ASTC formats are not supported
nullptr,
- MortonCopy<false, PixelFormat::G8R8U>,
- MortonCopy<false, PixelFormat::G8R8S>,
MortonCopy<false, PixelFormat::BGRA8>,
MortonCopy<false, PixelFormat::RGBA32F>,
MortonCopy<false, PixelFormat::RG32F>,
@@ -192,6 +188,7 @@ static MortonCopyFn GetSwizzleFunction(MortonSwizzleMode mode, Surface::PixelFor
return linear_to_morton_fns[static_cast<std::size_t>(format)];
}
UNREACHABLE();
+ return morton_to_linear_fns[static_cast<std::size_t>(format)];
}
/// 8x8 Z-Order coordinate from 2D coordinates
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index 06fc59dbe..ff5310848 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -4,6 +4,7 @@
#pragma once
+#include <functional>
#include "common/common_types.h"
#include "video_core/engines/fermi_2d.h"
#include "video_core/gpu.h"
@@ -11,6 +12,14 @@
namespace VideoCore {
+enum class LoadCallbackStage {
+ Prepare,
+ Decompile,
+ Build,
+ Complete,
+};
+using DiskResourceLoadCallback = std::function<void(LoadCallbackStage, std::size_t, std::size_t)>;
+
class RasterizerInterface {
public:
virtual ~RasterizerInterface() {}
diff --git a/src/video_core/renderer_base.cpp b/src/video_core/renderer_base.cpp
index 1482cdb40..94223f45f 100644
--- a/src/video_core/renderer_base.cpp
+++ b/src/video_core/renderer_base.cpp
@@ -27,4 +27,16 @@ void RendererBase::UpdateCurrentFramebufferLayout() {
render_window.UpdateCurrentFramebufferLayout(layout.width, layout.height);
}
+void RendererBase::RequestScreenshot(void* data, std::function<void()> callback,
+ const Layout::FramebufferLayout& layout) {
+ if (renderer_settings.screenshot_requested) {
+ LOG_ERROR(Render, "A screenshot is already requested or in progress, ignoring the request");
+ return;
+ }
+ renderer_settings.screenshot_bits = data;
+ renderer_settings.screenshot_complete_callback = std::move(callback);
+ renderer_settings.screenshot_framebuffer_layout = layout;
+ renderer_settings.screenshot_requested = true;
+}
+
} // namespace VideoCore
diff --git a/src/video_core/renderer_base.h b/src/video_core/renderer_base.h
index 669e26e15..1d54c3723 100644
--- a/src/video_core/renderer_base.h
+++ b/src/video_core/renderer_base.h
@@ -9,6 +9,7 @@
#include <optional>
#include "common/common_types.h"
+#include "core/frontend/emu_window.h"
#include "video_core/gpu.h"
#include "video_core/rasterizer_interface.h"
@@ -21,6 +22,12 @@ namespace VideoCore {
struct RendererSettings {
std::atomic_bool use_framelimiter{false};
std::atomic_bool set_background_color{false};
+
+ // Screenshot
+ std::atomic<bool> screenshot_requested{false};
+ void* screenshot_bits;
+ std::function<void()> screenshot_complete_callback;
+ Layout::FramebufferLayout screenshot_framebuffer_layout;
};
class RendererBase : NonCopyable {
@@ -57,9 +64,29 @@ public:
return *rasterizer;
}
+ Core::Frontend::EmuWindow& GetRenderWindow() {
+ return render_window;
+ }
+
+ const Core::Frontend::EmuWindow& GetRenderWindow() const {
+ return render_window;
+ }
+
+ RendererSettings& Settings() {
+ return renderer_settings;
+ }
+
+ const RendererSettings& Settings() const {
+ return renderer_settings;
+ }
+
/// Refreshes the settings common to all renderers
void RefreshBaseSettings();
+ /// Request a screenshot of the next frame
+ void RequestScreenshot(void* data, std::function<void()> callback,
+ const Layout::FramebufferLayout& layout);
+
protected:
Core::Frontend::EmuWindow& render_window; ///< Reference to the render window handle.
std::unique_ptr<RasterizerInterface> rasterizer;
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.cpp b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
index 46a6c0308..bd2b30e77 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
@@ -14,7 +14,7 @@
namespace OpenGL {
OGLBufferCache::OGLBufferCache(RasterizerOpenGL& rasterizer, std::size_t size)
- : RasterizerCache{rasterizer}, stream_buffer(GL_ARRAY_BUFFER, size) {}
+ : RasterizerCache{rasterizer}, stream_buffer(size, true) {}
GLintptr OGLBufferCache::UploadMemory(Tegra::GPUVAddr gpu_addr, std::size_t size,
std::size_t alignment, bool cache) {
diff --git a/src/video_core/renderer_opengl/gl_global_cache.cpp b/src/video_core/renderer_opengl/gl_global_cache.cpp
new file mode 100644
index 000000000..c7f32feaa
--- /dev/null
+++ b/src/video_core/renderer_opengl/gl_global_cache.cpp
@@ -0,0 +1,94 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <glad/glad.h>
+
+#include "common/assert.h"
+#include "common/logging/log.h"
+#include "core/core.h"
+#include "core/memory.h"
+#include "video_core/renderer_opengl/gl_global_cache.h"
+#include "video_core/renderer_opengl/gl_rasterizer.h"
+#include "video_core/renderer_opengl/gl_shader_decompiler.h"
+#include "video_core/renderer_opengl/utils.h"
+
+namespace OpenGL {
+
+CachedGlobalRegion::CachedGlobalRegion(VAddr addr, u32 size) : addr{addr}, size{size} {
+ buffer.Create();
+ // Bind and unbind the buffer so it gets allocated by the driver
+ glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer.handle);
+ glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
+ LabelGLObject(GL_BUFFER, buffer.handle, addr, "GlobalMemory");
+}
+
+void CachedGlobalRegion::Reload(u32 size_) {
+ constexpr auto max_size = static_cast<u32>(RasterizerOpenGL::MaxGlobalMemorySize);
+
+ size = size_;
+ if (size > max_size) {
+ size = max_size;
+ LOG_CRITICAL(HW_GPU, "Global region size {} exceeded the expected size {}!", size_,
+ max_size);
+ }
+
+ // TODO(Rodrigo): Get rid of Memory::GetPointer with a staging buffer
+ glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer.handle);
+ glBufferData(GL_SHADER_STORAGE_BUFFER, size, Memory::GetPointer(addr), GL_DYNAMIC_DRAW);
+}
+
+GlobalRegion GlobalRegionCacheOpenGL::TryGetReservedGlobalRegion(VAddr addr, u32 size) const {
+ const auto search{reserve.find(addr)};
+ if (search == reserve.end()) {
+ return {};
+ }
+ return search->second;
+}
+
+GlobalRegion GlobalRegionCacheOpenGL::GetUncachedGlobalRegion(VAddr addr, u32 size) {
+ GlobalRegion region{TryGetReservedGlobalRegion(addr, size)};
+ if (!region) {
+ // No reserved surface available, create a new one and reserve it
+ region = std::make_shared<CachedGlobalRegion>(addr, size);
+ ReserveGlobalRegion(region);
+ }
+ region->Reload(size);
+ return region;
+}
+
+void GlobalRegionCacheOpenGL::ReserveGlobalRegion(const GlobalRegion& region) {
+ reserve[region->GetAddr()] = region;
+}
+
+GlobalRegionCacheOpenGL::GlobalRegionCacheOpenGL(RasterizerOpenGL& rasterizer)
+ : RasterizerCache{rasterizer} {}
+
+GlobalRegion GlobalRegionCacheOpenGL::GetGlobalRegion(
+ const GLShader::GlobalMemoryEntry& global_region,
+ Tegra::Engines::Maxwell3D::Regs::ShaderStage stage) {
+
+ auto& gpu{Core::System::GetInstance().GPU()};
+ const auto cbufs = gpu.Maxwell3D().state.shader_stages[static_cast<u64>(stage)];
+ const auto cbuf_addr = gpu.MemoryManager().GpuToCpuAddress(
+ cbufs.const_buffers[global_region.GetCbufIndex()].address + global_region.GetCbufOffset());
+ ASSERT(cbuf_addr);
+
+ const auto actual_addr_gpu = Memory::Read64(*cbuf_addr);
+ const auto size = Memory::Read32(*cbuf_addr + 8);
+ const auto actual_addr = gpu.MemoryManager().GpuToCpuAddress(actual_addr_gpu);
+ ASSERT(actual_addr);
+
+ // Look up global region in the cache based on address
+ GlobalRegion region = TryGet(*actual_addr);
+
+ if (!region) {
+ // No global region found - create a new one
+ region = GetUncachedGlobalRegion(*actual_addr, size);
+ Register(region);
+ }
+
+ return region;
+}
+
+} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_global_cache.h b/src/video_core/renderer_opengl/gl_global_cache.h
new file mode 100644
index 000000000..37830bb7c
--- /dev/null
+++ b/src/video_core/renderer_opengl/gl_global_cache.h
@@ -0,0 +1,78 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+#include <unordered_map>
+
+#include <glad/glad.h>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/maxwell_3d.h"
+#include "video_core/rasterizer_cache.h"
+#include "video_core/renderer_opengl/gl_resource_manager.h"
+
+namespace OpenGL {
+
+namespace GLShader {
+class GlobalMemoryEntry;
+} // namespace GLShader
+
+class RasterizerOpenGL;
+class CachedGlobalRegion;
+using GlobalRegion = std::shared_ptr<CachedGlobalRegion>;
+
+class CachedGlobalRegion final : public RasterizerCacheObject {
+public:
+ explicit CachedGlobalRegion(VAddr addr, u32 size);
+
+ /// Gets the address of the shader in guest memory, required for cache management
+ VAddr GetAddr() const {
+ return addr;
+ }
+
+ /// Gets the size of the shader in guest memory, required for cache management
+ std::size_t GetSizeInBytes() const {
+ return size;
+ }
+
+ /// Gets the GL program handle for the buffer
+ GLuint GetBufferHandle() const {
+ return buffer.handle;
+ }
+
+ /// Reloads the global region from guest memory
+ void Reload(u32 size_);
+
+ // TODO(Rodrigo): When global memory is written (STG), implement flushing
+ void Flush() override {
+ UNIMPLEMENTED();
+ }
+
+private:
+ VAddr addr{};
+ u32 size{};
+
+ OGLBuffer buffer;
+};
+
+class GlobalRegionCacheOpenGL final : public RasterizerCache<GlobalRegion> {
+public:
+ explicit GlobalRegionCacheOpenGL(RasterizerOpenGL& rasterizer);
+
+ /// Gets the current specified shader stage program
+ GlobalRegion GetGlobalRegion(const GLShader::GlobalMemoryEntry& descriptor,
+ Tegra::Engines::Maxwell3D::Regs::ShaderStage stage);
+
+private:
+ GlobalRegion TryGetReservedGlobalRegion(VAddr addr, u32 size) const;
+ GlobalRegion GetUncachedGlobalRegion(VAddr addr, u32 size);
+ void ReserveGlobalRegion(const GlobalRegion& region);
+
+ std::unordered_map<VAddr, GlobalRegion> reserve;
+};
+
+} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index 82b7a0649..ee313cb2f 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -79,33 +79,37 @@ struct DrawParameters {
}
};
+struct FramebufferCacheKey {
+ bool is_single_buffer = false;
+ bool stencil_enable = false;
+
+ std::array<GLenum, Maxwell::NumRenderTargets> color_attachments{};
+ std::array<GLuint, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> colors{};
+ u32 colors_count = 0;
+
+ GLuint zeta = 0;
+
+ auto Tie() const {
+ return std::tie(is_single_buffer, stencil_enable, color_attachments, colors, colors_count,
+ zeta);
+ }
+
+ bool operator<(const FramebufferCacheKey& rhs) const {
+ return Tie() < rhs.Tie();
+ }
+};
+
RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
: res_cache{*this}, shader_cache{*this}, emu_window{window}, screen_info{info},
- buffer_cache(*this, STREAM_BUFFER_SIZE) {
+ buffer_cache(*this, STREAM_BUFFER_SIZE), global_cache{*this} {
// Create sampler objects
for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
texture_samplers[i].Create();
state.texture_units[i].sampler = texture_samplers[i].sampler.handle;
}
- GLint ext_num;
- glGetIntegerv(GL_NUM_EXTENSIONS, &ext_num);
- for (GLint i = 0; i < ext_num; i++) {
- const std::string_view extension{
- reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i))};
-
- if (extension == "GL_ARB_direct_state_access") {
- has_ARB_direct_state_access = true;
- } else if (extension == "GL_ARB_multi_bind") {
- has_ARB_multi_bind = true;
- }
- }
-
OpenGLState::ApplyDefaultState();
- // Create render framebuffer
- framebuffer.Create();
-
shader_program_manager = std::make_unique<GLShader::ProgramManager>();
state.draw.shader_program = 0;
state.Apply();
@@ -113,31 +117,49 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uniform_buffer_alignment);
LOG_CRITICAL(Render_OpenGL, "Sync fixed function OpenGL state here!");
+ CheckExtensions();
}
RasterizerOpenGL::~RasterizerOpenGL() {}
-void RasterizerOpenGL::SetupVertexFormat() {
+void RasterizerOpenGL::CheckExtensions() {
+ if (!GLAD_GL_ARB_texture_filter_anisotropic && !GLAD_GL_EXT_texture_filter_anisotropic) {
+ LOG_WARNING(
+ Render_OpenGL,
+ "Anisotropic filter is not supported! This can cause graphical issues in some games.");
+ }
+ if (!GLAD_GL_ARB_buffer_storage) {
+ LOG_WARNING(
+ Render_OpenGL,
+ "Buffer storage control is not supported! This can cause performance degradation.");
+ }
+}
+
+GLuint RasterizerOpenGL::SetupVertexFormat() {
auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
const auto& regs = gpu.regs;
- if (!gpu.dirty_flags.vertex_attrib_format)
- return;
+ if (!gpu.dirty_flags.vertex_attrib_format) {
+ return state.draw.vertex_array;
+ }
gpu.dirty_flags.vertex_attrib_format = false;
MICROPROFILE_SCOPE(OpenGL_VAO);
auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
- auto& VAO = iter->second;
+ auto& vao_entry = iter->second;
if (is_cache_miss) {
- VAO.Create();
- state.draw.vertex_array = VAO.handle;
- state.ApplyVertexBufferState();
+ vao_entry.Create();
+ const GLuint vao = vao_entry.handle;
+
+ // Eventhough we are using DSA to create this vertex array, there is a bug on Intel's blob
+ // that fails to properly create the vertex array if it's not bound even after creating it
+ // with glCreateVertexArrays
+ state.draw.vertex_array = vao;
+ state.ApplyVertexArrayState();
- // The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
- // around.
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_cache.GetHandle());
+ glVertexArrayElementBuffer(vao, buffer_cache.GetHandle());
// Use the vertex array as-is, assumes that the data is formatted correctly for OpenGL.
// Enables the first 16 vertex attributes always, as we don't know which ones are actually
@@ -145,7 +167,7 @@ void RasterizerOpenGL::SetupVertexFormat() {
// for now to avoid OpenGL errors.
// TODO(Subv): Analyze the shader to identify which attributes are actually used and don't
// assume every shader uses them all.
- for (unsigned index = 0; index < 16; ++index) {
+ for (u32 index = 0; index < 16; ++index) {
const auto& attrib = regs.vertex_attrib_format[index];
// Ignore invalid attributes.
@@ -160,28 +182,29 @@ void RasterizerOpenGL::SetupVertexFormat() {
ASSERT(buffer.IsEnabled());
- glEnableVertexAttribArray(index);
+ glEnableVertexArrayAttrib(vao, index);
if (attrib.type == Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::SignedInt ||
attrib.type ==
Tegra::Engines::Maxwell3D::Regs::VertexAttribute::Type::UnsignedInt) {
- glVertexAttribIFormat(index, attrib.ComponentCount(),
- MaxwellToGL::VertexType(attrib), attrib.offset);
+ glVertexArrayAttribIFormat(vao, index, attrib.ComponentCount(),
+ MaxwellToGL::VertexType(attrib), attrib.offset);
} else {
- glVertexAttribFormat(index, attrib.ComponentCount(),
- MaxwellToGL::VertexType(attrib),
- attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
+ glVertexArrayAttribFormat(
+ vao, index, attrib.ComponentCount(), MaxwellToGL::VertexType(attrib),
+ attrib.IsNormalized() ? GL_TRUE : GL_FALSE, attrib.offset);
}
- glVertexAttribBinding(index, attrib.buffer);
+ glVertexArrayAttribBinding(vao, index, attrib.buffer);
}
}
- state.draw.vertex_array = VAO.handle;
- state.ApplyVertexBufferState();
// Rebinding the VAO invalidates the vertex buffer bindings.
gpu.dirty_flags.vertex_array = 0xFFFFFFFF;
+
+ state.draw.vertex_array = vao_entry.handle;
+ return vao_entry.handle;
}
-void RasterizerOpenGL::SetupVertexBuffer() {
+void RasterizerOpenGL::SetupVertexBuffer(GLuint vao) {
auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
const auto& regs = gpu.regs;
@@ -199,7 +222,7 @@ void RasterizerOpenGL::SetupVertexBuffer() {
if (!vertex_array.IsEnabled())
continue;
- Tegra::GPUVAddr start = vertex_array.StartAddress();
+ const Tegra::GPUVAddr start = vertex_array.StartAddress();
const Tegra::GPUVAddr end = regs.vertex_array_limit[index].LimitAddress();
ASSERT(end > start);
@@ -207,21 +230,18 @@ void RasterizerOpenGL::SetupVertexBuffer() {
const GLintptr vertex_buffer_offset = buffer_cache.UploadMemory(start, size);
// Bind the vertex array to the buffer at the current offset.
- glBindVertexBuffer(index, buffer_cache.GetHandle(), vertex_buffer_offset,
- vertex_array.stride);
+ glVertexArrayVertexBuffer(vao, index, buffer_cache.GetHandle(), vertex_buffer_offset,
+ vertex_array.stride);
if (regs.instanced_arrays.IsInstancingEnabled(index) && vertex_array.divisor != 0) {
// Enable vertex buffer instancing with the specified divisor.
- glVertexBindingDivisor(index, vertex_array.divisor);
+ glVertexArrayBindingDivisor(vao, index, vertex_array.divisor);
} else {
// Disable the vertex buffer instancing.
- glVertexBindingDivisor(index, 0);
+ glVertexArrayBindingDivisor(vao, index, 0);
}
}
- // Implicit set by glBindVertexBuffer. Stupid glstate handling...
- state.draw.vertex_buffer = buffer_cache.GetHandle();
-
gpu.dirty_flags.vertex_array = 0;
}
@@ -275,12 +295,10 @@ DrawParameters RasterizerOpenGL::SetupDraw() {
void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
MICROPROFILE_SCOPE(OpenGL_Shader);
- const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
+ auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
- // Next available bindpoints to use when uploading the const buffers and textures to the GLSL
- // shaders. The constbuffer bindpoint starts after the shader stage configuration bind points.
- u32 current_constbuffer_bindpoint = Tegra::Engines::Maxwell3D::Regs::MaxShaderStage;
- u32 current_texture_bindpoint = 0;
+ BaseBindings base_bindings;
+ std::array<bool, Maxwell::NumClipDistances> clip_distances{};
for (std::size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
const auto& shader_config = gpu.regs.shader_config[index];
@@ -303,49 +321,93 @@ void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
const GLintptr offset = buffer_cache.UploadHostMemory(
&ubo, sizeof(ubo), static_cast<std::size_t>(uniform_buffer_alignment));
- // Bind the buffer
- glBindBufferRange(GL_UNIFORM_BUFFER, static_cast<GLuint>(stage), buffer_cache.GetHandle(),
- offset, static_cast<GLsizeiptr>(sizeof(ubo)));
+ // Bind the emulation info buffer
+ glBindBufferRange(GL_UNIFORM_BUFFER, base_bindings.cbuf, buffer_cache.GetHandle(), offset,
+ static_cast<GLsizeiptr>(sizeof(ubo)));
Shader shader{shader_cache.GetStageProgram(program)};
+ const auto [program_handle, next_bindings] =
+ shader->GetProgramHandle(primitive_mode, base_bindings);
switch (program) {
case Maxwell::ShaderProgram::VertexA:
- case Maxwell::ShaderProgram::VertexB: {
- shader_program_manager->UseProgrammableVertexShader(
- shader->GetProgramHandle(primitive_mode));
+ case Maxwell::ShaderProgram::VertexB:
+ shader_program_manager->UseProgrammableVertexShader(program_handle);
break;
- }
- case Maxwell::ShaderProgram::Geometry: {
- shader_program_manager->UseProgrammableGeometryShader(
- shader->GetProgramHandle(primitive_mode));
+ case Maxwell::ShaderProgram::Geometry:
+ shader_program_manager->UseProgrammableGeometryShader(program_handle);
break;
- }
- case Maxwell::ShaderProgram::Fragment: {
- shader_program_manager->UseProgrammableFragmentShader(
- shader->GetProgramHandle(primitive_mode));
+ case Maxwell::ShaderProgram::Fragment:
+ shader_program_manager->UseProgrammableFragmentShader(program_handle);
break;
- }
default:
LOG_CRITICAL(HW_GPU, "Unimplemented shader index={}, enable={}, offset=0x{:08X}", index,
shader_config.enable.Value(), shader_config.offset);
UNREACHABLE();
}
- // Configure the const buffers for this shader stage.
- current_constbuffer_bindpoint =
- SetupConstBuffers(static_cast<Maxwell::ShaderStage>(stage), shader, primitive_mode,
- current_constbuffer_bindpoint);
-
- // Configure the textures for this shader stage.
- current_texture_bindpoint = SetupTextures(static_cast<Maxwell::ShaderStage>(stage), shader,
- primitive_mode, current_texture_bindpoint);
+ const auto stage_enum = static_cast<Maxwell::ShaderStage>(stage);
+ SetupConstBuffers(stage_enum, shader, program_handle, base_bindings);
+ SetupGlobalRegions(stage_enum, shader, program_handle, base_bindings);
+ SetupTextures(stage_enum, shader, program_handle, base_bindings);
+
+ // Workaround for Intel drivers.
+ // When a clip distance is enabled but not set in the shader it crops parts of the screen
+ // (sometimes it's half the screen, sometimes three quarters). To avoid this, enable the
+ // clip distances only when it's written by a shader stage.
+ for (std::size_t i = 0; i < Maxwell::NumClipDistances; ++i) {
+ clip_distances[i] = clip_distances[i] || shader->GetShaderEntries().clip_distances[i];
+ }
// When VertexA is enabled, we have dual vertex shaders
if (program == Maxwell::ShaderProgram::VertexA) {
// VertexB was combined with VertexA, so we skip the VertexB iteration
index++;
}
+
+ base_bindings = next_bindings;
+ }
+
+ SyncClipEnabled(clip_distances);
+
+ gpu.dirty_flags.shaders = false;
+}
+
+void RasterizerOpenGL::SetupCachedFramebuffer(const FramebufferCacheKey& fbkey,
+ OpenGLState& current_state) {
+ const auto [entry, is_cache_miss] = framebuffer_cache.try_emplace(fbkey);
+ auto& framebuffer = entry->second;
+
+ if (is_cache_miss)
+ framebuffer.Create();
+
+ current_state.draw.draw_framebuffer = framebuffer.handle;
+ current_state.ApplyFramebufferState();
+
+ if (!is_cache_miss)
+ return;
+
+ if (fbkey.is_single_buffer) {
+ if (fbkey.color_attachments[0] != GL_NONE) {
+ glFramebufferTexture(GL_DRAW_FRAMEBUFFER, fbkey.color_attachments[0], fbkey.colors[0],
+ 0);
+ }
+ glDrawBuffer(fbkey.color_attachments[0]);
+ } else {
+ for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
+ if (fbkey.colors[index]) {
+ glFramebufferTexture(GL_DRAW_FRAMEBUFFER,
+ GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
+ fbkey.colors[index], 0);
+ }
+ }
+ glDrawBuffers(fbkey.colors_count, fbkey.color_attachments.data());
+ }
+
+ if (fbkey.zeta) {
+ GLenum zeta_attachment =
+ fbkey.stencil_enable ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT;
+ glFramebufferTexture(GL_DRAW_FRAMEBUFFER, zeta_attachment, fbkey.zeta, 0);
}
}
@@ -419,23 +481,32 @@ void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool us
bool using_depth_fb, bool preserve_contents,
std::optional<std::size_t> single_color_target) {
MICROPROFILE_SCOPE(OpenGL_Framebuffer);
- const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
+ const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
+ const auto& regs = gpu.regs;
+
+ const FramebufferConfigState fb_config_state{using_color_fb, using_depth_fb, preserve_contents,
+ single_color_target};
+ if (fb_config_state == current_framebuffer_config_state && gpu.dirty_flags.color_buffer == 0 &&
+ !gpu.dirty_flags.zeta_buffer) {
+ // Only skip if the previous ConfigureFramebuffers call was from the same kind (multiple or
+ // single color targets). This is done because the guest registers may not change but the
+ // host framebuffer may contain different attachments
+ return;
+ }
+ current_framebuffer_config_state = fb_config_state;
Surface depth_surface;
if (using_depth_fb) {
depth_surface = res_cache.GetDepthBufferSurface(preserve_contents);
}
- // TODO(bunnei): Figure out how the below register works. According to envytools, this should be
- // used to enable multiple render targets. However, it is left unset on all games that I have
- // tested.
- ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(regs.rt_separate_frag_data == 0);
// Bind the framebuffer surfaces
- current_state.draw.draw_framebuffer = framebuffer.handle;
- current_state.ApplyFramebufferState();
current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
+ FramebufferCacheKey fbkey;
+
if (using_color_fb) {
if (single_color_target) {
// Used when just a single color attachment is enabled, e.g. for clearing a color buffer
@@ -451,14 +522,12 @@ void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool us
state.framebuffer_srgb.enabled |= color_surface->GetSurfaceParams().srgb_conversion;
}
- glFramebufferTexture2D(
- GL_DRAW_FRAMEBUFFER,
- GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target), GL_TEXTURE_2D,
- color_surface != nullptr ? color_surface->Texture().handle : 0, 0);
- glDrawBuffer(GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target));
+ fbkey.is_single_buffer = true;
+ fbkey.color_attachments[0] =
+ GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(*single_color_target);
+ fbkey.colors[0] = color_surface != nullptr ? color_surface->Texture().handle : 0;
} else {
// Multiple color attachments are enabled
- std::array<GLenum, Maxwell::NumRenderTargets> buffers;
for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
Surface color_surface = res_cache.GetColorBufferSurface(index, preserve_contents);
@@ -473,22 +542,17 @@ void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool us
color_surface->GetSurfaceParams().srgb_conversion;
}
- buffers[index] = GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
- glFramebufferTexture2D(
- GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index),
- GL_TEXTURE_2D, color_surface != nullptr ? color_surface->Texture().handle : 0,
- 0);
+ fbkey.color_attachments[index] =
+ GL_COLOR_ATTACHMENT0 + regs.rt_control.GetMap(index);
+ fbkey.colors[index] =
+ color_surface != nullptr ? color_surface->Texture().handle : 0;
}
- glDrawBuffers(regs.rt_control.count, buffers.data());
+ fbkey.is_single_buffer = false;
+ fbkey.colors_count = regs.rt_control.count;
}
} else {
- // No color attachments are enabled - zero out all of them
- for (std::size_t index = 0; index < Maxwell::NumRenderTargets; ++index) {
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
- GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(index), GL_TEXTURE_2D,
- 0, 0);
- }
- glDrawBuffer(GL_NONE);
+ // No color attachments are enabled - leave them as zero
+ fbkey.is_single_buffer = true;
}
if (depth_surface) {
@@ -496,22 +560,12 @@ void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool us
// the shader doesn't actually write to it.
depth_surface->MarkAsModified(true, res_cache);
- if (regs.stencil_enable) {
- // Attach both depth and stencil
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- depth_surface->Texture().handle, 0);
- } else {
- // Attach depth
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
- depth_surface->Texture().handle, 0);
- // Clear stencil attachment
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
- }
- } else {
- // Clear both depth and stencil attachment
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
- 0);
+ fbkey.zeta = depth_surface->Texture().handle;
+ fbkey.stencil_enable = regs.stencil_enable;
}
+
+ SetupCachedFramebuffer(fbkey, current_state);
+
SyncViewport(current_state);
}
@@ -580,8 +634,6 @@ void RasterizerOpenGL::Clear() {
return;
}
- ScopeAcquireGLContext acquire_context{emu_window};
-
ConfigureFramebuffers(clear_state, use_color, use_depth || use_stencil, false,
regs.clear_buffers.RT.Value());
if (regs.clear_flags.scissor) {
@@ -615,8 +667,6 @@ void RasterizerOpenGL::DrawArrays() {
auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
const auto& regs = gpu.regs;
- ScopeAcquireGLContext acquire_context{emu_window};
-
ConfigureFramebuffers(state);
SyncColorMask();
SyncFragmentColorClampState();
@@ -639,9 +689,6 @@ void RasterizerOpenGL::DrawArrays() {
// Draw the vertex batch
const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
- state.draw.vertex_buffer = buffer_cache.GetHandle();
- state.ApplyVertexBufferState();
-
std::size_t buffer_size = CalculateVertexArraysSize();
// Add space for index buffer (keeping in mind non-core primitives)
@@ -671,8 +718,9 @@ void RasterizerOpenGL::DrawArrays() {
gpu.dirty_flags.vertex_array = 0xFFFFFFFF;
}
- SetupVertexFormat();
- SetupVertexBuffer();
+ const GLuint vao = SetupVertexFormat();
+ SetupVertexBuffer(vao);
+
DrawParameters params = SetupDraw();
SetupShaders(params.primitive_mode);
@@ -711,6 +759,7 @@ void RasterizerOpenGL::InvalidateRegion(VAddr addr, u64 size) {
MICROPROFILE_SCOPE(OpenGL_CacheManagement);
res_cache.InvalidateRegion(addr, size);
shader_cache.InvalidateRegion(addr, size);
+ global_cache.InvalidateRegion(addr, size);
buffer_cache.InvalidateRegion(addr, size);
}
@@ -866,13 +915,14 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntr
}
}
-u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
- GLenum primitive_mode, u32 current_bindpoint) {
+void RasterizerOpenGL::SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
+ const Shader& shader, GLuint program_handle,
+ BaseBindings base_bindings) {
MICROPROFILE_SCOPE(OpenGL_UBO);
const auto& gpu = Core::System::GetInstance().GPU();
const auto& maxwell3d = gpu.Maxwell3D();
const auto& shader_stage = maxwell3d.state.shader_stages[static_cast<std::size_t>(stage)];
- const auto& entries = shader->GetShaderEntries().const_buffer_entries;
+ const auto& entries = shader->GetShaderEntries().const_buffers;
constexpr u64 max_binds = Tegra::Engines::Maxwell3D::Regs::MaxConstBuffers;
std::array<GLuint, max_binds> bind_buffers;
@@ -915,72 +965,73 @@ u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shad
size = Common::AlignUp(size, sizeof(GLvec4));
ASSERT_MSG(size <= MaxConstbufferSize, "Constbuffer too big");
- GLintptr const_buffer_offset = buffer_cache.UploadMemory(
+ const GLintptr const_buffer_offset = buffer_cache.UploadMemory(
buffer.address, size, static_cast<std::size_t>(uniform_buffer_alignment));
- // Now configure the bindpoint of the buffer inside the shader
- glUniformBlockBinding(shader->GetProgramHandle(primitive_mode),
- shader->GetProgramResourceIndex(used_buffer),
- current_bindpoint + bindpoint);
-
// Prepare values for multibind
bind_buffers[bindpoint] = buffer_cache.GetHandle();
bind_offsets[bindpoint] = const_buffer_offset;
bind_sizes[bindpoint] = size;
}
- glBindBuffersRange(GL_UNIFORM_BUFFER, current_bindpoint, static_cast<GLsizei>(entries.size()),
+ // The first binding is reserved for emulation values
+ const GLuint ubo_base_binding = base_bindings.cbuf + 1;
+ glBindBuffersRange(GL_UNIFORM_BUFFER, ubo_base_binding, static_cast<GLsizei>(entries.size()),
bind_buffers.data(), bind_offsets.data(), bind_sizes.data());
+}
+
+void RasterizerOpenGL::SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
+ const Shader& shader, GLenum primitive_mode,
+ BaseBindings base_bindings) {
+ // TODO(Rodrigo): Use ARB_multi_bind here
+ const auto& entries = shader->GetShaderEntries().global_memory_entries;
- return current_bindpoint + static_cast<u32>(entries.size());
+ for (u32 bindpoint = 0; bindpoint < static_cast<u32>(entries.size()); ++bindpoint) {
+ const auto& entry = entries[bindpoint];
+ const u32 current_bindpoint = base_bindings.gmem + bindpoint;
+ const auto& region = global_cache.GetGlobalRegion(entry, stage);
+
+ glBindBufferBase(GL_SHADER_STORAGE_BUFFER, current_bindpoint, region->GetBufferHandle());
+ }
}
-u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
- GLenum primitive_mode, u32 current_unit) {
+void RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, const Shader& shader,
+ GLuint program_handle, BaseBindings base_bindings) {
MICROPROFILE_SCOPE(OpenGL_Texture);
const auto& gpu = Core::System::GetInstance().GPU();
const auto& maxwell3d = gpu.Maxwell3D();
- const auto& entries = shader->GetShaderEntries().texture_samplers;
+ const auto& entries = shader->GetShaderEntries().samplers;
- ASSERT_MSG(current_unit + entries.size() <= std::size(state.texture_units),
+ ASSERT_MSG(base_bindings.sampler + entries.size() <= std::size(state.texture_units),
"Exceeded the number of active textures.");
for (u32 bindpoint = 0; bindpoint < entries.size(); ++bindpoint) {
const auto& entry = entries[bindpoint];
- const u32 current_bindpoint = current_unit + bindpoint;
-
- // Bind the uniform to the sampler.
-
- glProgramUniform1i(shader->GetProgramHandle(primitive_mode),
- shader->GetUniformLocation(entry), current_bindpoint);
+ const u32 current_bindpoint = base_bindings.sampler + bindpoint;
+ auto& unit = state.texture_units[current_bindpoint];
const auto texture = maxwell3d.GetStageTexture(entry.GetStage(), entry.GetOffset());
-
if (!texture.enabled) {
- state.texture_units[current_bindpoint].texture = 0;
+ unit.texture = 0;
continue;
}
texture_samplers[current_bindpoint].SyncWithConfig(texture.tsc);
+
Surface surface = res_cache.GetTextureSurface(texture, entry);
if (surface != nullptr) {
- state.texture_units[current_bindpoint].texture = surface->Texture().handle;
- state.texture_units[current_bindpoint].target = surface->Target();
- state.texture_units[current_bindpoint].swizzle.r =
- MaxwellToGL::SwizzleSource(texture.tic.x_source);
- state.texture_units[current_bindpoint].swizzle.g =
- MaxwellToGL::SwizzleSource(texture.tic.y_source);
- state.texture_units[current_bindpoint].swizzle.b =
- MaxwellToGL::SwizzleSource(texture.tic.z_source);
- state.texture_units[current_bindpoint].swizzle.a =
- MaxwellToGL::SwizzleSource(texture.tic.w_source);
+ unit.texture =
+ entry.IsArray() ? surface->TextureLayer().handle : surface->Texture().handle;
+ unit.target = entry.IsArray() ? surface->TargetLayer() : surface->Target();
+ unit.swizzle.r = MaxwellToGL::SwizzleSource(texture.tic.x_source);
+ unit.swizzle.g = MaxwellToGL::SwizzleSource(texture.tic.y_source);
+ unit.swizzle.b = MaxwellToGL::SwizzleSource(texture.tic.z_source);
+ unit.swizzle.a = MaxwellToGL::SwizzleSource(texture.tic.w_source);
} else {
// Can occur when texture addr is null or its memory is unmapped/invalid
- state.texture_units[current_bindpoint].texture = 0;
+ unit.texture = 0;
}
}
-
- return current_unit + static_cast<u32>(entries.size());
}
void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
@@ -992,29 +1043,35 @@ void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
for (std::size_t i = 0; i < viewport_count; i++) {
auto& viewport = current_state.viewports[i];
const auto& src = regs.viewports[i];
- if (regs.viewport_transform_enabled) {
- const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
- viewport.x = viewport_rect.left;
- viewport.y = viewport_rect.bottom;
- viewport.width = viewport_rect.GetWidth();
- viewport.height = viewport_rect.GetHeight();
- } else {
- viewport.x = src.x;
- viewport.y = src.y;
- viewport.width = src.width;
- viewport.height = src.height;
- }
+ const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
+ viewport.x = viewport_rect.left;
+ viewport.y = viewport_rect.bottom;
+ viewport.width = viewport_rect.GetWidth();
+ viewport.height = viewport_rect.GetHeight();
viewport.depth_range_far = regs.viewports[i].depth_range_far;
viewport.depth_range_near = regs.viewports[i].depth_range_near;
}
+ state.depth_clamp.far_plane = regs.view_volume_clip_control.depth_clamp_far != 0;
+ state.depth_clamp.near_plane = regs.view_volume_clip_control.depth_clamp_near != 0;
}
-void RasterizerOpenGL::SyncClipEnabled() {
- UNREACHABLE();
+void RasterizerOpenGL::SyncClipEnabled(
+ const std::array<bool, Maxwell::Regs::NumClipDistances>& clip_mask) {
+
+ const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
+ const std::array<bool, Maxwell::Regs::NumClipDistances> reg_state{
+ regs.clip_distance_enabled.c0 != 0, regs.clip_distance_enabled.c1 != 0,
+ regs.clip_distance_enabled.c2 != 0, regs.clip_distance_enabled.c3 != 0,
+ regs.clip_distance_enabled.c4 != 0, regs.clip_distance_enabled.c5 != 0,
+ regs.clip_distance_enabled.c6 != 0, regs.clip_distance_enabled.c7 != 0};
+
+ for (std::size_t i = 0; i < Maxwell::Regs::NumClipDistances; ++i) {
+ state.clip_distance[i] = reg_state[i] && clip_mask[i];
+ }
}
void RasterizerOpenGL::SyncClipCoef() {
- UNREACHABLE();
+ UNIMPLEMENTED();
}
void RasterizerOpenGL::SyncCullMode() {
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index dfb4616f2..a103692f9 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -23,6 +23,7 @@
#include "video_core/rasterizer_cache.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/renderer_opengl/gl_buffer_cache.h"
+#include "video_core/renderer_opengl/gl_global_cache.h"
#include "video_core/renderer_opengl/gl_primitive_assembler.h"
#include "video_core/renderer_opengl/gl_rasterizer_cache.h"
#include "video_core/renderer_opengl/gl_resource_manager.h"
@@ -40,6 +41,7 @@ namespace OpenGL {
struct ScreenInfo;
struct DrawParameters;
+struct FramebufferCacheKey;
class RasterizerOpenGL : public VideoCore::RasterizerInterface {
public:
@@ -60,25 +62,15 @@ public:
bool AccelerateDrawBatch(bool is_indexed) override;
void UpdatePagesCachedCount(Tegra::GPUVAddr addr, u64 size, int delta) override;
- /// OpenGL shader generated for a given Maxwell register state
- struct MaxwellShader {
- /// OpenGL shader resource
- OGLProgram shader;
- };
-
- struct VertexShader {
- OGLShader shader;
- };
-
- struct FragmentShader {
- OGLShader shader;
- };
-
/// Maximum supported size that a constbuffer can have in bytes.
static constexpr std::size_t MaxConstbufferSize = 0x10000;
static_assert(MaxConstbufferSize % sizeof(GLvec4) == 0,
"The maximum size of a constbuffer must be a multiple of the size of GLvec4");
+ static constexpr std::size_t MaxGlobalMemorySize = 0x10000;
+ static_assert(MaxGlobalMemorySize % sizeof(float) == 0,
+ "The maximum size of a global memory must be a multiple of the size of float");
+
private:
class SamplerInfo {
public:
@@ -107,6 +99,23 @@ private:
float max_anisotropic = 1.0f;
};
+ struct FramebufferConfigState {
+ bool using_color_fb{};
+ bool using_depth_fb{};
+ bool preserve_contents{};
+ std::optional<std::size_t> single_color_target;
+
+ bool operator==(const FramebufferConfigState& rhs) const {
+ return std::tie(using_color_fb, using_depth_fb, preserve_contents,
+ single_color_target) == std::tie(rhs.using_color_fb, rhs.using_depth_fb,
+ rhs.preserve_contents,
+ rhs.single_color_target);
+ }
+ bool operator!=(const FramebufferConfigState& rhs) const {
+ return !operator==(rhs);
+ }
+ };
+
/**
* Configures the color and depth framebuffer states.
* @param use_color_fb If true, configure color framebuffers.
@@ -118,31 +127,25 @@ private:
bool using_depth_fb = true, bool preserve_contents = true,
std::optional<std::size_t> single_color_target = {});
- /*
- * Configures the current constbuffers to use for the draw command.
- * @param stage The shader stage to configure buffers for.
- * @param shader The shader object that contains the specified stage.
- * @param current_bindpoint The offset at which to start counting new buffer bindpoints.
- * @returns The next available bindpoint for use in the next shader stage.
- */
- u32 SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
- GLenum primitive_mode, u32 current_bindpoint);
-
- /*
- * Configures the current textures to use for the draw command.
- * @param stage The shader stage to configure textures for.
- * @param shader The shader object that contains the specified stage.
- * @param current_unit The offset at which to start counting unused texture units.
- * @returns The next available bindpoint for use in the next shader stage.
- */
- u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
- GLenum primitive_mode, u32 current_unit);
+ /// Configures the current constbuffers to use for the draw command.
+ void SetupConstBuffers(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, const Shader& shader,
+ GLuint program_handle, BaseBindings base_bindings);
+
+ /// Configures the current global memory entries to use for the draw command.
+ void SetupGlobalRegions(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage,
+ const Shader& shader, GLenum primitive_mode,
+ BaseBindings base_bindings);
+
+ /// Configures the current textures to use for the draw command.
+ void SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, const Shader& shader,
+ GLuint program_handle, BaseBindings base_bindings);
/// Syncs the viewport and depth range to match the guest state
void SyncViewport(OpenGLState& current_state);
/// Syncs the clip enabled status to match the guest state
- void SyncClipEnabled();
+ void SyncClipEnabled(
+ const std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances>& clip_mask);
/// Syncs the clip coefficients to match the guest state
void SyncClipCoef();
@@ -189,13 +192,15 @@ private:
/// Check asserts for alpha testing.
void CheckAlphaTests();
- bool has_ARB_direct_state_access = false;
- bool has_ARB_multi_bind = false;
+ /// Check for extension that are not strictly required
+ /// but are needed for correct emulation
+ void CheckExtensions();
OpenGLState state;
RasterizerCacheOpenGL res_cache;
ShaderCacheOpenGL shader_cache;
+ GlobalRegionCacheOpenGL global_cache;
Core::Frontend::EmuWindow& emu_window;
@@ -207,11 +212,13 @@ private:
OGLVertexArray>
vertex_array_cache;
+ std::map<FramebufferCacheKey, OGLFramebuffer> framebuffer_cache;
+ FramebufferConfigState current_framebuffer_config_state;
+
std::array<SamplerInfo, Tegra::Engines::Maxwell3D::Regs::NumTextureSamplers> texture_samplers;
static constexpr std::size_t STREAM_BUFFER_SIZE = 128 * 1024 * 1024;
OGLBufferCache buffer_cache;
- OGLFramebuffer framebuffer;
PrimitiveAssembler primitive_assembler{buffer_cache};
GLint uniform_buffer_alignment;
@@ -219,13 +226,17 @@ private:
std::size_t CalculateIndexBufferSize() const;
- void SetupVertexFormat();
- void SetupVertexBuffer();
+ /// Updates and returns a vertex array object representing current vertex format
+ GLuint SetupVertexFormat();
+
+ void SetupVertexBuffer(GLuint vao);
DrawParameters SetupDraw();
void SetupShaders(GLenum primitive_mode);
+ void SetupCachedFramebuffer(const FramebufferCacheKey& fbkey, OpenGLState& current_state);
+
enum class AccelDraw { Disabled, Arrays, Indexed };
AccelDraw accelerate_draw = AccelDraw::Disabled;
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
index dde2f468d..2b9c4628f 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
@@ -44,6 +44,17 @@ struct FormatTuple {
bool compressed;
};
+static void ApplyTextureDefaults(GLenum target, u32 max_mip_level) {
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, max_mip_level - 1);
+ if (max_mip_level == 1) {
+ glTexParameterf(target, GL_TEXTURE_LOD_BIAS, 1000.0);
+ }
+}
+
void SurfaceParams::InitCacheParameters(Tegra::GPUVAddr gpu_addr_) {
auto& memory_manager{Core::System::GetInstance().GPU().MemoryManager()};
const auto cpu_addr{memory_manager.GpuToCpuAddress(gpu_addr_)};
@@ -101,12 +112,23 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
params.srgb_conversion = config.tic.IsSrgbConversionEnabled();
params.pixel_format = PixelFormatFromTextureFormat(config.tic.format, config.tic.r_type.Value(),
params.srgb_conversion);
+
+ if (params.pixel_format == PixelFormat::R16U && config.tsc.depth_compare_enabled) {
+ // Some titles create a 'R16U' (normalized 16-bit) texture with depth_compare enabled,
+ // then attempt to sample from it via a shadow sampler. Convert format to Z16 (which also
+ // causes GetFormatType to properly return 'Depth' below).
+ params.pixel_format = PixelFormat::Z16;
+ }
+
params.component_type = ComponentTypeFromTexture(config.tic.r_type.Value());
params.type = GetFormatType(params.pixel_format);
+ UNIMPLEMENTED_IF(params.type == SurfaceType::ColorTexture && config.tsc.depth_compare_enabled);
+
params.width = Common::AlignUp(config.tic.Width(), GetCompressionFactor(params.pixel_format));
params.height = Common::AlignUp(config.tic.Height(), GetCompressionFactor(params.pixel_format));
params.unaligned_height = config.tic.Height();
params.target = SurfaceTargetFromTextureType(config.tic.texture_type);
+ params.identity = SurfaceClass::Uploaded;
switch (params.target) {
case SurfaceTarget::Texture1D:
@@ -146,6 +168,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
}
params.is_layered = SurfaceTargetIsLayered(params.target);
+ params.is_array = SurfaceTargetIsArray(params.target);
params.max_mip_level = config.tic.max_mip_level + 1;
params.rt = {};
@@ -173,6 +196,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
params.height = config.height;
params.unaligned_height = config.height;
params.target = SurfaceTarget::Texture2D;
+ params.identity = SurfaceClass::RenderTarget;
params.depth = 1;
params.max_mip_level = 1;
params.is_layered = false;
@@ -208,6 +232,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
params.height = zeta_height;
params.unaligned_height = zeta_height;
params.target = SurfaceTarget::Texture2D;
+ params.identity = SurfaceClass::DepthBuffer;
params.depth = 1;
params.max_mip_level = 1;
params.is_layered = false;
@@ -236,6 +261,7 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
params.height = config.height;
params.unaligned_height = config.height;
params.target = SurfaceTarget::Texture2D;
+ params.identity = SurfaceClass::Copy;
params.depth = 1;
params.max_mip_level = 1;
params.rt = {};
@@ -257,7 +283,7 @@ static constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex
{GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, ComponentType::UInt, false}, // R8UI
{GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, ComponentType::Float, false}, // RGBA16F
{GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT, ComponentType::UNorm, false}, // RGBA16U
- {GL_RGBA16UI, GL_RGBA, GL_UNSIGNED_SHORT, ComponentType::UInt, false}, // RGBA16UI
+ {GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, ComponentType::UInt, false}, // RGBA16UI
{GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, ComponentType::Float,
false}, // R11FG11FB10F
{GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, ComponentType::UInt, false}, // RGBA32UI
@@ -278,8 +304,6 @@ static constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex
{GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB, GL_UNSIGNED_INT_8_8_8_8, ComponentType::Float,
true}, // BC6H_SF16
{GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_4X4
- {GL_RG8, GL_RG, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // G8R8U
- {GL_RG8, GL_RG, GL_BYTE, ComponentType::SNorm, false}, // G8R8S
{GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // BGRA8
{GL_RGBA32F, GL_RGBA, GL_FLOAT, ComponentType::Float, false}, // RGBA32F
{GL_RG32F, GL_RG, GL_FLOAT, ComponentType::Float, false}, // RG32F
@@ -405,138 +429,6 @@ void SwizzleFunc(const MortonSwizzleMode& mode, const SurfaceParams& params,
}
}
-MICROPROFILE_DEFINE(OpenGL_BlitSurface, "OpenGL", "BlitSurface", MP_RGB(128, 192, 64));
-static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
- GLuint read_fb_handle, GLuint draw_fb_handle, GLenum src_attachment = 0,
- GLenum dst_attachment = 0, std::size_t cubemap_face = 0) {
- MICROPROFILE_SCOPE(OpenGL_BlitSurface);
-
- const auto& src_params{src_surface->GetSurfaceParams()};
- const auto& dst_params{dst_surface->GetSurfaceParams()};
-
- OpenGLState prev_state{OpenGLState::GetCurState()};
- SCOPE_EXIT({ prev_state.Apply(); });
-
- OpenGLState state;
- state.draw.read_framebuffer = read_fb_handle;
- state.draw.draw_framebuffer = draw_fb_handle;
- // Set sRGB enabled if the destination surfaces need it
- state.framebuffer_srgb.enabled = dst_params.srgb_conversion;
- state.ApplyFramebufferState();
-
- u32 buffers{};
-
- if (src_params.type == SurfaceType::ColorTexture) {
- switch (src_params.target) {
- case SurfaceTarget::Texture2D:
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- GL_TEXTURE_2D, src_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- 0, 0);
- break;
- case SurfaceTarget::TextureCubemap:
- glFramebufferTexture2D(
- GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face),
- src_surface->Texture().handle, 0);
- glFramebufferTexture2D(
- GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
- static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0);
- break;
- case SurfaceTarget::Texture2DArray:
- glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- src_surface->Texture().handle, 0, 0);
- glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0);
- break;
- case SurfaceTarget::Texture3D:
- glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- SurfaceTargetToGL(src_params.target),
- src_surface->Texture().handle, 0, 0);
- glFramebufferTexture3D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
- SurfaceTargetToGL(src_params.target), 0, 0, 0);
- break;
- default:
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- GL_TEXTURE_2D, src_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- 0, 0);
- break;
- }
-
- switch (dst_params.target) {
- case SurfaceTarget::Texture2D:
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- GL_TEXTURE_2D, dst_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- 0, 0);
- break;
- case SurfaceTarget::TextureCubemap:
- glFramebufferTexture2D(
- GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face),
- dst_surface->Texture().handle, 0);
- glFramebufferTexture2D(
- GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
- static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + cubemap_face), 0, 0);
- break;
- case SurfaceTarget::Texture2DArray:
- glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- dst_surface->Texture().handle, 0, 0);
- glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, 0, 0, 0);
- break;
-
- case SurfaceTarget::Texture3D:
- glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- SurfaceTargetToGL(dst_params.target),
- dst_surface->Texture().handle, 0, 0);
- glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
- SurfaceTargetToGL(dst_params.target), 0, 0, 0);
- break;
- default:
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- GL_TEXTURE_2D, dst_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- 0, 0);
- break;
- }
-
- buffers = GL_COLOR_BUFFER_BIT;
- } else if (src_params.type == SurfaceType::Depth) {
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- GL_TEXTURE_2D, 0, 0);
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
- src_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
-
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- GL_TEXTURE_2D, 0, 0);
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
- dst_surface->Texture().handle, 0);
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
-
- buffers = GL_DEPTH_BUFFER_BIT;
- } else if (src_params.type == SurfaceType::DepthStencil) {
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + src_attachment,
- GL_TEXTURE_2D, 0, 0);
- glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- src_surface->Texture().handle, 0);
-
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + dst_attachment,
- GL_TEXTURE_2D, 0, 0);
- glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D,
- dst_surface->Texture().handle, 0);
-
- buffers = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
- }
-
- const auto& rect{src_params.GetRect()};
- glBlitFramebuffer(rect.left, rect.bottom, rect.right, rect.top, rect.left, rect.bottom,
- rect.right, rect.top, buffers,
- buffers == GL_COLOR_BUFFER_BIT ? GL_LINEAR : GL_NEAREST);
-
- return true;
-}
-
static void FastCopySurface(const Surface& src_surface, const Surface& dst_surface) {
const auto& src_params{src_surface->GetSurfaceParams()};
const auto& dst_params{dst_surface->GetSurfaceParams()};
@@ -565,7 +457,7 @@ static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
const std::size_t buffer_size = std::max(src_params.size_in_bytes, dst_params.size_in_bytes);
glBindBuffer(GL_PIXEL_PACK_BUFFER, copy_pbo_handle);
- glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_DRAW);
+ glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_COPY);
if (source_format.compressed) {
glGetCompressedTextureImage(src_surface->Texture().handle, src_attachment,
static_cast<GLsizei>(src_params.size_in_bytes), nullptr);
@@ -654,6 +546,9 @@ CachedSurface::CachedSurface(const SurfaceParams& params)
glActiveTexture(GL_TEXTURE0);
const auto& format_tuple = GetFormatTuple(params.pixel_format, params.component_type);
+ gl_internal_format = format_tuple.internal_format;
+ gl_is_compressed = format_tuple.compressed;
+
if (!format_tuple.compressed) {
// Only pre-create the texture for non-compressed textures.
switch (params.target) {
@@ -682,18 +577,9 @@ CachedSurface::CachedSurface(const SurfaceParams& params)
}
}
- glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glTexParameteri(SurfaceTargetToGL(params.target), GL_TEXTURE_MAX_LEVEL,
- params.max_mip_level - 1);
- if (params.max_mip_level == 1) {
- glTexParameterf(SurfaceTargetToGL(params.target), GL_TEXTURE_LOD_BIAS, 1000.0);
- }
+ ApplyTextureDefaults(SurfaceTargetToGL(params.target), params.max_mip_level);
- LabelGLObject(GL_TEXTURE, texture.handle, params.addr,
- SurfaceParams::SurfaceTargetName(params.target));
+ OpenGL::LabelGLObject(GL_TEXTURE, texture.handle, params.addr, params.IdentityString());
// Clamp size to mapped GPU memory region
// TODO(bunnei): Super Mario Odyssey maps a 0x40000 byte region and then uses it for a 0x80000
@@ -742,18 +628,6 @@ static void ConvertS8Z24ToZ24S8(std::vector<u8>& data, u32 width, u32 height, bo
}
}
-static void ConvertG8R8ToR8G8(std::vector<u8>& data, u32 width, u32 height) {
- constexpr auto bpp{GetBytesPerPixel(PixelFormat::G8R8U)};
- for (std::size_t y = 0; y < height; ++y) {
- for (std::size_t x = 0; x < width; ++x) {
- const std::size_t offset{bpp * (y * width + x)};
- const u8 temp{data[offset]};
- data[offset] = data[offset + 1];
- data[offset + 1] = temp;
- }
- }
-}
-
/**
* Helper function to perform software conversion (as needed) when loading a buffer from Switch
* memory. This is for Maxwell pixel formats that cannot be represented as-is in OpenGL or with
@@ -786,12 +660,6 @@ static void ConvertFormatAsNeeded_LoadGLBuffer(std::vector<u8>& data, PixelForma
// Convert the S8Z24 depth format to Z24S8, as OpenGL does not support S8Z24.
ConvertS8Z24ToZ24S8(data, width, height, false);
break;
-
- case PixelFormat::G8R8U:
- case PixelFormat::G8R8S:
- // Convert the G8R8 color format to R8G8, as OpenGL does not support G8R8.
- ConvertG8R8ToR8G8(data, width, height);
- break;
}
}
@@ -803,8 +671,6 @@ static void ConvertFormatAsNeeded_LoadGLBuffer(std::vector<u8>& data, PixelForma
static void ConvertFormatAsNeeded_FlushGLBuffer(std::vector<u8>& data, PixelFormat pixel_format,
u32 width, u32 height) {
switch (pixel_format) {
- case PixelFormat::G8R8U:
- case PixelFormat::G8R8S:
case PixelFormat::ASTC_2D_4X4:
case PixelFormat::ASTC_2D_8X8:
case PixelFormat::ASTC_2D_4X4_SRGB:
@@ -841,9 +707,10 @@ void CachedSurface::LoadGLBuffer() {
const auto texture_src_data_end{texture_src_data + params.size_in_bytes_gl};
gl_buffer[0].assign(texture_src_data, texture_src_data_end);
}
- for (u32 i = 0; i < params.max_mip_level; i++)
+ for (u32 i = 0; i < params.max_mip_level; i++) {
ConvertFormatAsNeeded_LoadGLBuffer(gl_buffer[i], params.pixel_format, params.MipWidth(i),
params.MipHeight(i), params.MipDepth(i));
+ }
}
MICROPROFILE_DEFINE(OpenGL_SurfaceFlush, "OpenGL", "Surface Flush", MP_RGB(128, 192, 64));
@@ -1007,6 +874,34 @@ void CachedSurface::UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle,
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
+void CachedSurface::EnsureTextureView() {
+ if (texture_view.handle != 0)
+ return;
+ // Compressed texture are not being created with immutable storage
+ UNIMPLEMENTED_IF(gl_is_compressed);
+
+ const GLenum target{TargetLayer()};
+ const GLuint num_layers{target == GL_TEXTURE_CUBE_MAP_ARRAY ? 6u : 1u};
+ constexpr GLuint min_layer = 0;
+ constexpr GLuint min_level = 0;
+
+ texture_view.Create();
+ glTextureView(texture_view.handle, target, texture.handle, gl_internal_format, min_level,
+ params.max_mip_level, min_layer, num_layers);
+
+ OpenGLState cur_state = OpenGLState::GetCurState();
+ const auto& old_tex = cur_state.texture_units[0];
+ SCOPE_EXIT({
+ cur_state.texture_units[0] = old_tex;
+ cur_state.Apply();
+ });
+ cur_state.texture_units[0].texture = texture_view.handle;
+ cur_state.texture_units[0].target = target;
+ cur_state.Apply();
+
+ ApplyTextureDefaults(target, params.max_mip_level);
+}
+
MICROPROFILE_DEFINE(OpenGL_TextureUL, "OpenGL", "Texture Upload", MP_RGB(128, 192, 64));
void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle) {
if (params.type == SurfaceType::Fill)
@@ -1031,9 +926,16 @@ Surface RasterizerCacheOpenGL::GetTextureSurface(const Tegra::Texture::FullTextu
}
Surface RasterizerCacheOpenGL::GetDepthBufferSurface(bool preserve_contents) {
- const auto& regs{Core::System::GetInstance().GPU().Maxwell3D().regs};
+ auto& gpu{Core::System::GetInstance().GPU().Maxwell3D()};
+ const auto& regs{gpu.regs};
+
+ if (!gpu.dirty_flags.zeta_buffer) {
+ return last_depth_buffer;
+ }
+ gpu.dirty_flags.zeta_buffer = false;
+
if (!regs.zeta.Address() || !regs.zeta_enable) {
- return {};
+ return last_depth_buffer = {};
}
SurfaceParams depth_params{SurfaceParams::CreateForDepthBuffer(
@@ -1041,25 +943,31 @@ Surface RasterizerCacheOpenGL::GetDepthBufferSurface(bool preserve_contents) {
regs.zeta.memory_layout.block_width, regs.zeta.memory_layout.block_height,
regs.zeta.memory_layout.block_depth, regs.zeta.memory_layout.type)};
- return GetSurface(depth_params, preserve_contents);
+ return last_depth_buffer = GetSurface(depth_params, preserve_contents);
}
Surface RasterizerCacheOpenGL::GetColorBufferSurface(std::size_t index, bool preserve_contents) {
- const auto& regs{Core::System::GetInstance().GPU().Maxwell3D().regs};
+ auto& gpu{Core::System::GetInstance().GPU().Maxwell3D()};
+ const auto& regs{gpu.regs};
+
+ if ((gpu.dirty_flags.color_buffer & (1u << static_cast<u32>(index))) == 0) {
+ return last_color_buffers[index];
+ }
+ gpu.dirty_flags.color_buffer &= ~(1u << static_cast<u32>(index));
ASSERT(index < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets);
if (index >= regs.rt_control.count) {
- return {};
+ return last_color_buffers[index] = {};
}
if (regs.rt[index].Address() == 0 || regs.rt[index].format == Tegra::RenderTargetFormat::NONE) {
- return {};
+ return last_color_buffers[index] = {};
}
const SurfaceParams color_params{SurfaceParams::CreateForFramebuffer(index)};
- return GetSurface(color_params, preserve_contents);
+ return last_color_buffers[index] = GetSurface(color_params, preserve_contents);
}
void RasterizerCacheOpenGL::LoadSurface(const Surface& surface) {
@@ -1163,7 +1071,10 @@ void RasterizerCacheOpenGL::AccurateCopySurface(const Surface& src_surface,
const Surface& dst_surface) {
const auto& src_params{src_surface->GetSurfaceParams()};
const auto& dst_params{dst_surface->GetSurfaceParams()};
- FlushRegion(src_params.addr, dst_params.MemorySize());
+
+ // Flush enough memory for both the source and destination surface
+ FlushRegion(src_params.addr, std::max(src_params.MemorySize(), dst_params.MemorySize()));
+
LoadSurface(dst_surface);
}
@@ -1189,20 +1100,9 @@ Surface RasterizerCacheOpenGL::RecreateSurface(const Surface& old_surface,
return new_surface;
}
- // If the format is the same, just do a framebuffer blit. This is significantly faster than
- // using PBOs. The is also likely less accurate, as textures will be converted rather than
- // reinterpreted. When use_accurate_gpu_emulation setting is enabled, perform a more accurate
- // surface copy, where pixels are reinterpreted as a new format (without conversion). This
- // code path uses OpenGL PBOs and is quite slow.
- const bool is_blit{old_params.pixel_format == new_params.pixel_format};
-
switch (new_params.target) {
case SurfaceTarget::Texture2D:
- if (is_blit) {
- BlitSurface(old_surface, new_surface, read_framebuffer.handle, draw_framebuffer.handle);
- } else {
- CopySurface(old_surface, new_surface, copy_pbo.handle);
- }
+ CopySurface(old_surface, new_surface, copy_pbo.handle);
break;
case SurfaceTarget::Texture3D:
AccurateCopySurface(old_surface, new_surface);
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.h b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
index c710aa245..8d7d6722c 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
@@ -35,6 +35,14 @@ using PixelFormat = VideoCore::Surface::PixelFormat;
using ComponentType = VideoCore::Surface::ComponentType;
struct SurfaceParams {
+
+ enum class SurfaceClass {
+ Uploaded,
+ RenderTarget,
+ DepthBuffer,
+ Copy,
+ };
+
static std::string SurfaceTargetName(SurfaceTarget target) {
switch (target) {
case SurfaceTarget::Texture1D:
@@ -210,6 +218,48 @@ struct SurfaceParams {
/// Initializes parameters for caching, should be called after everything has been initialized
void InitCacheParameters(Tegra::GPUVAddr gpu_addr);
+ std::string TargetName() const {
+ switch (target) {
+ case SurfaceTarget::Texture1D:
+ return "1D";
+ case SurfaceTarget::Texture2D:
+ return "2D";
+ case SurfaceTarget::Texture3D:
+ return "3D";
+ case SurfaceTarget::Texture1DArray:
+ return "1DArray";
+ case SurfaceTarget::Texture2DArray:
+ return "2DArray";
+ case SurfaceTarget::TextureCubemap:
+ return "Cube";
+ default:
+ LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
+ UNREACHABLE();
+ return fmt::format("TUK({})", static_cast<u32>(target));
+ }
+ }
+
+ std::string ClassName() const {
+ switch (identity) {
+ case SurfaceClass::Uploaded:
+ return "UP";
+ case SurfaceClass::RenderTarget:
+ return "RT";
+ case SurfaceClass::DepthBuffer:
+ return "DB";
+ case SurfaceClass::Copy:
+ return "CP";
+ default:
+ LOG_CRITICAL(HW_GPU, "Unimplemented surface_class={}", static_cast<u32>(identity));
+ UNREACHABLE();
+ return fmt::format("CUK({})", static_cast<u32>(identity));
+ }
+ }
+
+ std::string IdentityString() const {
+ return ClassName() + '_' + TargetName() + '_' + (is_tiled ? 'T' : 'L');
+ }
+
bool is_tiled;
u32 block_width;
u32 block_height;
@@ -223,8 +273,10 @@ struct SurfaceParams {
u32 depth;
u32 unaligned_height;
SurfaceTarget target;
+ SurfaceClass identity;
u32 max_mip_level;
bool is_layered;
+ bool is_array;
bool srgb_conversion;
// Parameters used for caching
VAddr addr;
@@ -255,6 +307,7 @@ struct SurfaceReserveKey : Common::HashableStruct<OpenGL::SurfaceParams> {
static SurfaceReserveKey Create(const OpenGL::SurfaceParams& params) {
SurfaceReserveKey res;
res.state = params;
+ res.state.identity = {}; // Ignore the origin of the texture
res.state.gpu_addr = {}; // Ignore GPU vaddr in caching
res.state.rt = {}; // Ignore rt config in caching
return res;
@@ -293,10 +346,31 @@ public:
return texture;
}
+ const OGLTexture& TextureLayer() {
+ if (params.is_array) {
+ return Texture();
+ }
+ EnsureTextureView();
+ return texture_view;
+ }
+
GLenum Target() const {
return gl_target;
}
+ GLenum TargetLayer() const {
+ using VideoCore::Surface::SurfaceTarget;
+ switch (params.target) {
+ case SurfaceTarget::Texture1D:
+ return GL_TEXTURE_1D_ARRAY;
+ case SurfaceTarget::Texture2D:
+ return GL_TEXTURE_2D_ARRAY;
+ case SurfaceTarget::TextureCubemap:
+ return GL_TEXTURE_CUBE_MAP_ARRAY;
+ }
+ return Target();
+ }
+
const SurfaceParams& GetSurfaceParams() const {
return params;
}
@@ -311,11 +385,16 @@ public:
private:
void UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle, GLuint draw_fb_handle);
+ void EnsureTextureView();
+
OGLTexture texture;
+ OGLTexture texture_view;
std::vector<std::vector<u8>> gl_buffer;
- SurfaceParams params;
- GLenum gl_target;
- std::size_t cached_size_in_bytes;
+ SurfaceParams params{};
+ GLenum gl_target{};
+ GLenum gl_internal_format{};
+ bool gl_is_compressed{};
+ std::size_t cached_size_in_bytes{};
};
class RasterizerCacheOpenGL final : public RasterizerCache<Surface> {
@@ -370,6 +449,9 @@ private:
/// Use a Pixel Buffer Object to download the previous texture and then upload it to the new one
/// using the new format.
OGLBuffer copy_pbo;
+
+ std::array<Surface, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> last_color_buffers;
+ Surface last_depth_buffer;
};
} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_resource_manager.cpp b/src/video_core/renderer_opengl/gl_resource_manager.cpp
index c17d5ac00..1da744158 100644
--- a/src/video_core/renderer_opengl/gl_resource_manager.cpp
+++ b/src/video_core/renderer_opengl/gl_resource_manager.cpp
@@ -117,7 +117,7 @@ void OGLBuffer::Create() {
return;
MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
- glGenBuffers(1, &handle);
+ glCreateBuffers(1, &handle);
}
void OGLBuffer::Release() {
@@ -126,7 +126,6 @@ void OGLBuffer::Release() {
MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
glDeleteBuffers(1, &handle);
- OpenGLState::GetCurState().ResetBuffer(handle).Apply();
handle = 0;
}
@@ -152,7 +151,7 @@ void OGLVertexArray::Create() {
return;
MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
- glGenVertexArrays(1, &handle);
+ glCreateVertexArrays(1, &handle);
}
void OGLVertexArray::Release() {
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index 038b25c75..90eda7814 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -2,17 +2,23 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <boost/functional/hash.hpp>
#include "common/assert.h"
+#include "common/hash.h"
#include "core/core.h"
#include "core/memory.h"
#include "video_core/engines/maxwell_3d.h"
#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/gl_shader_cache.h"
+#include "video_core/renderer_opengl/gl_shader_decompiler.h"
#include "video_core/renderer_opengl/gl_shader_manager.h"
#include "video_core/renderer_opengl/utils.h"
+#include "video_core/shader/shader_ir.h"
namespace OpenGL {
+using VideoCommon::Shader::ProgramCode;
+
/// Gets the address for the specified shader stage program
static VAddr GetShaderAddress(Maxwell::ShaderProgram program) {
const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
@@ -22,42 +28,31 @@ static VAddr GetShaderAddress(Maxwell::ShaderProgram program) {
}
/// Gets the shader program code from memory for the specified address
-static GLShader::ProgramCode GetShaderCode(VAddr addr) {
- GLShader::ProgramCode program_code(GLShader::MAX_PROGRAM_CODE_LENGTH);
+static ProgramCode GetShaderCode(VAddr addr) {
+ ProgramCode program_code(VideoCommon::Shader::MAX_PROGRAM_LENGTH);
Memory::ReadBlock(addr, program_code.data(), program_code.size() * sizeof(u64));
return program_code;
}
-/// Helper function to set shader uniform block bindings for a single shader stage
-static void SetShaderUniformBlockBinding(GLuint shader, const char* name,
- Maxwell::ShaderStage binding, std::size_t expected_size) {
- const GLuint ub_index = glGetUniformBlockIndex(shader, name);
- if (ub_index == GL_INVALID_INDEX) {
- return;
+/// Gets the shader type from a Maxwell program type
+constexpr GLenum GetShaderType(Maxwell::ShaderProgram program_type) {
+ switch (program_type) {
+ case Maxwell::ShaderProgram::VertexA:
+ case Maxwell::ShaderProgram::VertexB:
+ return GL_VERTEX_SHADER;
+ case Maxwell::ShaderProgram::Geometry:
+ return GL_GEOMETRY_SHADER;
+ case Maxwell::ShaderProgram::Fragment:
+ return GL_FRAGMENT_SHADER;
+ default:
+ return GL_NONE;
}
-
- GLint ub_size = 0;
- glGetActiveUniformBlockiv(shader, ub_index, GL_UNIFORM_BLOCK_DATA_SIZE, &ub_size);
- ASSERT_MSG(static_cast<std::size_t>(ub_size) == expected_size,
- "Uniform block size did not match! Got {}, expected {}", ub_size, expected_size);
- glUniformBlockBinding(shader, ub_index, static_cast<GLuint>(binding));
-}
-
-/// Sets shader uniform block bindings for an entire shader program
-static void SetShaderUniformBlockBindings(GLuint shader) {
- SetShaderUniformBlockBinding(shader, "vs_config", Maxwell::ShaderStage::Vertex,
- sizeof(GLShader::MaxwellUniformData));
- SetShaderUniformBlockBinding(shader, "gs_config", Maxwell::ShaderStage::Geometry,
- sizeof(GLShader::MaxwellUniformData));
- SetShaderUniformBlockBinding(shader, "fs_config", Maxwell::ShaderStage::Fragment,
- sizeof(GLShader::MaxwellUniformData));
}
CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
: addr{addr}, program_type{program_type}, setup{GetShaderCode(addr)} {
GLShader::ProgramResult program_result;
- GLenum gl_type{};
switch (program_type) {
case Maxwell::ShaderProgram::VertexA:
@@ -66,16 +61,16 @@ CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
// stage here.
setup.SetProgramB(GetShaderCode(GetShaderAddress(Maxwell::ShaderProgram::VertexB)));
case Maxwell::ShaderProgram::VertexB:
+ CalculateProperties();
program_result = GLShader::GenerateVertexShader(setup);
- gl_type = GL_VERTEX_SHADER;
break;
case Maxwell::ShaderProgram::Geometry:
+ CalculateProperties();
program_result = GLShader::GenerateGeometryShader(setup);
- gl_type = GL_GEOMETRY_SHADER;
break;
case Maxwell::ShaderProgram::Fragment:
+ CalculateProperties();
program_result = GLShader::GenerateFragmentShader(setup);
- gl_type = GL_FRAGMENT_SHADER;
break;
default:
LOG_CRITICAL(HW_GPU, "Unimplemented program_type={}", static_cast<u32>(program_type));
@@ -83,66 +78,156 @@ CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
return;
}
+ code = program_result.first;
entries = program_result.second;
shader_length = entries.shader_length;
+}
- if (program_type != Maxwell::ShaderProgram::Geometry) {
- OGLShader shader;
- shader.Create(program_result.first.c_str(), gl_type);
- program.Create(true, shader.handle);
- SetShaderUniformBlockBindings(program.handle);
- LabelGLObject(GL_PROGRAM, program.handle, addr);
+std::tuple<GLuint, BaseBindings> CachedShader::GetProgramHandle(GLenum primitive_mode,
+ BaseBindings base_bindings) {
+ GLuint handle{};
+ if (program_type == Maxwell::ShaderProgram::Geometry) {
+ handle = GetGeometryShader(primitive_mode, base_bindings);
} else {
- // Store shader's code to lazily build it on draw
- geometry_programs.code = program_result.first;
+ const auto [entry, is_cache_miss] = programs.try_emplace(base_bindings);
+ auto& program = entry->second;
+ if (is_cache_miss) {
+ std::string source = AllocateBindings(base_bindings);
+ source += code;
+
+ OGLShader shader;
+ shader.Create(source.c_str(), GetShaderType(program_type));
+ program.Create(true, shader.handle);
+ LabelGLObject(GL_PROGRAM, program.handle, addr);
+ }
+
+ handle = program.handle;
}
+
+ // Add const buffer and samplers offset reserved by this shader. One UBO binding is reserved for
+ // emulation values
+ base_bindings.cbuf += static_cast<u32>(entries.const_buffers.size()) + 1;
+ base_bindings.gmem += static_cast<u32>(entries.global_memory_entries.size());
+ base_bindings.sampler += static_cast<u32>(entries.samplers.size());
+
+ return {handle, base_bindings};
}
-GLuint CachedShader::GetProgramResourceIndex(const GLShader::ConstBufferEntry& buffer) {
- const auto search{resource_cache.find(buffer.GetHash())};
- if (search == resource_cache.end()) {
- const GLuint index{
- glGetProgramResourceIndex(program.handle, GL_UNIFORM_BLOCK, buffer.GetName().c_str())};
- resource_cache[buffer.GetHash()] = index;
- return index;
+std::string CachedShader::AllocateBindings(BaseBindings base_bindings) {
+ std::string code = "#version 430 core\n";
+ code += fmt::format("#define EMULATION_UBO_BINDING {}\n", base_bindings.cbuf++);
+
+ for (const auto& cbuf : entries.const_buffers) {
+ code += fmt::format("#define CBUF_BINDING_{} {}\n", cbuf.GetIndex(), base_bindings.cbuf++);
}
- return search->second;
-}
+ for (const auto& gmem : entries.global_memory_entries) {
+ code += fmt::format("#define GMEM_BINDING_{}_{} {}\n", gmem.GetCbufIndex(),
+ gmem.GetCbufOffset(), base_bindings.gmem++);
+ }
-GLint CachedShader::GetUniformLocation(const GLShader::SamplerEntry& sampler) {
- const auto search{uniform_cache.find(sampler.GetHash())};
- if (search == uniform_cache.end()) {
- const GLint index{glGetUniformLocation(program.handle, sampler.GetName().c_str())};
- uniform_cache[sampler.GetHash()] = index;
- return index;
+ for (const auto& sampler : entries.samplers) {
+ code += fmt::format("#define SAMPLER_BINDING_{} {}\n", sampler.GetIndex(),
+ base_bindings.sampler++);
}
- return search->second;
+ return code;
+}
+
+GLuint CachedShader::GetGeometryShader(GLenum primitive_mode, BaseBindings base_bindings) {
+ const auto [entry, is_cache_miss] = geometry_programs.try_emplace(base_bindings);
+ auto& programs = entry->second;
+
+ switch (primitive_mode) {
+ case GL_POINTS:
+ return LazyGeometryProgram(programs.points, base_bindings, "points", 1, "ShaderPoints");
+ case GL_LINES:
+ case GL_LINE_STRIP:
+ return LazyGeometryProgram(programs.lines, base_bindings, "lines", 2, "ShaderLines");
+ case GL_LINES_ADJACENCY:
+ case GL_LINE_STRIP_ADJACENCY:
+ return LazyGeometryProgram(programs.lines_adjacency, base_bindings, "lines_adjacency", 4,
+ "ShaderLinesAdjacency");
+ case GL_TRIANGLES:
+ case GL_TRIANGLE_STRIP:
+ case GL_TRIANGLE_FAN:
+ return LazyGeometryProgram(programs.triangles, base_bindings, "triangles", 3,
+ "ShaderTriangles");
+ case GL_TRIANGLES_ADJACENCY:
+ case GL_TRIANGLE_STRIP_ADJACENCY:
+ return LazyGeometryProgram(programs.triangles_adjacency, base_bindings,
+ "triangles_adjacency", 6, "ShaderTrianglesAdjacency");
+ default:
+ UNREACHABLE_MSG("Unknown primitive mode.");
+ return LazyGeometryProgram(programs.points, base_bindings, "points", 1, "ShaderPoints");
+ }
}
-GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
+GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program, BaseBindings base_bindings,
const std::string& glsl_topology, u32 max_vertices,
const std::string& debug_name) {
if (target_program.handle != 0) {
return target_program.handle;
}
- std::string source = "#version 430 core\n";
+ std::string source = AllocateBindings(base_bindings);
source += "layout (" + glsl_topology + ") in;\n";
source += "#define MAX_VERTEX_INPUT " + std::to_string(max_vertices) + '\n';
- source += geometry_programs.code;
+ source += code;
OGLShader shader;
shader.Create(source.c_str(), GL_GEOMETRY_SHADER);
target_program.Create(true, shader.handle);
- SetShaderUniformBlockBindings(target_program.handle);
LabelGLObject(GL_PROGRAM, target_program.handle, addr, debug_name);
return target_program.handle;
};
+static bool IsSchedInstruction(std::size_t offset, std::size_t main_offset) {
+ // sched instructions appear once every 4 instructions.
+ static constexpr std::size_t SchedPeriod = 4;
+ const std::size_t absolute_offset = offset - main_offset;
+ return (absolute_offset % SchedPeriod) == 0;
+}
+
+static std::size_t CalculateProgramSize(const GLShader::ProgramCode& program) {
+ constexpr std::size_t start_offset = 10;
+ std::size_t offset = start_offset;
+ std::size_t size = start_offset * sizeof(u64);
+ while (offset < program.size()) {
+ const u64 inst = program[offset];
+ if (!IsSchedInstruction(offset, start_offset)) {
+ if (inst == 0 || (inst >> 52) == 0x50b) {
+ break;
+ }
+ }
+ size += sizeof(inst);
+ offset++;
+ }
+ return size;
+}
+
+void CachedShader::CalculateProperties() {
+ setup.program.real_size = CalculateProgramSize(setup.program.code);
+ setup.program.real_size_b = 0;
+ setup.program.unique_identifier = Common::CityHash64(
+ reinterpret_cast<const char*>(setup.program.code.data()), setup.program.real_size);
+ if (program_type == Maxwell::ShaderProgram::VertexA) {
+ std::size_t seed = 0;
+ boost::hash_combine(seed, setup.program.unique_identifier);
+ setup.program.real_size_b = CalculateProgramSize(setup.program.code_b);
+ const u64 identifier_b = Common::CityHash64(
+ reinterpret_cast<const char*>(setup.program.code_b.data()), setup.program.real_size_b);
+ boost::hash_combine(seed, identifier_b);
+ setup.program.unique_identifier = static_cast<u64>(seed);
+ }
+}
+
ShaderCacheOpenGL::ShaderCacheOpenGL(RasterizerOpenGL& rasterizer) : RasterizerCache{rasterizer} {}
Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
+ if (!Core::System::GetInstance().GPU().Maxwell3D().dirty_flags.shaders) {
+ return last_shaders[static_cast<u32>(program)];
+ }
+
const VAddr program_addr{GetShaderAddress(program)};
// Look up shader in the cache based on address
@@ -154,7 +239,7 @@ Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
Register(shader);
}
- return shader;
+ return last_shaders[static_cast<u32>(program)] = shader;
}
} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.h b/src/video_core/renderer_opengl/gl_shader_cache.h
index 08f470de3..904d15dd0 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.h
+++ b/src/video_core/renderer_opengl/gl_shader_cache.h
@@ -4,13 +4,18 @@
#pragma once
+#include <array>
#include <map>
#include <memory>
+#include <tuple>
+
+#include <glad/glad.h>
#include "common/assert.h"
#include "common/common_types.h"
#include "video_core/rasterizer_cache.h"
#include "video_core/renderer_opengl/gl_resource_manager.h"
+#include "video_core/renderer_opengl/gl_shader_decompiler.h"
#include "video_core/renderer_opengl/gl_shader_gen.h"
namespace OpenGL {
@@ -21,6 +26,16 @@ class RasterizerOpenGL;
using Shader = std::shared_ptr<CachedShader>;
using Maxwell = Tegra::Engines::Maxwell3D::Regs;
+struct BaseBindings {
+ u32 cbuf{};
+ u32 gmem{};
+ u32 sampler{};
+
+ bool operator<(const BaseBindings& rhs) const {
+ return std::tie(cbuf, gmem, sampler) < std::tie(rhs.cbuf, rhs.gmem, rhs.sampler);
+ }
+};
+
class CachedShader final : public RasterizerCacheObject {
public:
CachedShader(VAddr addr, Maxwell::ShaderProgram program_type);
@@ -42,67 +57,45 @@ public:
}
/// Gets the GL program handle for the shader
- GLuint GetProgramHandle(GLenum primitive_mode) {
- if (program_type != Maxwell::ShaderProgram::Geometry) {
- return program.handle;
- }
- switch (primitive_mode) {
- case GL_POINTS:
- return LazyGeometryProgram(geometry_programs.points, "points", 1, "ShaderPoints");
- case GL_LINES:
- case GL_LINE_STRIP:
- return LazyGeometryProgram(geometry_programs.lines, "lines", 2, "ShaderLines");
- case GL_LINES_ADJACENCY:
- case GL_LINE_STRIP_ADJACENCY:
- return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency", 4,
- "ShaderLinesAdjacency");
- case GL_TRIANGLES:
- case GL_TRIANGLE_STRIP:
- case GL_TRIANGLE_FAN:
- return LazyGeometryProgram(geometry_programs.triangles, "triangles", 3,
- "ShaderTriangles");
- case GL_TRIANGLES_ADJACENCY:
- case GL_TRIANGLE_STRIP_ADJACENCY:
- return LazyGeometryProgram(geometry_programs.triangles_adjacency, "triangles_adjacency",
- 6, "ShaderTrianglesAdjacency");
- default:
- UNREACHABLE_MSG("Unknown primitive mode.");
- }
- }
-
- /// Gets the GL program resource location for the specified resource, caching as needed
- GLuint GetProgramResourceIndex(const GLShader::ConstBufferEntry& buffer);
-
- /// Gets the GL uniform location for the specified resource, caching as needed
- GLint GetUniformLocation(const GLShader::SamplerEntry& sampler);
+ std::tuple<GLuint, BaseBindings> GetProgramHandle(GLenum primitive_mode,
+ BaseBindings base_bindings);
private:
- /// Generates a geometry shader or returns one that already exists.
- GLuint LazyGeometryProgram(OGLProgram& target_program, const std::string& glsl_topology,
- u32 max_vertices, const std::string& debug_name);
-
- VAddr addr;
- std::size_t shader_length;
- Maxwell::ShaderProgram program_type;
- GLShader::ShaderSetup setup;
- GLShader::ShaderEntries entries;
-
- // Non-geometry program.
- OGLProgram program;
-
// Geometry programs. These are needed because GLSL needs an input topology but it's not
// declared by the hardware. Workaround this issue by generating a different shader per input
// topology class.
- struct {
- std::string code;
+ struct GeometryPrograms {
OGLProgram points;
OGLProgram lines;
OGLProgram lines_adjacency;
OGLProgram triangles;
OGLProgram triangles_adjacency;
- } geometry_programs;
+ };
+
+ std::string AllocateBindings(BaseBindings base_bindings);
- std::map<u32, GLuint> resource_cache;
+ GLuint GetGeometryShader(GLenum primitive_mode, BaseBindings base_bindings);
+
+ /// Generates a geometry shader or returns one that already exists.
+ GLuint LazyGeometryProgram(OGLProgram& target_program, BaseBindings base_bindings,
+ const std::string& glsl_topology, u32 max_vertices,
+ const std::string& debug_name);
+
+ void CalculateProperties();
+
+ VAddr addr{};
+ std::size_t shader_length{};
+ Maxwell::ShaderProgram program_type{};
+ GLShader::ShaderSetup setup;
+ GLShader::ShaderEntries entries;
+
+ std::string code;
+
+ std::map<BaseBindings, OGLProgram> programs;
+ std::map<BaseBindings, GeometryPrograms> geometry_programs;
+
+ std::map<u32, GLuint> cbuf_resource_cache;
+ std::map<u32, GLuint> gmem_resource_cache;
std::map<u32, GLint> uniform_cache;
};
@@ -112,6 +105,9 @@ public:
/// Gets the current specified shader stage program
Shader GetStageProgram(Maxwell::ShaderProgram program);
+
+private:
+ std::array<Shader, Maxwell::MaxShaderProgram> last_shaders;
};
} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index 0c4524d5c..004245431 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -2,213 +2,55 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
-#include <map>
-#include <optional>
-#include <set>
+#include <array>
#include <string>
#include <string_view>
-#include <unordered_set>
+#include <variant>
#include <fmt/format.h>
+#include "common/alignment.h"
#include "common/assert.h"
#include "common/common_types.h"
-#include "video_core/engines/shader_bytecode.h"
-#include "video_core/engines/shader_header.h"
+#include "video_core/engines/maxwell_3d.h"
#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/gl_shader_decompiler.h"
+#include "video_core/shader/shader_ir.h"
-namespace OpenGL::GLShader::Decompiler {
+namespace OpenGL::GLShader {
using Tegra::Shader::Attribute;
-using Tegra::Shader::Instruction;
-using Tegra::Shader::LogicOperation;
-using Tegra::Shader::OpCode;
+using Tegra::Shader::Header;
+using Tegra::Shader::IpaInterpMode;
+using Tegra::Shader::IpaMode;
+using Tegra::Shader::IpaSampleMode;
using Tegra::Shader::Register;
-using Tegra::Shader::Sampler;
-using Tegra::Shader::SubOp;
+using namespace VideoCommon::Shader;
-constexpr u32 PROGRAM_END = MAX_PROGRAM_CODE_LENGTH;
-constexpr u32 PROGRAM_HEADER_SIZE = sizeof(Tegra::Shader::Header);
+using Maxwell = Tegra::Engines::Maxwell3D::Regs;
+using ShaderStage = Tegra::Engines::Maxwell3D::Regs::ShaderStage;
+using Operation = const OperationNode&;
-constexpr u32 MAX_GEOMETRY_BUFFERS = 6;
-constexpr u32 MAX_ATTRIBUTES = 0x100; // Size in vec4s, this value is untested
+enum : u32 { POSITION_VARYING_LOCATION = 0, GENERIC_VARYING_START_LOCATION = 1 };
+constexpr u32 MAX_CONSTBUFFER_ELEMENTS =
+ static_cast<u32>(RasterizerOpenGL::MaxConstbufferSize) / (4 * sizeof(float));
+constexpr u32 MAX_GLOBALMEMORY_ELEMENTS =
+ static_cast<u32>(RasterizerOpenGL::MaxGlobalMemorySize) / sizeof(float);
-static const char* INTERNAL_FLAG_NAMES[] = {"zero_flag", "sign_flag", "carry_flag",
- "overflow_flag"};
-
-enum class InternalFlag : u64 {
- ZeroFlag = 0,
- SignFlag = 1,
- CarryFlag = 2,
- OverflowFlag = 3,
- Amount
-};
-
-class DecompileFail : public std::runtime_error {
-public:
- using std::runtime_error::runtime_error;
-};
-
-/// Translate topology
-static std::string GetTopologyName(Tegra::Shader::OutputTopology topology) {
- switch (topology) {
- case Tegra::Shader::OutputTopology::PointList:
- return "points";
- case Tegra::Shader::OutputTopology::LineStrip:
- return "line_strip";
- case Tegra::Shader::OutputTopology::TriangleStrip:
- return "triangle_strip";
- default:
- UNIMPLEMENTED_MSG("Unknown output topology: {}", static_cast<u32>(topology));
- return "points";
- }
-}
-
-/// Describes the behaviour of code path of a given entry point and a return point.
-enum class ExitMethod {
- Undetermined, ///< Internal value. Only occur when analyzing JMP loop.
- AlwaysReturn, ///< All code paths reach the return point.
- Conditional, ///< Code path reaches the return point or an END instruction conditionally.
- AlwaysEnd, ///< All code paths reach a END instruction.
-};
-
-/// A subroutine is a range of code refereced by a CALL, IF or LOOP instruction.
-struct Subroutine {
- /// Generates a name suitable for GLSL source code.
- std::string GetName() const {
- return "sub_" + std::to_string(begin) + '_' + std::to_string(end) + '_' + suffix;
- }
-
- u32 begin; ///< Entry point of the subroutine.
- u32 end; ///< Return point of the subroutine.
- const std::string& suffix; ///< Suffix of the shader, used to make a unique subroutine name
- ExitMethod exit_method; ///< Exit method of the subroutine.
- std::set<u32> labels; ///< Addresses refereced by JMP instructions.
-
- bool operator<(const Subroutine& rhs) const {
- return std::tie(begin, end) < std::tie(rhs.begin, rhs.end);
- }
-};
-
-/// Analyzes shader code and produces a set of subroutines.
-class ControlFlowAnalyzer {
-public:
- ControlFlowAnalyzer(const ProgramCode& program_code, u32 main_offset, const std::string& suffix)
- : program_code(program_code), shader_coverage_begin(main_offset),
- shader_coverage_end(main_offset + 1) {
-
- // Recursively finds all subroutines.
- const Subroutine& program_main = AddSubroutine(main_offset, PROGRAM_END, suffix);
- if (program_main.exit_method != ExitMethod::AlwaysEnd)
- throw DecompileFail("Program does not always end");
- }
-
- std::set<Subroutine> GetSubroutines() {
- return std::move(subroutines);
- }
-
- std::size_t GetShaderLength() const {
- return shader_coverage_end * sizeof(u64);
- }
-
-private:
- const ProgramCode& program_code;
- std::set<Subroutine> subroutines;
- std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
- u32 shader_coverage_begin;
- u32 shader_coverage_end;
-
- /// Adds and analyzes a new subroutine if it is not added yet.
- const Subroutine& AddSubroutine(u32 begin, u32 end, const std::string& suffix) {
- Subroutine subroutine{begin, end, suffix, ExitMethod::Undetermined, {}};
-
- const auto iter = subroutines.find(subroutine);
- if (iter != subroutines.end()) {
- return *iter;
- }
-
- subroutine.exit_method = Scan(begin, end, subroutine.labels);
- if (subroutine.exit_method == ExitMethod::Undetermined) {
- throw DecompileFail("Recursive function detected");
- }
-
- return *subroutines.insert(std::move(subroutine)).first;
- }
-
- /// Merges exit method of two parallel branches.
- static ExitMethod ParallelExit(ExitMethod a, ExitMethod b) {
- if (a == ExitMethod::Undetermined) {
- return b;
- }
- if (b == ExitMethod::Undetermined) {
- return a;
- }
- if (a == b) {
- return a;
- }
- return ExitMethod::Conditional;
- }
-
- /// Scans a range of code for labels and determines the exit method.
- ExitMethod Scan(u32 begin, u32 end, std::set<u32>& labels) {
- const auto [iter, inserted] =
- exit_method_map.emplace(std::make_pair(begin, end), ExitMethod::Undetermined);
- ExitMethod& exit_method = iter->second;
- if (!inserted)
- return exit_method;
-
- for (u32 offset = begin; offset != end && offset != PROGRAM_END; ++offset) {
- shader_coverage_begin = std::min(shader_coverage_begin, offset);
- shader_coverage_end = std::max(shader_coverage_end, offset + 1);
-
- const Instruction instr = {program_code[offset]};
- if (const auto opcode = OpCode::Decode(instr)) {
- switch (opcode->get().GetId()) {
- case OpCode::Id::EXIT: {
- // The EXIT instruction can be predicated, which means that the shader can
- // conditionally end on this instruction. We have to consider the case where the
- // condition is not met and check the exit method of that other basic block.
- using Tegra::Shader::Pred;
- if (instr.pred.pred_index == static_cast<u64>(Pred::UnusedIndex)) {
- return exit_method = ExitMethod::AlwaysEnd;
- } else {
- const ExitMethod not_met = Scan(offset + 1, end, labels);
- return exit_method = ParallelExit(ExitMethod::AlwaysEnd, not_met);
- }
- }
- case OpCode::Id::BRA: {
- const u32 target = offset + instr.bra.GetBranchTarget();
- labels.insert(target);
- const ExitMethod no_jmp = Scan(offset + 1, end, labels);
- const ExitMethod jmp = Scan(target, end, labels);
- return exit_method = ParallelExit(no_jmp, jmp);
- }
- case OpCode::Id::SSY:
- case OpCode::Id::PBK: {
- // The SSY and PBK use a similar encoding as the BRA instruction.
- UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
- "Constant buffer branching is not supported");
- const u32 target = offset + instr.bra.GetBranchTarget();
- labels.insert(target);
- // Continue scanning for an exit method.
- break;
- }
- }
- }
- }
- return exit_method = ExitMethod::AlwaysReturn;
- }
-};
+enum class Type { Bool, Bool2, Float, Int, Uint, HalfFloat };
class ShaderWriter {
public:
- void AddLine(std::string_view text) {
+ void AddExpression(std::string_view text) {
DEBUG_ASSERT(scope >= 0);
if (!text.empty()) {
AppendIndentation();
}
shader_source += text;
+ }
+
+ void AddLine(std::string_view text) {
+ AddExpression(text);
AddNewLine();
}
@@ -224,11 +66,17 @@ public:
shader_source += '\n';
}
+ std::string GenerateTemporal() {
+ std::string temporal = "tmp";
+ temporal += std::to_string(temporal_index++);
+ return temporal;
+ }
+
std::string GetResult() {
return std::move(shader_source);
}
- int scope = 0;
+ s32 scope = 0;
private:
void AppendIndentation() {
@@ -236,3731 +84,1482 @@ private:
}
std::string shader_source;
+ u32 temporal_index = 1;
};
-/**
- * Represents an emulated shader register, used to track the state of that register for emulation
- * with GLSL. At this time, a register can be used as a float or an integer. This class is used for
- * bookkeeping within the GLSL program.
- */
-class GLSLRegister {
-public:
- enum class Type {
- Float,
- Integer,
- UnsignedInteger,
- };
-
- GLSLRegister(std::size_t index, const std::string& suffix) : index{index}, suffix{suffix} {}
-
- /// Gets the GLSL type string for a register
- static std::string GetTypeString() {
- return "float";
- }
-
- /// Gets the GLSL register prefix string, used for declarations and referencing
- static std::string GetPrefixString() {
- return "reg_";
- }
-
- /// Returns a GLSL string representing the current state of the register
- std::string GetString() const {
- return GetPrefixString() + std::to_string(index) + '_' + suffix;
- }
-
- /// Returns the index of the register
- std::size_t GetIndex() const {
- return index;
- }
-
-private:
- const std::size_t index;
- const std::string& suffix;
-};
-
-/**
- * Used to manage shader registers that are emulated with GLSL. This class keeps track of the state
- * of all registers (e.g. whether they are currently being used as Floats or Integers), and
- * generates the necessary GLSL code to perform conversions as needed. This class is used for
- * bookkeeping within the GLSL program.
- */
-class GLSLRegisterManager {
-public:
- GLSLRegisterManager(ShaderWriter& shader, ShaderWriter& declarations,
- const Maxwell3D::Regs::ShaderStage& stage, const std::string& suffix,
- const Tegra::Shader::Header& header)
- : shader{shader}, declarations{declarations}, stage{stage}, suffix{suffix}, header{header},
- fixed_pipeline_output_attributes_used{}, local_memory_size{0} {
- BuildRegisterList();
- BuildInputList();
- }
-
- /**
- * Returns code that does an integer size conversion for the specified size.
- * @param value Value to perform integer size conversion on.
- * @param size Register size to use for conversion instructions.
- * @returns GLSL string corresponding to the value converted to the specified size.
- */
- static std::string ConvertIntegerSize(const std::string& value, Register::Size size) {
- switch (size) {
- case Register::Size::Byte:
- return "((" + value + " << 24) >> 24)";
- case Register::Size::Short:
- return "((" + value + " << 16) >> 16)";
- case Register::Size::Word:
- // Default - do nothing
- return value;
- default:
- UNIMPLEMENTED_MSG("Unimplemented conversion size: {}", static_cast<u32>(size));
- }
- }
-
- /**
- * Gets a register as an float.
- * @param reg The register to get.
- * @param elem The element to use for the operation.
- * @returns GLSL string corresponding to the register as a float.
- */
- std::string GetRegisterAsFloat(const Register& reg, unsigned elem = 0) {
- return GetRegister(reg, elem);
- }
-
- /**
- * Gets a register as an integer.
- * @param reg The register to get.
- * @param elem The element to use for the operation.
- * @param is_signed Whether to get the register as a signed (or unsigned) integer.
- * @param size Register size to use for conversion instructions.
- * @returns GLSL string corresponding to the register as an integer.
- */
- std::string GetRegisterAsInteger(const Register& reg, unsigned elem = 0, bool is_signed = true,
- Register::Size size = Register::Size::Word) {
- const std::string func{is_signed ? "floatBitsToInt" : "floatBitsToUint"};
- const std::string value{func + '(' + GetRegister(reg, elem) + ')'};
- return ConvertIntegerSize(value, size);
- }
-
- /**
- * Writes code that does a register assignment to float value operation.
- * @param reg The destination register to use.
- * @param elem The element to use for the operation.
- * @param value The code representing the value to assign.
- * @param dest_num_components Number of components in the destination.
- * @param value_num_components Number of components in the value.
- * @param is_saturated Optional, when True, saturates the provided value.
- * @param dest_elem Optional, the destination element to use for the operation.
- */
- void SetRegisterToFloat(const Register& reg, u64 elem, const std::string& value,
- u64 dest_num_components, u64 value_num_components,
- bool is_saturated = false, u64 dest_elem = 0, bool precise = false) {
-
- SetRegister(reg, elem, is_saturated ? "clamp(" + value + ", 0.0, 1.0)" : value,
- dest_num_components, value_num_components, dest_elem, precise);
- }
-
- /**
- * Writes code that does a register assignment to integer value operation.
- * @param reg The destination register to use.
- * @param elem The element to use for the operation.
- * @param value The code representing the value to assign.
- * @param dest_num_components Number of components in the destination.
- * @param value_num_components Number of components in the value.
- * @param is_saturated Optional, when True, saturates the provided value.
- * @param dest_elem Optional, the destination element to use for the operation.
- * @param size Register size to use for conversion instructions.
- */
- void SetRegisterToInteger(const Register& reg, bool is_signed, u64 elem,
- const std::string& value, u64 dest_num_components,
- u64 value_num_components, bool is_saturated = false,
- u64 dest_elem = 0, Register::Size size = Register::Size::Word,
- bool sets_cc = false) {
- UNIMPLEMENTED_IF(is_saturated);
-
- const std::string func{is_signed ? "intBitsToFloat" : "uintBitsToFloat"};
-
- SetRegister(reg, elem, func + '(' + ConvertIntegerSize(value, size) + ')',
- dest_num_components, value_num_components, dest_elem, false);
-
- if (sets_cc) {
- const std::string zero_condition = "( " + ConvertIntegerSize(value, size) + " == 0 )";
- SetInternalFlag(InternalFlag::ZeroFlag, zero_condition);
- LOG_WARNING(HW_GPU, "Condition codes implementation is incomplete.");
- }
- }
-
- /**
- * Writes code that does a register assignment to a half float value operation.
- * @param reg The destination register to use.
- * @param elem The element to use for the operation.
- * @param value The code representing the value to assign. Type has to be half float.
- * @param merge Half float kind of assignment.
- * @param dest_num_components Number of components in the destination.
- * @param value_num_components Number of components in the value.
- * @param is_saturated Optional, when True, saturates the provided value.
- * @param dest_elem Optional, the destination element to use for the operation.
- */
- void SetRegisterToHalfFloat(const Register& reg, u64 elem, const std::string& value,
- Tegra::Shader::HalfMerge merge, u64 dest_num_components,
- u64 value_num_components, bool is_saturated = false,
- u64 dest_elem = 0) {
- UNIMPLEMENTED_IF(is_saturated);
-
- const std::string result = [&]() {
- switch (merge) {
- case Tegra::Shader::HalfMerge::H0_H1:
- return "uintBitsToFloat(packHalf2x16(" + value + "))";
- case Tegra::Shader::HalfMerge::F32:
- // Half float instructions take the first component when doing a float cast.
- return "float(" + value + ".x)";
- case Tegra::Shader::HalfMerge::Mrg_H0:
- // TODO(Rodrigo): I guess Mrg_H0 and Mrg_H1 take their respective component from the
- // pack. I couldn't test this on hardware but it shouldn't really matter since most
- // of the time when a Mrg_* flag is used both components will be mirrored. That
- // being said, it deserves a test.
- return "((" + GetRegisterAsInteger(reg, 0, false) +
- " & 0xffff0000) | (packHalf2x16(" + value + ") & 0x0000ffff))";
- case Tegra::Shader::HalfMerge::Mrg_H1:
- return "((" + GetRegisterAsInteger(reg, 0, false) +
- " & 0x0000ffff) | (packHalf2x16(" + value + ") & 0xffff0000))";
- default:
- UNREACHABLE();
- return std::string("0");
- }
- }();
-
- SetRegister(reg, elem, result, dest_num_components, value_num_components, dest_elem, false);
- }
-
- /**
- * Writes code that does a register assignment to input attribute operation. Input attributes
- * are stored as floats, so this may require conversion.
- * @param reg The destination register to use.
- * @param elem The element to use for the operation.
- * @param attribute The input attribute to use as the source value.
- * @param input_mode The input mode.
- * @param vertex The register that decides which vertex to read from (used in GS).
- */
- void SetRegisterToInputAttibute(const Register& reg, u64 elem, Attribute::Index attribute,
- const Tegra::Shader::IpaMode& input_mode,
- std::optional<Register> vertex = {}) {
- const std::string dest = GetRegisterAsFloat(reg);
- const std::string src = GetInputAttribute(attribute, input_mode, vertex) + GetSwizzle(elem);
- shader.AddLine(dest + " = " + src + ';');
- }
-
- std::string GetLocalMemoryAsFloat(const std::string& index) {
- return "lmem[" + index + ']';
- }
-
- std::string GetLocalMemoryAsInteger(const std::string& index, bool is_signed = false) {
- const std::string func{is_signed ? "floatToIntBits" : "floatBitsToUint"};
- return func + "(lmem[" + index + "])";
- }
+/// Generates code to use for a swizzle operation.
+static std::string GetSwizzle(u32 elem) {
+ ASSERT(elem <= 3);
+ std::string swizzle = ".";
+ swizzle += "xyzw"[elem];
+ return swizzle;
+}
- void SetLocalMemoryAsFloat(const std::string& index, const std::string& value) {
- shader.AddLine("lmem[" + index + "] = " + value + ';');
+/// Translate topology
+static std::string GetTopologyName(Tegra::Shader::OutputTopology topology) {
+ switch (topology) {
+ case Tegra::Shader::OutputTopology::PointList:
+ return "points";
+ case Tegra::Shader::OutputTopology::LineStrip:
+ return "line_strip";
+ case Tegra::Shader::OutputTopology::TriangleStrip:
+ return "triangle_strip";
+ default:
+ UNIMPLEMENTED_MSG("Unknown output topology: {}", static_cast<u32>(topology));
+ return "points";
}
+}
- void SetLocalMemoryAsInteger(const std::string& index, const std::string& value,
- bool is_signed = false) {
- const std::string func{is_signed ? "intBitsToFloat" : "uintBitsToFloat"};
- shader.AddLine("lmem[" + index + "] = " + func + '(' + value + ");");
- }
+/// Returns true if an object has to be treated as precise
+static bool IsPrecise(Operation operand) {
+ const auto& meta = operand.GetMeta();
- std::string GetConditionCode(const Tegra::Shader::ConditionCode cc) const {
- switch (cc) {
- case Tegra::Shader::ConditionCode::NEU:
- return "!(" + GetInternalFlag(InternalFlag::ZeroFlag) + ')';
- default:
- UNIMPLEMENTED_MSG("Unimplemented condition code: {}", static_cast<u32>(cc));
- return "false";
- }
+ if (const auto arithmetic = std::get_if<MetaArithmetic>(&meta)) {
+ return arithmetic->precise;
}
-
- std::string GetInternalFlag(const InternalFlag flag) const {
- const auto index = static_cast<u32>(flag);
- ASSERT(index < static_cast<u32>(InternalFlag::Amount));
-
- return std::string(INTERNAL_FLAG_NAMES[index]) + '_' + suffix;
+ if (const auto half_arithmetic = std::get_if<MetaHalfArithmetic>(&meta)) {
+ return half_arithmetic->precise;
}
+ return false;
+}
- void SetInternalFlag(const InternalFlag flag, const std::string& value) const {
- shader.AddLine(GetInternalFlag(flag) + " = " + value + ';');
+static bool IsPrecise(Node node) {
+ if (const auto operation = std::get_if<OperationNode>(node)) {
+ return IsPrecise(*operation);
}
+ return false;
+}
- /**
- * Writes code that does a output attribute assignment to register operation. Output attributes
- * are stored as floats, so this may require conversion.
- * @param attribute The destination output attribute.
- * @param elem The element to use for the operation.
- * @param val_reg The register to use as the source value.
- * @param buf_reg The register that tells which buffer to write to (used in geometry shaders).
- */
- void SetOutputAttributeToRegister(Attribute::Index attribute, u64 elem, const Register& val_reg,
- const Register& buf_reg) {
- const std::string dest = GetOutputAttribute(attribute);
- const std::string src = GetRegisterAsFloat(val_reg);
- if (dest.empty())
- return;
+class GLSLDecompiler final {
+public:
+ explicit GLSLDecompiler(const ShaderIR& ir, ShaderStage stage, std::string suffix)
+ : ir{ir}, stage{stage}, suffix{suffix}, header{ir.GetHeader()} {}
- // Can happen with unknown/unimplemented output attributes, in which case we ignore the
- // instruction for now.
- if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
- // TODO(Rodrigo): nouveau sets some attributes after setting emitting a geometry
- // shader. These instructions use a dirty register as buffer index, to avoid some
- // drivers from complaining about out of boundary writes, guard them.
- const std::string buf_index{"((" + GetRegisterAsInteger(buf_reg) + ") % " +
- std::to_string(MAX_GEOMETRY_BUFFERS) + ')'};
- shader.AddLine("amem[" + buf_index + "][" +
- std::to_string(static_cast<u32>(attribute)) + ']' + GetSwizzle(elem) +
- " = " + src + ';');
- return;
- }
+ void Decompile() {
+ DeclareVertex();
+ DeclareGeometry();
+ DeclareRegisters();
+ DeclarePredicates();
+ DeclareLocalMemory();
+ DeclareInternalFlags();
+ DeclareInputAttributes();
+ DeclareOutputAttributes();
+ DeclareConstantBuffers();
+ DeclareGlobalMemory();
+ DeclareSamplers();
- switch (attribute) {
- case Attribute::Index::ClipDistances0123:
- case Attribute::Index::ClipDistances4567: {
- const u64 index = (attribute == Attribute::Index::ClipDistances4567 ? 4 : 0) + elem;
- UNIMPLEMENTED_IF_MSG(
- ((header.vtg.clip_distances >> index) & 1) == 0,
- "Shader is setting gl_ClipDistance{} without enabling it in the header", index);
+ code.AddLine("void execute_" + suffix + "() {");
+ ++code.scope;
- fixed_pipeline_output_attributes_used.insert(attribute);
- shader.AddLine(dest + '[' + std::to_string(index) + "] = " + src + ';');
- break;
- }
- case Attribute::Index::PointSize:
- fixed_pipeline_output_attributes_used.insert(attribute);
- shader.AddLine(dest + " = " + src + ';');
- break;
- default:
- shader.AddLine(dest + GetSwizzle(elem) + " = " + src + ';');
- break;
- }
- }
+ // VM's program counter
+ const auto first_address = ir.GetBasicBlocks().begin()->first;
+ code.AddLine("uint jmp_to = " + std::to_string(first_address) + "u;");
- /// Generates code representing a uniform (C buffer) register, interpreted as the input type.
- std::string GetUniform(u64 index, u64 offset, GLSLRegister::Type type,
- Register::Size size = Register::Size::Word) {
- declr_const_buffers[index].MarkAsUsed(index, offset, stage);
- std::string value = 'c' + std::to_string(index) + '[' + std::to_string(offset / 4) + "][" +
- std::to_string(offset % 4) + ']';
+ // TODO(Subv): Figure out the actual depth of the flow stack, for now it seems
+ // unlikely that shaders will use 20 nested SSYs and PBKs.
+ constexpr u32 FLOW_STACK_SIZE = 20;
+ code.AddLine(fmt::format("uint flow_stack[{}];", FLOW_STACK_SIZE));
+ code.AddLine("uint flow_stack_top = 0u;");
- if (type == GLSLRegister::Type::Float) {
- // Do nothing, default
- } else if (type == GLSLRegister::Type::Integer) {
- value = "floatBitsToInt(" + value + ')';
- } else if (type == GLSLRegister::Type::UnsignedInteger) {
- value = "floatBitsToUint(" + value + ')';
- } else {
- UNREACHABLE();
- }
+ code.AddLine("while (true) {");
+ ++code.scope;
- return ConvertIntegerSize(value, size);
- }
+ code.AddLine("switch (jmp_to) {");
- std::string GetUniformIndirect(u64 cbuf_index, s64 offset, const std::string& index_str,
- GLSLRegister::Type type) {
- declr_const_buffers[cbuf_index].MarkAsUsedIndirect(cbuf_index, stage);
+ for (const auto& pair : ir.GetBasicBlocks()) {
+ const auto [address, bb] = pair;
+ code.AddLine(fmt::format("case 0x{:x}u: {{", address));
+ ++code.scope;
- const std::string final_offset = fmt::format("({} + {})", index_str, offset / 4);
- const std::string value = 'c' + std::to_string(cbuf_index) + '[' + final_offset + " / 4][" +
- final_offset + " % 4]";
+ VisitBasicBlock(bb);
- if (type == GLSLRegister::Type::Float) {
- return value;
- } else if (type == GLSLRegister::Type::Integer) {
- return "floatBitsToInt(" + value + ')';
- } else {
- UNREACHABLE();
+ --code.scope;
+ code.AddLine('}');
}
- }
-
- /// Add declarations.
- void GenerateDeclarations(const std::string& suffix) {
- GenerateVertex();
- GenerateRegisters(suffix);
- GenerateLocalMemory();
- GenerateInternalFlags();
- GenerateInputAttrs();
- GenerateOutputAttrs();
- GenerateConstBuffers();
- GenerateSamplers();
- GenerateGeometry();
- }
-
- /// Returns a list of constant buffer declarations.
- std::vector<ConstBufferEntry> GetConstBuffersDeclarations() const {
- std::vector<ConstBufferEntry> result;
- std::copy_if(declr_const_buffers.begin(), declr_const_buffers.end(),
- std::back_inserter(result), [](const auto& entry) { return entry.IsUsed(); });
- return result;
- }
- /// Returns a list of samplers used in the shader.
- const std::vector<SamplerEntry>& GetSamplers() const {
- return used_samplers;
- }
+ code.AddLine("default: return;");
+ code.AddLine('}');
- /// Returns the GLSL sampler used for the input shader sampler, and creates a new one if
- /// necessary.
- std::string AccessSampler(const Sampler& sampler, Tegra::Shader::TextureType type,
- bool is_array, bool is_shadow) {
- const auto offset = static_cast<std::size_t>(sampler.index.Value());
-
- // If this sampler has already been used, return the existing mapping.
- const auto itr =
- std::find_if(used_samplers.begin(), used_samplers.end(),
- [&](const SamplerEntry& entry) { return entry.GetOffset() == offset; });
-
- if (itr != used_samplers.end()) {
- ASSERT(itr->GetType() == type && itr->IsArray() == is_array &&
- itr->IsShadow() == is_shadow);
- return itr->GetName();
+ for (std::size_t i = 0; i < 2; ++i) {
+ --code.scope;
+ code.AddLine('}');
}
-
- // Otherwise create a new mapping for this sampler
- const std::size_t next_index = used_samplers.size();
- const SamplerEntry entry{stage, offset, next_index, type, is_array, is_shadow};
- used_samplers.emplace_back(entry);
- return entry.GetName();
}
- void SetLocalMemory(u64 lmem) {
- local_memory_size = lmem;
+ std::string GetResult() {
+ return code.GetResult();
}
-private:
- /// Generates declarations for registers.
- void GenerateRegisters(const std::string& suffix) {
- for (const auto& reg : regs) {
- declarations.AddLine(GLSLRegister::GetTypeString() + ' ' + reg.GetPrefixString() +
- std::to_string(reg.GetIndex()) + '_' + suffix + " = 0;");
+ ShaderEntries GetShaderEntries() const {
+ ShaderEntries entries;
+ for (const auto& cbuf : ir.GetConstantBuffers()) {
+ entries.const_buffers.emplace_back(cbuf.second, stage, GetConstBufferBlock(cbuf.first),
+ cbuf.first);
}
- declarations.AddNewLine();
- }
-
- /// Generates declarations for local memory.
- void GenerateLocalMemory() {
- if (local_memory_size > 0) {
- declarations.AddLine("float lmem[" + std::to_string((local_memory_size - 1 + 4) / 4) +
- "];");
- declarations.AddNewLine();
+ for (const auto& sampler : ir.GetSamplers()) {
+ entries.samplers.emplace_back(sampler, stage, GetSampler(sampler));
}
- }
-
- /// Generates declarations for internal flags.
- void GenerateInternalFlags() {
- for (u32 flag = 0; flag < static_cast<u32>(InternalFlag::Amount); flag++) {
- const InternalFlag code = static_cast<InternalFlag>(flag);
- declarations.AddLine("bool " + GetInternalFlag(code) + " = false;");
+ for (const auto& gmem : ir.GetGlobalMemoryBases()) {
+ entries.global_memory_entries.emplace_back(gmem.cbuf_index, gmem.cbuf_offset, stage,
+ GetGlobalMemoryBlock(gmem));
}
- declarations.AddNewLine();
+ entries.clip_distances = ir.GetClipDistances();
+ entries.shader_length = ir.GetLength();
+ return entries;
}
- /// Generates declarations for input attributes.
- void GenerateInputAttrs() {
- for (const auto element : declr_input_attribute) {
- // TODO(bunnei): Use proper number of elements for these
- u32 idx =
- static_cast<u32>(element.first) - static_cast<u32>(Attribute::Index::Attribute_0);
- if (stage != Maxwell3D::Regs::ShaderStage::Vertex) {
- // If inputs are varyings, add an offset
- idx += GENERIC_VARYING_START_LOCATION;
- }
-
- std::string attr{GetInputAttribute(element.first, element.second)};
- if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
- attr = "gs_" + attr + "[]";
- }
- declarations.AddLine("layout (location = " + std::to_string(idx) + ") " +
- GetInputFlags(element.first) + "in vec4 " + attr + ';');
- }
-
- declarations.AddNewLine();
- }
+private:
+ using OperationDecompilerFn = std::string (GLSLDecompiler::*)(Operation);
+ using OperationDecompilersArray =
+ std::array<OperationDecompilerFn, static_cast<std::size_t>(OperationCode::Amount)>;
- /// Generates declarations for output attributes.
- void GenerateOutputAttrs() {
- for (const auto& index : declr_output_attribute) {
- // TODO(bunnei): Use proper number of elements for these
- const u32 idx = static_cast<u32>(index) -
- static_cast<u32>(Attribute::Index::Attribute_0) +
- GENERIC_VARYING_START_LOCATION;
- declarations.AddLine("layout (location = " + std::to_string(idx) + ") out vec4 " +
- GetOutputAttribute(index) + ';');
- }
- declarations.AddNewLine();
- }
-
- /// Generates declarations for constant buffers.
- void GenerateConstBuffers() {
- for (const auto& entry : GetConstBuffersDeclarations()) {
- declarations.AddLine("layout (std140) uniform " + entry.GetName());
- declarations.AddLine('{');
- declarations.AddLine(" vec4 c" + std::to_string(entry.GetIndex()) +
- "[MAX_CONSTBUFFER_ELEMENTS];");
- declarations.AddLine("};");
- declarations.AddNewLine();
- }
- declarations.AddNewLine();
- }
+ void DeclareVertex() {
+ if (stage != ShaderStage::Vertex)
+ return;
- /// Generates declarations for samplers.
- void GenerateSamplers() {
- const auto& samplers = GetSamplers();
- for (const auto& sampler : samplers) {
- declarations.AddLine("uniform " + sampler.GetTypeString() + ' ' + sampler.GetName() +
- ';');
- }
- declarations.AddNewLine();
+ DeclareVertexRedeclarations();
}
- /// Generates declarations used for geometry shaders.
- void GenerateGeometry() {
- if (stage != Maxwell3D::Regs::ShaderStage::Geometry)
+ void DeclareGeometry() {
+ if (stage != ShaderStage::Geometry)
return;
- declarations.AddLine(
- "layout (" + GetTopologyName(header.common3.output_topology) +
- ", max_vertices = " + std::to_string(header.common4.max_output_vertices) + ") out;");
- declarations.AddNewLine();
-
- declarations.AddLine("vec4 amem[" + std::to_string(MAX_GEOMETRY_BUFFERS) + "][" +
- std::to_string(MAX_ATTRIBUTES) + "];");
- declarations.AddNewLine();
-
- constexpr char buffer[] = "amem[output_buffer]";
- declarations.AddLine("void emit_vertex(uint output_buffer) {");
- ++declarations.scope;
- for (const auto element : declr_output_attribute) {
- declarations.AddLine(GetOutputAttribute(element) + " = " + buffer + '[' +
- std::to_string(static_cast<u32>(element)) + "];");
- }
-
- declarations.AddLine("position = " + std::string(buffer) + '[' +
- std::to_string(static_cast<u32>(Attribute::Index::Position)) + "];");
+ const auto topology = GetTopologyName(header.common3.output_topology);
+ const auto max_vertices = std::to_string(header.common4.max_output_vertices);
+ code.AddLine("layout (" + topology + ", max_vertices = " + max_vertices + ") out;");
+ code.AddNewLine();
- // If a geometry shader is attached, it will always flip (it's the last stage before
- // fragment). For more info about flipping, refer to gl_shader_gen.cpp.
- declarations.AddLine("position.xy *= viewport_flip.xy;");
- declarations.AddLine("gl_Position = position;");
- declarations.AddLine("position.w = 1.0;");
- declarations.AddLine("EmitVertex();");
- --declarations.scope;
- declarations.AddLine('}');
- declarations.AddNewLine();
+ DeclareVertexRedeclarations();
}
- void GenerateVertex() {
- if (stage != Maxwell3D::Regs::ShaderStage::Vertex)
- return;
+ void DeclareVertexRedeclarations() {
bool clip_distances_declared = false;
- declarations.AddLine("out gl_PerVertex {");
- ++declarations.scope;
- declarations.AddLine("vec4 gl_Position;");
- for (auto& o : fixed_pipeline_output_attributes_used) {
+ code.AddLine("out gl_PerVertex {");
+ ++code.scope;
+
+ code.AddLine("vec4 gl_Position;");
+
+ for (const auto o : ir.GetOutputAttributes()) {
if (o == Attribute::Index::PointSize)
- declarations.AddLine("float gl_PointSize;");
+ code.AddLine("float gl_PointSize;");
if (!clip_distances_declared && (o == Attribute::Index::ClipDistances0123 ||
o == Attribute::Index::ClipDistances4567)) {
- declarations.AddLine("float gl_ClipDistance[];");
+ code.AddLine("float gl_ClipDistance[];");
clip_distances_declared = true;
}
}
- --declarations.scope;
- declarations.AddLine("};");
- }
- /// Generates code representing a temporary (GPR) register.
- std::string GetRegister(const Register& reg, unsigned elem) {
- if (reg == Register::ZeroIndex) {
- return "0";
- }
-
- return regs[reg.GetSwizzledIndex(elem)].GetString();
- }
-
- /**
- * Writes code that does a register assignment to value operation.
- * @param reg The destination register to use.
- * @param elem The element to use for the operation.
- * @param value The code representing the value to assign.
- * @param dest_num_components Number of components in the destination.
- * @param value_num_components Number of components in the value.
- * @param dest_elem Optional, the destination element to use for the operation.
- */
- void SetRegister(const Register& reg, u64 elem, const std::string& value,
- u64 dest_num_components, u64 value_num_components, u64 dest_elem,
- bool precise) {
- if (reg == Register::ZeroIndex) {
- // Setting RZ is a nop in hardware.
- return;
- }
-
- std::string dest = GetRegister(reg, static_cast<u32>(dest_elem));
- if (dest_num_components > 1) {
- dest += GetSwizzle(elem);
- }
-
- std::string src = '(' + value + ')';
- if (value_num_components > 1) {
- src += GetSwizzle(elem);
- }
+ --code.scope;
+ code.AddLine("};");
+ code.AddNewLine();
+ }
- if (precise && stage != Maxwell3D::Regs::ShaderStage::Fragment) {
- shader.AddLine('{');
- ++shader.scope;
- // This avoids optimizations of constant propagation and keeps the code as the original
- // Sadly using the precise keyword causes "linking" errors on fragment shaders.
- shader.AddLine("precise float tmp = " + src + ';');
- shader.AddLine(dest + " = tmp;");
- --shader.scope;
- shader.AddLine('}');
- } else {
- shader.AddLine(dest + " = " + src + ';');
+ void DeclareRegisters() {
+ const auto& registers = ir.GetRegisters();
+ for (const u32 gpr : registers) {
+ code.AddLine("float " + GetRegister(gpr) + " = 0;");
}
+ if (!registers.empty())
+ code.AddNewLine();
}
- /// Build the GLSL register list.
- void BuildRegisterList() {
- regs.reserve(Register::NumRegisters);
-
- for (std::size_t index = 0; index < Register::NumRegisters; ++index) {
- regs.emplace_back(index, suffix);
+ void DeclarePredicates() {
+ const auto& predicates = ir.GetPredicates();
+ for (const auto pred : predicates) {
+ code.AddLine("bool " + GetPredicate(pred) + " = false;");
}
+ if (!predicates.empty())
+ code.AddNewLine();
}
- void BuildInputList() {
- const u32 size = static_cast<u32>(Attribute::Index::Attribute_31) -
- static_cast<u32>(Attribute::Index::Attribute_0) + 1;
- declr_input_attribute.reserve(size);
+ void DeclareLocalMemory() {
+ if (const u64 local_memory_size = header.GetLocalMemorySize(); local_memory_size > 0) {
+ const auto element_count = Common::AlignUp(local_memory_size, 4) / 4;
+ code.AddLine("float " + GetLocalMemory() + '[' + std::to_string(element_count) + "];");
+ code.AddNewLine();
+ }
}
- /// Generates code representing an input attribute register.
- std::string GetInputAttribute(Attribute::Index attribute,
- const Tegra::Shader::IpaMode& input_mode,
- std::optional<Register> vertex = {}) {
- auto GeometryPass = [&](const std::string& name) {
- if (stage == Maxwell3D::Regs::ShaderStage::Geometry && vertex) {
- // TODO(Rodrigo): Guard geometry inputs against out of bound reads. Some games set
- // an 0x80000000 index for those and the shader fails to build. Find out why this
- // happens and what's its intent.
- return "gs_" + name + '[' + GetRegisterAsInteger(*vertex, 0, false) +
- " % MAX_VERTEX_INPUT]";
- }
- return name;
- };
-
- switch (attribute) {
- case Attribute::Index::Position:
- if (stage != Maxwell3D::Regs::ShaderStage::Fragment) {
- return GeometryPass("position");
- } else {
- return "vec4(gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1.0)";
- }
- case Attribute::Index::PointCoord:
- return "vec4(gl_PointCoord.x, gl_PointCoord.y, 0, 0)";
- case Attribute::Index::TessCoordInstanceIDVertexID:
- // TODO(Subv): Find out what the values are for the first two elements when inside a
- // vertex shader, and what's the value of the fourth element when inside a Tess Eval
- // shader.
- ASSERT(stage == Maxwell3D::Regs::ShaderStage::Vertex);
- // Config pack's first value is instance_id.
- return "vec4(0, 0, uintBitsToFloat(config_pack[0]), uintBitsToFloat(gl_VertexID))";
- case Attribute::Index::FrontFacing:
- // TODO(Subv): Find out what the values are for the other elements.
- ASSERT(stage == Maxwell3D::Regs::ShaderStage::Fragment);
- return "vec4(0, 0, 0, uintBitsToFloat(gl_FrontFacing ? 1 : 0))";
- default:
- const u32 index{static_cast<u32>(attribute) -
- static_cast<u32>(Attribute::Index::Attribute_0)};
- if (attribute >= Attribute::Index::Attribute_0 &&
- attribute <= Attribute::Index::Attribute_31) {
- if (declr_input_attribute.count(attribute) == 0) {
- declr_input_attribute[attribute] = input_mode;
- } else {
- UNIMPLEMENTED_IF_MSG(declr_input_attribute[attribute] != input_mode,
- "Multiple input modes for the same attribute");
- }
- return GeometryPass("input_attribute_" + std::to_string(index));
- }
-
- UNIMPLEMENTED_MSG("Unhandled input attribute: {}", static_cast<u32>(attribute));
+ void DeclareInternalFlags() {
+ for (u32 flag = 0; flag < static_cast<u32>(InternalFlag::Amount); flag++) {
+ const InternalFlag flag_code = static_cast<InternalFlag>(flag);
+ code.AddLine("bool " + GetInternalFlag(flag_code) + " = false;");
}
-
- return "vec4(0, 0, 0, 0)";
+ code.AddNewLine();
}
- std::string GetInputFlags(const Attribute::Index attribute) {
- const Tegra::Shader::IpaSampleMode sample_mode =
- declr_input_attribute[attribute].sampling_mode;
- const Tegra::Shader::IpaInterpMode interp_mode =
- declr_input_attribute[attribute].interpolation_mode;
+ std::string GetInputFlags(const IpaMode& input_mode) {
+ const IpaSampleMode sample_mode = input_mode.sampling_mode;
+ const IpaInterpMode interp_mode = input_mode.interpolation_mode;
std::string out;
+
switch (interp_mode) {
- case Tegra::Shader::IpaInterpMode::Flat: {
+ case IpaInterpMode::Flat:
out += "flat ";
break;
- }
- case Tegra::Shader::IpaInterpMode::Linear: {
+ case IpaInterpMode::Linear:
out += "noperspective ";
break;
- }
- case Tegra::Shader::IpaInterpMode::Perspective: {
+ case IpaInterpMode::Perspective:
// Default, Smooth
break;
- }
- default: {
+ default:
UNIMPLEMENTED_MSG("Unhandled IPA interp mode: {}", static_cast<u32>(interp_mode));
}
- }
switch (sample_mode) {
- case Tegra::Shader::IpaSampleMode::Centroid:
- // It can be implemented with the "centroid " keyword in glsl
+ case IpaSampleMode::Centroid:
+ // It can be implemented with the "centroid " keyword in GLSL
UNIMPLEMENTED_MSG("Unimplemented IPA sampler mode centroid");
break;
- case Tegra::Shader::IpaSampleMode::Default:
+ case IpaSampleMode::Default:
// Default, n/a
break;
- default: {
+ default:
UNIMPLEMENTED_MSG("Unimplemented IPA sampler mode: {}", static_cast<u32>(sample_mode));
- break;
- }
}
return out;
}
- /// Generates code representing the declaration name of an output attribute register.
- std::string GetOutputAttribute(Attribute::Index attribute) {
- switch (attribute) {
- case Attribute::Index::PointSize:
- return "gl_PointSize";
- case Attribute::Index::Position:
- return "position";
- case Attribute::Index::ClipDistances0123:
- case Attribute::Index::ClipDistances4567: {
- return "gl_ClipDistance";
- }
- default:
- const u32 index{static_cast<u32>(attribute) -
- static_cast<u32>(Attribute::Index::Attribute_0)};
- if (attribute >= Attribute::Index::Attribute_0) {
- declr_output_attribute.insert(attribute);
- return "output_attribute_" + std::to_string(index);
+ void DeclareInputAttributes() {
+ const auto& attributes = ir.GetInputAttributes();
+ for (const auto element : attributes) {
+ const Attribute::Index index = element.first;
+ const IpaMode& input_mode = *element.second.begin();
+ if (index < Attribute::Index::Attribute_0 || index > Attribute::Index::Attribute_31) {
+ // Skip when it's not a generic attribute
+ continue;
}
- UNIMPLEMENTED_MSG("Unhandled output attribute={}", index);
- return {};
- }
- }
-
- /// Generates code to use for a swizzle operation.
- static std::string GetSwizzle(u64 elem) {
- ASSERT(elem <= 3);
- std::string swizzle = ".";
- swizzle += "xyzw"[elem];
- return swizzle;
- }
-
- ShaderWriter& shader;
- ShaderWriter& declarations;
- std::vector<GLSLRegister> regs;
- std::unordered_map<Attribute::Index, Tegra::Shader::IpaMode> declr_input_attribute;
- std::set<Attribute::Index> declr_output_attribute;
- std::array<ConstBufferEntry, Maxwell3D::Regs::MaxConstBuffers> declr_const_buffers;
- std::vector<SamplerEntry> used_samplers;
- const Maxwell3D::Regs::ShaderStage& stage;
- const std::string& suffix;
- const Tegra::Shader::Header& header;
- std::unordered_set<Attribute::Index> fixed_pipeline_output_attributes_used;
- u64 local_memory_size;
-};
-
-class GLSLGenerator {
-public:
- GLSLGenerator(const std::set<Subroutine>& subroutines, const ProgramCode& program_code,
- u32 main_offset, Maxwell3D::Regs::ShaderStage stage, const std::string& suffix,
- std::size_t shader_length)
- : subroutines(subroutines), program_code(program_code), main_offset(main_offset),
- stage(stage), suffix(suffix), shader_length(shader_length) {
- std::memcpy(&header, program_code.data(), sizeof(Tegra::Shader::Header));
- local_memory_size = header.GetLocalMemorySize();
- regs.SetLocalMemory(local_memory_size);
- Generate(suffix);
- }
-
- std::string GetShaderCode() {
- return declarations.GetResult() + shader.GetResult();
- }
-
- /// Returns entries in the shader that are useful for external functions
- ShaderEntries GetEntries() const {
- return {regs.GetConstBuffersDeclarations(), regs.GetSamplers(), shader_length};
- }
-
-private:
- /// Gets the Subroutine object corresponding to the specified address.
- const Subroutine& GetSubroutine(u32 begin, u32 end) const {
- const auto iter = subroutines.find(Subroutine{begin, end, suffix});
- ASSERT(iter != subroutines.end());
- return *iter;
- }
-
- /// Generates code representing a 19-bit immediate value
- static std::string GetImmediate19(const Instruction& instr) {
- return fmt::format("uintBitsToFloat({})", instr.alu.GetImm20_19());
- }
-
- /// Generates code representing a 32-bit immediate value
- static std::string GetImmediate32(const Instruction& instr) {
- return fmt::format("uintBitsToFloat({})", instr.alu.GetImm20_32());
- }
-
- /// Generates code representing a vec2 pair unpacked from a half float immediate
- static std::string UnpackHalfImmediate(const Instruction& instr, bool negate) {
- const std::string immediate = GetHalfFloat(std::to_string(instr.half_imm.PackImmediates()));
- if (!negate) {
- return immediate;
- }
- const std::string negate_first = instr.half_imm.first_negate != 0 ? "-" : "";
- const std::string negate_second = instr.half_imm.second_negate != 0 ? "-" : "";
- const std::string negate_vec = "vec2(" + negate_first + "1, " + negate_second + "1)";
-
- return '(' + immediate + " * " + negate_vec + ')';
- }
+ ASSERT(element.second.size() > 0);
+ UNIMPLEMENTED_IF_MSG(element.second.size() > 1,
+ "Multiple input flag modes are not supported in GLSL");
- /// Generates code representing a texture sampler.
- std::string GetSampler(const Sampler& sampler, Tegra::Shader::TextureType type, bool is_array,
- bool is_shadow) {
- return regs.AccessSampler(sampler, type, is_array, is_shadow);
- }
+ // TODO(bunnei): Use proper number of elements for these
+ u32 idx = static_cast<u32>(index) - static_cast<u32>(Attribute::Index::Attribute_0);
+ if (stage != ShaderStage::Vertex) {
+ // If inputs are varyings, add an offset
+ idx += GENERIC_VARYING_START_LOCATION;
+ }
- /**
- * Adds code that calls a subroutine.
- * @param subroutine the subroutine to call.
- */
- void CallSubroutine(const Subroutine& subroutine) {
- if (subroutine.exit_method == ExitMethod::AlwaysEnd) {
- shader.AddLine(subroutine.GetName() + "();");
- shader.AddLine("return true;");
- } else if (subroutine.exit_method == ExitMethod::Conditional) {
- shader.AddLine("if (" + subroutine.GetName() + "()) { return true; }");
- } else {
- shader.AddLine(subroutine.GetName() + "();");
+ std::string attr = GetInputAttribute(index);
+ if (stage == ShaderStage::Geometry) {
+ attr = "gs_" + attr + "[]";
+ }
+ code.AddLine("layout (location = " + std::to_string(idx) + ") " +
+ GetInputFlags(input_mode) + "in vec4 " + attr + ';');
}
+ if (!attributes.empty())
+ code.AddNewLine();
}
- /*
- * Writes code that assigns a predicate boolean variable.
- * @param pred The id of the predicate to write to.
- * @param value The expression value to assign to the predicate.
- */
- void SetPredicate(u64 pred, const std::string& value) {
- using Tegra::Shader::Pred;
- // Can't assign to the constant predicate.
- ASSERT(pred != static_cast<u64>(Pred::UnusedIndex));
-
- std::string variable = 'p' + std::to_string(pred) + '_' + suffix;
- shader.AddLine(variable + " = " + value + ';');
- declr_predicates.insert(std::move(variable));
- }
-
- /*
- * Returns the condition to use in the 'if' for a predicated instruction.
- * @param instr Instruction to generate the if condition for.
- * @returns string containing the predicate condition.
- */
- std::string GetPredicateCondition(u64 index, bool negate) {
- using Tegra::Shader::Pred;
- std::string variable;
-
- // Index 7 is used as an 'Always True' condition.
- if (index == static_cast<u64>(Pred::UnusedIndex)) {
- variable = "true";
- } else {
- variable = 'p' + std::to_string(index) + '_' + suffix;
- declr_predicates.insert(variable);
- }
- if (negate) {
- return "!(" + variable + ')';
- }
-
- return variable;
- }
-
- /**
- * Returns the comparison string to use to compare two values in the 'set' family of
- * instructions.
- * @param condition The condition used in the 'set'-family instruction.
- * @param op_a First operand to use for the comparison.
- * @param op_b Second operand to use for the comparison.
- * @returns String corresponding to the GLSL operator that matches the desired comparison.
- */
- std::string GetPredicateComparison(Tegra::Shader::PredCondition condition,
- const std::string& op_a, const std::string& op_b) const {
- using Tegra::Shader::PredCondition;
- static const std::unordered_map<PredCondition, const char*> PredicateComparisonStrings = {
- {PredCondition::LessThan, "<"},
- {PredCondition::Equal, "=="},
- {PredCondition::LessEqual, "<="},
- {PredCondition::GreaterThan, ">"},
- {PredCondition::NotEqual, "!="},
- {PredCondition::GreaterEqual, ">="},
- {PredCondition::LessThanWithNan, "<"},
- {PredCondition::NotEqualWithNan, "!="},
- {PredCondition::LessEqualWithNan, "<="},
- {PredCondition::GreaterThanWithNan, ">"},
- {PredCondition::GreaterEqualWithNan, ">="}};
-
- const auto& comparison{PredicateComparisonStrings.find(condition)};
- UNIMPLEMENTED_IF_MSG(comparison == PredicateComparisonStrings.end(),
- "Unknown predicate comparison operation");
-
- std::string predicate{'(' + op_a + ") " + comparison->second + " (" + op_b + ')'};
- if (condition == PredCondition::LessThanWithNan ||
- condition == PredCondition::NotEqualWithNan ||
- condition == PredCondition::LessEqualWithNan ||
- condition == PredCondition::GreaterThanWithNan ||
- condition == PredCondition::GreaterEqualWithNan) {
- predicate += " || isnan(" + op_a + ") || isnan(" + op_b + ')';
- }
-
- return predicate;
- }
-
- /**
- * Returns the operator string to use to combine two predicates in the 'setp' family of
- * instructions.
- * @params operation The operator used in the 'setp'-family instruction.
- * @returns String corresponding to the GLSL operator that matches the desired operator.
- */
- std::string GetPredicateCombiner(Tegra::Shader::PredOperation operation) const {
- using Tegra::Shader::PredOperation;
- static const std::unordered_map<PredOperation, const char*> PredicateOperationStrings = {
- {PredOperation::And, "&&"},
- {PredOperation::Or, "||"},
- {PredOperation::Xor, "^^"},
- };
-
- auto op = PredicateOperationStrings.find(operation);
- UNIMPLEMENTED_IF_MSG(op == PredicateOperationStrings.end(), "Unknown predicate operation");
- return op->second;
- }
-
- /**
- * Transforms the input string GLSL operand into one that applies the abs() function and negates
- * the output if necessary. When both abs and neg are true, the negation will be applied after
- * taking the absolute value.
- * @param operand The input operand to take the abs() of, negate, or both.
- * @param abs Whether to apply the abs() function to the input operand.
- * @param neg Whether to negate the input operand.
- * @returns String corresponding to the operand after being transformed by the abs() and
- * negation operations.
- */
- static std::string GetOperandAbsNeg(const std::string& operand, bool abs, bool neg) {
- std::string result = operand;
-
- if (abs) {
- result = "abs(" + result + ')';
- }
-
- if (neg) {
- result = "-(" + result + ')';
- }
-
- return result;
- }
-
- /*
- * Transforms the input string GLSL operand into an unpacked half float pair.
- * @note This function returns a float type pair instead of a half float pair. This is because
- * real half floats are not standardized in GLSL but unpackHalf2x16 (which returns a vec2) is.
- * @param operand Input operand. It has to be an unsigned integer.
- * @param type How to unpack the unsigned integer to a half float pair.
- * @param abs Get the absolute value of unpacked half floats.
- * @param neg Get the negative value of unpacked half floats.
- * @returns String corresponding to a half float pair.
- */
- static std::string GetHalfFloat(const std::string& operand,
- Tegra::Shader::HalfType type = Tegra::Shader::HalfType::H0_H1,
- bool abs = false, bool neg = false) {
- // "vec2" calls emitted in this function are intended to alias components.
- const std::string value = [&]() {
- switch (type) {
- case Tegra::Shader::HalfType::H0_H1:
- return "unpackHalf2x16(" + operand + ')';
- case Tegra::Shader::HalfType::F32:
- return "vec2(uintBitsToFloat(" + operand + "))";
- case Tegra::Shader::HalfType::H0_H0:
- case Tegra::Shader::HalfType::H1_H1: {
- const bool high = type == Tegra::Shader::HalfType::H1_H1;
- const char unpack_index = "xy"[high ? 1 : 0];
- return "vec2(unpackHalf2x16(" + operand + ")." + unpack_index + ')';
- }
- default:
- UNREACHABLE();
- return std::string("vec2(0)");
+ void DeclareOutputAttributes() {
+ const auto& attributes = ir.GetOutputAttributes();
+ for (const auto index : attributes) {
+ if (index < Attribute::Index::Attribute_0 || index > Attribute::Index::Attribute_31) {
+ // Skip when it's not a generic attribute
+ continue;
}
- }();
-
- return GetOperandAbsNeg(value, abs, neg);
- }
-
- /*
- * Returns whether the instruction at the specified offset is a 'sched' instruction.
- * Sched instructions always appear before a sequence of 3 instructions.
- */
- bool IsSchedInstruction(u32 offset) const {
- // sched instructions appear once every 4 instructions.
- static constexpr std::size_t SchedPeriod = 4;
- u32 absolute_offset = offset - main_offset;
-
- return (absolute_offset % SchedPeriod) == 0;
- }
-
- void WriteLogicOperation(Register dest, LogicOperation logic_op, const std::string& op_a,
- const std::string& op_b,
- Tegra::Shader::PredicateResultMode predicate_mode,
- Tegra::Shader::Pred predicate) {
- std::string result{};
- switch (logic_op) {
- case LogicOperation::And: {
- result = '(' + op_a + " & " + op_b + ')';
- break;
- }
- case LogicOperation::Or: {
- result = '(' + op_a + " | " + op_b + ')';
- break;
- }
- case LogicOperation::Xor: {
- result = '(' + op_a + " ^ " + op_b + ')';
- break;
- }
- case LogicOperation::PassB: {
- result = op_b;
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unimplemented logic operation={}", static_cast<u32>(logic_op));
- }
-
- if (dest != Tegra::Shader::Register::ZeroIndex) {
- regs.SetRegisterToInteger(dest, true, 0, result, 1, 1);
- }
-
- using Tegra::Shader::PredicateResultMode;
- // Write the predicate value depending on the predicate mode.
- switch (predicate_mode) {
- case PredicateResultMode::None:
- // Do nothing.
- return;
- case PredicateResultMode::NotZero:
- // Set the predicate to true if the result is not zero.
- SetPredicate(static_cast<u64>(predicate), '(' + result + ") != 0");
- break;
- default:
- UNIMPLEMENTED_MSG("Unimplemented predicate result mode: {}",
- static_cast<u32>(predicate_mode));
+ // TODO(bunnei): Use proper number of elements for these
+ const auto idx = static_cast<u32>(index) -
+ static_cast<u32>(Attribute::Index::Attribute_0) +
+ GENERIC_VARYING_START_LOCATION;
+ code.AddLine("layout (location = " + std::to_string(idx) + ") out vec4 " +
+ GetOutputAttribute(index) + ';');
}
+ if (!attributes.empty())
+ code.AddNewLine();
}
- void WriteLop3Instruction(Register dest, const std::string& op_a, const std::string& op_b,
- const std::string& op_c, const std::string& imm_lut) {
- if (dest == Tegra::Shader::Register::ZeroIndex) {
- return;
+ void DeclareConstantBuffers() {
+ for (const auto& entry : ir.GetConstantBuffers()) {
+ const auto [index, size] = entry;
+ code.AddLine("layout (std140, binding = CBUF_BINDING_" + std::to_string(index) +
+ ") uniform " + GetConstBufferBlock(index) + " {");
+ code.AddLine(" vec4 " + GetConstBuffer(index) + "[MAX_CONSTBUFFER_ELEMENTS];");
+ code.AddLine("};");
+ code.AddNewLine();
}
-
- static constexpr std::array<const char*, 32> shift_amounts = {
- "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
- "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
- "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
-
- std::string result;
- result += '(';
-
- for (std::size_t i = 0; i < shift_amounts.size(); ++i) {
- if (i)
- result += '|';
- result += "(((" + imm_lut + " >> (((" + op_c + " >> " + shift_amounts[i] +
- ") & 1) | ((" + op_b + " >> " + shift_amounts[i] + ") & 1) << 1 | ((" + op_a +
- " >> " + shift_amounts[i] + ") & 1) << 2)) & 1) << " + shift_amounts[i] + ")";
- }
-
- result += ')';
-
- regs.SetRegisterToInteger(dest, true, 0, result, 1, 1);
}
- void WriteTexsInstruction(const Instruction& instr, const std::string& coord,
- const std::string& texture) {
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine(coord);
- shader.AddLine("vec4 texture_tmp = " + texture + ';');
-
- // TEXS has two destination registers and a swizzle. The first two elements in the swizzle
- // go into gpr0+0 and gpr0+1, and the rest goes into gpr28+0 and gpr28+1
-
- std::size_t written_components = 0;
- for (u32 component = 0; component < 4; ++component) {
- if (!instr.texs.IsComponentEnabled(component)) {
- continue;
- }
-
- if (written_components < 2) {
- // Write the first two swizzle components to gpr0 and gpr0+1
- regs.SetRegisterToFloat(instr.gpr0, component, "texture_tmp", 1, 4, false,
- written_components % 2);
- } else {
- ASSERT(instr.texs.HasTwoDestinations());
- // Write the rest of the swizzle components to gpr28 and gpr28+1
- regs.SetRegisterToFloat(instr.gpr28, component, "texture_tmp", 1, 4, false,
- written_components % 2);
- }
-
- ++written_components;
- }
- --shader.scope;
- shader.AddLine('}');
- }
-
- static u32 TextureCoordinates(Tegra::Shader::TextureType texture_type) {
- switch (texture_type) {
- case Tegra::Shader::TextureType::Texture1D:
- return 1;
- case Tegra::Shader::TextureType::Texture2D:
- return 2;
- case Tegra::Shader::TextureType::Texture3D:
- case Tegra::Shader::TextureType::TextureCube:
- return 3;
- default:
- UNIMPLEMENTED_MSG("Unhandled texture type: {}", static_cast<u32>(texture_type));
- return 0;
+ void DeclareGlobalMemory() {
+ for (const auto& entry : ir.GetGlobalMemoryBases()) {
+ const std::string binding =
+ fmt::format("GMEM_BINDING_{}_{}", entry.cbuf_index, entry.cbuf_offset);
+ code.AddLine("layout (std430, binding = " + binding + ") buffer " +
+ GetGlobalMemoryBlock(entry) + " {");
+ code.AddLine(" float " + GetGlobalMemory(entry) + "[MAX_GLOBALMEMORY_ELEMENTS];");
+ code.AddLine("};");
+ code.AddNewLine();
}
}
- /*
- * Emits code to push the input target address to the flow address stack, incrementing the stack
- * top.
- */
- void EmitPushToFlowStack(u32 target) {
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine("flow_stack[flow_stack_top] = " + std::to_string(target) + "u;");
- shader.AddLine("flow_stack_top++;");
- --shader.scope;
- shader.AddLine('}');
- }
-
- /*
- * Emits code to pop an address from the flow address stack, setting the jump address to the
- * popped address and decrementing the stack top.
- */
- void EmitPopFromFlowStack() {
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine("flow_stack_top--;");
- shader.AddLine("jmp_to = flow_stack[flow_stack_top];");
- shader.AddLine("break;");
- --shader.scope;
- shader.AddLine('}');
- }
-
- /// Writes the output values from a fragment shader to the corresponding GLSL output variables.
- void EmitFragmentOutputsWrite() {
- ASSERT(stage == Maxwell3D::Regs::ShaderStage::Fragment);
-
- UNIMPLEMENTED_IF_MSG(header.ps.omap.sample_mask != 0, "Samplemask write is unimplemented");
-
- shader.AddLine("if (alpha_test[0] != 0) {");
- ++shader.scope;
- // We start on the register containing the alpha value in the first RT.
- u32 current_reg = 3;
- for (u32 render_target = 0; render_target < Maxwell3D::Regs::NumRenderTargets;
- ++render_target) {
- // TODO(Blinkhawk): verify the behavior of alpha testing on hardware when
- // multiple render targets are used.
- if (header.ps.IsColorComponentOutputEnabled(render_target, 0) ||
- header.ps.IsColorComponentOutputEnabled(render_target, 1) ||
- header.ps.IsColorComponentOutputEnabled(render_target, 2) ||
- header.ps.IsColorComponentOutputEnabled(render_target, 3)) {
- shader.AddLine(fmt::format("if (!AlphaFunc({})) discard;",
- regs.GetRegisterAsFloat(current_reg)));
- current_reg += 4;
- }
- }
- --shader.scope;
- shader.AddLine('}');
-
- // Write the color outputs using the data in the shader registers, disabled
- // rendertargets/components are skipped in the register assignment.
- current_reg = 0;
- for (u32 render_target = 0; render_target < Maxwell3D::Regs::NumRenderTargets;
- ++render_target) {
- // TODO(Subv): Figure out how dual-source blending is configured in the Switch.
- for (u32 component = 0; component < 4; ++component) {
- if (header.ps.IsColorComponentOutputEnabled(render_target, component)) {
- shader.AddLine(fmt::format("FragColor{}[{}] = {};", render_target, component,
- regs.GetRegisterAsFloat(current_reg)));
- ++current_reg;
+ void DeclareSamplers() {
+ const auto& samplers = ir.GetSamplers();
+ for (const auto& sampler : samplers) {
+ std::string sampler_type = [&]() {
+ switch (sampler.GetType()) {
+ case Tegra::Shader::TextureType::Texture1D:
+ return "sampler1D";
+ case Tegra::Shader::TextureType::Texture2D:
+ return "sampler2D";
+ case Tegra::Shader::TextureType::Texture3D:
+ return "sampler3D";
+ case Tegra::Shader::TextureType::TextureCube:
+ return "samplerCube";
+ default:
+ UNREACHABLE();
+ return "sampler2D";
}
- }
- }
-
- if (header.ps.omap.depth) {
- // The depth output is always 2 registers after the last color output, and current_reg
- // already contains one past the last color register.
+ }();
+ if (sampler.IsArray())
+ sampler_type += "Array";
+ if (sampler.IsShadow())
+ sampler_type += "Shadow";
- shader.AddLine(
- "gl_FragDepth = " +
- regs.GetRegisterAsFloat(static_cast<Tegra::Shader::Register>(current_reg) + 1) +
- ';');
+ code.AddLine("layout (binding = SAMPLER_BINDING_" + std::to_string(sampler.GetIndex()) +
+ ") uniform " + sampler_type + ' ' + GetSampler(sampler) + ';');
}
+ if (!samplers.empty())
+ code.AddNewLine();
}
- /// Unpacks a video instruction operand (e.g. VMAD).
- std::string GetVideoOperand(const std::string& op, bool is_chunk, bool is_signed,
- Tegra::Shader::VideoType type, u64 byte_height) {
- const std::string value = [&]() {
- if (!is_chunk) {
- const auto offset = static_cast<u32>(byte_height * 8);
- return "((" + op + " >> " + std::to_string(offset) + ") & 0xff)";
+ void VisitBasicBlock(const BasicBlock& bb) {
+ for (const Node node : bb) {
+ if (const std::string expr = Visit(node); !expr.empty()) {
+ code.AddLine(expr);
}
- const std::string zero = "0";
-
- switch (type) {
- case Tegra::Shader::VideoType::Size16_Low:
- return '(' + op + " & 0xffff)";
- case Tegra::Shader::VideoType::Size16_High:
- return '(' + op + " >> 16)";
- case Tegra::Shader::VideoType::Size32:
- // TODO(Rodrigo): From my hardware tests it becomes a bit "mad" when
- // this type is used (1 * 1 + 0 == 0x5b800000). Until a better
- // explanation is found: abort.
- UNIMPLEMENTED();
- return zero;
- case Tegra::Shader::VideoType::Invalid:
- UNREACHABLE_MSG("Invalid instruction encoding");
- return zero;
- default:
- UNREACHABLE();
- return zero;
- }
- }();
-
- if (is_signed) {
- return "int(" + value + ')';
- }
- return value;
- };
-
- /// Gets the A operand for a video instruction.
- std::string GetVideoOperandA(Instruction instr) {
- return GetVideoOperand(regs.GetRegisterAsInteger(instr.gpr8, 0, false),
- instr.video.is_byte_chunk_a != 0, instr.video.signed_a,
- instr.video.type_a, instr.video.byte_height_a);
- }
-
- /// Gets the B operand for a video instruction.
- std::string GetVideoOperandB(Instruction instr) {
- if (instr.video.use_register_b) {
- return GetVideoOperand(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
- instr.video.is_byte_chunk_b != 0, instr.video.signed_b,
- instr.video.type_b, instr.video.byte_height_b);
- } else {
- return '(' +
- std::to_string(instr.video.signed_b ? static_cast<s16>(instr.alu.GetImm20_16())
- : instr.alu.GetImm20_16()) +
- ')';
}
}
- /**
- * Compiles a single instruction from Tegra to GLSL.
- * @param offset the offset of the Tegra shader instruction.
- * @return the offset of the next instruction to execute. Usually it is the current offset
- * + 1. If the current instruction always terminates the program, returns PROGRAM_END.
- */
- u32 CompileInstr(u32 offset) {
- // Ignore sched instructions when generating code.
- if (IsSchedInstruction(offset)) {
- return offset + 1;
- }
-
- const Instruction instr = {program_code[offset]};
- const auto opcode = OpCode::Decode(instr);
-
- // Decoding failure
- if (!opcode) {
- UNIMPLEMENTED_MSG("Unhandled instruction: {0:x}", instr.value);
- return offset + 1;
- }
-
- shader.AddLine(
- fmt::format("// {}: {} (0x{:016x})", offset, opcode->get().GetName(), instr.value));
-
- using Tegra::Shader::Pred;
- UNIMPLEMENTED_IF_MSG(instr.pred.full_pred == Pred::NeverExecute,
- "NeverExecute predicate not implemented");
-
- // Some instructions (like SSY) don't have a predicate field, they are always
- // unconditionally executed.
- bool can_be_predicated = OpCode::IsPredicatedInstruction(opcode->get().GetId());
-
- if (can_be_predicated && instr.pred.pred_index != static_cast<u64>(Pred::UnusedIndex)) {
- shader.AddLine("if (" +
- GetPredicateCondition(instr.pred.pred_index, instr.negate_pred != 0) +
- ')');
- shader.AddLine('{');
- ++shader.scope;
- }
-
- switch (opcode->get().GetType()) {
- case OpCode::Type::Arithmetic: {
- std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
-
- std::string op_b;
-
- if (instr.is_b_imm) {
- op_b = GetImmediate19(instr);
- } else {
- if (instr.is_b_gpr) {
- op_b = regs.GetRegisterAsFloat(instr.gpr20);
- } else {
- op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- }
+ std::string Visit(Node node) {
+ if (const auto operation = std::get_if<OperationNode>(node)) {
+ const auto operation_index = static_cast<std::size_t>(operation->GetCode());
+ const auto decompiler = operation_decompilers[operation_index];
+ if (decompiler == nullptr) {
+ UNREACHABLE_MSG("Operation decompiler {} not defined", operation_index);
}
+ return (this->*decompiler)(*operation);
- switch (opcode->get().GetId()) {
- case OpCode::Id::MOV_C:
- case OpCode::Id::MOV_R: {
- // MOV does not have neither 'abs' nor 'neg' bits.
- regs.SetRegisterToFloat(instr.gpr0, 0, op_b, 1, 1);
- break;
+ } else if (const auto gpr = std::get_if<GprNode>(node)) {
+ const u32 index = gpr->GetIndex();
+ if (index == Register::ZeroIndex) {
+ return "0";
}
+ return GetRegister(index);
- case OpCode::Id::FMUL_C:
- case OpCode::Id::FMUL_R:
- case OpCode::Id::FMUL_IMM: {
- // FMUL does not have 'abs' bits and only the second operand has a 'neg' bit.
- UNIMPLEMENTED_IF_MSG(instr.fmul.tab5cb8_2 != 0,
- "FMUL tab5cb8_2({}) is not implemented",
- instr.fmul.tab5cb8_2.Value());
- UNIMPLEMENTED_IF_MSG(instr.fmul.tab5c68_1 != 0,
- "FMUL tab5cb8_1({}) is not implemented",
- instr.fmul.tab5c68_1.Value());
- UNIMPLEMENTED_IF_MSG(
- instr.fmul.tab5c68_0 != 1, "FMUL tab5cb8_0({}) is not implemented",
- instr.fmul.tab5c68_0
- .Value()); // SMO typical sends 1 here which seems to be the default
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in FMUL is not implemented");
-
- op_b = GetOperandAbsNeg(op_b, false, instr.fmul.negate_b);
-
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " * " + op_b, 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
+ } else if (const auto immediate = std::get_if<ImmediateNode>(node)) {
+ const u32 value = immediate->GetValue();
+ if (value < 10) {
+ // For eyecandy avoid using hex numbers on single digits
+ return fmt::format("utof({}u)", immediate->GetValue());
}
- case OpCode::Id::FADD_C:
- case OpCode::Id::FADD_R:
- case OpCode::Id::FADD_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in FADD is not implemented");
-
- op_a = GetOperandAbsNeg(op_a, instr.alu.abs_a, instr.alu.negate_a);
- op_b = GetOperandAbsNeg(op_b, instr.alu.abs_b, instr.alu.negate_b);
+ return fmt::format("utof(0x{:x}u)", immediate->GetValue());
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- }
- case OpCode::Id::MUFU: {
- op_a = GetOperandAbsNeg(op_a, instr.alu.abs_a, instr.alu.negate_a);
- switch (instr.sub_op) {
- case SubOp::Cos:
- regs.SetRegisterToFloat(instr.gpr0, 0, "cos(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Sin:
- regs.SetRegisterToFloat(instr.gpr0, 0, "sin(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Ex2:
- regs.SetRegisterToFloat(instr.gpr0, 0, "exp2(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Lg2:
- regs.SetRegisterToFloat(instr.gpr0, 0, "log2(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Rcp:
- regs.SetRegisterToFloat(instr.gpr0, 0, "1.0 / " + op_a, 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Rsq:
- regs.SetRegisterToFloat(instr.gpr0, 0, "inversesqrt(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
- case SubOp::Sqrt:
- regs.SetRegisterToFloat(instr.gpr0, 0, "sqrt(" + op_a + ')', 1, 1,
- instr.alu.saturate_d, 0, true);
- break;
+ } else if (const auto predicate = std::get_if<PredicateNode>(node)) {
+ const auto value = [&]() -> std::string {
+ switch (const auto index = predicate->GetIndex(); index) {
+ case Tegra::Shader::Pred::UnusedIndex:
+ return "true";
+ case Tegra::Shader::Pred::NeverExecute:
+ return "false";
default:
- UNIMPLEMENTED_MSG("Unhandled MUFU sub op={0:x}",
- static_cast<unsigned>(instr.sub_op.Value()));
+ return GetPredicate(index);
}
- break;
- }
- case OpCode::Id::FMNMX_C:
- case OpCode::Id::FMNMX_R:
- case OpCode::Id::FMNMX_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in FMNMX is not implemented");
-
- op_a = GetOperandAbsNeg(op_a, instr.alu.abs_a, instr.alu.negate_a);
- op_b = GetOperandAbsNeg(op_b, instr.alu.abs_b, instr.alu.negate_b);
-
- std::string condition =
- GetPredicateCondition(instr.alu.fmnmx.pred, instr.alu.fmnmx.negate_pred != 0);
- std::string parameters = op_a + ',' + op_b;
- regs.SetRegisterToFloat(instr.gpr0, 0,
- '(' + condition + ") ? min(" + parameters + ") : max(" +
- parameters + ')',
- 1, 1, false, 0, true);
- break;
- }
- case OpCode::Id::RRO_C:
- case OpCode::Id::RRO_R:
- case OpCode::Id::RRO_IMM: {
- // Currently RRO is only implemented as a register move.
- op_b = GetOperandAbsNeg(op_b, instr.alu.abs_b, instr.alu.negate_b);
- regs.SetRegisterToFloat(instr.gpr0, 0, op_b, 1, 1);
- LOG_WARNING(HW_GPU, "RRO instruction is incomplete");
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled arithmetic instruction: {}", opcode->get().GetName());
- }
- }
- break;
- }
- case OpCode::Type::ArithmeticImmediate: {
- switch (opcode->get().GetId()) {
- case OpCode::Id::MOV32_IMM: {
- regs.SetRegisterToFloat(instr.gpr0, 0, GetImmediate32(instr), 1, 1);
- break;
- }
- case OpCode::Id::FMUL32_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
- "Condition codes generation in FMUL32 is not implemented");
-
- regs.SetRegisterToFloat(instr.gpr0, 0,
- regs.GetRegisterAsFloat(instr.gpr8) + " * " +
- GetImmediate32(instr),
- 1, 1, instr.fmul32.saturate, 0, true);
- break;
+ }();
+ if (predicate->IsNegated()) {
+ return "!(" + value + ')';
}
- case OpCode::Id::FADD32I: {
- UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
- "Condition codes generation in FADD32I is not implemented");
-
- std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
- std::string op_b = GetImmediate32(instr);
-
- if (instr.fadd32i.abs_a) {
- op_a = "abs(" + op_a + ')';
- }
-
- if (instr.fadd32i.negate_a) {
- op_a = "-(" + op_a + ')';
- }
+ return value;
- if (instr.fadd32i.abs_b) {
- op_b = "abs(" + op_b + ')';
+ } else if (const auto abuf = std::get_if<AbufNode>(node)) {
+ const auto attribute = abuf->GetIndex();
+ const auto element = abuf->GetElement();
+
+ const auto GeometryPass = [&](const std::string& name) {
+ if (stage == ShaderStage::Geometry && abuf->GetBuffer()) {
+ // TODO(Rodrigo): Guard geometry inputs against out of bound reads. Some games
+ // set an 0x80000000 index for those and the shader fails to build. Find out why
+ // this happens and what's its intent.
+ return "gs_" + name + "[ftou(" + Visit(abuf->GetBuffer()) +
+ ") % MAX_VERTEX_INPUT]";
+ }
+ return name;
+ };
+
+ switch (attribute) {
+ case Attribute::Index::Position:
+ if (stage != ShaderStage::Fragment) {
+ return GeometryPass("position") + GetSwizzle(element);
+ } else {
+ return element == 3 ? "1.0f" : "gl_FragCoord" + GetSwizzle(element);
+ }
+ case Attribute::Index::PointCoord:
+ switch (element) {
+ case 0:
+ return "gl_PointCoord.x";
+ case 1:
+ return "gl_PointCoord.y";
+ case 2:
+ case 3:
+ return "0";
}
-
- if (instr.fadd32i.negate_b) {
- op_b = "-(" + op_b + ')';
+ UNREACHABLE();
+ return "0";
+ case Attribute::Index::TessCoordInstanceIDVertexID:
+ // TODO(Subv): Find out what the values are for the first two elements when inside a
+ // vertex shader, and what's the value of the fourth element when inside a Tess Eval
+ // shader.
+ ASSERT(stage == ShaderStage::Vertex);
+ switch (element) {
+ case 2:
+ // Config pack's first value is instance_id.
+ return "uintBitsToFloat(config_pack[0])";
+ case 3:
+ return "uintBitsToFloat(gl_VertexID)";
+ }
+ UNIMPLEMENTED_MSG("Unmanaged TessCoordInstanceIDVertexID element={}", element);
+ return "0";
+ case Attribute::Index::FrontFacing:
+ // TODO(Subv): Find out what the values are for the other elements.
+ ASSERT(stage == ShaderStage::Fragment);
+ switch (element) {
+ case 3:
+ return "itof(gl_FrontFacing ? -1 : 0)";
+ }
+ UNIMPLEMENTED_MSG("Unmanaged FrontFacing element={}", element);
+ return "0";
+ default:
+ if (attribute >= Attribute::Index::Attribute_0 &&
+ attribute <= Attribute::Index::Attribute_31) {
+ return GeometryPass(GetInputAttribute(attribute)) + GetSwizzle(element);
}
-
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1, false, 0, true);
break;
}
- }
- break;
- }
- case OpCode::Type::Bfe: {
- UNIMPLEMENTED_IF(instr.bfe.negate_b);
+ UNIMPLEMENTED_MSG("Unhandled input attribute: {}", static_cast<u32>(attribute));
- std::string op_a = instr.bfe.negate_a ? "-" : "";
- op_a += regs.GetRegisterAsInteger(instr.gpr8);
+ } else if (const auto cbuf = std::get_if<CbufNode>(node)) {
+ const Node offset = cbuf->GetOffset();
+ if (const auto immediate = std::get_if<ImmediateNode>(offset)) {
+ // Direct access
+ const u32 offset_imm = immediate->GetValue();
+ return fmt::format("{}[{}][{}]", GetConstBuffer(cbuf->GetIndex()), offset_imm / 4,
+ offset_imm % 4);
+
+ } else if (std::holds_alternative<OperationNode>(*offset)) {
+ // Indirect access
+ const std::string final_offset = code.GenerateTemporal();
+ code.AddLine("uint " + final_offset + " = (ftou(" + Visit(offset) + ") / 4) & " +
+ std::to_string(MAX_CONSTBUFFER_ELEMENTS - 1) + ';');
+ return fmt::format("{}[{} / 4][{} % 4]", GetConstBuffer(cbuf->GetIndex()),
+ final_offset, final_offset);
- switch (opcode->get().GetId()) {
- case OpCode::Id::BFE_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in BFE is not implemented");
+ } else {
+ UNREACHABLE_MSG("Unmanaged offset node type");
+ }
- std::string inner_shift =
- '(' + op_a + " << " + std::to_string(instr.bfe.GetLeftShiftValue()) + ')';
- std::string outer_shift =
- '(' + inner_shift + " >> " +
- std::to_string(instr.bfe.GetLeftShiftValue() + instr.bfe.shift_position) + ')';
+ } else if (const auto gmem = std::get_if<GmemNode>(node)) {
+ const std::string real = Visit(gmem->GetRealAddress());
+ const std::string base = Visit(gmem->GetBaseAddress());
+ const std::string final_offset = "(ftou(" + real + ") - ftou(" + base + ")) / 4";
+ return fmt::format("{}[{}]", GetGlobalMemory(gmem->GetDescriptor()), final_offset);
- regs.SetRegisterToInteger(instr.gpr0, true, 0, outer_shift, 1, 1);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled BFE instruction: {}", opcode->get().GetName());
- }
- }
+ } else if (const auto lmem = std::get_if<LmemNode>(node)) {
+ return fmt::format("{}[ftou({}) / 4]", GetLocalMemory(), Visit(lmem->GetAddress()));
- break;
- }
- case OpCode::Type::Bfi: {
- UNIMPLEMENTED_IF(instr.generates_cc);
-
- const auto [base, packed_shift] = [&]() -> std::tuple<std::string, std::string> {
- switch (opcode->get().GetId()) {
- case OpCode::Id::BFI_IMM_R:
- return {regs.GetRegisterAsInteger(instr.gpr39, 0, false),
- std::to_string(instr.alu.GetSignedImm20_20())};
- default:
- UNREACHABLE();
- }
- }();
- const std::string offset = '(' + packed_shift + " & 0xff)";
- const std::string bits = "((" + packed_shift + " >> 8) & 0xff)";
- const std::string insert = regs.GetRegisterAsInteger(instr.gpr8, 0, false);
- regs.SetRegisterToInteger(
- instr.gpr0, false, 0,
- "bitfieldInsert(" + base + ", " + insert + ", " + offset + ", " + bits + ')', 1, 1);
- break;
- }
- case OpCode::Type::Shift: {
- std::string op_a = regs.GetRegisterAsInteger(instr.gpr8, 0, true);
- std::string op_b;
+ } else if (const auto internal_flag = std::get_if<InternalFlagNode>(node)) {
+ return GetInternalFlag(internal_flag->GetFlag());
- if (instr.is_b_imm) {
- op_b += '(' + std::to_string(instr.alu.GetSignedImm20_20()) + ')';
- } else {
- if (instr.is_b_gpr) {
- op_b += regs.GetRegisterAsInteger(instr.gpr20);
- } else {
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Integer);
- }
- }
+ } else if (const auto conditional = std::get_if<ConditionalNode>(node)) {
+ // It's invalid to call conditional on nested nodes, use an operation instead
+ code.AddLine("if (" + Visit(conditional->GetCondition()) + ") {");
+ ++code.scope;
- switch (opcode->get().GetId()) {
- case OpCode::Id::SHR_C:
- case OpCode::Id::SHR_R:
- case OpCode::Id::SHR_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in SHR is not implemented");
+ VisitBasicBlock(conditional->GetCode());
- if (!instr.shift.is_signed) {
- // Logical shift right
- op_a = "uint(" + op_a + ')';
- }
+ --code.scope;
+ code.AddLine('}');
+ return {};
- // Cast to int is superfluous for arithmetic shift, it's only for a logical shift
- regs.SetRegisterToInteger(instr.gpr0, true, 0, "int(" + op_a + " >> " + op_b + ')',
- 1, 1);
- break;
- }
- case OpCode::Id::SHL_C:
- case OpCode::Id::SHL_R:
- case OpCode::Id::SHL_IMM:
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in SHL is not implemented");
- regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " << " + op_b, 1, 1);
- break;
- default: {
- UNIMPLEMENTED_MSG("Unhandled shift instruction: {}", opcode->get().GetName());
- }
- }
- break;
+ } else if (const auto comment = std::get_if<CommentNode>(node)) {
+ return "// " + comment->GetText();
}
- case OpCode::Type::ArithmeticIntegerImmediate: {
- std::string op_a = regs.GetRegisterAsInteger(instr.gpr8);
- std::string op_b = std::to_string(instr.alu.imm20_32.Value());
+ UNREACHABLE();
+ return {};
+ }
- switch (opcode->get().GetId()) {
- case OpCode::Id::IADD32I:
- UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
- "Condition codes generation in IADD32I is not implemented");
+ std::string ApplyPrecise(Operation operation, const std::string& value) {
+ if (!IsPrecise(operation)) {
+ return value;
+ }
+ // There's a bug in NVidia's proprietary drivers that makes precise fail on fragment shaders
+ const std::string precise = stage != ShaderStage::Fragment ? "precise " : "";
- if (instr.iadd32i.negate_a)
- op_a = "-(" + op_a + ')';
+ const std::string temporal = code.GenerateTemporal();
+ code.AddLine(precise + "float " + temporal + " = " + value + ';');
+ return temporal;
+ }
- regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
- instr.iadd32i.saturate != 0);
- break;
- case OpCode::Id::LOP32I: {
- UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
- "Condition codes generation in LOP32I is not implemented");
+ std::string VisitOperand(Operation operation, std::size_t operand_index) {
+ const auto& operand = operation[operand_index];
+ const bool parent_precise = IsPrecise(operation);
+ const bool child_precise = IsPrecise(operand);
+ const bool child_trivial = !std::holds_alternative<OperationNode>(*operand);
+ if (!parent_precise || child_precise || child_trivial) {
+ return Visit(operand);
+ }
- if (instr.alu.lop32i.invert_a)
- op_a = "~(" + op_a + ')';
+ const std::string temporal = code.GenerateTemporal();
+ code.AddLine("float " + temporal + " = " + Visit(operand) + ';');
+ return temporal;
+ }
- if (instr.alu.lop32i.invert_b)
- op_b = "~(" + op_b + ')';
+ std::string VisitOperand(Operation operation, std::size_t operand_index, Type type) {
+ std::string value = VisitOperand(operation, operand_index);
- WriteLogicOperation(instr.gpr0, instr.alu.lop32i.operation, op_a, op_b,
- Tegra::Shader::PredicateResultMode::None,
- Tegra::Shader::Pred::UnusedIndex);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled ArithmeticIntegerImmediate instruction: {}",
- opcode->get().GetName());
+ switch (type) {
+ case Type::Bool:
+ case Type::Bool2:
+ case Type::Float:
+ return value;
+ case Type::Int:
+ return "ftoi(" + value + ')';
+ case Type::Uint:
+ return "ftou(" + value + ')';
+ case Type::HalfFloat:
+ const auto half_meta = std::get_if<MetaHalfArithmetic>(&operation.GetMeta());
+ if (!half_meta) {
+ value = "toHalf2(" + value + ')';
}
+
+ switch (half_meta->types.at(operand_index)) {
+ case Tegra::Shader::HalfType::H0_H1:
+ return "toHalf2(" + value + ')';
+ case Tegra::Shader::HalfType::F32:
+ return "vec2(" + value + ')';
+ case Tegra::Shader::HalfType::H0_H0:
+ return "vec2(toHalf2(" + value + ")[0])";
+ case Tegra::Shader::HalfType::H1_H1:
+ return "vec2(toHalf2(" + value + ")[1])";
}
- break;
}
- case OpCode::Type::ArithmeticInteger: {
- std::string op_a = regs.GetRegisterAsInteger(instr.gpr8);
- std::string op_b;
- if (instr.is_b_imm) {
- op_b += '(' + std::to_string(instr.alu.GetSignedImm20_20()) + ')';
- } else {
- if (instr.is_b_gpr) {
- op_b += regs.GetRegisterAsInteger(instr.gpr20);
- } else {
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Integer);
- }
- }
+ UNREACHABLE();
+ return value;
+ }
- switch (opcode->get().GetId()) {
- case OpCode::Id::IADD_C:
- case OpCode::Id::IADD_R:
- case OpCode::Id::IADD_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in IADD is not implemented");
+ std::string BitwiseCastResult(std::string value, Type type, bool needs_parenthesis = false) {
+ switch (type) {
+ case Type::Bool:
+ case Type::Float:
+ if (needs_parenthesis) {
+ return '(' + value + ')';
+ }
+ return value;
+ case Type::Int:
+ return "itof(" + value + ')';
+ case Type::Uint:
+ return "utof(" + value + ')';
+ case Type::HalfFloat:
+ return "fromHalf2(" + value + ')';
+ }
+ UNREACHABLE();
+ return value;
+ }
- if (instr.alu_integer.negate_a)
- op_a = "-(" + op_a + ')';
+ std::string GenerateUnary(Operation operation, const std::string& func, Type result_type,
+ Type type_a, bool needs_parenthesis = true) {
+ return ApplyPrecise(operation,
+ BitwiseCastResult(func + '(' + VisitOperand(operation, 0, type_a) + ')',
+ result_type, needs_parenthesis));
+ }
- if (instr.alu_integer.negate_b)
- op_b = "-(" + op_b + ')';
+ std::string GenerateBinaryInfix(Operation operation, const std::string& func, Type result_type,
+ Type type_a, Type type_b) {
+ const std::string op_a = VisitOperand(operation, 0, type_a);
+ const std::string op_b = VisitOperand(operation, 1, type_b);
- regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
- instr.alu.saturate_d);
- break;
- }
- case OpCode::Id::IADD3_C:
- case OpCode::Id::IADD3_R:
- case OpCode::Id::IADD3_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in IADD3 is not implemented");
-
- std::string op_c = regs.GetRegisterAsInteger(instr.gpr39);
-
- auto apply_height = [](auto height, auto& oprand) {
- switch (height) {
- case Tegra::Shader::IAdd3Height::None:
- break;
- case Tegra::Shader::IAdd3Height::LowerHalfWord:
- oprand = "((" + oprand + ") & 0xFFFF)";
- break;
- case Tegra::Shader::IAdd3Height::UpperHalfWord:
- oprand = "((" + oprand + ") >> 16)";
- break;
- default:
- UNIMPLEMENTED_MSG("Unhandled IADD3 height: {}",
- static_cast<u32>(height.Value()));
- }
- };
-
- if (opcode->get().GetId() == OpCode::Id::IADD3_R) {
- apply_height(instr.iadd3.height_a, op_a);
- apply_height(instr.iadd3.height_b, op_b);
- apply_height(instr.iadd3.height_c, op_c);
- }
+ return ApplyPrecise(
+ operation, BitwiseCastResult('(' + op_a + ' ' + func + ' ' + op_b + ')', result_type));
+ }
- if (instr.iadd3.neg_a)
- op_a = "-(" + op_a + ')';
-
- if (instr.iadd3.neg_b)
- op_b = "-(" + op_b + ')';
-
- if (instr.iadd3.neg_c)
- op_c = "-(" + op_c + ')';
-
- std::string result;
- if (opcode->get().GetId() == OpCode::Id::IADD3_R) {
- switch (instr.iadd3.mode) {
- case Tegra::Shader::IAdd3Mode::RightShift:
- // TODO(tech4me): According to
- // https://envytools.readthedocs.io/en/latest/hw/graph/maxwell/cuda/int.html?highlight=iadd3
- // The addition between op_a and op_b should be done in uint33, more
- // investigation required
- result = "(((" + op_a + " + " + op_b + ") >> 16) + " + op_c + ')';
- break;
- case Tegra::Shader::IAdd3Mode::LeftShift:
- result = "(((" + op_a + " + " + op_b + ") << 16) + " + op_c + ')';
- break;
- default:
- result = '(' + op_a + " + " + op_b + " + " + op_c + ')';
- break;
- }
- } else {
- result = '(' + op_a + " + " + op_b + " + " + op_c + ')';
- }
+ std::string GenerateBinaryCall(Operation operation, const std::string& func, Type result_type,
+ Type type_a, Type type_b) {
+ const std::string op_a = VisitOperand(operation, 0, type_a);
+ const std::string op_b = VisitOperand(operation, 1, type_b);
- regs.SetRegisterToInteger(instr.gpr0, true, 0, result, 1, 1);
- break;
- }
- case OpCode::Id::ISCADD_C:
- case OpCode::Id::ISCADD_R:
- case OpCode::Id::ISCADD_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in ISCADD is not implemented");
+ return ApplyPrecise(operation,
+ BitwiseCastResult(func + '(' + op_a + ", " + op_b + ')', result_type));
+ }
- if (instr.alu_integer.negate_a)
- op_a = "-(" + op_a + ')';
+ std::string GenerateTernary(Operation operation, const std::string& func, Type result_type,
+ Type type_a, Type type_b, Type type_c) {
+ const std::string op_a = VisitOperand(operation, 0, type_a);
+ const std::string op_b = VisitOperand(operation, 1, type_b);
+ const std::string op_c = VisitOperand(operation, 2, type_c);
- if (instr.alu_integer.negate_b)
- op_b = "-(" + op_b + ')';
+ return ApplyPrecise(
+ operation,
+ BitwiseCastResult(func + '(' + op_a + ", " + op_b + ", " + op_c + ')', result_type));
+ }
- const std::string shift = std::to_string(instr.alu_integer.shift_amount.Value());
+ std::string GenerateQuaternary(Operation operation, const std::string& func, Type result_type,
+ Type type_a, Type type_b, Type type_c, Type type_d) {
+ const std::string op_a = VisitOperand(operation, 0, type_a);
+ const std::string op_b = VisitOperand(operation, 1, type_b);
+ const std::string op_c = VisitOperand(operation, 2, type_c);
+ const std::string op_d = VisitOperand(operation, 3, type_d);
- regs.SetRegisterToInteger(instr.gpr0, true, 0,
- "((" + op_a + " << " + shift + ") + " + op_b + ')', 1, 1);
- break;
- }
- case OpCode::Id::POPC_C:
- case OpCode::Id::POPC_R:
- case OpCode::Id::POPC_IMM: {
- if (instr.popc.invert) {
- op_b = "~(" + op_b + ')';
- }
- regs.SetRegisterToInteger(instr.gpr0, true, 0, "bitCount(" + op_b + ')', 1, 1);
- break;
- }
- case OpCode::Id::SEL_C:
- case OpCode::Id::SEL_R:
- case OpCode::Id::SEL_IMM: {
- const std::string condition =
- GetPredicateCondition(instr.sel.pred, instr.sel.neg_pred != 0);
- regs.SetRegisterToInteger(instr.gpr0, true, 0,
- '(' + condition + ") ? " + op_a + " : " + op_b, 1, 1);
- break;
- }
- case OpCode::Id::LOP_C:
- case OpCode::Id::LOP_R:
- case OpCode::Id::LOP_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in LOP is not implemented");
+ return ApplyPrecise(operation, BitwiseCastResult(func + '(' + op_a + ", " + op_b + ", " +
+ op_c + ", " + op_d + ')',
+ result_type));
+ }
- if (instr.alu.lop.invert_a)
- op_a = "~(" + op_a + ')';
+ std::string GenerateTexture(Operation operation, const std::string& func,
+ bool is_extra_int = false) {
+ constexpr std::array<const char*, 4> coord_constructors = {"float", "vec2", "vec3", "vec4"};
- if (instr.alu.lop.invert_b)
- op_b = "~(" + op_b + ')';
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ const auto count = static_cast<u32>(operation.GetOperandsCount());
+ ASSERT(meta);
- WriteLogicOperation(instr.gpr0, instr.alu.lop.operation, op_a, op_b,
- instr.alu.lop.pred_result_mode, instr.alu.lop.pred48);
- break;
- }
- case OpCode::Id::LOP3_C:
- case OpCode::Id::LOP3_R:
- case OpCode::Id::LOP3_IMM: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in LOP3 is not implemented");
+ std::string expr = func;
+ expr += '(';
+ expr += GetSampler(meta->sampler);
+ expr += ", ";
- const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39);
- std::string lut;
+ expr += coord_constructors[meta->coords_count - 1];
+ expr += '(';
+ for (u32 i = 0; i < count; ++i) {
+ const bool is_extra = i >= meta->coords_count;
+ const bool is_array = i == meta->array_index;
- if (opcode->get().GetId() == OpCode::Id::LOP3_R) {
- lut = '(' + std::to_string(instr.alu.lop3.GetImmLut28()) + ')';
+ std::string operand = [&]() {
+ if (is_extra && is_extra_int) {
+ if (const auto immediate = std::get_if<ImmediateNode>(operation[i])) {
+ return std::to_string(static_cast<s32>(immediate->GetValue()));
+ } else {
+ return "ftoi(" + Visit(operation[i]) + ')';
+ }
} else {
- lut = '(' + std::to_string(instr.alu.lop3.GetImmLut48()) + ')';
+ return Visit(operation[i]);
}
-
- WriteLop3Instruction(instr.gpr0, op_a, op_b, op_c, lut);
- break;
- }
- case OpCode::Id::IMNMX_C:
- case OpCode::Id::IMNMX_R:
- case OpCode::Id::IMNMX_IMM: {
- UNIMPLEMENTED_IF(instr.imnmx.exchange != Tegra::Shader::IMinMaxExchange::None);
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in IMNMX is not implemented");
-
- const std::string condition =
- GetPredicateCondition(instr.imnmx.pred, instr.imnmx.negate_pred != 0);
- const std::string parameters = op_a + ',' + op_b;
- regs.SetRegisterToInteger(instr.gpr0, instr.imnmx.is_signed, 0,
- '(' + condition + ") ? min(" + parameters + ") : max(" +
- parameters + ')',
- 1, 1);
- break;
+ }();
+ if (is_array) {
+ ASSERT(!is_extra);
+ operand = "float(ftoi(" + operand + "))";
}
- case OpCode::Id::LEA_R2:
- case OpCode::Id::LEA_R1:
- case OpCode::Id::LEA_IMM:
- case OpCode::Id::LEA_RZ:
- case OpCode::Id::LEA_HI: {
- std::string op_c;
-
- switch (opcode->get().GetId()) {
- case OpCode::Id::LEA_R2: {
- op_a = regs.GetRegisterAsInteger(instr.gpr20);
- op_b = regs.GetRegisterAsInteger(instr.gpr39);
- op_c = std::to_string(instr.lea.r2.entry_a);
- break;
- }
-
- case OpCode::Id::LEA_R1: {
- const bool neg = instr.lea.r1.neg != 0;
- op_a = regs.GetRegisterAsInteger(instr.gpr8);
- if (neg)
- op_a = "-(" + op_a + ')';
- op_b = regs.GetRegisterAsInteger(instr.gpr20);
- op_c = std::to_string(instr.lea.r1.entry_a);
- break;
- }
-
- case OpCode::Id::LEA_IMM: {
- const bool neg = instr.lea.imm.neg != 0;
- op_b = regs.GetRegisterAsInteger(instr.gpr8);
- if (neg)
- op_b = "-(" + op_b + ')';
- op_a = std::to_string(instr.lea.imm.entry_a);
- op_c = std::to_string(instr.lea.imm.entry_b);
- break;
- }
-
- case OpCode::Id::LEA_RZ: {
- const bool neg = instr.lea.rz.neg != 0;
- op_b = regs.GetRegisterAsInteger(instr.gpr8);
- if (neg)
- op_b = "-(" + op_b + ')';
- op_a = regs.GetUniform(instr.lea.rz.cb_index, instr.lea.rz.cb_offset,
- GLSLRegister::Type::Integer);
- op_c = std::to_string(instr.lea.rz.entry_a);
-
- break;
- }
- case OpCode::Id::LEA_HI:
- default: {
- op_b = regs.GetRegisterAsInteger(instr.gpr8);
- op_a = std::to_string(instr.lea.imm.entry_a);
- op_c = std::to_string(instr.lea.imm.entry_b);
- UNIMPLEMENTED_MSG("Unhandled LEA subinstruction: {}", opcode->get().GetName());
- }
- }
- UNIMPLEMENTED_IF_MSG(instr.lea.pred48 != static_cast<u64>(Pred::UnusedIndex),
- "Unhandled LEA Predicate");
- const std::string value = '(' + op_a + " + (" + op_b + "*(1 << " + op_c + ")))";
- regs.SetRegisterToInteger(instr.gpr0, true, 0, value, 1, 1);
-
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled ArithmeticInteger instruction: {}",
- opcode->get().GetName());
- }
- }
+ expr += operand;
- break;
- }
- case OpCode::Type::ArithmeticHalf: {
- if (opcode->get().GetId() == OpCode::Id::HADD2_C ||
- opcode->get().GetId() == OpCode::Id::HADD2_R) {
- UNIMPLEMENTED_IF(instr.alu_half.ftz != 0);
+ if (i + 1 == meta->coords_count) {
+ expr += ')';
}
- const bool negate_a =
- opcode->get().GetId() != OpCode::Id::HMUL2_R && instr.alu_half.negate_a != 0;
- const bool negate_b =
- opcode->get().GetId() != OpCode::Id::HMUL2_C && instr.alu_half.negate_b != 0;
-
- const std::string op_a =
- GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.alu_half.type_a,
- instr.alu_half.abs_a != 0, negate_a);
-
- std::string op_b;
- switch (opcode->get().GetId()) {
- case OpCode::Id::HADD2_C:
- case OpCode::Id::HMUL2_C:
- op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::UnsignedInteger);
- break;
- case OpCode::Id::HADD2_R:
- case OpCode::Id::HMUL2_R:
- op_b = regs.GetRegisterAsInteger(instr.gpr20, 0, false);
- break;
- default:
- UNREACHABLE();
- op_b = "0";
- break;
+ if (i + 1 < count) {
+ expr += ", ";
}
- op_b = GetHalfFloat(op_b, instr.alu_half.type_b, instr.alu_half.abs_b != 0, negate_b);
-
- const std::string result = [&]() {
- switch (opcode->get().GetId()) {
- case OpCode::Id::HADD2_C:
- case OpCode::Id::HADD2_R:
- return '(' + op_a + " + " + op_b + ')';
- case OpCode::Id::HMUL2_C:
- case OpCode::Id::HMUL2_R:
- return '(' + op_a + " * " + op_b + ')';
- default:
- UNIMPLEMENTED_MSG("Unhandled half float instruction: {}",
- opcode->get().GetName());
- return std::string("0");
- }
- }();
-
- regs.SetRegisterToHalfFloat(instr.gpr0, 0, result, instr.alu_half.merge, 1, 1,
- instr.alu_half.saturate != 0);
- break;
}
- case OpCode::Type::ArithmeticHalfImmediate: {
- if (opcode->get().GetId() == OpCode::Id::HADD2_IMM) {
- UNIMPLEMENTED_IF(instr.alu_half_imm.ftz != 0);
- } else {
- UNIMPLEMENTED_IF(instr.alu_half_imm.precision !=
- Tegra::Shader::HalfPrecision::None);
- }
+ expr += ')';
+ return expr;
+ }
- const std::string op_a = GetHalfFloat(
- regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.alu_half_imm.type_a,
- instr.alu_half_imm.abs_a != 0, instr.alu_half_imm.negate_a != 0);
+ std::string Assign(Operation operation) {
+ const Node dest = operation[0];
+ const Node src = operation[1];
- const std::string op_b = UnpackHalfImmediate(instr, true);
+ std::string target;
+ if (const auto gpr = std::get_if<GprNode>(dest)) {
+ if (gpr->GetIndex() == Register::ZeroIndex) {
+ // Writing to Register::ZeroIndex is a no op
+ return {};
+ }
+ target = GetRegister(gpr->GetIndex());
- const std::string result = [&]() {
- switch (opcode->get().GetId()) {
- case OpCode::Id::HADD2_IMM:
- return op_a + " + " + op_b;
- case OpCode::Id::HMUL2_IMM:
- return op_a + " * " + op_b;
+ } else if (const auto abuf = std::get_if<AbufNode>(dest)) {
+ target = [&]() -> std::string {
+ switch (const auto attribute = abuf->GetIndex(); abuf->GetIndex()) {
+ case Attribute::Index::Position:
+ return "position" + GetSwizzle(abuf->GetElement());
+ case Attribute::Index::PointSize:
+ return "gl_PointSize";
+ case Attribute::Index::ClipDistances0123:
+ return "gl_ClipDistance[" + std::to_string(abuf->GetElement()) + ']';
+ case Attribute::Index::ClipDistances4567:
+ return "gl_ClipDistance[" + std::to_string(abuf->GetElement() + 4) + ']';
default:
- UNREACHABLE();
- return std::string("0");
+ if (attribute >= Attribute::Index::Attribute_0 &&
+ attribute <= Attribute::Index::Attribute_31) {
+ return GetOutputAttribute(attribute) + GetSwizzle(abuf->GetElement());
+ }
+ UNIMPLEMENTED_MSG("Unhandled output attribute: {}",
+ static_cast<u32>(attribute));
+ return "0";
}
}();
- regs.SetRegisterToHalfFloat(instr.gpr0, 0, result, instr.alu_half_imm.merge, 1, 1,
- instr.alu_half_imm.saturate != 0);
- break;
- }
- case OpCode::Type::Ffma: {
- const std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
- std::string op_b = instr.ffma.negate_b ? "-" : "";
- std::string op_c = instr.ffma.negate_c ? "-" : "";
-
- UNIMPLEMENTED_IF_MSG(instr.ffma.cc != 0, "FFMA cc not implemented");
- UNIMPLEMENTED_IF_MSG(
- instr.ffma.tab5980_0 != 1, "FFMA tab5980_0({}) not implemented",
- instr.ffma.tab5980_0.Value()); // Seems to be 1 by default based on SMO
- UNIMPLEMENTED_IF_MSG(instr.ffma.tab5980_1 != 0, "FFMA tab5980_1({}) not implemented",
- instr.ffma.tab5980_1.Value());
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in FFMA is not implemented");
-
- switch (opcode->get().GetId()) {
- case OpCode::Id::FFMA_CR: {
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- op_c += regs.GetRegisterAsFloat(instr.gpr39);
- break;
- }
- case OpCode::Id::FFMA_RR: {
- op_b += regs.GetRegisterAsFloat(instr.gpr20);
- op_c += regs.GetRegisterAsFloat(instr.gpr39);
- break;
- }
- case OpCode::Id::FFMA_RC: {
- op_b += regs.GetRegisterAsFloat(instr.gpr39);
- op_c += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- break;
- }
- case OpCode::Id::FFMA_IMM: {
- op_b += GetImmediate19(instr);
- op_c += regs.GetRegisterAsFloat(instr.gpr39);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled FFMA instruction: {}", opcode->get().GetName());
- }
- }
+ } else if (const auto lmem = std::get_if<LmemNode>(dest)) {
+ target = GetLocalMemory() + "[ftou(" + Visit(lmem->GetAddress()) + ") / 4]";
- regs.SetRegisterToFloat(instr.gpr0, 0, "fma(" + op_a + ", " + op_b + ", " + op_c + ')',
- 1, 1, instr.alu.saturate_d, 0, true);
- break;
+ } else {
+ UNREACHABLE_MSG("Assign called without a proper target");
}
- case OpCode::Type::Hfma2: {
- if (opcode->get().GetId() == OpCode::Id::HFMA2_RR) {
- UNIMPLEMENTED_IF(instr.hfma2.rr.precision != Tegra::Shader::HalfPrecision::None);
- } else {
- UNIMPLEMENTED_IF(instr.hfma2.precision != Tegra::Shader::HalfPrecision::None);
- }
- const bool saturate = opcode->get().GetId() == OpCode::Id::HFMA2_RR
- ? instr.hfma2.rr.saturate != 0
- : instr.hfma2.saturate != 0;
-
- const std::string op_a =
- GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hfma2.type_a);
- std::string op_b, op_c;
-
- switch (opcode->get().GetId()) {
- case OpCode::Id::HFMA2_CR:
- op_b = GetHalfFloat(regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::UnsignedInteger),
- instr.hfma2.type_b, false, instr.hfma2.negate_b);
- op_c = GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr39, 0, false),
- instr.hfma2.type_reg39, false, instr.hfma2.negate_c);
- break;
- case OpCode::Id::HFMA2_RC:
- op_b = GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr39, 0, false),
- instr.hfma2.type_reg39, false, instr.hfma2.negate_b);
- op_c = GetHalfFloat(regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::UnsignedInteger),
- instr.hfma2.type_b, false, instr.hfma2.negate_c);
- break;
- case OpCode::Id::HFMA2_RR:
- op_b = GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
- instr.hfma2.type_b, false, instr.hfma2.negate_b);
- op_c = GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr39, 0, false),
- instr.hfma2.rr.type_c, false, instr.hfma2.rr.negate_c);
- break;
- case OpCode::Id::HFMA2_IMM_R:
- op_b = UnpackHalfImmediate(instr, true);
- op_c = GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr39, 0, false),
- instr.hfma2.type_reg39, false, instr.hfma2.negate_c);
- break;
- default:
- UNREACHABLE();
- op_c = op_b = "vec2(0)";
- break;
- }
- const std::string result = '(' + op_a + " * " + op_b + " + " + op_c + ')';
+ code.AddLine(target + " = " + Visit(src) + ';');
+ return {};
+ }
- regs.SetRegisterToHalfFloat(instr.gpr0, 0, result, instr.hfma2.merge, 1, 1, saturate);
- break;
+ std::string Composite(Operation operation) {
+ std::string value = "vec4(";
+ for (std::size_t i = 0; i < 4; ++i) {
+ value += Visit(operation[i]);
+ if (i < 3)
+ value += ", ";
}
- case OpCode::Type::Conversion: {
- switch (opcode->get().GetId()) {
- case OpCode::Id::I2I_R: {
- UNIMPLEMENTED_IF(instr.conversion.selector);
-
- std::string op_a = regs.GetRegisterAsInteger(
- instr.gpr20, 0, instr.conversion.is_input_signed, instr.conversion.src_size);
+ value += ')';
+ return value;
+ }
- if (instr.conversion.abs_a) {
- op_a = "abs(" + op_a + ')';
- }
+ template <Type type>
+ std::string Add(Operation operation) {
+ return GenerateBinaryInfix(operation, "+", type, type, type);
+ }
- if (instr.conversion.negate_a) {
- op_a = "-(" + op_a + ')';
- }
+ template <Type type>
+ std::string Mul(Operation operation) {
+ return GenerateBinaryInfix(operation, "*", type, type, type);
+ }
- regs.SetRegisterToInteger(instr.gpr0, instr.conversion.is_output_signed, 0, op_a, 1,
- 1, instr.alu.saturate_d, 0, instr.conversion.dest_size,
- instr.generates_cc.Value() != 0);
- break;
- }
- case OpCode::Id::I2F_R:
- case OpCode::Id::I2F_C: {
- UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
- UNIMPLEMENTED_IF(instr.conversion.selector);
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in I2F is not implemented");
-
- std::string op_a{};
-
- if (instr.is_b_gpr) {
- op_a =
- regs.GetRegisterAsInteger(instr.gpr20, 0, instr.conversion.is_input_signed,
- instr.conversion.src_size);
- } else {
- op_a = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- instr.conversion.is_input_signed
- ? GLSLRegister::Type::Integer
- : GLSLRegister::Type::UnsignedInteger,
- instr.conversion.src_size);
- }
+ template <Type type>
+ std::string Div(Operation operation) {
+ return GenerateBinaryInfix(operation, "/", type, type, type);
+ }
- if (instr.conversion.abs_a) {
- op_a = "abs(" + op_a + ')';
- }
+ template <Type type>
+ std::string Fma(Operation operation) {
+ return GenerateTernary(operation, "fma", type, type, type, type);
+ }
- if (instr.conversion.negate_a) {
- op_a = "-(" + op_a + ')';
- }
+ template <Type type>
+ std::string Negate(Operation operation) {
+ return GenerateUnary(operation, "-", type, type, true);
+ }
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
- break;
- }
- case OpCode::Id::F2F_R: {
- UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
- UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in F2F is not implemented");
- std::string op_a = regs.GetRegisterAsFloat(instr.gpr20);
-
- if (instr.conversion.abs_a) {
- op_a = "abs(" + op_a + ')';
- }
+ template <Type type>
+ std::string Absolute(Operation operation) {
+ return GenerateUnary(operation, "abs", type, type, false);
+ }
- if (instr.conversion.negate_a) {
- op_a = "-(" + op_a + ')';
- }
+ std::string FClamp(Operation operation) {
+ return GenerateTernary(operation, "clamp", Type::Float, Type::Float, Type::Float,
+ Type::Float);
+ }
- switch (instr.conversion.f2f.rounding) {
- case Tegra::Shader::F2fRoundingOp::None:
- break;
- case Tegra::Shader::F2fRoundingOp::Round:
- op_a = "roundEven(" + op_a + ')';
- break;
- case Tegra::Shader::F2fRoundingOp::Floor:
- op_a = "floor(" + op_a + ')';
- break;
- case Tegra::Shader::F2fRoundingOp::Ceil:
- op_a = "ceil(" + op_a + ')';
- break;
- case Tegra::Shader::F2fRoundingOp::Trunc:
- op_a = "trunc(" + op_a + ')';
- break;
- default:
- UNIMPLEMENTED_MSG("Unimplemented F2F rounding mode {}",
- static_cast<u32>(instr.conversion.f2f.rounding.Value()));
- break;
- }
+ template <Type type>
+ std::string Min(Operation operation) {
+ return GenerateBinaryCall(operation, "min", type, type, type);
+ }
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1, instr.alu.saturate_d);
- break;
- }
- case OpCode::Id::F2I_R:
- case OpCode::Id::F2I_C: {
- UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in F2I is not implemented");
- std::string op_a{};
-
- if (instr.is_b_gpr) {
- op_a = regs.GetRegisterAsFloat(instr.gpr20);
- } else {
- op_a = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- }
+ template <Type type>
+ std::string Max(Operation operation) {
+ return GenerateBinaryCall(operation, "max", type, type, type);
+ }
- if (instr.conversion.abs_a) {
- op_a = "abs(" + op_a + ')';
- }
+ std::string Select(Operation operation) {
+ const std::string condition = Visit(operation[0]);
+ const std::string true_case = Visit(operation[1]);
+ const std::string false_case = Visit(operation[2]);
+ return ApplyPrecise(operation,
+ '(' + condition + " ? " + true_case + " : " + false_case + ')');
+ }
- if (instr.conversion.negate_a) {
- op_a = "-(" + op_a + ')';
- }
+ std::string FCos(Operation operation) {
+ return GenerateUnary(operation, "cos", Type::Float, Type::Float, false);
+ }
- switch (instr.conversion.f2i.rounding) {
- case Tegra::Shader::F2iRoundingOp::None:
- break;
- case Tegra::Shader::F2iRoundingOp::Floor:
- op_a = "floor(" + op_a + ')';
- break;
- case Tegra::Shader::F2iRoundingOp::Ceil:
- op_a = "ceil(" + op_a + ')';
- break;
- case Tegra::Shader::F2iRoundingOp::Trunc:
- op_a = "trunc(" + op_a + ')';
- break;
- default:
- UNIMPLEMENTED_MSG("Unimplemented F2I rounding mode {}",
- static_cast<u32>(instr.conversion.f2i.rounding.Value()));
- break;
- }
+ std::string FSin(Operation operation) {
+ return GenerateUnary(operation, "sin", Type::Float, Type::Float, false);
+ }
- if (instr.conversion.is_output_signed) {
- op_a = "int(" + op_a + ')';
- } else {
- op_a = "uint(" + op_a + ')';
- }
+ std::string FExp2(Operation operation) {
+ return GenerateUnary(operation, "exp2", Type::Float, Type::Float, false);
+ }
- regs.SetRegisterToInteger(instr.gpr0, instr.conversion.is_output_signed, 0, op_a, 1,
- 1, false, 0, instr.conversion.dest_size);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled conversion instruction: {}", opcode->get().GetName());
- }
- }
- break;
- }
- case OpCode::Type::Memory: {
- switch (opcode->get().GetId()) {
- case OpCode::Id::LD_A: {
- // Note: Shouldn't this be interp mode flat? As in no interpolation made.
- UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
- "Indirect attribute loads are not supported");
- UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
- "Unaligned attribute loads are not supported");
-
- Tegra::Shader::IpaMode input_mode{Tegra::Shader::IpaInterpMode::Perspective,
- Tegra::Shader::IpaSampleMode::Default};
-
- u64 next_element = instr.attribute.fmt20.element;
- u64 next_index = static_cast<u64>(instr.attribute.fmt20.index.Value());
-
- const auto LoadNextElement = [&](u32 reg_offset) {
- regs.SetRegisterToInputAttibute(instr.gpr0.Value() + reg_offset, next_element,
- static_cast<Attribute::Index>(next_index),
- input_mode, instr.gpr39.Value());
-
- // Load the next attribute element into the following register. If the element
- // to load goes beyond the vec4 size, load the first element of the next
- // attribute.
- next_element = (next_element + 1) % 4;
- next_index = next_index + (next_element == 0 ? 1 : 0);
- };
-
- const u32 num_words = static_cast<u32>(instr.attribute.fmt20.size.Value()) + 1;
- for (u32 reg_offset = 0; reg_offset < num_words; ++reg_offset) {
- LoadNextElement(reg_offset);
- }
- break;
- }
- case OpCode::Id::LD_C: {
- UNIMPLEMENTED_IF(instr.ld_c.unknown != 0);
-
- // Add an extra scope and declare the index register inside to prevent
- // overwriting it in case it is used as an output of the LD instruction.
- shader.AddLine("{");
- ++shader.scope;
-
- shader.AddLine("uint index = (" + regs.GetRegisterAsInteger(instr.gpr8, 0, false) +
- " / 4) & (MAX_CONSTBUFFER_ELEMENTS - 1);");
-
- const std::string op_a =
- regs.GetUniformIndirect(instr.cbuf36.index, instr.cbuf36.offset + 0, "index",
- GLSLRegister::Type::Float);
-
- switch (instr.ld_c.type.Value()) {
- case Tegra::Shader::UniformType::Single:
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
- break;
-
- case Tegra::Shader::UniformType::Double: {
- const std::string op_b =
- regs.GetUniformIndirect(instr.cbuf36.index, instr.cbuf36.offset + 4,
- "index", GLSLRegister::Type::Float);
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
- regs.SetRegisterToFloat(instr.gpr0.Value() + 1, 0, op_b, 1, 1);
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled type: {}",
- static_cast<unsigned>(instr.ld_c.type.Value()));
- }
+ std::string FLog2(Operation operation) {
+ return GenerateUnary(operation, "log2", Type::Float, Type::Float, false);
+ }
- --shader.scope;
- shader.AddLine("}");
- break;
- }
- case OpCode::Id::LD_L: {
- UNIMPLEMENTED_IF_MSG(instr.ld_l.unknown == 1, "LD_L Unhandled mode: {}",
- static_cast<unsigned>(instr.ld_l.unknown.Value()));
+ std::string FInverseSqrt(Operation operation) {
+ return GenerateUnary(operation, "inversesqrt", Type::Float, Type::Float, false);
+ }
- // Add an extra scope and declare the index register inside to prevent
- // overwriting it in case it is used as an output of the LD instruction.
- shader.AddLine('{');
- ++shader.scope;
+ std::string FSqrt(Operation operation) {
+ return GenerateUnary(operation, "sqrt", Type::Float, Type::Float, false);
+ }
- std::string op = '(' + regs.GetRegisterAsInteger(instr.gpr8, 0, false) + " + " +
- std::to_string(instr.smem_imm.Value()) + ')';
+ std::string FRoundEven(Operation operation) {
+ return GenerateUnary(operation, "roundEven", Type::Float, Type::Float, false);
+ }
- shader.AddLine("uint index = (" + op + " / 4);");
+ std::string FFloor(Operation operation) {
+ return GenerateUnary(operation, "floor", Type::Float, Type::Float, false);
+ }
- const std::string op_a = regs.GetLocalMemoryAsFloat("index");
+ std::string FCeil(Operation operation) {
+ return GenerateUnary(operation, "ceil", Type::Float, Type::Float, false);
+ }
- switch (instr.ldst_sl.type.Value()) {
- case Tegra::Shader::StoreType::Bytes32:
- regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
- break;
- default:
- UNIMPLEMENTED_MSG("LD_L Unhandled type: {}",
- static_cast<unsigned>(instr.ldst_sl.type.Value()));
- }
+ std::string FTrunc(Operation operation) {
+ return GenerateUnary(operation, "trunc", Type::Float, Type::Float, false);
+ }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::ST_A: {
- UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
- "Indirect attribute loads are not supported");
- UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
- "Unaligned attribute loads are not supported");
-
- u64 next_element = instr.attribute.fmt20.element;
- u64 next_index = static_cast<u64>(instr.attribute.fmt20.index.Value());
-
- const auto StoreNextElement = [&](u32 reg_offset) {
- regs.SetOutputAttributeToRegister(static_cast<Attribute::Index>(next_index),
- next_element, instr.gpr0.Value() + reg_offset,
- instr.gpr39.Value());
-
- // Load the next attribute element into the following register. If the element
- // to load goes beyond the vec4 size, load the first element of the next
- // attribute.
- next_element = (next_element + 1) % 4;
- next_index = next_index + (next_element == 0 ? 1 : 0);
- };
-
- const u32 num_words = static_cast<u32>(instr.attribute.fmt20.size.Value()) + 1;
- for (u32 reg_offset = 0; reg_offset < num_words; ++reg_offset) {
- StoreNextElement(reg_offset);
- }
+ template <Type type>
+ std::string FCastInteger(Operation operation) {
+ return GenerateUnary(operation, "float", Type::Float, type, false);
+ }
- break;
- }
- case OpCode::Id::ST_L: {
- UNIMPLEMENTED_IF_MSG(instr.st_l.unknown == 0, "ST_L Unhandled mode: {}",
- static_cast<unsigned>(instr.st_l.unknown.Value()));
+ std::string ICastFloat(Operation operation) {
+ return GenerateUnary(operation, "int", Type::Int, Type::Float, false);
+ }
- // Add an extra scope and declare the index register inside to prevent
- // overwriting it in case it is used as an output of the LD instruction.
- shader.AddLine('{');
- ++shader.scope;
+ std::string ICastUnsigned(Operation operation) {
+ return GenerateUnary(operation, "int", Type::Int, Type::Uint, false);
+ }
- std::string op = '(' + regs.GetRegisterAsInteger(instr.gpr8, 0, false) + " + " +
- std::to_string(instr.smem_imm.Value()) + ')';
+ template <Type type>
+ std::string LogicalShiftLeft(Operation operation) {
+ return GenerateBinaryInfix(operation, "<<", type, type, Type::Uint);
+ }
- shader.AddLine("uint index = (" + op + " / 4);");
+ std::string ILogicalShiftRight(Operation operation) {
+ const std::string op_a = VisitOperand(operation, 0, Type::Uint);
+ const std::string op_b = VisitOperand(operation, 1, Type::Uint);
- switch (instr.ldst_sl.type.Value()) {
- case Tegra::Shader::StoreType::Bytes32:
- regs.SetLocalMemoryAsFloat("index", regs.GetRegisterAsFloat(instr.gpr0));
- break;
- default:
- UNIMPLEMENTED_MSG("ST_L Unhandled type: {}",
- static_cast<unsigned>(instr.ldst_sl.type.Value()));
- }
+ return ApplyPrecise(operation,
+ BitwiseCastResult("int(" + op_a + " >> " + op_b + ')', Type::Int));
+ }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TEX: {
- Tegra::Shader::TextureType texture_type{instr.tex.texture_type};
- std::string coord;
- const bool is_array = instr.tex.array != 0;
-
- UNIMPLEMENTED_IF_MSG(instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
-
- const bool depth_compare =
- instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
- u32 num_coordinates = TextureCoordinates(texture_type);
- u32 start_index = 0;
- std::string array_elem;
- if (is_array) {
- array_elem = regs.GetRegisterAsInteger(instr.gpr8);
- start_index = 1;
- }
- const auto process_mode = instr.tex.GetTextureProcessMode();
- u32 start_index_b = 0;
- std::string lod_value;
- if (process_mode != Tegra::Shader::TextureProcessMode::LZ &&
- process_mode != Tegra::Shader::TextureProcessMode::None) {
- start_index_b = 1;
- lod_value = regs.GetRegisterAsFloat(instr.gpr20);
- }
+ std::string IArithmeticShiftRight(Operation operation) {
+ return GenerateBinaryInfix(operation, ">>", Type::Int, Type::Int, Type::Uint);
+ }
- std::string depth_value;
- if (depth_compare) {
- depth_value = regs.GetRegisterAsFloat(instr.gpr20.Value() + start_index_b);
- }
+ template <Type type>
+ std::string BitwiseAnd(Operation operation) {
+ return GenerateBinaryInfix(operation, "&", type, type, type);
+ }
- bool depth_compare_extra = false;
-
- switch (num_coordinates) {
- case 1: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index);
- if (is_array) {
- if (depth_compare) {
- coord = "vec3 coords = vec3(" + x + ", " + depth_value + ", " +
- array_elem + ");";
- } else {
- coord = "vec2 coords = vec2(" + x + ", " + array_elem + ");";
- }
- } else {
- if (depth_compare) {
- coord = "vec2 coords = vec2(" + x + ", " + depth_value + ");";
- } else {
- coord = "float coords = " + x + ';';
- }
- }
- break;
- }
- case 2: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index);
- const std::string y =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index + 1);
- if (is_array) {
- if (depth_compare) {
- coord = "vec4 coords = vec4(" + x + ", " + y + ", " + depth_value +
- ", " + array_elem + ");";
- } else {
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + array_elem + ");";
- }
- } else {
- if (depth_compare) {
- coord =
- "vec3 coords = vec3(" + x + ", " + y + ", " + depth_value + ");";
- } else {
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- }
- }
- break;
- }
- case 3: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index);
- const std::string y =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index + 1);
- const std::string z =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + start_index + 2);
- if (is_array) {
- depth_compare_extra = depth_compare;
- coord = "vec4 coords = vec4(" + x + ", " + y + ", " + z + ", " +
- array_elem + ");";
- } else {
- if (depth_compare) {
- coord = "vec4 coords = vec4(" + x + ", " + y + ", " + z + ", " +
- depth_value + ");";
- } else {
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
- }
- }
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
-
- // Fallback to interpreting as a 2D texture for now
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- texture_type = Tegra::Shader::TextureType::Texture2D;
- }
+ template <Type type>
+ std::string BitwiseOr(Operation operation) {
+ return GenerateBinaryInfix(operation, "|", type, type, type);
+ }
- const std::string sampler =
- GetSampler(instr.sampler, texture_type, is_array, depth_compare);
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
+ template <Type type>
+ std::string BitwiseXor(Operation operation) {
+ return GenerateBinaryInfix(operation, "^", type, type, type);
+ }
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine(coord);
- std::string texture;
+ template <Type type>
+ std::string BitwiseNot(Operation operation) {
+ return GenerateUnary(operation, "~", type, type, false);
+ }
- switch (instr.tex.GetTextureProcessMode()) {
- case Tegra::Shader::TextureProcessMode::None: {
- if (!depth_compare_extra) {
- texture = "texture(" + sampler + ", coords)";
- } else {
- texture = "texture(" + sampler + ", coords, " + depth_value + ')';
- }
- break;
- }
- case Tegra::Shader::TextureProcessMode::LZ: {
- if (!depth_compare_extra) {
- texture = "textureLod(" + sampler + ", coords, 0.0)";
- } else {
- texture = "texture(" + sampler + ", coords, " + depth_value + ')';
- }
- break;
- }
- case Tegra::Shader::TextureProcessMode::LB:
- case Tegra::Shader::TextureProcessMode::LBA: {
- // TODO: Figure if A suffix changes the equation at all.
- if (!depth_compare_extra) {
- texture = "texture(" + sampler + ", coords, " + lod_value + ')';
- } else {
- texture = "texture(" + sampler + ", coords, " + depth_value + ')';
- LOG_WARNING(HW_GPU,
- "OpenGL Limitation: can't set bias value along depth compare");
- }
- break;
- }
- case Tegra::Shader::TextureProcessMode::LL:
- case Tegra::Shader::TextureProcessMode::LLA: {
- // TODO: Figure if A suffix changes the equation at all.
- if (!depth_compare_extra) {
- texture = "textureLod(" + sampler + ", coords, " + lod_value + ')';
- } else {
- texture = "texture(" + sampler + ", coords, " + depth_value + ')';
- LOG_WARNING(HW_GPU,
- "OpenGL Limitation: can't set lod value along depth compare");
- }
- break;
- }
- default: {
- if (!depth_compare_extra) {
- texture = "texture(" + sampler + ", coords)";
- } else {
- texture = "texture(" + sampler + ", coords, " + depth_value + ')';
- }
- UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
- static_cast<u32>(instr.tex.GetTextureProcessMode()));
- }
- }
- if (!depth_compare) {
- shader.AddLine("vec4 texture_tmp = " + texture + ';');
- std::size_t dest_elem{};
- for (std::size_t elem = 0; elem < 4; ++elem) {
- if (!instr.tex.IsComponentEnabled(elem)) {
- // Skip disabled components
- continue;
- }
- regs.SetRegisterToFloat(instr.gpr0, elem, "texture_tmp", 1, 4, false,
- dest_elem);
- ++dest_elem;
- }
- } else {
- regs.SetRegisterToFloat(instr.gpr0, 0, texture, 1, 1, false);
- }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TEXS: {
- Tegra::Shader::TextureType texture_type{instr.texs.GetTextureType()};
- bool is_array{instr.texs.IsArrayTexture()};
-
- UNIMPLEMENTED_IF_MSG(instr.texs.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
-
- const bool depth_compare =
- instr.texs.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
- u32 num_coordinates = TextureCoordinates(texture_type);
- const auto process_mode = instr.texs.GetTextureProcessMode();
- std::string lod_value;
- std::string coord;
- u32 lod_offset = 0;
- if (process_mode == Tegra::Shader::TextureProcessMode::LL) {
- if (num_coordinates > 2) {
- lod_value = regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
- lod_offset = 2;
- } else {
- lod_value = regs.GetRegisterAsFloat(instr.gpr20);
- lod_offset = 1;
- }
- }
+ std::string UCastFloat(Operation operation) {
+ return GenerateUnary(operation, "uint", Type::Uint, Type::Float, false);
+ }
- switch (num_coordinates) {
- case 1: {
- coord = "float coords = " + regs.GetRegisterAsFloat(instr.gpr8) + ';';
- break;
- }
- case 2: {
- if (is_array) {
- if (depth_compare) {
- const std::string index = regs.GetRegisterAsInteger(instr.gpr8);
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- const std::string z = regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
- coord = "vec4 coords = vec4(" + x + ", " + y + ", " + z + ", " + index +
- ");";
- } else {
- const std::string index = regs.GetRegisterAsInteger(instr.gpr8);
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + index + ");";
- }
- } else {
- if (lod_offset != 0) {
- if (depth_compare) {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string z =
- regs.GetRegisterAsFloat(instr.gpr20.Value() + lod_offset);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
- } else {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- }
- } else {
- if (depth_compare) {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y =
- regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string z = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
- } else {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- }
- }
- }
- break;
- }
- case 3: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string z = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
-
- // Fallback to interpreting as a 2D texture for now
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- texture_type = Tegra::Shader::TextureType::Texture2D;
- is_array = false;
- }
- const std::string sampler =
- GetSampler(instr.sampler, texture_type, is_array, depth_compare);
- std::string texture;
- switch (process_mode) {
- case Tegra::Shader::TextureProcessMode::None: {
- texture = "texture(" + sampler + ", coords)";
- break;
- }
- case Tegra::Shader::TextureProcessMode::LZ: {
- if (depth_compare && is_array) {
- texture = "texture(" + sampler + ", coords)";
- } else {
- texture = "textureLod(" + sampler + ", coords, 0.0)";
- }
- break;
- }
- case Tegra::Shader::TextureProcessMode::LL: {
- texture = "textureLod(" + sampler + ", coords, " + lod_value + ')';
- break;
- }
- default: {
- texture = "texture(" + sampler + ", coords)";
- UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
- static_cast<u32>(instr.texs.GetTextureProcessMode()));
- }
- }
- if (!depth_compare) {
- WriteTexsInstruction(instr, coord, texture);
- } else {
- WriteTexsInstruction(instr, coord, "vec4(" + texture + ')');
- }
+ std::string UCastSigned(Operation operation) {
+ return GenerateUnary(operation, "uint", Type::Uint, Type::Int, false);
+ }
- break;
- }
- case OpCode::Id::TLDS: {
- const Tegra::Shader::TextureType texture_type{instr.tlds.GetTextureType()};
- const bool is_array{instr.tlds.IsArrayTexture()};
-
- ASSERT(texture_type == Tegra::Shader::TextureType::Texture2D);
- ASSERT(is_array == false);
-
- UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::MZ),
- "MZ is not implemented");
-
- u32 extra_op_offset = 0;
-
- // Scope to avoid variable name overlaps.
- shader.AddLine('{');
- ++shader.scope;
- std::string coords;
-
- switch (texture_type) {
- case Tegra::Shader::TextureType::Texture1D: {
- const std::string x = regs.GetRegisterAsInteger(instr.gpr8);
- coords = "float coords = " + x + ';';
- break;
- }
- case Tegra::Shader::TextureType::Texture2D: {
- UNIMPLEMENTED_IF_MSG(is_array, "Unhandled 2d array texture");
-
- const std::string x = regs.GetRegisterAsInteger(instr.gpr8);
- const std::string y = regs.GetRegisterAsInteger(instr.gpr20);
- // shader.AddLine("ivec2 coords = ivec2(" + x + ", " + y + ");");
- coords = "ivec2 coords = ivec2(" + x + ", " + y + ");";
- extra_op_offset = 1;
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled texture type {}", static_cast<u32>(texture_type));
- }
- const std::string sampler =
- GetSampler(instr.sampler, texture_type, is_array, false);
- std::string texture = "texelFetch(" + sampler + ", coords, 0)";
- switch (instr.tlds.GetTextureProcessMode()) {
- case Tegra::Shader::TextureProcessMode::LZ: {
- texture = "texelFetch(" + sampler + ", coords, 0)";
- break;
- }
- case Tegra::Shader::TextureProcessMode::LL: {
- shader.AddLine(
- "float lod = " +
- regs.GetRegisterAsInteger(instr.gpr20.Value() + extra_op_offset) + ';');
- texture = "texelFetch(" + sampler + ", coords, lod)";
- break;
- }
- default: {
- texture = "texelFetch(" + sampler + ", coords, 0)";
- UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
- static_cast<u32>(instr.tlds.GetTextureProcessMode()));
- }
- }
- WriteTexsInstruction(instr, coords, texture);
+ std::string UShiftRight(Operation operation) {
+ return GenerateBinaryInfix(operation, ">>", Type::Uint, Type::Uint, Type::Uint);
+ }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TLD4: {
- ASSERT(instr.tld4.texture_type == Tegra::Shader::TextureType::Texture2D);
- ASSERT(instr.tld4.array == 0);
- std::string coord;
-
- UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
- "NDV is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::PTP),
- "PTP is not implemented");
- const bool depth_compare =
- instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
- auto texture_type = instr.tld4.texture_type.Value();
- u32 num_coordinates = TextureCoordinates(texture_type);
- if (depth_compare)
- num_coordinates += 1;
-
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
- shader.AddLine('{');
- ++shader.scope;
-
- switch (num_coordinates) {
- case 2: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
- break;
- }
- case 3: {
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- const std::string z = regs.GetRegisterAsFloat(instr.gpr8.Value() + 2);
- shader.AddLine("vec3 coords = vec3(" + x + ", " + y + ", " + z + ");");
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
- texture_type = Tegra::Shader::TextureType::Texture2D;
- }
+ template <Type type>
+ std::string BitfieldInsert(Operation operation) {
+ return GenerateQuaternary(operation, "bitfieldInsert", type, type, type, Type::Int,
+ Type::Int);
+ }
- const std::string sampler =
- GetSampler(instr.sampler, texture_type, false, depth_compare);
-
- const std::string texture = "textureGather(" + sampler + ", coords, " +
- std::to_string(instr.tld4.component) + ')';
-
- if (!depth_compare) {
- shader.AddLine("vec4 texture_tmp = " + texture + ';');
- std::size_t dest_elem{};
- for (std::size_t elem = 0; elem < 4; ++elem) {
- if (!instr.tex.IsComponentEnabled(elem)) {
- // Skip disabled components
- continue;
- }
- regs.SetRegisterToFloat(instr.gpr0, elem, "texture_tmp", 1, 4, false,
- dest_elem);
- ++dest_elem;
- }
- } else {
- regs.SetRegisterToFloat(instr.gpr0, 0, texture, 1, 1, false);
- }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TLD4S: {
- UNIMPLEMENTED_IF_MSG(
- instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- UNIMPLEMENTED_IF_MSG(
- instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
-
- // Scope to avoid variable name overlaps.
- shader.AddLine('{');
- ++shader.scope;
- std::string coords;
-
- const bool depth_compare =
- instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
- const std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string op_b = regs.GetRegisterAsFloat(instr.gpr20);
- // TODO(Subv): Figure out how the sampler type is encoded in the TLD4S instruction.
- const std::string sampler = GetSampler(
- instr.sampler, Tegra::Shader::TextureType::Texture2D, false, depth_compare);
- if (!depth_compare) {
- coords = "vec2 coords = vec2(" + op_a + ", " + op_b + ");";
- } else {
- // Note: TLD4S coordinate encoding works just like TEXS's
- const std::string op_y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coords = "vec3 coords = vec3(" + op_a + ", " + op_y + ", " + op_b + ");";
- }
- const std::string texture = "textureGather(" + sampler + ", coords, " +
- std::to_string(instr.tld4s.component) + ')';
+ template <Type type>
+ std::string BitfieldExtract(Operation operation) {
+ return GenerateTernary(operation, "bitfieldExtract", type, type, Type::Int, Type::Int);
+ }
- if (!depth_compare) {
- WriteTexsInstruction(instr, coords, texture);
- } else {
- WriteTexsInstruction(instr, coords, "vec4(" + texture + ')');
- }
+ template <Type type>
+ std::string BitCount(Operation operation) {
+ return GenerateUnary(operation, "bitCount", type, type, false);
+ }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TXQ: {
- UNIMPLEMENTED_IF_MSG(instr.txq.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
-
- ++shader.scope;
- shader.AddLine('{');
- // TODO: the new commits on the texture refactor, change the way samplers work.
- // Sadly, not all texture instructions specify the type of texture their sampler
- // uses. This must be fixed at a later instance.
- const std::string sampler =
- GetSampler(instr.sampler, Tegra::Shader::TextureType::Texture2D, false, false);
- switch (instr.txq.query_type) {
- case Tegra::Shader::TextureQueryType::Dimension: {
- const std::string texture = "textureSize(" + sampler + ", " +
- regs.GetRegisterAsInteger(instr.gpr8) + ')';
- const std::string mip_level = "textureQueryLevels(" + sampler + ')';
- shader.AddLine("ivec2 sizes = " + texture + ';');
- regs.SetRegisterToInteger(instr.gpr0, true, 0, "sizes.x", 1, 1);
- regs.SetRegisterToInteger(instr.gpr0.Value() + 1, true, 0, "sizes.y", 1, 1);
- regs.SetRegisterToInteger(instr.gpr0.Value() + 2, true, 0, "0", 1, 1);
- regs.SetRegisterToInteger(instr.gpr0.Value() + 3, true, 0, mip_level, 1, 1);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled texture query type: {}",
- static_cast<u32>(instr.txq.query_type.Value()));
- }
- }
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- case OpCode::Id::TMML: {
- UNIMPLEMENTED_IF_MSG(instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- UNIMPLEMENTED_IF_MSG(instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
- "NDV is not implemented");
-
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const bool is_array = instr.tmml.array != 0;
- auto texture_type = instr.tmml.texture_type.Value();
- const std::string sampler =
- GetSampler(instr.sampler, texture_type, is_array, false);
-
- // TODO: add coordinates for different samplers once other texture types are
- // implemented.
- std::string coord;
- switch (texture_type) {
- case Tegra::Shader::TextureType::Texture1D: {
- coord = "float coords = " + x + ';';
- break;
- }
- case Tegra::Shader::TextureType::Texture2D: {
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- break;
- }
- default:
- UNIMPLEMENTED_MSG("Unhandled texture type {}", static_cast<u32>(texture_type));
+ std::string HNegate(Operation operation) {
+ const auto GetNegate = [&](std::size_t index) -> std::string {
+ return VisitOperand(operation, index, Type::Bool) + " ? -1 : 1";
+ };
+ const std::string value = '(' + VisitOperand(operation, 0, Type::HalfFloat) + " * vec2(" +
+ GetNegate(1) + ", " + GetNegate(2) + "))";
+ return BitwiseCastResult(value, Type::HalfFloat);
+ }
- // Fallback to interpreting as a 2D texture for now
- const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- texture_type = Tegra::Shader::TextureType::Texture2D;
- }
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine(coord);
- const std::string texture = "textureQueryLod(" + sampler + ", coords)";
- const std::string tmp = "vec2 tmp = " + texture + "*vec2(256.0, 256.0);";
- shader.AddLine(tmp);
-
- regs.SetRegisterToInteger(instr.gpr0, true, 0, "int(tmp.y)", 1, 1);
- regs.SetRegisterToInteger(instr.gpr0.Value() + 1, false, 0, "uint(tmp.x)", 1, 1);
- --shader.scope;
- shader.AddLine('}');
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled memory instruction: {}", opcode->get().GetName());
- }
- }
- break;
- }
- case OpCode::Type::FloatSetPredicate: {
- const std::string op_a =
- GetOperandAbsNeg(regs.GetRegisterAsFloat(instr.gpr8), instr.fsetp.abs_a != 0,
- instr.fsetp.neg_a != 0);
+ std::string HMergeF32(Operation operation) {
+ return "float(toHalf2(" + Visit(operation[0]) + ")[0])";
+ }
- std::string op_b;
+ std::string HMergeH0(Operation operation) {
+ return "fromHalf2(vec2(toHalf2(" + Visit(operation[0]) + ")[1], toHalf2(" +
+ Visit(operation[1]) + ")[0]))";
+ }
- if (instr.is_b_imm) {
- op_b += '(' + GetImmediate19(instr) + ')';
- } else {
- if (instr.is_b_gpr) {
- op_b += regs.GetRegisterAsFloat(instr.gpr20);
- } else {
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- }
- }
+ std::string HMergeH1(Operation operation) {
+ return "fromHalf2(vec2(toHalf2(" + Visit(operation[0]) + ")[0], toHalf2(" +
+ Visit(operation[1]) + ")[1]))";
+ }
- if (instr.fsetp.abs_b) {
- op_b = "abs(" + op_b + ')';
- }
+ std::string HPack2(Operation operation) {
+ return "utof(packHalf2x16(vec2(" + Visit(operation[0]) + ", " + Visit(operation[1]) + ")))";
+ }
- // We can't use the constant predicate as destination.
- ASSERT(instr.fsetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+ template <Type type>
+ std::string LogicalLessThan(Operation operation) {
+ return GenerateBinaryInfix(operation, "<", Type::Bool, type, type);
+ }
- const std::string second_pred =
- GetPredicateCondition(instr.fsetp.pred39, instr.fsetp.neg_pred != 0);
+ template <Type type>
+ std::string LogicalEqual(Operation operation) {
+ return GenerateBinaryInfix(operation, "==", Type::Bool, type, type);
+ }
- const std::string combiner = GetPredicateCombiner(instr.fsetp.op);
+ template <Type type>
+ std::string LogicalLessEqual(Operation operation) {
+ return GenerateBinaryInfix(operation, "<=", Type::Bool, type, type);
+ }
- const std::string predicate = GetPredicateComparison(instr.fsetp.cond, op_a, op_b);
- // Set the primary predicate to the result of Predicate OP SecondPredicate
- SetPredicate(instr.fsetp.pred3,
- '(' + predicate + ") " + combiner + " (" + second_pred + ')');
+ template <Type type>
+ std::string LogicalGreaterThan(Operation operation) {
+ return GenerateBinaryInfix(operation, ">", Type::Bool, type, type);
+ }
- if (instr.fsetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
- // if enabled
- SetPredicate(instr.fsetp.pred0,
- "!(" + predicate + ") " + combiner + " (" + second_pred + ')');
- }
- break;
- }
- case OpCode::Type::IntegerSetPredicate: {
- const std::string op_a =
- regs.GetRegisterAsInteger(instr.gpr8, 0, instr.isetp.is_signed);
- std::string op_b;
+ template <Type type>
+ std::string LogicalNotEqual(Operation operation) {
+ return GenerateBinaryInfix(operation, "!=", Type::Bool, type, type);
+ }
- if (instr.is_b_imm) {
- op_b += '(' + std::to_string(instr.alu.GetSignedImm20_20()) + ')';
- } else {
- if (instr.is_b_gpr) {
- op_b += regs.GetRegisterAsInteger(instr.gpr20, 0, instr.isetp.is_signed);
- } else {
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Integer);
- }
- }
+ template <Type type>
+ std::string LogicalGreaterEqual(Operation operation) {
+ return GenerateBinaryInfix(operation, ">=", Type::Bool, type, type);
+ }
- // We can't use the constant predicate as destination.
- ASSERT(instr.isetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+ std::string LogicalFIsNan(Operation operation) {
+ return GenerateUnary(operation, "isnan", Type::Bool, Type::Float, false);
+ }
- const std::string second_pred =
- GetPredicateCondition(instr.isetp.pred39, instr.isetp.neg_pred != 0);
+ std::string LogicalAssign(Operation operation) {
+ const Node dest = operation[0];
+ const Node src = operation[1];
- const std::string combiner = GetPredicateCombiner(instr.isetp.op);
+ std::string target;
- const std::string predicate = GetPredicateComparison(instr.isetp.cond, op_a, op_b);
- // Set the primary predicate to the result of Predicate OP SecondPredicate
- SetPredicate(instr.isetp.pred3,
- '(' + predicate + ") " + combiner + " (" + second_pred + ')');
+ if (const auto pred = std::get_if<PredicateNode>(dest)) {
+ ASSERT_MSG(!pred->IsNegated(), "Negating logical assignment");
- if (instr.isetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
- // if enabled
- SetPredicate(instr.isetp.pred0,
- "!(" + predicate + ") " + combiner + " (" + second_pred + ')');
+ const auto index = pred->GetIndex();
+ switch (index) {
+ case Tegra::Shader::Pred::NeverExecute:
+ case Tegra::Shader::Pred::UnusedIndex:
+ // Writing to these predicates is a no-op
+ return {};
}
- break;
+ target = GetPredicate(index);
+ } else if (const auto flag = std::get_if<InternalFlagNode>(dest)) {
+ target = GetInternalFlag(flag->GetFlag());
}
- case OpCode::Type::HalfSetPredicate: {
- UNIMPLEMENTED_IF(instr.hsetp2.ftz != 0);
-
- const std::string op_a =
- GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hsetp2.type_a,
- instr.hsetp2.abs_a, instr.hsetp2.negate_a);
-
- const std::string op_b = [&]() {
- switch (opcode->get().GetId()) {
- case OpCode::Id::HSETP2_R:
- return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
- instr.hsetp2.type_b, instr.hsetp2.abs_a,
- instr.hsetp2.negate_b);
- default:
- UNREACHABLE();
- return std::string("vec2(0)");
- }
- }();
- // We can't use the constant predicate as destination.
- ASSERT(instr.hsetp2.pred3 != static_cast<u64>(Pred::UnusedIndex));
+ code.AddLine(target + " = " + Visit(src) + ';');
+ return {};
+ }
- const std::string second_pred =
- GetPredicateCondition(instr.hsetp2.pred39, instr.hsetp2.neg_pred != 0);
+ std::string LogicalAnd(Operation operation) {
+ return GenerateBinaryInfix(operation, "&&", Type::Bool, Type::Bool, Type::Bool);
+ }
- const std::string combiner = GetPredicateCombiner(instr.hsetp2.op);
+ std::string LogicalOr(Operation operation) {
+ return GenerateBinaryInfix(operation, "||", Type::Bool, Type::Bool, Type::Bool);
+ }
- const std::string component_combiner = instr.hsetp2.h_and ? "&&" : "||";
- const std::string predicate =
- '(' + GetPredicateComparison(instr.hsetp2.cond, op_a + ".x", op_b + ".x") + ' ' +
- component_combiner + ' ' +
- GetPredicateComparison(instr.hsetp2.cond, op_a + ".y", op_b + ".y") + ')';
+ std::string LogicalXor(Operation operation) {
+ return GenerateBinaryInfix(operation, "^^", Type::Bool, Type::Bool, Type::Bool);
+ }
- // Set the primary predicate to the result of Predicate OP SecondPredicate
- SetPredicate(instr.hsetp2.pred3,
- '(' + predicate + ") " + combiner + " (" + second_pred + ')');
+ std::string LogicalNegate(Operation operation) {
+ return GenerateUnary(operation, "!", Type::Bool, Type::Bool, false);
+ }
- if (instr.hsetp2.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
- // if enabled
- SetPredicate(instr.hsetp2.pred0,
- "!(" + predicate + ") " + combiner + " (" + second_pred + ')');
- }
- break;
- }
- case OpCode::Type::PredicateSetRegister: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in PSET is not implemented");
-
- const std::string op_a =
- GetPredicateCondition(instr.pset.pred12, instr.pset.neg_pred12 != 0);
- const std::string op_b =
- GetPredicateCondition(instr.pset.pred29, instr.pset.neg_pred29 != 0);
-
- const std::string second_pred =
- GetPredicateCondition(instr.pset.pred39, instr.pset.neg_pred39 != 0);
-
- const std::string combiner = GetPredicateCombiner(instr.pset.op);
-
- const std::string predicate =
- '(' + op_a + ") " + GetPredicateCombiner(instr.pset.cond) + " (" + op_b + ')';
- const std::string result = '(' + predicate + ") " + combiner + " (" + second_pred + ')';
- if (instr.pset.bf == 0) {
- const std::string value = '(' + result + ") ? 0xFFFFFFFF : 0";
- regs.SetRegisterToInteger(instr.gpr0, false, 0, value, 1, 1);
- } else {
- const std::string value = '(' + result + ") ? 1.0 : 0.0";
- regs.SetRegisterToFloat(instr.gpr0, 0, value, 1, 1);
- }
- break;
- }
- case OpCode::Type::PredicateSetPredicate: {
- switch (opcode->get().GetId()) {
- case OpCode::Id::PSETP: {
- const std::string op_a =
- GetPredicateCondition(instr.psetp.pred12, instr.psetp.neg_pred12 != 0);
- const std::string op_b =
- GetPredicateCondition(instr.psetp.pred29, instr.psetp.neg_pred29 != 0);
-
- // We can't use the constant predicate as destination.
- ASSERT(instr.psetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
-
- const std::string second_pred =
- GetPredicateCondition(instr.psetp.pred39, instr.psetp.neg_pred39 != 0);
-
- const std::string combiner = GetPredicateCombiner(instr.psetp.op);
-
- const std::string predicate =
- '(' + op_a + ") " + GetPredicateCombiner(instr.psetp.cond) + " (" + op_b + ')';
-
- // Set the primary predicate to the result of Predicate OP SecondPredicate
- SetPredicate(instr.psetp.pred3,
- '(' + predicate + ") " + combiner + " (" + second_pred + ')');
-
- if (instr.psetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
- // if enabled
- SetPredicate(instr.psetp.pred0,
- "!(" + predicate + ") " + combiner + " (" + second_pred + ')');
- }
- break;
- }
- case OpCode::Id::CSETP: {
- const std::string pred =
- GetPredicateCondition(instr.csetp.pred39, instr.csetp.neg_pred39 != 0);
- const std::string combiner = GetPredicateCombiner(instr.csetp.op);
- const std::string condition_code = regs.GetConditionCode(instr.csetp.cc);
- if (instr.csetp.pred3 != static_cast<u64>(Pred::UnusedIndex)) {
- SetPredicate(instr.csetp.pred3,
- '(' + condition_code + ") " + combiner + " (" + pred + ')');
- }
- if (instr.csetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- SetPredicate(instr.csetp.pred0,
- "!(" + condition_code + ") " + combiner + " (" + pred + ')');
- }
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled predicate instruction: {}", opcode->get().GetName());
- }
- }
- break;
- }
- case OpCode::Type::RegisterSetPredicate: {
- UNIMPLEMENTED_IF(instr.r2p.mode != Tegra::Shader::R2pMode::Pr);
+ std::string LogicalPick2(Operation operation) {
+ const std::string pair = VisitOperand(operation, 0, Type::Bool2);
+ return pair + '[' + VisitOperand(operation, 1, Type::Uint) + ']';
+ }
- const std::string apply_mask = [&]() {
- switch (opcode->get().GetId()) {
- case OpCode::Id::R2P_IMM:
- return std::to_string(instr.r2p.immediate_mask);
- default:
- UNREACHABLE();
- }
- }();
- const std::string mask = '(' + regs.GetRegisterAsInteger(instr.gpr8, 0, false) +
- " >> " + std::to_string(instr.r2p.byte) + ')';
+ std::string LogicalAll2(Operation operation) {
+ return GenerateUnary(operation, "all", Type::Bool, Type::Bool2);
+ }
- constexpr u64 programmable_preds = 7;
- for (u64 pred = 0; pred < programmable_preds; ++pred) {
- const auto shift = std::to_string(1 << pred);
+ std::string LogicalAny2(Operation operation) {
+ return GenerateUnary(operation, "any", Type::Bool, Type::Bool2);
+ }
- shader.AddLine("if ((" + apply_mask + " & " + shift + ") != 0) {");
- ++shader.scope;
+ std::string Logical2HLessThan(Operation operation) {
+ return GenerateBinaryCall(operation, "lessThan", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- SetPredicate(pred, '(' + mask + " & " + shift + ") != 0");
+ std::string Logical2HEqual(Operation operation) {
+ return GenerateBinaryCall(operation, "equal", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- --shader.scope;
- shader.AddLine('}');
- }
- break;
- }
- case OpCode::Type::FloatSet: {
- const std::string op_a = GetOperandAbsNeg(regs.GetRegisterAsFloat(instr.gpr8),
- instr.fset.abs_a != 0, instr.fset.neg_a != 0);
+ std::string Logical2HLessEqual(Operation operation) {
+ return GenerateBinaryCall(operation, "lessThanEqual", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- std::string op_b;
+ std::string Logical2HGreaterThan(Operation operation) {
+ return GenerateBinaryCall(operation, "greaterThan", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- if (instr.is_b_imm) {
- const std::string imm = GetImmediate19(instr);
- op_b = imm;
- } else {
- if (instr.is_b_gpr) {
- op_b = regs.GetRegisterAsFloat(instr.gpr20);
- } else {
- op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Float);
- }
- }
+ std::string Logical2HNotEqual(Operation operation) {
+ return GenerateBinaryCall(operation, "notEqual", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- op_b = GetOperandAbsNeg(op_b, instr.fset.abs_b != 0, instr.fset.neg_b != 0);
+ std::string Logical2HGreaterEqual(Operation operation) {
+ return GenerateBinaryCall(operation, "greaterThanEqual", Type::Bool2, Type::HalfFloat,
+ Type::HalfFloat);
+ }
- // The fset instruction sets a register to 1.0 or -1 (depending on the bf bit) if the
- // condition is true, and to 0 otherwise.
- const std::string second_pred =
- GetPredicateCondition(instr.fset.pred39, instr.fset.neg_pred != 0);
+ std::string F4Texture(Operation operation) {
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ ASSERT(meta);
- const std::string combiner = GetPredicateCombiner(instr.fset.op);
+ std::string expr = GenerateTexture(operation, "texture");
+ if (meta->sampler.IsShadow()) {
+ expr = "vec4(" + expr + ')';
+ }
+ return expr + GetSwizzle(meta->element);
+ }
- const std::string predicate = "((" +
- GetPredicateComparison(instr.fset.cond, op_a, op_b) +
- ") " + combiner + " (" + second_pred + "))";
+ std::string F4TextureLod(Operation operation) {
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ ASSERT(meta);
- if (instr.fset.bf) {
- regs.SetRegisterToFloat(instr.gpr0, 0, predicate + " ? 1.0 : 0.0", 1, 1);
- } else {
- regs.SetRegisterToInteger(instr.gpr0, false, 0, predicate + " ? 0xFFFFFFFF : 0", 1,
- 1);
- }
- if (instr.generates_cc.Value() != 0) {
- regs.SetInternalFlag(InternalFlag::ZeroFlag, predicate);
- LOG_WARNING(HW_GPU, "FSET Condition Code is incomplete");
- }
- break;
+ std::string expr = GenerateTexture(operation, "textureLod");
+ if (meta->sampler.IsShadow()) {
+ expr = "vec4(" + expr + ')';
}
- case OpCode::Type::IntegerSet: {
- const std::string op_a = regs.GetRegisterAsInteger(instr.gpr8, 0, instr.iset.is_signed);
+ return expr + GetSwizzle(meta->element);
+ }
- std::string op_b;
+ std::string F4TextureGather(Operation operation) {
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ ASSERT(meta);
- if (instr.is_b_imm) {
- op_b = std::to_string(instr.alu.GetSignedImm20_20());
- } else {
- if (instr.is_b_gpr) {
- op_b = regs.GetRegisterAsInteger(instr.gpr20, 0, instr.iset.is_signed);
- } else {
- op_b = regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- GLSLRegister::Type::Integer);
- }
- }
-
- // The iset instruction sets a register to 1.0 or -1 (depending on the bf bit) if the
- // condition is true, and to 0 otherwise.
- const std::string second_pred =
- GetPredicateCondition(instr.iset.pred39, instr.iset.neg_pred != 0);
+ return GenerateTexture(operation, "textureGather", !meta->sampler.IsShadow()) +
+ GetSwizzle(meta->element);
+ }
- const std::string combiner = GetPredicateCombiner(instr.iset.op);
+ std::string F4TextureQueryDimensions(Operation operation) {
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ ASSERT(meta);
- const std::string predicate = "((" +
- GetPredicateComparison(instr.iset.cond, op_a, op_b) +
- ") " + combiner + " (" + second_pred + "))";
+ const std::string sampler = GetSampler(meta->sampler);
+ const std::string lod = VisitOperand(operation, 0, Type::Int);
- if (instr.iset.bf) {
- regs.SetRegisterToFloat(instr.gpr0, 0, predicate + " ? 1.0 : 0.0", 1, 1);
- } else {
- regs.SetRegisterToInteger(instr.gpr0, false, 0, predicate + " ? 0xFFFFFFFF : 0", 1,
- 1);
- }
- break;
+ switch (meta->element) {
+ case 0:
+ case 1:
+ return "textureSize(" + sampler + ", " + lod + ')' + GetSwizzle(meta->element);
+ case 2:
+ return "0";
+ case 3:
+ return "textureQueryLevels(" + sampler + ')';
}
- case OpCode::Type::HalfSet: {
- UNIMPLEMENTED_IF(instr.hset2.ftz != 0);
-
- const std::string op_a =
- GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hset2.type_a,
- instr.hset2.abs_a != 0, instr.hset2.negate_a != 0);
-
- const std::string op_b = [&]() {
- switch (opcode->get().GetId()) {
- case OpCode::Id::HSET2_R:
- return GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr20, 0, false),
- instr.hset2.type_b, instr.hset2.abs_b != 0,
- instr.hset2.negate_b != 0);
- default:
- UNREACHABLE();
- return std::string("vec2(0)");
- }
- }();
-
- const std::string second_pred =
- GetPredicateCondition(instr.hset2.pred39, instr.hset2.neg_pred != 0);
-
- const std::string combiner = GetPredicateCombiner(instr.hset2.op);
-
- // HSET2 operates on each half float in the pack.
- std::string result;
- for (int i = 0; i < 2; ++i) {
- const std::string float_value = i == 0 ? "0x00003c00" : "0x3c000000";
- const std::string integer_value = i == 0 ? "0x0000ffff" : "0xffff0000";
- const std::string value = instr.hset2.bf == 1 ? float_value : integer_value;
+ UNREACHABLE();
+ return "0";
+ }
- const std::string comp = std::string(".") + "xy"[i];
- const std::string predicate =
- "((" + GetPredicateComparison(instr.hset2.cond, op_a + comp, op_b + comp) +
- ") " + combiner + " (" + second_pred + "))";
+ std::string F4TextureQueryLod(Operation operation) {
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ ASSERT(meta);
- result += '(' + predicate + " ? " + value + " : 0)";
- if (i == 0) {
- result += " | ";
- }
- }
- regs.SetRegisterToInteger(instr.gpr0, false, 0, '(' + result + ')', 1, 1);
- break;
+ if (meta->element < 2) {
+ return "itof(int((" + GenerateTexture(operation, "textureQueryLod") + " * vec2(256))" +
+ GetSwizzle(meta->element) + "))";
}
- case OpCode::Type::Xmad: {
- UNIMPLEMENTED_IF(instr.xmad.sign_a);
- UNIMPLEMENTED_IF(instr.xmad.sign_b);
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in XMAD is not implemented");
-
- std::string op_a{regs.GetRegisterAsInteger(instr.gpr8, 0, instr.xmad.sign_a)};
- std::string op_b;
- std::string op_c;
-
- // TODO(bunnei): Needs to be fixed once op_a or op_b is signed
- UNIMPLEMENTED_IF(instr.xmad.sign_a != instr.xmad.sign_b);
- const bool is_signed{instr.xmad.sign_a == 1};
-
- bool is_merge{};
- switch (opcode->get().GetId()) {
- case OpCode::Id::XMAD_CR: {
- is_merge = instr.xmad.merge_56;
- op_b += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- instr.xmad.sign_b ? GLSLRegister::Type::Integer
- : GLSLRegister::Type::UnsignedInteger);
- op_c += regs.GetRegisterAsInteger(instr.gpr39, 0, is_signed);
- break;
- }
- case OpCode::Id::XMAD_RR: {
- is_merge = instr.xmad.merge_37;
- op_b += regs.GetRegisterAsInteger(instr.gpr20, 0, instr.xmad.sign_b);
- op_c += regs.GetRegisterAsInteger(instr.gpr39, 0, is_signed);
- break;
- }
- case OpCode::Id::XMAD_RC: {
- op_b += regs.GetRegisterAsInteger(instr.gpr39, 0, instr.xmad.sign_b);
- op_c += regs.GetUniform(instr.cbuf34.index, instr.cbuf34.offset,
- is_signed ? GLSLRegister::Type::Integer
- : GLSLRegister::Type::UnsignedInteger);
- break;
- }
- case OpCode::Id::XMAD_IMM: {
- is_merge = instr.xmad.merge_37;
- op_b += std::to_string(instr.xmad.imm20_16);
- op_c += regs.GetRegisterAsInteger(instr.gpr39, 0, is_signed);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled XMAD instruction: {}", opcode->get().GetName());
- }
- }
+ return "0";
+ }
- // TODO(bunnei): Ensure this is right with signed operands
- if (instr.xmad.high_a) {
- op_a = "((" + op_a + ") >> 16)";
- } else {
- op_a = "((" + op_a + ") & 0xFFFF)";
- }
+ std::string F4TexelFetch(Operation operation) {
+ constexpr std::array<const char*, 4> constructors = {"int", "ivec2", "ivec3", "ivec4"};
+ const auto meta = std::get_if<MetaTexture>(&operation.GetMeta());
+ const auto count = static_cast<u32>(operation.GetOperandsCount());
+ ASSERT(meta);
- std::string src2 = '(' + op_b + ')'; // Preserve original source 2
- if (instr.xmad.high_b) {
- op_b = '(' + src2 + " >> 16)";
- } else {
- op_b = '(' + src2 + " & 0xFFFF)";
- }
+ std::string expr = "texelFetch(";
+ expr += GetSampler(meta->sampler);
+ expr += ", ";
- std::string product = '(' + op_a + " * " + op_b + ')';
- if (instr.xmad.product_shift_left) {
- product = '(' + product + " << 16)";
- }
+ expr += constructors[meta->coords_count - 1];
+ expr += '(';
+ for (u32 i = 0; i < count; ++i) {
+ expr += VisitOperand(operation, i, Type::Int);
- switch (instr.xmad.mode) {
- case Tegra::Shader::XmadMode::None:
- break;
- case Tegra::Shader::XmadMode::CLo:
- op_c = "((" + op_c + ") & 0xFFFF)";
- break;
- case Tegra::Shader::XmadMode::CHi:
- op_c = "((" + op_c + ") >> 16)";
- break;
- case Tegra::Shader::XmadMode::CBcc:
- op_c = "((" + op_c + ") + (" + src2 + "<< 16))";
- break;
- default: {
- UNIMPLEMENTED_MSG("Unhandled XMAD mode: {}",
- static_cast<u32>(instr.xmad.mode.Value()));
- }
+ if (i + 1 == meta->coords_count) {
+ expr += ')';
}
-
- std::string sum{'(' + product + " + " + op_c + ')'};
- if (is_merge) {
- sum = "((" + sum + " & 0xFFFF) | (" + src2 + "<< 16))";
+ if (i + 1 < count) {
+ expr += ", ";
}
-
- regs.SetRegisterToInteger(instr.gpr0, is_signed, 0, sum, 1, 1);
- break;
}
- default: {
- switch (opcode->get().GetId()) {
- case OpCode::Id::EXIT: {
- const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
- UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
- "EXIT condition code used: {}", static_cast<u32>(cc));
-
- if (stage == Maxwell3D::Regs::ShaderStage::Fragment) {
- EmitFragmentOutputsWrite();
- }
-
- switch (instr.flow.cond) {
- case Tegra::Shader::FlowCondition::Always:
- shader.AddLine("return true;");
- if (instr.pred.pred_index == static_cast<u64>(Pred::UnusedIndex)) {
- // If this is an unconditional exit then just end processing here,
- // otherwise we have to account for the possibility of the condition
- // not being met, so continue processing the next instruction.
- offset = PROGRAM_END - 1;
- }
- break;
-
- case Tegra::Shader::FlowCondition::Fcsm_Tr:
- // TODO(bunnei): What is this used for? If we assume this conditon is not
- // satisifed, dual vertex shaders in Farming Simulator make more sense
- UNIMPLEMENTED_MSG("Skipping unknown FlowCondition::Fcsm_Tr");
- break;
-
- default:
- UNIMPLEMENTED_MSG("Unhandled flow condition: {}",
- static_cast<u32>(instr.flow.cond.Value()));
- }
- break;
- }
- case OpCode::Id::KIL: {
- UNIMPLEMENTED_IF(instr.flow.cond != Tegra::Shader::FlowCondition::Always);
-
- const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
- UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
- "KIL condition code used: {}", static_cast<u32>(cc));
+ expr += ')';
+ return expr + GetSwizzle(meta->element);
+ }
- // Enclose "discard" in a conditional, so that GLSL compilation does not complain
- // about unexecuted instructions that may follow this.
- shader.AddLine("if (true) {");
- ++shader.scope;
- shader.AddLine("discard;");
- --shader.scope;
- shader.AddLine("}");
+ std::string Branch(Operation operation) {
+ const auto target = std::get_if<ImmediateNode>(operation[0]);
+ UNIMPLEMENTED_IF(!target);
- break;
- }
- case OpCode::Id::OUT_R: {
- UNIMPLEMENTED_IF_MSG(instr.gpr20.Value() != Register::ZeroIndex,
- "Stream buffer is not supported");
- ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
- "OUT is expected to be used in a geometry shader.");
-
- if (instr.out.emit) {
- // gpr0 is used to store the next address. Hardware returns a pointer but
- // we just return the next index with a cyclic cap.
- const std::string current{regs.GetRegisterAsInteger(instr.gpr8, 0, false)};
- const std::string next = "((" + current + " + 1" + ") % " +
- std::to_string(MAX_GEOMETRY_BUFFERS) + ')';
- shader.AddLine("emit_vertex(" + current + ");");
- regs.SetRegisterToInteger(instr.gpr0, false, 0, next, 1, 1);
- }
- if (instr.out.cut) {
- shader.AddLine("EndPrimitive();");
- }
+ code.AddLine(fmt::format("jmp_to = 0x{:x}u;", target->GetValue()));
+ code.AddLine("break;");
+ return {};
+ }
- break;
- }
- case OpCode::Id::MOV_SYS: {
- switch (instr.sys20) {
- case Tegra::Shader::SystemVariable::InvocationInfo: {
- LOG_WARNING(HW_GPU, "MOV_SYS instruction with InvocationInfo is incomplete");
- regs.SetRegisterToInteger(instr.gpr0, false, 0, "0u", 1, 1);
- break;
- }
- case Tegra::Shader::SystemVariable::Ydirection: {
- // Config pack's third value is Y_NEGATE's state.
- regs.SetRegisterToFloat(instr.gpr0, 0, "uintBitsToFloat(config_pack[2])", 1, 1);
- break;
- }
- default: {
- UNIMPLEMENTED_MSG("Unhandled system move: {}",
- static_cast<u32>(instr.sys20.Value()));
- }
- }
- break;
- }
- case OpCode::Id::ISBERD: {
- UNIMPLEMENTED_IF(instr.isberd.o != 0);
- UNIMPLEMENTED_IF(instr.isberd.skew != 0);
- UNIMPLEMENTED_IF(instr.isberd.shift != Tegra::Shader::IsberdShift::None);
- UNIMPLEMENTED_IF(instr.isberd.mode != Tegra::Shader::IsberdMode::None);
- ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
- "ISBERD is expected to be used in a geometry shader.");
- LOG_WARNING(HW_GPU, "ISBERD instruction is incomplete");
- regs.SetRegisterToFloat(instr.gpr0, 0, regs.GetRegisterAsFloat(instr.gpr8), 1, 1);
- break;
- }
- case OpCode::Id::BRA: {
- UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
- "BRA with constant buffers are not implemented");
-
- const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
- const u32 target = offset + instr.bra.GetBranchTarget();
- if (cc != Tegra::Shader::ConditionCode::T) {
- const std::string condition_code = regs.GetConditionCode(cc);
- shader.AddLine("if (" + condition_code + "){");
- shader.scope++;
- shader.AddLine("{ jmp_to = " + std::to_string(target) + "u; break; }");
- shader.scope--;
- shader.AddLine('}');
- } else {
- shader.AddLine("{ jmp_to = " + std::to_string(target) + "u; break; }");
- }
- break;
- }
- case OpCode::Id::IPA: {
- const auto& attribute = instr.attribute.fmt28;
- const auto& reg = instr.gpr0;
+ std::string PushFlowStack(Operation operation) {
+ const auto target = std::get_if<ImmediateNode>(operation[0]);
+ UNIMPLEMENTED_IF(!target);
- Tegra::Shader::IpaMode input_mode{instr.ipa.interp_mode.Value(),
- instr.ipa.sample_mode.Value()};
- regs.SetRegisterToInputAttibute(reg, attribute.element, attribute.index,
- input_mode);
+ code.AddLine(fmt::format("flow_stack[flow_stack_top++] = 0x{:x}u;", target->GetValue()));
+ return {};
+ }
- if (instr.ipa.saturate) {
- regs.SetRegisterToFloat(reg, 0, regs.GetRegisterAsFloat(reg), 1, 1, true);
- }
- break;
- }
- case OpCode::Id::SSY: {
- // The SSY opcode tells the GPU where to re-converge divergent execution paths, it
- // sets the target of the jump that the SYNC instruction will make. The SSY opcode
- // has a similar structure to the BRA opcode.
- UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
- "Constant buffer flow is not supported");
-
- const u32 target = offset + instr.bra.GetBranchTarget();
- EmitPushToFlowStack(target);
- break;
- }
- case OpCode::Id::PBK: {
- // PBK pushes to a stack the address where BRK will jump to. This shares stack with
- // SSY but using SYNC on a PBK address will kill the shader execution. We don't
- // emulate this because it's very unlikely a driver will emit such invalid shader.
- UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
- "Constant buffer PBK is not supported");
-
- const u32 target = offset + instr.bra.GetBranchTarget();
- EmitPushToFlowStack(target);
- break;
- }
- case OpCode::Id::SYNC: {
- const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
- UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
- "SYNC condition code used: {}", static_cast<u32>(cc));
+ std::string PopFlowStack(Operation operation) {
+ code.AddLine("jmp_to = flow_stack[--flow_stack_top];");
+ code.AddLine("break;");
+ return {};
+ }
- // The SYNC opcode jumps to the address previously set by the SSY opcode
- EmitPopFromFlowStack();
- break;
+ std::string Exit(Operation operation) {
+ if (stage != ShaderStage::Fragment) {
+ code.AddLine("return;");
+ return {};
+ }
+ const auto& used_registers = ir.GetRegisters();
+ const auto SafeGetRegister = [&](u32 reg) -> std::string {
+ // TODO(Rodrigo): Replace with contains once C++20 releases
+ if (used_registers.find(reg) != used_registers.end()) {
+ return GetRegister(reg);
}
- case OpCode::Id::BRK: {
- // The BRK opcode jumps to the address previously set by the PBK opcode
- const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
- UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
- "BRK condition code used: {}", static_cast<u32>(cc));
+ return "0.0f";
+ };
- EmitPopFromFlowStack();
- break;
- }
- case OpCode::Id::DEPBAR: {
- // TODO(Subv): Find out if we actually have to care about this instruction or if
- // the GLSL compiler takes care of that for us.
- LOG_WARNING(HW_GPU, "DEPBAR instruction is stubbed");
- break;
- }
- case OpCode::Id::VMAD: {
- UNIMPLEMENTED_IF_MSG(instr.generates_cc,
- "Condition codes generation in VMAD is not implemented");
-
- const bool result_signed = instr.video.signed_a == 1 || instr.video.signed_b == 1;
- const std::string op_a = GetVideoOperandA(instr);
- const std::string op_b = GetVideoOperandB(instr);
- const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39, 0, result_signed);
-
- std::string result = '(' + op_a + " * " + op_b + " + " + op_c + ')';
-
- switch (instr.vmad.shr) {
- case Tegra::Shader::VmadShr::Shr7:
- result = '(' + result + " >> 7)";
- break;
- case Tegra::Shader::VmadShr::Shr15:
- result = '(' + result + " >> 15)";
- break;
- }
+ UNIMPLEMENTED_IF_MSG(header.ps.omap.sample_mask != 0, "Sample mask write is unimplemented");
- regs.SetRegisterToInteger(instr.gpr0, result_signed, 1, result, 1, 1,
- instr.vmad.saturate == 1, 0, Register::Size::Word,
- instr.vmad.cc);
- break;
+ code.AddLine("if (alpha_test[0] != 0) {");
+ ++code.scope;
+ // We start on the register containing the alpha value in the first RT.
+ u32 current_reg = 3;
+ for (u32 render_target = 0; render_target < Maxwell::NumRenderTargets; ++render_target) {
+ // TODO(Blinkhawk): verify the behavior of alpha testing on hardware when
+ // multiple render targets are used.
+ if (header.ps.IsColorComponentOutputEnabled(render_target, 0) ||
+ header.ps.IsColorComponentOutputEnabled(render_target, 1) ||
+ header.ps.IsColorComponentOutputEnabled(render_target, 2) ||
+ header.ps.IsColorComponentOutputEnabled(render_target, 3)) {
+ code.AddLine(
+ fmt::format("if (!AlphaFunc({})) discard;", SafeGetRegister(current_reg)));
+ current_reg += 4;
}
- case OpCode::Id::VSETP: {
- const std::string op_a = GetVideoOperandA(instr);
- const std::string op_b = GetVideoOperandB(instr);
-
- // We can't use the constant predicate as destination.
- ASSERT(instr.vsetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
-
- const std::string second_pred = GetPredicateCondition(instr.vsetp.pred39, false);
-
- const std::string combiner = GetPredicateCombiner(instr.vsetp.op);
-
- const std::string predicate = GetPredicateComparison(instr.vsetp.cond, op_a, op_b);
- // Set the primary predicate to the result of Predicate OP SecondPredicate
- SetPredicate(instr.vsetp.pred3,
- '(' + predicate + ") " + combiner + " (" + second_pred + ')');
+ }
+ --code.scope;
+ code.AddLine('}');
- if (instr.vsetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
- // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
- // if enabled
- SetPredicate(instr.vsetp.pred0,
- "!(" + predicate + ") " + combiner + " (" + second_pred + ')');
+ // Write the color outputs using the data in the shader registers, disabled
+ // rendertargets/components are skipped in the register assignment.
+ current_reg = 0;
+ for (u32 render_target = 0; render_target < Maxwell::NumRenderTargets; ++render_target) {
+ // TODO(Subv): Figure out how dual-source blending is configured in the Switch.
+ for (u32 component = 0; component < 4; ++component) {
+ if (header.ps.IsColorComponentOutputEnabled(render_target, component)) {
+ code.AddLine(fmt::format("FragColor{}[{}] = {};", render_target, component,
+ SafeGetRegister(current_reg)));
+ ++current_reg;
}
- break;
- }
- default: { UNIMPLEMENTED_MSG("Unhandled instruction: {}", opcode->get().GetName()); }
}
-
- break;
- }
}
- // Close the predicate condition scope.
- if (can_be_predicated && instr.pred.pred_index != static_cast<u64>(Pred::UnusedIndex)) {
- --shader.scope;
- shader.AddLine('}');
+ if (header.ps.omap.depth) {
+ // The depth output is always 2 registers after the last color output, and current_reg
+ // already contains one past the last color register.
+ code.AddLine("gl_FragDepth = " + SafeGetRegister(current_reg + 1) + ';');
}
- return offset + 1;
+ code.AddLine("return;");
+ return {};
}
- /**
- * Compiles a range of instructions from Tegra to GLSL.
- * @param begin the offset of the starting instruction.
- * @param end the offset where the compilation should stop (exclusive).
- * @return the offset of the next instruction to compile. PROGRAM_END if the program
- * terminates.
- */
- u32 CompileRange(u32 begin, u32 end) {
- u32 program_counter;
- for (program_counter = begin; program_counter < (begin > end ? PROGRAM_END : end);) {
- program_counter = CompileInstr(program_counter);
- }
- return program_counter;
+ std::string Discard(Operation operation) {
+ // Enclose "discard" in a conditional, so that GLSL compilation does not complain
+ // about unexecuted instructions that may follow this.
+ code.AddLine("if (true) {");
+ ++code.scope;
+ code.AddLine("discard;");
+ --code.scope;
+ code.AddLine("}");
+ return {};
}
- void Generate(const std::string& suffix) {
- // Add declarations for all subroutines
- for (const auto& subroutine : subroutines) {
- shader.AddLine("bool " + subroutine.GetName() + "();");
- }
- shader.AddNewLine();
-
- // Add the main entry point
- shader.AddLine("bool exec_" + suffix + "() {");
- ++shader.scope;
- CallSubroutine(GetSubroutine(main_offset, PROGRAM_END));
- --shader.scope;
- shader.AddLine("}\n");
+ std::string EmitVertex(Operation operation) {
+ ASSERT_MSG(stage == ShaderStage::Geometry,
+ "EmitVertex is expected to be used in a geometry shader.");
- // Add definitions for all subroutines
- for (const auto& subroutine : subroutines) {
- std::set<u32> labels = subroutine.labels;
-
- shader.AddLine("bool " + subroutine.GetName() + "() {");
- ++shader.scope;
-
- if (labels.empty()) {
- if (CompileRange(subroutine.begin, subroutine.end) != PROGRAM_END) {
- shader.AddLine("return false;");
- }
- } else {
- labels.insert(subroutine.begin);
- shader.AddLine("uint jmp_to = " + std::to_string(subroutine.begin) + "u;");
-
- // TODO(Subv): Figure out the actual depth of the flow stack, for now it seems
- // unlikely that shaders will use 20 nested SSYs and PBKs.
- constexpr u32 FLOW_STACK_SIZE = 20;
- shader.AddLine("uint flow_stack[" + std::to_string(FLOW_STACK_SIZE) + "];");
- shader.AddLine("uint flow_stack_top = 0u;");
-
- shader.AddLine("while (true) {");
- ++shader.scope;
+ // If a geometry shader is attached, it will always flip (it's the last stage before
+ // fragment). For more info about flipping, refer to gl_shader_gen.cpp.
+ code.AddLine("position.xy *= viewport_flip.xy;");
+ code.AddLine("gl_Position = position;");
+ code.AddLine("position.w = 1.0;");
+ code.AddLine("EmitVertex();");
+ return {};
+ }
+
+ std::string EndPrimitive(Operation operation) {
+ ASSERT_MSG(stage == ShaderStage::Geometry,
+ "EndPrimitive is expected to be used in a geometry shader.");
+
+ code.AddLine("EndPrimitive();");
+ return {};
+ }
+
+ std::string YNegate(Operation operation) {
+ // Config pack's third value is Y_NEGATE's state.
+ return "uintBitsToFloat(config_pack[2])";
+ }
+
+ static constexpr OperationDecompilersArray operation_decompilers = {
+ &GLSLDecompiler::Assign,
+
+ &GLSLDecompiler::Select,
+
+ &GLSLDecompiler::Add<Type::Float>,
+ &GLSLDecompiler::Mul<Type::Float>,
+ &GLSLDecompiler::Div<Type::Float>,
+ &GLSLDecompiler::Fma<Type::Float>,
+ &GLSLDecompiler::Negate<Type::Float>,
+ &GLSLDecompiler::Absolute<Type::Float>,
+ &GLSLDecompiler::FClamp,
+ &GLSLDecompiler::Min<Type::Float>,
+ &GLSLDecompiler::Max<Type::Float>,
+ &GLSLDecompiler::FCos,
+ &GLSLDecompiler::FSin,
+ &GLSLDecompiler::FExp2,
+ &GLSLDecompiler::FLog2,
+ &GLSLDecompiler::FInverseSqrt,
+ &GLSLDecompiler::FSqrt,
+ &GLSLDecompiler::FRoundEven,
+ &GLSLDecompiler::FFloor,
+ &GLSLDecompiler::FCeil,
+ &GLSLDecompiler::FTrunc,
+ &GLSLDecompiler::FCastInteger<Type::Int>,
+ &GLSLDecompiler::FCastInteger<Type::Uint>,
+
+ &GLSLDecompiler::Add<Type::Int>,
+ &GLSLDecompiler::Mul<Type::Int>,
+ &GLSLDecompiler::Div<Type::Int>,
+ &GLSLDecompiler::Negate<Type::Int>,
+ &GLSLDecompiler::Absolute<Type::Int>,
+ &GLSLDecompiler::Min<Type::Int>,
+ &GLSLDecompiler::Max<Type::Int>,
+
+ &GLSLDecompiler::ICastFloat,
+ &GLSLDecompiler::ICastUnsigned,
+ &GLSLDecompiler::LogicalShiftLeft<Type::Int>,
+ &GLSLDecompiler::ILogicalShiftRight,
+ &GLSLDecompiler::IArithmeticShiftRight,
+ &GLSLDecompiler::BitwiseAnd<Type::Int>,
+ &GLSLDecompiler::BitwiseOr<Type::Int>,
+ &GLSLDecompiler::BitwiseXor<Type::Int>,
+ &GLSLDecompiler::BitwiseNot<Type::Int>,
+ &GLSLDecompiler::BitfieldInsert<Type::Int>,
+ &GLSLDecompiler::BitfieldExtract<Type::Int>,
+ &GLSLDecompiler::BitCount<Type::Int>,
+
+ &GLSLDecompiler::Add<Type::Uint>,
+ &GLSLDecompiler::Mul<Type::Uint>,
+ &GLSLDecompiler::Div<Type::Uint>,
+ &GLSLDecompiler::Min<Type::Uint>,
+ &GLSLDecompiler::Max<Type::Uint>,
+ &GLSLDecompiler::UCastFloat,
+ &GLSLDecompiler::UCastSigned,
+ &GLSLDecompiler::LogicalShiftLeft<Type::Uint>,
+ &GLSLDecompiler::UShiftRight,
+ &GLSLDecompiler::UShiftRight,
+ &GLSLDecompiler::BitwiseAnd<Type::Uint>,
+ &GLSLDecompiler::BitwiseOr<Type::Uint>,
+ &GLSLDecompiler::BitwiseXor<Type::Uint>,
+ &GLSLDecompiler::BitwiseNot<Type::Uint>,
+ &GLSLDecompiler::BitfieldInsert<Type::Uint>,
+ &GLSLDecompiler::BitfieldExtract<Type::Uint>,
+ &GLSLDecompiler::BitCount<Type::Uint>,
+
+ &GLSLDecompiler::Add<Type::HalfFloat>,
+ &GLSLDecompiler::Mul<Type::HalfFloat>,
+ &GLSLDecompiler::Fma<Type::HalfFloat>,
+ &GLSLDecompiler::Absolute<Type::HalfFloat>,
+ &GLSLDecompiler::HNegate,
+ &GLSLDecompiler::HMergeF32,
+ &GLSLDecompiler::HMergeH0,
+ &GLSLDecompiler::HMergeH1,
+ &GLSLDecompiler::HPack2,
+
+ &GLSLDecompiler::LogicalAssign,
+ &GLSLDecompiler::LogicalAnd,
+ &GLSLDecompiler::LogicalOr,
+ &GLSLDecompiler::LogicalXor,
+ &GLSLDecompiler::LogicalNegate,
+ &GLSLDecompiler::LogicalPick2,
+ &GLSLDecompiler::LogicalAll2,
+ &GLSLDecompiler::LogicalAny2,
+
+ &GLSLDecompiler::LogicalLessThan<Type::Float>,
+ &GLSLDecompiler::LogicalEqual<Type::Float>,
+ &GLSLDecompiler::LogicalLessEqual<Type::Float>,
+ &GLSLDecompiler::LogicalGreaterThan<Type::Float>,
+ &GLSLDecompiler::LogicalNotEqual<Type::Float>,
+ &GLSLDecompiler::LogicalGreaterEqual<Type::Float>,
+ &GLSLDecompiler::LogicalFIsNan,
+
+ &GLSLDecompiler::LogicalLessThan<Type::Int>,
+ &GLSLDecompiler::LogicalEqual<Type::Int>,
+ &GLSLDecompiler::LogicalLessEqual<Type::Int>,
+ &GLSLDecompiler::LogicalGreaterThan<Type::Int>,
+ &GLSLDecompiler::LogicalNotEqual<Type::Int>,
+ &GLSLDecompiler::LogicalGreaterEqual<Type::Int>,
+
+ &GLSLDecompiler::LogicalLessThan<Type::Uint>,
+ &GLSLDecompiler::LogicalEqual<Type::Uint>,
+ &GLSLDecompiler::LogicalLessEqual<Type::Uint>,
+ &GLSLDecompiler::LogicalGreaterThan<Type::Uint>,
+ &GLSLDecompiler::LogicalNotEqual<Type::Uint>,
+ &GLSLDecompiler::LogicalGreaterEqual<Type::Uint>,
+
+ &GLSLDecompiler::Logical2HLessThan,
+ &GLSLDecompiler::Logical2HEqual,
+ &GLSLDecompiler::Logical2HLessEqual,
+ &GLSLDecompiler::Logical2HGreaterThan,
+ &GLSLDecompiler::Logical2HNotEqual,
+ &GLSLDecompiler::Logical2HGreaterEqual,
+
+ &GLSLDecompiler::F4Texture,
+ &GLSLDecompiler::F4TextureLod,
+ &GLSLDecompiler::F4TextureGather,
+ &GLSLDecompiler::F4TextureQueryDimensions,
+ &GLSLDecompiler::F4TextureQueryLod,
+ &GLSLDecompiler::F4TexelFetch,
+
+ &GLSLDecompiler::Branch,
+ &GLSLDecompiler::PushFlowStack,
+ &GLSLDecompiler::PopFlowStack,
+ &GLSLDecompiler::Exit,
+ &GLSLDecompiler::Discard,
+
+ &GLSLDecompiler::EmitVertex,
+ &GLSLDecompiler::EndPrimitive,
+
+ &GLSLDecompiler::YNegate,
+ };
- shader.AddLine("switch (jmp_to) {");
+ std::string GetRegister(u32 index) const {
+ return GetDeclarationWithSuffix(index, "gpr");
+ }
- for (auto label : labels) {
- shader.AddLine("case " + std::to_string(label) + "u: {");
- ++shader.scope;
+ std::string GetPredicate(Tegra::Shader::Pred pred) const {
+ return GetDeclarationWithSuffix(static_cast<u32>(pred), "pred");
+ }
- const auto next_it = labels.lower_bound(label + 1);
- const u32 next_label = next_it == labels.end() ? subroutine.end : *next_it;
+ std::string GetInputAttribute(Attribute::Index attribute) const {
+ const auto index{static_cast<u32>(attribute) -
+ static_cast<u32>(Attribute::Index::Attribute_0)};
+ return GetDeclarationWithSuffix(index, "input_attr");
+ }
- const u32 compile_end = CompileRange(label, next_label);
- if (compile_end > next_label && compile_end != PROGRAM_END) {
- // This happens only when there is a label inside a IF/LOOP block
- shader.AddLine(" jmp_to = " + std::to_string(compile_end) + "u; break; }");
- labels.emplace(compile_end);
- }
+ std::string GetOutputAttribute(Attribute::Index attribute) const {
+ const auto index{static_cast<u32>(attribute) -
+ static_cast<u32>(Attribute::Index::Attribute_0)};
+ return GetDeclarationWithSuffix(index, "output_attr");
+ }
- --shader.scope;
- shader.AddLine('}');
- }
+ std::string GetConstBuffer(u32 index) const {
+ return GetDeclarationWithSuffix(index, "cbuf");
+ }
- shader.AddLine("default: return false;");
- shader.AddLine('}');
+ std::string GetGlobalMemory(const GlobalMemoryBase& descriptor) const {
+ return fmt::format("gmem_{}_{}_{}", descriptor.cbuf_index, descriptor.cbuf_offset, suffix);
+ }
- --shader.scope;
- shader.AddLine('}');
+ std::string GetGlobalMemoryBlock(const GlobalMemoryBase& descriptor) const {
+ return fmt::format("gmem_block_{}_{}_{}", descriptor.cbuf_index, descriptor.cbuf_offset,
+ suffix);
+ }
- shader.AddLine("return false;");
- }
+ std::string GetConstBufferBlock(u32 index) const {
+ return GetDeclarationWithSuffix(index, "cbuf_block");
+ }
- --shader.scope;
- shader.AddLine("}\n");
+ std::string GetLocalMemory() const {
+ return "lmem_" + suffix;
+ }
- DEBUG_ASSERT(shader.scope == 0);
- }
+ std::string GetInternalFlag(InternalFlag flag) const {
+ constexpr std::array<const char*, 4> InternalFlagNames = {"zero_flag", "sign_flag",
+ "carry_flag", "overflow_flag"};
+ const auto index = static_cast<u32>(flag);
+ ASSERT(index < static_cast<u32>(InternalFlag::Amount));
- GenerateDeclarations();
+ return std::string(InternalFlagNames[index]) + '_' + suffix;
}
- /// Add declarations for registers
- void GenerateDeclarations() {
- regs.GenerateDeclarations(suffix);
+ std::string GetSampler(const Sampler& sampler) const {
+ return GetDeclarationWithSuffix(static_cast<u32>(sampler.GetIndex()), "sampler");
+ }
- for (const auto& pred : declr_predicates) {
- declarations.AddLine("bool " + pred + " = false;");
- }
- declarations.AddNewLine();
+ std::string GetDeclarationWithSuffix(u32 index, const std::string& name) const {
+ return name + '_' + std::to_string(index) + '_' + suffix;
}
-private:
- const std::set<Subroutine>& subroutines;
- const ProgramCode& program_code;
- Tegra::Shader::Header header;
- const u32 main_offset;
- Maxwell3D::Regs::ShaderStage stage;
- const std::string& suffix;
- u64 local_memory_size;
- std::size_t shader_length;
-
- ShaderWriter shader;
- ShaderWriter declarations;
- GLSLRegisterManager regs{shader, declarations, stage, suffix, header};
-
- // Declarations
- std::set<std::string> declr_predicates;
-}; // namespace OpenGL::GLShader::Decompiler
+ const ShaderIR& ir;
+ const ShaderStage stage;
+ const std::string suffix;
+ const Header header;
+
+ ShaderWriter code;
+};
std::string GetCommonDeclarations() {
- return fmt::format("#define MAX_CONSTBUFFER_ELEMENTS {}\n",
- RasterizerOpenGL::MaxConstbufferSize / sizeof(GLvec4));
+ const auto cbuf = std::to_string(MAX_CONSTBUFFER_ELEMENTS);
+ const auto gmem = std::to_string(MAX_GLOBALMEMORY_ELEMENTS);
+ return "#define MAX_CONSTBUFFER_ELEMENTS " + cbuf + "\n" +
+ "#define MAX_GLOBALMEMORY_ELEMENTS " + gmem + "\n" +
+ "#define ftoi floatBitsToInt\n"
+ "#define ftou floatBitsToUint\n"
+ "#define itof intBitsToFloat\n"
+ "#define utof uintBitsToFloat\n\n"
+ "float fromHalf2(vec2 pair) {\n"
+ " return utof(packHalf2x16(pair));\n"
+ "}\n\n"
+ "vec2 toHalf2(float value) {\n"
+ " return unpackHalf2x16(ftou(value));\n"
+ "}\n";
}
-std::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset,
- Maxwell3D::Regs::ShaderStage stage,
- const std::string& suffix) {
- try {
- ControlFlowAnalyzer analyzer(program_code, main_offset, suffix);
- const auto subroutines = analyzer.GetSubroutines();
- GLSLGenerator generator(subroutines, program_code, main_offset, stage, suffix,
- analyzer.GetShaderLength());
- return ProgramResult{generator.GetShaderCode(), generator.GetEntries()};
- } catch (const DecompileFail& exception) {
- LOG_ERROR(HW_GPU, "Shader decompilation failed: {}", exception.what());
- }
- return {};
+ProgramResult Decompile(const ShaderIR& ir, Maxwell::ShaderStage stage, const std::string& suffix) {
+ GLSLDecompiler decompiler(ir, stage, suffix);
+ decompiler.Decompile();
+ return {decompiler.GetResult(), decompiler.GetShaderEntries()};
}
-} // namespace OpenGL::GLShader::Decompiler
+} // namespace OpenGL::GLShader \ No newline at end of file
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.h b/src/video_core/renderer_opengl/gl_shader_decompiler.h
index d01a4a7ee..0856a1361 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.h
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.h
@@ -5,21 +5,106 @@
#pragma once
#include <array>
-#include <functional>
-#include <optional>
#include <string>
+#include <utility>
+#include <vector>
#include "common/common_types.h"
#include "video_core/engines/maxwell_3d.h"
-#include "video_core/renderer_opengl/gl_shader_gen.h"
+#include "video_core/shader/shader_ir.h"
-namespace OpenGL::GLShader::Decompiler {
+namespace VideoCommon::Shader {
+class ShaderIR;
+}
-using Tegra::Engines::Maxwell3D;
+namespace OpenGL::GLShader {
+
+using Maxwell = Tegra::Engines::Maxwell3D::Regs;
+
+class ConstBufferEntry : public VideoCommon::Shader::ConstBuffer {
+public:
+ explicit ConstBufferEntry(const VideoCommon::Shader::ConstBuffer& entry,
+ Maxwell::ShaderStage stage, const std::string& name, u32 index)
+ : VideoCommon::Shader::ConstBuffer{entry}, stage{stage}, name{name}, index{index} {}
+
+ const std::string& GetName() const {
+ return name;
+ }
+
+ Maxwell::ShaderStage GetStage() const {
+ return stage;
+ }
+
+ u32 GetIndex() const {
+ return index;
+ }
+
+private:
+ std::string name;
+ Maxwell::ShaderStage stage{};
+ u32 index{};
+};
+
+class SamplerEntry : public VideoCommon::Shader::Sampler {
+public:
+ explicit SamplerEntry(const VideoCommon::Shader::Sampler& entry, Maxwell::ShaderStage stage,
+ const std::string& name)
+ : VideoCommon::Shader::Sampler{entry}, stage{stage}, name{name} {}
+
+ const std::string& GetName() const {
+ return name;
+ }
+
+ Maxwell::ShaderStage GetStage() const {
+ return stage;
+ }
+
+private:
+ std::string name;
+ Maxwell::ShaderStage stage{};
+};
+
+class GlobalMemoryEntry {
+public:
+ explicit GlobalMemoryEntry(u32 cbuf_index, u32 cbuf_offset, Maxwell::ShaderStage stage,
+ std::string name)
+ : cbuf_index{cbuf_index}, cbuf_offset{cbuf_offset}, stage{stage}, name{std::move(name)} {}
+
+ u32 GetCbufIndex() const {
+ return cbuf_index;
+ }
+
+ u32 GetCbufOffset() const {
+ return cbuf_offset;
+ }
+
+ const std::string& GetName() const {
+ return name;
+ }
+
+ Maxwell::ShaderStage GetStage() const {
+ return stage;
+ }
+
+private:
+ u32 cbuf_index{};
+ u32 cbuf_offset{};
+ Maxwell::ShaderStage stage{};
+ std::string name;
+};
+
+struct ShaderEntries {
+ std::vector<ConstBufferEntry> const_buffers;
+ std::vector<SamplerEntry> samplers;
+ std::vector<GlobalMemoryEntry> global_memory_entries;
+ std::array<bool, Maxwell::NumClipDistances> clip_distances{};
+ std::size_t shader_length{};
+};
+
+using ProgramResult = std::pair<std::string, ShaderEntries>;
std::string GetCommonDeclarations();
-std::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u32 main_offset,
- Maxwell3D::Regs::ShaderStage stage,
- const std::string& suffix);
+ProgramResult Decompile(const VideoCommon::Shader::ShaderIR& ir, Maxwell::ShaderStage stage,
+ const std::string& suffix);
-} // namespace OpenGL::GLShader::Decompiler
+} // namespace OpenGL::GLShader \ No newline at end of file
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp
index 23ed91e27..04e1db911 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp
@@ -2,65 +2,62 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <fmt/format.h>
#include "common/assert.h"
#include "video_core/engines/maxwell_3d.h"
#include "video_core/renderer_opengl/gl_shader_decompiler.h"
#include "video_core/renderer_opengl/gl_shader_gen.h"
+#include "video_core/shader/shader_ir.h"
namespace OpenGL::GLShader {
using Tegra::Engines::Maxwell3D;
+using VideoCommon::Shader::ProgramCode;
+using VideoCommon::Shader::ShaderIR;
static constexpr u32 PROGRAM_OFFSET{10};
ProgramResult GenerateVertexShader(const ShaderSetup& setup) {
- std::string out = "#version 430 core\n";
- out += "#extension GL_ARB_separate_shader_objects : enable\n\n";
- out += Decompiler::GetCommonDeclarations();
+ const std::string id = fmt::format("{:016x}", setup.program.unique_identifier);
- out += R"(
+ std::string out = "#extension GL_ARB_separate_shader_objects : enable\n\n";
+ out += "// Shader Unique Id: VS" + id + "\n\n";
+ out += GetCommonDeclarations();
+ out += R"(
layout (location = 0) out vec4 position;
-layout(std140) uniform vs_config {
+layout (std140, binding = EMULATION_UBO_BINDING) uniform vs_config {
vec4 viewport_flip;
uvec4 config_pack; // instance_id, flip_stage, y_direction, padding
uvec4 alpha_test;
};
-)";
-
- if (setup.IsDualProgram()) {
- out += "bool exec_vertex_b();\n";
- }
- ProgramResult program =
- Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
- Maxwell3D::Regs::ShaderStage::Vertex, "vertex")
- .value_or(ProgramResult());
+)";
+ ShaderIR program_ir(setup.program.code, PROGRAM_OFFSET);
+ ProgramResult program = Decompile(program_ir, Maxwell3D::Regs::ShaderStage::Vertex, "vertex");
out += program.first;
if (setup.IsDualProgram()) {
+ ShaderIR program_ir_b(setup.program.code_b, PROGRAM_OFFSET);
ProgramResult program_b =
- Decompiler::DecompileProgram(setup.program.code_b, PROGRAM_OFFSET,
- Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b")
- .value_or(ProgramResult());
+ Decompile(program_ir_b, Maxwell3D::Regs::ShaderStage::Vertex, "vertex_b");
+
out += program_b.first;
}
out += R"(
-
void main() {
position = vec4(0.0, 0.0, 0.0, 0.0);
- exec_vertex();
+ execute_vertex();
)";
if (setup.IsDualProgram()) {
- out += " exec_vertex_b();";
+ out += " execute_vertex_b();";
}
out += R"(
-
// Check if the flip stage is VertexB
// Config pack's second value is flip_stage
if (config_pack[1] == 1) {
@@ -74,69 +71,62 @@ void main() {
if (config_pack[1] == 1) {
position.w = 1.0;
}
-}
-
-)";
+})";
return {out, program.second};
}
ProgramResult GenerateGeometryShader(const ShaderSetup& setup) {
- // Version is intentionally skipped in shader generation, it's added by the lazy compilation.
+ const std::string id = fmt::format("{:016x}", setup.program.unique_identifier);
+
std::string out = "#extension GL_ARB_separate_shader_objects : enable\n\n";
- out += Decompiler::GetCommonDeclarations();
- out += "bool exec_geometry();\n";
+ out += "// Shader Unique Id: GS" + id + "\n\n";
+ out += GetCommonDeclarations();
- ProgramResult program =
- Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
- Maxwell3D::Regs::ShaderStage::Geometry, "geometry")
- .value_or(ProgramResult());
out += R"(
-out gl_PerVertex {
- vec4 gl_Position;
-};
-
layout (location = 0) in vec4 gs_position[];
layout (location = 0) out vec4 position;
-layout (std140) uniform gs_config {
+layout (std140, binding = EMULATION_UBO_BINDING) uniform gs_config {
vec4 viewport_flip;
uvec4 config_pack; // instance_id, flip_stage, y_direction, padding
uvec4 alpha_test;
};
-void main() {
- exec_geometry();
-}
-
)";
+ ShaderIR program_ir(setup.program.code, PROGRAM_OFFSET);
+ ProgramResult program =
+ Decompile(program_ir, Maxwell3D::Regs::ShaderStage::Geometry, "geometry");
out += program.first;
+
+ out += R"(
+void main() {
+ execute_geometry();
+};)";
+
return {out, program.second};
}
ProgramResult GenerateFragmentShader(const ShaderSetup& setup) {
- std::string out = "#version 430 core\n";
- out += "#extension GL_ARB_separate_shader_objects : enable\n\n";
- out += Decompiler::GetCommonDeclarations();
- out += "bool exec_fragment();\n";
+ const std::string id = fmt::format("{:016x}", setup.program.unique_identifier);
+
+ std::string out = "#extension GL_ARB_separate_shader_objects : enable\n\n";
+ out += "// Shader Unique Id: FS" + id + "\n\n";
+ out += GetCommonDeclarations();
- ProgramResult program =
- Decompiler::DecompileProgram(setup.program.code, PROGRAM_OFFSET,
- Maxwell3D::Regs::ShaderStage::Fragment, "fragment")
- .value_or(ProgramResult());
out += R"(
-layout(location = 0) out vec4 FragColor0;
-layout(location = 1) out vec4 FragColor1;
-layout(location = 2) out vec4 FragColor2;
-layout(location = 3) out vec4 FragColor3;
-layout(location = 4) out vec4 FragColor4;
-layout(location = 5) out vec4 FragColor5;
-layout(location = 6) out vec4 FragColor6;
-layout(location = 7) out vec4 FragColor7;
+layout (location = 0) out vec4 FragColor0;
+layout (location = 1) out vec4 FragColor1;
+layout (location = 2) out vec4 FragColor2;
+layout (location = 3) out vec4 FragColor3;
+layout (location = 4) out vec4 FragColor4;
+layout (location = 5) out vec4 FragColor5;
+layout (location = 6) out vec4 FragColor6;
+layout (location = 7) out vec4 FragColor7;
layout (location = 0) in vec4 position;
-layout (std140) uniform fs_config {
+layout (std140, binding = EMULATION_UBO_BINDING) uniform fs_config {
vec4 viewport_flip;
uvec4 config_pack; // instance_id, flip_stage, y_direction, padding
uvec4 alpha_test;
@@ -166,12 +156,20 @@ bool AlphaFunc(in float value) {
}
}
+)";
+ ShaderIR program_ir(setup.program.code, PROGRAM_OFFSET);
+ ProgramResult program =
+ Decompile(program_ir, Maxwell3D::Regs::ShaderStage::Fragment, "fragment");
+
+ out += program.first;
+
+ out += R"(
void main() {
- exec_fragment();
+ execute_fragment();
}
)";
- out += program.first;
return {out, program.second};
}
-} // namespace OpenGL::GLShader
+
+} // namespace OpenGL::GLShader \ No newline at end of file
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.h b/src/video_core/renderer_opengl/gl_shader_gen.h
index b425d98ae..ac5e6917b 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.h
+++ b/src/video_core/renderer_opengl/gl_shader_gen.h
@@ -10,163 +10,12 @@
#include "common/common_types.h"
#include "video_core/engines/shader_bytecode.h"
+#include "video_core/renderer_opengl/gl_shader_decompiler.h"
+#include "video_core/shader/shader_ir.h"
namespace OpenGL::GLShader {
-constexpr std::size_t MAX_PROGRAM_CODE_LENGTH{0x1000};
-using ProgramCode = std::vector<u64>;
-
-enum : u32 { POSITION_VARYING_LOCATION = 0, GENERIC_VARYING_START_LOCATION = 1 };
-
-class ConstBufferEntry {
- using Maxwell = Tegra::Engines::Maxwell3D::Regs;
-
-public:
- void MarkAsUsed(u64 index, u64 offset, Maxwell::ShaderStage stage) {
- is_used = true;
- this->index = static_cast<unsigned>(index);
- this->stage = stage;
- max_offset = std::max(max_offset, static_cast<unsigned>(offset));
- }
-
- void MarkAsUsedIndirect(u64 index, Maxwell::ShaderStage stage) {
- is_used = true;
- is_indirect = true;
- this->index = static_cast<unsigned>(index);
- this->stage = stage;
- }
-
- bool IsUsed() const {
- return is_used;
- }
-
- bool IsIndirect() const {
- return is_indirect;
- }
-
- unsigned GetIndex() const {
- return index;
- }
-
- unsigned GetSize() const {
- return max_offset + 1;
- }
-
- std::string GetName() const {
- return BufferBaseNames[static_cast<std::size_t>(stage)] + std::to_string(index);
- }
-
- u32 GetHash() const {
- return (static_cast<u32>(stage) << 16) | index;
- }
-
-private:
- static constexpr std::array<const char*, Maxwell::MaxShaderStage> BufferBaseNames = {
- "buffer_vs_c", "buffer_tessc_c", "buffer_tesse_c", "buffer_gs_c", "buffer_fs_c",
- };
-
- bool is_used{};
- bool is_indirect{};
- unsigned index{};
- unsigned max_offset{};
- Maxwell::ShaderStage stage;
-};
-
-class SamplerEntry {
- using Maxwell = Tegra::Engines::Maxwell3D::Regs;
-
-public:
- SamplerEntry(Maxwell::ShaderStage stage, std::size_t offset, std::size_t index,
- Tegra::Shader::TextureType type, bool is_array, bool is_shadow)
- : offset(offset), stage(stage), sampler_index(index), type(type), is_array(is_array),
- is_shadow(is_shadow) {}
-
- std::size_t GetOffset() const {
- return offset;
- }
-
- std::size_t GetIndex() const {
- return sampler_index;
- }
-
- Maxwell::ShaderStage GetStage() const {
- return stage;
- }
-
- std::string GetName() const {
- return std::string(TextureSamplerNames[static_cast<std::size_t>(stage)]) + '_' +
- std::to_string(sampler_index);
- }
-
- std::string GetTypeString() const {
- using Tegra::Shader::TextureType;
- std::string glsl_type;
-
- switch (type) {
- case TextureType::Texture1D:
- glsl_type = "sampler1D";
- break;
- case TextureType::Texture2D:
- glsl_type = "sampler2D";
- break;
- case TextureType::Texture3D:
- glsl_type = "sampler3D";
- break;
- case TextureType::TextureCube:
- glsl_type = "samplerCube";
- break;
- default:
- UNIMPLEMENTED();
- }
- if (is_array)
- glsl_type += "Array";
- if (is_shadow)
- glsl_type += "Shadow";
- return glsl_type;
- }
-
- Tegra::Shader::TextureType GetType() const {
- return type;
- }
-
- bool IsArray() const {
- return is_array;
- }
-
- bool IsShadow() const {
- return is_shadow;
- }
-
- u32 GetHash() const {
- return (static_cast<u32>(stage) << 16) | static_cast<u32>(sampler_index);
- }
-
- static std::string GetArrayName(Maxwell::ShaderStage stage) {
- return TextureSamplerNames[static_cast<std::size_t>(stage)];
- }
-
-private:
- static constexpr std::array<const char*, Maxwell::MaxShaderStage> TextureSamplerNames = {
- "tex_vs", "tex_tessc", "tex_tesse", "tex_gs", "tex_fs",
- };
-
- /// Offset in TSC memory from which to read the sampler object, as specified by the sampling
- /// instruction.
- std::size_t offset;
- Maxwell::ShaderStage stage; ///< Shader stage where this sampler was used.
- std::size_t sampler_index; ///< Value used to index into the generated GLSL sampler array.
- Tegra::Shader::TextureType type; ///< The type used to sample this texture (Texture2D, etc)
- bool is_array; ///< Whether the texture is being sampled as an array texture or not.
- bool is_shadow; ///< Whether the texture is being sampled as a depth texture or not.
-};
-
-struct ShaderEntries {
- std::vector<ConstBufferEntry> const_buffer_entries;
- std::vector<SamplerEntry> texture_samplers;
- std::size_t shader_length;
-};
-
-using ProgramResult = std::pair<std::string, ShaderEntries>;
+using VideoCommon::Shader::ProgramCode;
struct ShaderSetup {
explicit ShaderSetup(ProgramCode program_code) {
@@ -176,6 +25,9 @@ struct ShaderSetup {
struct {
ProgramCode code;
ProgramCode code_b; // Used for dual vertex shaders
+ u64 unique_identifier;
+ std::size_t real_size;
+ std::size_t real_size_b;
} program;
/// Used in scenarios where we have a dual vertex shaders
diff --git a/src/video_core/renderer_opengl/gl_shader_manager.h b/src/video_core/renderer_opengl/gl_shader_manager.h
index b757f5f44..4970aafed 100644
--- a/src/video_core/renderer_opengl/gl_shader_manager.h
+++ b/src/video_core/renderer_opengl/gl_shader_manager.h
@@ -60,6 +60,17 @@ public:
}
void ApplyTo(OpenGLState& state) {
+ UpdatePipeline();
+ state.draw.shader_program = 0;
+ state.draw.program_pipeline = pipeline.handle;
+ state.geometry_shaders.enabled = (gs != 0);
+ }
+
+private:
+ void UpdatePipeline() {
+ // Avoid updating the pipeline when values have no changed
+ if (old_vs == vs && old_fs == fs && old_gs == gs)
+ return;
// Workaround for AMD bug
glUseProgramStages(pipeline.handle,
GL_VERTEX_SHADER_BIT | GL_GEOMETRY_SHADER_BIT | GL_FRAGMENT_SHADER_BIT,
@@ -68,14 +79,16 @@ public:
glUseProgramStages(pipeline.handle, GL_VERTEX_SHADER_BIT, vs);
glUseProgramStages(pipeline.handle, GL_GEOMETRY_SHADER_BIT, gs);
glUseProgramStages(pipeline.handle, GL_FRAGMENT_SHADER_BIT, fs);
- state.draw.shader_program = 0;
- state.draw.program_pipeline = pipeline.handle;
- state.geometry_shaders.enabled = (gs != 0);
+
+ // Update the old values
+ old_vs = vs;
+ old_fs = fs;
+ old_gs = gs;
}
-private:
OGLPipeline pipeline;
GLuint vs{}, fs{}, gs{};
+ GLuint old_vs{}, old_fs{}, old_gs{};
};
} // namespace OpenGL::GLShader
diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp
index b3bfad6a0..b7ba59350 100644
--- a/src/video_core/renderer_opengl/gl_state.cpp
+++ b/src/video_core/renderer_opengl/gl_state.cpp
@@ -83,8 +83,6 @@ OpenGLState::OpenGLState() {
draw.read_framebuffer = 0;
draw.draw_framebuffer = 0;
draw.vertex_array = 0;
- draw.vertex_buffer = 0;
- draw.uniform_buffer = 0;
draw.shader_program = 0;
draw.program_pipeline = 0;
@@ -92,7 +90,8 @@ OpenGLState::OpenGLState() {
point.size = 1;
fragment_color_clamp.enabled = false;
-
+ depth_clamp.far_plane = false;
+ depth_clamp.near_plane = false;
polygon_offset.fill_enable = false;
polygon_offset.line_enable = false;
polygon_offset.point_enable = false;
@@ -147,7 +146,7 @@ void OpenGLState::ApplyCulling() const {
}
void OpenGLState::ApplyColorMask() const {
- if (GLAD_GL_ARB_viewport_array && independant_blend.enabled) {
+ if (independant_blend.enabled) {
for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
const auto& updated = color_mask[i];
const auto& current = cur_state.color_mask[i];
@@ -264,7 +263,7 @@ void OpenGLState::EmulateViewportWithScissor() {
}
void OpenGLState::ApplyViewport() const {
- if (GLAD_GL_ARB_viewport_array && geometry_shaders.enabled) {
+ if (geometry_shaders.enabled) {
for (GLuint i = 0; i < static_cast<GLuint>(Tegra::Engines::Maxwell3D::Regs::NumViewports);
i++) {
const auto& current = cur_state.viewports[i];
@@ -504,7 +503,6 @@ void OpenGLState::ApplySamplers() const {
}
void OpenGLState::ApplyFramebufferState() const {
- // Framebuffer
if (draw.read_framebuffer != cur_state.draw.read_framebuffer) {
glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer);
}
@@ -513,25 +511,30 @@ void OpenGLState::ApplyFramebufferState() const {
}
}
-void OpenGLState::ApplyVertexBufferState() const {
- // Vertex array
+void OpenGLState::ApplyVertexArrayState() const {
if (draw.vertex_array != cur_state.draw.vertex_array) {
glBindVertexArray(draw.vertex_array);
}
+}
- // Vertex buffer
- if (draw.vertex_buffer != cur_state.draw.vertex_buffer) {
- glBindBuffer(GL_ARRAY_BUFFER, draw.vertex_buffer);
+void OpenGLState::ApplyDepthClamp() const {
+ if (depth_clamp.far_plane == cur_state.depth_clamp.far_plane &&
+ depth_clamp.near_plane == cur_state.depth_clamp.near_plane) {
+ return;
+ }
+ if (depth_clamp.far_plane != depth_clamp.near_plane) {
+ UNIMPLEMENTED_MSG("Unimplemented Depth Clamp Separation!");
+ }
+ if (depth_clamp.far_plane || depth_clamp.near_plane) {
+ glEnable(GL_DEPTH_CLAMP);
+ } else {
+ glDisable(GL_DEPTH_CLAMP);
}
}
void OpenGLState::Apply() const {
ApplyFramebufferState();
- ApplyVertexBufferState();
- // Uniform buffer
- if (draw.uniform_buffer != cur_state.draw.uniform_buffer) {
- glBindBuffer(GL_UNIFORM_BUFFER, draw.uniform_buffer);
- }
+ ApplyVertexArrayState();
// Shader program
if (draw.shader_program != cur_state.draw.shader_program) {
@@ -556,11 +559,9 @@ void OpenGLState::Apply() const {
if (point.size != cur_state.point.size) {
glPointSize(point.size);
}
- if (GLAD_GL_ARB_color_buffer_float) {
- if (fragment_color_clamp.enabled != cur_state.fragment_color_clamp.enabled) {
- glClampColor(GL_CLAMP_FRAGMENT_COLOR_ARB,
- fragment_color_clamp.enabled ? GL_TRUE : GL_FALSE);
- }
+ if (fragment_color_clamp.enabled != cur_state.fragment_color_clamp.enabled) {
+ glClampColor(GL_CLAMP_FRAGMENT_COLOR_ARB,
+ fragment_color_clamp.enabled ? GL_TRUE : GL_FALSE);
}
if (multisample_control.alpha_to_coverage != cur_state.multisample_control.alpha_to_coverage) {
if (multisample_control.alpha_to_coverage) {
@@ -576,7 +577,7 @@ void OpenGLState::Apply() const {
glDisable(GL_SAMPLE_ALPHA_TO_ONE);
}
}
-
+ ApplyDepthClamp();
ApplyColorMask();
ApplyViewport();
ApplyStencilTest();
@@ -624,16 +625,6 @@ OpenGLState& OpenGLState::ResetPipeline(GLuint handle) {
return *this;
}
-OpenGLState& OpenGLState::ResetBuffer(GLuint handle) {
- if (draw.vertex_buffer == handle) {
- draw.vertex_buffer = 0;
- }
- if (draw.uniform_buffer == handle) {
- draw.uniform_buffer = 0;
- }
- return *this;
-}
-
OpenGLState& OpenGLState::ResetVertexArray(GLuint handle) {
if (draw.vertex_array == handle) {
draw.vertex_array = 0;
diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h
index 0bf19ed07..a5a7c0920 100644
--- a/src/video_core/renderer_opengl/gl_state.h
+++ b/src/video_core/renderer_opengl/gl_state.h
@@ -49,6 +49,11 @@ public:
} fragment_color_clamp;
struct {
+ bool far_plane;
+ bool near_plane;
+ } depth_clamp; // GL_DEPTH_CLAMP
+
+ struct {
bool enabled; // viewports arrays are only supported when geometry shaders are enabled.
} geometry_shaders;
@@ -149,8 +154,6 @@ public:
GLuint read_framebuffer; // GL_READ_FRAMEBUFFER_BINDING
GLuint draw_framebuffer; // GL_DRAW_FRAMEBUFFER_BINDING
GLuint vertex_array; // GL_VERTEX_ARRAY_BINDING
- GLuint vertex_buffer; // GL_ARRAY_BUFFER_BINDING
- GLuint uniform_buffer; // GL_UNIFORM_BUFFER_BINDING
GLuint shader_program; // GL_CURRENT_PROGRAM
GLuint program_pipeline; // GL_PROGRAM_PIPELINE_BINDING
} draw;
@@ -185,7 +188,7 @@ public:
GLfloat clamp;
} polygon_offset;
- std::array<bool, 2> clip_distance; // GL_CLIP_DISTANCE
+ std::array<bool, 8> clip_distance; // GL_CLIP_DISTANCE
OpenGLState();
@@ -201,10 +204,10 @@ public:
}
/// Apply this state as the current OpenGL state
void Apply() const;
- /// Apply only the state afecting the framebuffer
+ /// Apply only the state affecting the framebuffer
void ApplyFramebufferState() const;
- /// Apply only the state afecting the vertex buffer
- void ApplyVertexBufferState() const;
+ /// Apply only the state affecting the vertex array
+ void ApplyVertexArrayState() const;
/// Set the initial OpenGL state
static void ApplyDefaultState();
/// Resets any references to the given resource
@@ -212,7 +215,6 @@ public:
OpenGLState& ResetSampler(GLuint handle);
OpenGLState& ResetProgram(GLuint handle);
OpenGLState& ResetPipeline(GLuint handle);
- OpenGLState& ResetBuffer(GLuint handle);
OpenGLState& ResetVertexArray(GLuint handle);
OpenGLState& ResetFramebuffer(GLuint handle);
void EmulateViewportWithScissor();
@@ -235,6 +237,7 @@ private:
void ApplyLogicOp() const;
void ApplyTextures() const;
void ApplySamplers() const;
+ void ApplyDepthClamp() const;
void ApplyPolygonOffset() const;
};
diff --git a/src/video_core/renderer_opengl/gl_stream_buffer.cpp b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
index b97b895a4..d0b14b3f6 100644
--- a/src/video_core/renderer_opengl/gl_stream_buffer.cpp
+++ b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
@@ -15,13 +15,12 @@ MICROPROFILE_DEFINE(OpenGL_StreamBuffer, "OpenGL", "Stream Buffer Orphaning",
namespace OpenGL {
-OGLStreamBuffer::OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coherent)
- : gl_target(target), buffer_size(size) {
+OGLStreamBuffer::OGLStreamBuffer(GLsizeiptr size, bool vertex_data_usage, bool prefer_coherent)
+ : buffer_size(size) {
gl_buffer.Create();
- glBindBuffer(gl_target, gl_buffer.handle);
GLsizeiptr allocate_size = size;
- if (target == GL_ARRAY_BUFFER) {
+ if (vertex_data_usage) {
// On AMD GPU there is a strange crash in indexed drawing. The crash happens when the buffer
// read position is near the end and is an out-of-bound access to the vertex buffer. This is
// probably a bug in the driver and is related to the usage of vec3<byte> attributes in the
@@ -35,18 +34,17 @@ OGLStreamBuffer::OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coh
coherent = prefer_coherent;
const GLbitfield flags =
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | (coherent ? GL_MAP_COHERENT_BIT : 0);
- glBufferStorage(gl_target, allocate_size, nullptr, flags);
- mapped_ptr = static_cast<u8*>(glMapBufferRange(
- gl_target, 0, buffer_size, flags | (coherent ? 0 : GL_MAP_FLUSH_EXPLICIT_BIT)));
+ glNamedBufferStorage(gl_buffer.handle, allocate_size, nullptr, flags);
+ mapped_ptr = static_cast<u8*>(glMapNamedBufferRange(
+ gl_buffer.handle, 0, buffer_size, flags | (coherent ? 0 : GL_MAP_FLUSH_EXPLICIT_BIT)));
} else {
- glBufferData(gl_target, allocate_size, nullptr, GL_STREAM_DRAW);
+ glNamedBufferData(gl_buffer.handle, allocate_size, nullptr, GL_STREAM_DRAW);
}
}
OGLStreamBuffer::~OGLStreamBuffer() {
if (persistent) {
- glBindBuffer(gl_target, gl_buffer.handle);
- glUnmapBuffer(gl_target);
+ glUnmapNamedBuffer(gl_buffer.handle);
}
gl_buffer.Release();
}
@@ -74,7 +72,7 @@ std::tuple<u8*, GLintptr, bool> OGLStreamBuffer::Map(GLsizeiptr size, GLintptr a
invalidate = true;
if (persistent) {
- glUnmapBuffer(gl_target);
+ glUnmapNamedBuffer(gl_buffer.handle);
}
}
@@ -84,7 +82,7 @@ std::tuple<u8*, GLintptr, bool> OGLStreamBuffer::Map(GLsizeiptr size, GLintptr a
(coherent ? GL_MAP_COHERENT_BIT : GL_MAP_FLUSH_EXPLICIT_BIT) |
(invalidate ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_UNSYNCHRONIZED_BIT);
mapped_ptr = static_cast<u8*>(
- glMapBufferRange(gl_target, buffer_pos, buffer_size - buffer_pos, flags));
+ glMapNamedBufferRange(gl_buffer.handle, buffer_pos, buffer_size - buffer_pos, flags));
mapped_offset = buffer_pos;
}
@@ -95,11 +93,11 @@ void OGLStreamBuffer::Unmap(GLsizeiptr size) {
ASSERT(size <= mapped_size);
if (!coherent && size > 0) {
- glFlushMappedBufferRange(gl_target, buffer_pos - mapped_offset, size);
+ glFlushMappedNamedBufferRange(gl_buffer.handle, buffer_pos - mapped_offset, size);
}
if (!persistent) {
- glUnmapBuffer(gl_target);
+ glUnmapNamedBuffer(gl_buffer.handle);
}
buffer_pos += size;
diff --git a/src/video_core/renderer_opengl/gl_stream_buffer.h b/src/video_core/renderer_opengl/gl_stream_buffer.h
index ae7961bd7..3d18ecb4d 100644
--- a/src/video_core/renderer_opengl/gl_stream_buffer.h
+++ b/src/video_core/renderer_opengl/gl_stream_buffer.h
@@ -13,7 +13,7 @@ namespace OpenGL {
class OGLStreamBuffer : private NonCopyable {
public:
- explicit OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coherent = false);
+ explicit OGLStreamBuffer(GLsizeiptr size, bool vertex_data_usage, bool prefer_coherent = false);
~OGLStreamBuffer();
GLuint GetHandle() const;
@@ -33,7 +33,6 @@ public:
private:
OGLBuffer gl_buffer;
- GLenum gl_target;
bool coherent = false;
bool persistent = false;
diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp
index 4fd0d66c5..e37b65b38 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.cpp
+++ b/src/video_core/renderer_opengl/renderer_opengl.cpp
@@ -14,6 +14,7 @@
#include "core/core.h"
#include "core/core_timing.h"
#include "core/frontend/emu_window.h"
+#include "core/frontend/scope_acquire_window_context.h"
#include "core/memory.h"
#include "core/perf_stats.h"
#include "core/settings.h"
@@ -97,18 +98,6 @@ static std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(const float width, cons
return matrix;
}
-ScopeAcquireGLContext::ScopeAcquireGLContext(Core::Frontend::EmuWindow& emu_window_)
- : emu_window{emu_window_} {
- if (Settings::values.use_multi_core) {
- emu_window.MakeCurrent();
- }
-}
-ScopeAcquireGLContext::~ScopeAcquireGLContext() {
- if (Settings::values.use_multi_core) {
- emu_window.DoneCurrent();
- }
-}
-
RendererOpenGL::RendererOpenGL(Core::Frontend::EmuWindow& window)
: VideoCore::RendererBase{window} {}
@@ -117,7 +106,6 @@ RendererOpenGL::~RendererOpenGL() = default;
/// Swap buffers (render frame)
void RendererOpenGL::SwapBuffers(
std::optional<std::reference_wrapper<const Tegra::FramebufferConfig>> framebuffer) {
- ScopeAcquireGLContext acquire_context{render_window};
Core::System::GetInstance().GetPerfStats().EndSystemFrame();
@@ -138,7 +126,12 @@ void RendererOpenGL::SwapBuffers(
// Load the framebuffer from memory, draw it to the screen, and swap buffers
LoadFBToScreenInfo(*framebuffer);
- DrawScreen();
+
+ if (renderer_settings.screenshot_requested)
+ CaptureScreenshot();
+
+ DrawScreen(render_window.GetFramebufferLayout());
+
render_window.SwapBuffers();
}
@@ -240,20 +233,20 @@ void RendererOpenGL::InitOpenGLObjects() {
// Generate VAO
vertex_array.Create();
-
state.draw.vertex_array = vertex_array.handle;
- state.draw.vertex_buffer = vertex_buffer.handle;
- state.draw.uniform_buffer = 0;
- state.Apply();
// Attach vertex data to VAO
- glBufferData(GL_ARRAY_BUFFER, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
- glVertexAttribPointer(attrib_position, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex),
- (GLvoid*)offsetof(ScreenRectVertex, position));
- glVertexAttribPointer(attrib_tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(ScreenRectVertex),
- (GLvoid*)offsetof(ScreenRectVertex, tex_coord));
- glEnableVertexAttribArray(attrib_position);
- glEnableVertexAttribArray(attrib_tex_coord);
+ glNamedBufferData(vertex_buffer.handle, sizeof(ScreenRectVertex) * 4, nullptr, GL_STREAM_DRAW);
+ glVertexArrayAttribFormat(vertex_array.handle, attrib_position, 2, GL_FLOAT, GL_FALSE,
+ offsetof(ScreenRectVertex, position));
+ glVertexArrayAttribFormat(vertex_array.handle, attrib_tex_coord, 2, GL_FLOAT, GL_FALSE,
+ offsetof(ScreenRectVertex, tex_coord));
+ glVertexArrayAttribBinding(vertex_array.handle, attrib_position, 0);
+ glVertexArrayAttribBinding(vertex_array.handle, attrib_tex_coord, 0);
+ glEnableVertexArrayAttrib(vertex_array.handle, attrib_position);
+ glEnableVertexArrayAttrib(vertex_array.handle, attrib_tex_coord);
+ glVertexArrayVertexBuffer(vertex_array.handle, 0, vertex_buffer.handle, 0,
+ sizeof(ScreenRectVertex));
// Allocate textures for the screen
screen_info.texture.resource.Create();
@@ -365,14 +358,12 @@ void RendererOpenGL::DrawScreenTriangles(const ScreenInfo& screen_info, float x,
state.texture_units[0].texture = screen_info.display_texture;
state.texture_units[0].swizzle = {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA};
// Workaround brigthness problems in SMO by enabling sRGB in the final output
- // if it has been used in the frame
- // Needed because of this bug in QT
- // QTBUG-50987
+ // if it has been used in the frame. Needed because of this bug in QT: QTBUG-50987
state.framebuffer_srgb.enabled = OpenGLState::GetsRGBUsed();
state.Apply();
- glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data());
+ glNamedBufferSubData(vertex_buffer.handle, 0, sizeof(vertices), vertices.data());
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
- // restore default state
+ // Restore default state
state.framebuffer_srgb.enabled = false;
state.texture_units[0].texture = 0;
state.Apply();
@@ -383,14 +374,13 @@ void RendererOpenGL::DrawScreenTriangles(const ScreenInfo& screen_info, float x,
/**
* Draws the emulated screens to the emulator window.
*/
-void RendererOpenGL::DrawScreen() {
+void RendererOpenGL::DrawScreen(const Layout::FramebufferLayout& layout) {
if (renderer_settings.set_background_color) {
// Update background color before drawing
glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue,
0.0f);
}
- const auto& layout = render_window.GetFramebufferLayout();
const auto& screen = layout.screen;
glViewport(0, 0, layout.width, layout.height);
@@ -414,6 +404,37 @@ void RendererOpenGL::DrawScreen() {
/// Updates the framerate
void RendererOpenGL::UpdateFramerate() {}
+void RendererOpenGL::CaptureScreenshot() {
+ // Draw the current frame to the screenshot framebuffer
+ screenshot_framebuffer.Create();
+ GLuint old_read_fb = state.draw.read_framebuffer;
+ GLuint old_draw_fb = state.draw.draw_framebuffer;
+ state.draw.read_framebuffer = state.draw.draw_framebuffer = screenshot_framebuffer.handle;
+ state.Apply();
+
+ Layout::FramebufferLayout layout{renderer_settings.screenshot_framebuffer_layout};
+
+ GLuint renderbuffer;
+ glGenRenderbuffers(1, &renderbuffer);
+ glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB8, layout.width, layout.height);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
+
+ DrawScreen(layout);
+
+ glReadPixels(0, 0, layout.width, layout.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
+ renderer_settings.screenshot_bits);
+
+ screenshot_framebuffer.Release();
+ state.draw.read_framebuffer = old_read_fb;
+ state.draw.draw_framebuffer = old_draw_fb;
+ state.Apply();
+ glDeleteRenderbuffers(1, &renderbuffer);
+
+ renderer_settings.screenshot_complete_callback();
+ renderer_settings.screenshot_requested = false;
+}
+
static const char* GetSource(GLenum source) {
#define RET(s) \
case GL_DEBUG_SOURCE_##s: \
@@ -427,6 +448,7 @@ static const char* GetSource(GLenum source) {
RET(OTHER);
default:
UNREACHABLE();
+ return "Unknown source";
}
#undef RET
}
@@ -445,6 +467,7 @@ static const char* GetType(GLenum type) {
RET(MARKER);
default:
UNREACHABLE();
+ return "Unknown type";
}
#undef RET
}
@@ -471,7 +494,7 @@ static void APIENTRY DebugHandler(GLenum source, GLenum type, GLuint id, GLenum
/// Initialize the renderer
bool RendererOpenGL::Init() {
- ScopeAcquireGLContext acquire_context{render_window};
+ Core::Frontend::ScopeAcquireWindowContext acquire_context{render_window};
if (GLAD_GL_KHR_debug) {
glEnable(GL_DEBUG_OUTPUT);
diff --git a/src/video_core/renderer_opengl/renderer_opengl.h b/src/video_core/renderer_opengl/renderer_opengl.h
index c0868c0e4..1665018db 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.h
+++ b/src/video_core/renderer_opengl/renderer_opengl.h
@@ -16,6 +16,10 @@ namespace Core::Frontend {
class EmuWindow;
}
+namespace Layout {
+struct FramebufferLayout;
+}
+
namespace OpenGL {
/// Structure used for storing information about the textures for the Switch screen
@@ -35,16 +39,6 @@ struct ScreenInfo {
TextureInfo texture;
};
-/// Helper class to acquire/release OpenGL context within a given scope
-class ScopeAcquireGLContext : NonCopyable {
-public:
- explicit ScopeAcquireGLContext(Core::Frontend::EmuWindow& window);
- ~ScopeAcquireGLContext();
-
-private:
- Core::Frontend::EmuWindow& emu_window;
-};
-
class RendererOpenGL : public VideoCore::RendererBase {
public:
explicit RendererOpenGL(Core::Frontend::EmuWindow& window);
@@ -66,10 +60,12 @@ private:
void ConfigureFramebufferTexture(TextureInfo& texture,
const Tegra::FramebufferConfig& framebuffer);
- void DrawScreen();
+ void DrawScreen(const Layout::FramebufferLayout& layout);
void DrawScreenTriangles(const ScreenInfo& screen_info, float x, float y, float w, float h);
void UpdateFramerate();
+ void CaptureScreenshot();
+
// Loads framebuffer from emulated memory into the display information structure
void LoadFBToScreenInfo(const Tegra::FramebufferConfig& framebuffer);
// Fills active OpenGL texture with the given RGBA color.
@@ -82,6 +78,7 @@ private:
OGLVertexArray vertex_array;
OGLBuffer vertex_buffer;
OGLProgram shader;
+ OGLFramebuffer screenshot_framebuffer;
/// Display information for Switch screen
ScreenInfo screen_info;
diff --git a/src/video_core/shader/decode.cpp b/src/video_core/shader/decode.cpp
new file mode 100644
index 000000000..812983a99
--- /dev/null
+++ b/src/video_core/shader/decode.cpp
@@ -0,0 +1,206 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <cstring>
+#include <set>
+
+#include <fmt/format.h>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/engines/shader_header.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+namespace {
+
+/// Merges exit method of two parallel branches.
+constexpr ExitMethod ParallelExit(ExitMethod a, ExitMethod b) {
+ if (a == ExitMethod::Undetermined) {
+ return b;
+ }
+ if (b == ExitMethod::Undetermined) {
+ return a;
+ }
+ if (a == b) {
+ return a;
+ }
+ return ExitMethod::Conditional;
+}
+
+/**
+ * Returns whether the instruction at the specified offset is a 'sched' instruction.
+ * Sched instructions always appear before a sequence of 3 instructions.
+ */
+constexpr bool IsSchedInstruction(u32 offset, u32 main_offset) {
+ constexpr u32 SchedPeriod = 4;
+ u32 absolute_offset = offset - main_offset;
+
+ return (absolute_offset % SchedPeriod) == 0;
+}
+
+} // namespace
+
+void ShaderIR::Decode() {
+ std::memcpy(&header, program_code.data(), sizeof(Tegra::Shader::Header));
+
+ std::set<u32> labels;
+ const ExitMethod exit_method = Scan(main_offset, MAX_PROGRAM_LENGTH, labels);
+ if (exit_method != ExitMethod::AlwaysEnd) {
+ UNREACHABLE_MSG("Program does not always end");
+ }
+
+ if (labels.empty()) {
+ basic_blocks.insert({main_offset, DecodeRange(main_offset, MAX_PROGRAM_LENGTH)});
+ return;
+ }
+
+ labels.insert(main_offset);
+
+ for (const u32 label : labels) {
+ const auto next_it = labels.lower_bound(label + 1);
+ const u32 next_label = next_it == labels.end() ? MAX_PROGRAM_LENGTH : *next_it;
+
+ basic_blocks.insert({label, DecodeRange(label, next_label)});
+ }
+}
+
+ExitMethod ShaderIR::Scan(u32 begin, u32 end, std::set<u32>& labels) {
+ const auto [iter, inserted] =
+ exit_method_map.emplace(std::make_pair(begin, end), ExitMethod::Undetermined);
+ ExitMethod& exit_method = iter->second;
+ if (!inserted)
+ return exit_method;
+
+ for (u32 offset = begin; offset != end && offset != MAX_PROGRAM_LENGTH; ++offset) {
+ coverage_begin = std::min(coverage_begin, offset);
+ coverage_end = std::max(coverage_end, offset + 1);
+
+ const Instruction instr = {program_code[offset]};
+ const auto opcode = OpCode::Decode(instr);
+ if (!opcode)
+ continue;
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::EXIT: {
+ // The EXIT instruction can be predicated, which means that the shader can conditionally
+ // end on this instruction. We have to consider the case where the condition is not met
+ // and check the exit method of that other basic block.
+ using Tegra::Shader::Pred;
+ if (instr.pred.pred_index == static_cast<u64>(Pred::UnusedIndex)) {
+ return exit_method = ExitMethod::AlwaysEnd;
+ } else {
+ const ExitMethod not_met = Scan(offset + 1, end, labels);
+ return exit_method = ParallelExit(ExitMethod::AlwaysEnd, not_met);
+ }
+ }
+ case OpCode::Id::BRA: {
+ const u32 target = offset + instr.bra.GetBranchTarget();
+ labels.insert(target);
+ const ExitMethod no_jmp = Scan(offset + 1, end, labels);
+ const ExitMethod jmp = Scan(target, end, labels);
+ return exit_method = ParallelExit(no_jmp, jmp);
+ }
+ case OpCode::Id::SSY:
+ case OpCode::Id::PBK: {
+ // The SSY and PBK use a similar encoding as the BRA instruction.
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer branching is not supported");
+ const u32 target = offset + instr.bra.GetBranchTarget();
+ labels.insert(target);
+ // Continue scanning for an exit method.
+ break;
+ }
+ }
+ }
+ return exit_method = ExitMethod::AlwaysReturn;
+}
+
+BasicBlock ShaderIR::DecodeRange(u32 begin, u32 end) {
+ BasicBlock basic_block;
+ for (u32 pc = begin; pc < (begin > end ? MAX_PROGRAM_LENGTH : end);) {
+ pc = DecodeInstr(basic_block, pc);
+ }
+ return basic_block;
+}
+
+u32 ShaderIR::DecodeInstr(BasicBlock& bb, u32 pc) {
+ // Ignore sched instructions when generating code.
+ if (IsSchedInstruction(pc, main_offset)) {
+ return pc + 1;
+ }
+
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ // Decoding failure
+ if (!opcode) {
+ UNIMPLEMENTED_MSG("Unhandled instruction: {0:x}", instr.value);
+ return pc + 1;
+ }
+
+ bb.push_back(
+ Comment(fmt::format("{}: {} (0x{:016x})", pc, opcode->get().GetName(), instr.value)));
+
+ using Tegra::Shader::Pred;
+ UNIMPLEMENTED_IF_MSG(instr.pred.full_pred == Pred::NeverExecute,
+ "NeverExecute predicate not implemented");
+
+ static const std::map<OpCode::Type, u32 (ShaderIR::*)(BasicBlock&, const BasicBlock&, u32)>
+ decoders = {
+ {OpCode::Type::Arithmetic, &ShaderIR::DecodeArithmetic},
+ {OpCode::Type::ArithmeticImmediate, &ShaderIR::DecodeArithmeticImmediate},
+ {OpCode::Type::Bfe, &ShaderIR::DecodeBfe},
+ {OpCode::Type::Bfi, &ShaderIR::DecodeBfi},
+ {OpCode::Type::Shift, &ShaderIR::DecodeShift},
+ {OpCode::Type::ArithmeticInteger, &ShaderIR::DecodeArithmeticInteger},
+ {OpCode::Type::ArithmeticIntegerImmediate, &ShaderIR::DecodeArithmeticIntegerImmediate},
+ {OpCode::Type::ArithmeticHalf, &ShaderIR::DecodeArithmeticHalf},
+ {OpCode::Type::ArithmeticHalfImmediate, &ShaderIR::DecodeArithmeticHalfImmediate},
+ {OpCode::Type::Ffma, &ShaderIR::DecodeFfma},
+ {OpCode::Type::Hfma2, &ShaderIR::DecodeHfma2},
+ {OpCode::Type::Conversion, &ShaderIR::DecodeConversion},
+ {OpCode::Type::Memory, &ShaderIR::DecodeMemory},
+ {OpCode::Type::FloatSetPredicate, &ShaderIR::DecodeFloatSetPredicate},
+ {OpCode::Type::IntegerSetPredicate, &ShaderIR::DecodeIntegerSetPredicate},
+ {OpCode::Type::HalfSetPredicate, &ShaderIR::DecodeHalfSetPredicate},
+ {OpCode::Type::PredicateSetRegister, &ShaderIR::DecodePredicateSetRegister},
+ {OpCode::Type::PredicateSetPredicate, &ShaderIR::DecodePredicateSetPredicate},
+ {OpCode::Type::RegisterSetPredicate, &ShaderIR::DecodeRegisterSetPredicate},
+ {OpCode::Type::FloatSet, &ShaderIR::DecodeFloatSet},
+ {OpCode::Type::IntegerSet, &ShaderIR::DecodeIntegerSet},
+ {OpCode::Type::HalfSet, &ShaderIR::DecodeHalfSet},
+ {OpCode::Type::Video, &ShaderIR::DecodeVideo},
+ {OpCode::Type::Xmad, &ShaderIR::DecodeXmad},
+ };
+
+ std::vector<Node> tmp_block;
+ if (const auto decoder = decoders.find(opcode->get().GetType()); decoder != decoders.end()) {
+ pc = (this->*decoder->second)(tmp_block, bb, pc);
+ } else {
+ pc = DecodeOther(tmp_block, bb, pc);
+ }
+
+ // Some instructions (like SSY) don't have a predicate field, they are always unconditionally
+ // executed.
+ const bool can_be_predicated = OpCode::IsPredicatedInstruction(opcode->get().GetId());
+ const auto pred_index = static_cast<u32>(instr.pred.pred_index);
+
+ if (can_be_predicated && pred_index != static_cast<u32>(Pred::UnusedIndex)) {
+ bb.push_back(
+ Conditional(GetPredicate(pred_index, instr.negate_pred != 0), std::move(tmp_block)));
+ } else {
+ for (auto& node : tmp_block) {
+ bb.push_back(std::move(node));
+ }
+ }
+
+ return pc + 1;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic.cpp b/src/video_core/shader/decode/arithmetic.cpp
new file mode 100644
index 000000000..e7847f614
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic.cpp
@@ -0,0 +1,155 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::SubOp;
+
+u32 ShaderIR::DecodeArithmetic(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ Node op_a = GetRegister(instr.gpr8);
+
+ Node op_b = [&]() -> Node {
+ if (instr.is_b_imm) {
+ return GetImmediate19(instr);
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::MOV_C:
+ case OpCode::Id::MOV_R: {
+ // MOV does not have neither 'abs' nor 'neg' bits.
+ SetRegister(bb, instr.gpr0, op_b);
+ break;
+ }
+ case OpCode::Id::FMUL_C:
+ case OpCode::Id::FMUL_R:
+ case OpCode::Id::FMUL_IMM: {
+ // FMUL does not have 'abs' bits and only the second operand has a 'neg' bit.
+ UNIMPLEMENTED_IF_MSG(instr.fmul.tab5cb8_2 != 0, "FMUL tab5cb8_2({}) is not implemented",
+ instr.fmul.tab5cb8_2.Value());
+ UNIMPLEMENTED_IF_MSG(
+ instr.fmul.tab5c68_0 != 1, "FMUL tab5cb8_0({}) is not implemented",
+ instr.fmul.tab5c68_0.Value()); // SMO typical sends 1 here which seems to be the default
+
+ op_b = GetOperandAbsNegFloat(op_b, false, instr.fmul.negate_b);
+
+ // TODO(Rodrigo): Should precise be used when there's a postfactor?
+ Node value = Operation(OperationCode::FMul, PRECISE, op_a, op_b);
+
+ if (instr.fmul.postfactor != 0) {
+ auto postfactor = static_cast<s32>(instr.fmul.postfactor);
+
+ // Postfactor encoded as 3-bit 1's complement in instruction, interpreted with below
+ // logic.
+ if (postfactor >= 4) {
+ postfactor = 7 - postfactor;
+ } else {
+ postfactor = 0 - postfactor;
+ }
+
+ if (postfactor > 0) {
+ value = Operation(OperationCode::FMul, NO_PRECISE, value,
+ Immediate(static_cast<f32>(1 << postfactor)));
+ } else {
+ value = Operation(OperationCode::FDiv, NO_PRECISE, value,
+ Immediate(static_cast<f32>(1 << -postfactor)));
+ }
+ }
+
+ value = GetSaturatedFloat(value, instr.alu.saturate_d);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::FADD_C:
+ case OpCode::Id::FADD_R:
+ case OpCode::Id::FADD_IMM: {
+ op_a = GetOperandAbsNegFloat(op_a, instr.alu.abs_a, instr.alu.negate_a);
+ op_b = GetOperandAbsNegFloat(op_b, instr.alu.abs_b, instr.alu.negate_b);
+
+ Node value = Operation(OperationCode::FAdd, PRECISE, op_a, op_b);
+ value = GetSaturatedFloat(value, instr.alu.saturate_d);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::MUFU: {
+ op_a = GetOperandAbsNegFloat(op_a, instr.alu.abs_a, instr.alu.negate_a);
+
+ Node value = [&]() {
+ switch (instr.sub_op) {
+ case SubOp::Cos:
+ return Operation(OperationCode::FCos, PRECISE, op_a);
+ case SubOp::Sin:
+ return Operation(OperationCode::FSin, PRECISE, op_a);
+ case SubOp::Ex2:
+ return Operation(OperationCode::FExp2, PRECISE, op_a);
+ case SubOp::Lg2:
+ return Operation(OperationCode::FLog2, PRECISE, op_a);
+ case SubOp::Rcp:
+ return Operation(OperationCode::FDiv, PRECISE, Immediate(1.0f), op_a);
+ case SubOp::Rsq:
+ return Operation(OperationCode::FInverseSqrt, PRECISE, op_a);
+ case SubOp::Sqrt:
+ return Operation(OperationCode::FSqrt, PRECISE, op_a);
+ default:
+ UNIMPLEMENTED_MSG("Unhandled MUFU sub op={0:x}",
+ static_cast<unsigned>(instr.sub_op.Value()));
+ return Immediate(0);
+ }
+ }();
+ value = GetSaturatedFloat(value, instr.alu.saturate_d);
+
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::FMNMX_C:
+ case OpCode::Id::FMNMX_R:
+ case OpCode::Id::FMNMX_IMM: {
+ op_a = GetOperandAbsNegFloat(op_a, instr.alu.abs_a, instr.alu.negate_a);
+ op_b = GetOperandAbsNegFloat(op_b, instr.alu.abs_b, instr.alu.negate_b);
+
+ const Node condition = GetPredicate(instr.alu.fmnmx.pred, instr.alu.fmnmx.negate_pred != 0);
+
+ const Node min = Operation(OperationCode::FMin, NO_PRECISE, op_a, op_b);
+ const Node max = Operation(OperationCode::FMax, NO_PRECISE, op_a, op_b);
+ const Node value = Operation(OperationCode::Select, NO_PRECISE, condition, min, max);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::RRO_C:
+ case OpCode::Id::RRO_R:
+ case OpCode::Id::RRO_IMM: {
+ // Currently RRO is only implemented as a register move.
+ op_b = GetOperandAbsNegFloat(op_b, instr.alu.abs_b, instr.alu.negate_b);
+ SetRegister(bb, instr.gpr0, op_b);
+ LOG_WARNING(HW_GPU, "RRO instruction is incomplete");
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled arithmetic instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic_half.cpp b/src/video_core/shader/decode/arithmetic_half.cpp
new file mode 100644
index 000000000..a237dcb92
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic_half.cpp
@@ -0,0 +1,70 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeArithmeticHalf(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ if (opcode->get().GetId() == OpCode::Id::HADD2_C ||
+ opcode->get().GetId() == OpCode::Id::HADD2_R) {
+ UNIMPLEMENTED_IF(instr.alu_half.ftz != 0);
+ }
+ UNIMPLEMENTED_IF_MSG(instr.alu_half.saturate != 0, "Half float saturation not implemented");
+
+ const bool negate_a =
+ opcode->get().GetId() != OpCode::Id::HMUL2_R && instr.alu_half.negate_a != 0;
+ const bool negate_b =
+ opcode->get().GetId() != OpCode::Id::HMUL2_C && instr.alu_half.negate_b != 0;
+
+ const Node op_a = GetOperandAbsNegHalf(GetRegister(instr.gpr8), instr.alu_half.abs_a, negate_a);
+
+ // instr.alu_half.type_a
+
+ Node op_b = [&]() {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HADD2_C:
+ case OpCode::Id::HMUL2_C:
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ case OpCode::Id::HADD2_R:
+ case OpCode::Id::HMUL2_R:
+ return GetRegister(instr.gpr20);
+ default:
+ UNREACHABLE();
+ return Immediate(0);
+ }
+ }();
+ op_b = GetOperandAbsNegHalf(op_b, instr.alu_half.abs_b, negate_b);
+
+ Node value = [&]() {
+ MetaHalfArithmetic meta{true, {instr.alu_half_imm.type_a, instr.alu_half.type_b}};
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HADD2_C:
+ case OpCode::Id::HADD2_R:
+ return Operation(OperationCode::HAdd, meta, op_a, op_b);
+ case OpCode::Id::HMUL2_C:
+ case OpCode::Id::HMUL2_R:
+ return Operation(OperationCode::HMul, meta, op_a, op_b);
+ default:
+ UNIMPLEMENTED_MSG("Unhandled half float instruction: {}", opcode->get().GetName());
+ return Immediate(0);
+ }
+ }();
+ value = HalfMerge(GetRegister(instr.gpr0), value, instr.alu_half.merge);
+
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic_half_immediate.cpp b/src/video_core/shader/decode/arithmetic_half_immediate.cpp
new file mode 100644
index 000000000..7b4f7d284
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic_half_immediate.cpp
@@ -0,0 +1,51 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeArithmeticHalfImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ if (opcode->get().GetId() == OpCode::Id::HADD2_IMM) {
+ UNIMPLEMENTED_IF(instr.alu_half_imm.ftz != 0);
+ } else {
+ UNIMPLEMENTED_IF(instr.alu_half_imm.precision != Tegra::Shader::HalfPrecision::None);
+ }
+ UNIMPLEMENTED_IF_MSG(instr.alu_half_imm.saturate != 0,
+ "Half float immediate saturation not implemented");
+
+ Node op_a = GetRegister(instr.gpr8);
+ op_a = GetOperandAbsNegHalf(op_a, instr.alu_half_imm.abs_a, instr.alu_half_imm.negate_a);
+
+ const Node op_b = UnpackHalfImmediate(instr, true);
+
+ Node value = [&]() {
+ MetaHalfArithmetic meta{true, {instr.alu_half_imm.type_a}};
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HADD2_IMM:
+ return Operation(OperationCode::HAdd, meta, op_a, op_b);
+ case OpCode::Id::HMUL2_IMM:
+ return Operation(OperationCode::HMul, meta, op_a, op_b);
+ default:
+ UNREACHABLE();
+ return Immediate(0);
+ }
+ }();
+ value = HalfMerge(GetRegister(instr.gpr0), value, instr.alu_half_imm.merge);
+
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic_immediate.cpp b/src/video_core/shader/decode/arithmetic_immediate.cpp
new file mode 100644
index 000000000..4fd3db54e
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic_immediate.cpp
@@ -0,0 +1,52 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeArithmeticImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::MOV32_IMM: {
+ SetRegister(bb, instr.gpr0, GetImmediate32(instr));
+ break;
+ }
+ case OpCode::Id::FMUL32_IMM: {
+ Node value =
+ Operation(OperationCode::FMul, PRECISE, GetRegister(instr.gpr8), GetImmediate32(instr));
+ value = GetSaturatedFloat(value, instr.fmul32.saturate);
+
+ SetInternalFlagsFromFloat(bb, value, instr.op_32.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::FADD32I: {
+ const Node op_a = GetOperandAbsNegFloat(GetRegister(instr.gpr8), instr.fadd32i.abs_a,
+ instr.fadd32i.negate_a);
+ const Node op_b = GetOperandAbsNegFloat(GetImmediate32(instr), instr.fadd32i.abs_b,
+ instr.fadd32i.negate_b);
+
+ const Node value = Operation(OperationCode::FAdd, PRECISE, op_a, op_b);
+ SetInternalFlagsFromFloat(bb, value, instr.op_32.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled arithmetic immediate instruction: {}",
+ opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic_integer.cpp b/src/video_core/shader/decode/arithmetic_integer.cpp
new file mode 100644
index 000000000..4a8cc1a1c
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic_integer.cpp
@@ -0,0 +1,287 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::IAdd3Height;
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+using Tegra::Shader::Register;
+
+u32 ShaderIR::DecodeArithmeticInteger(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ Node op_a = GetRegister(instr.gpr8);
+ Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return Immediate(instr.alu.GetSignedImm20_20());
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::IADD_C:
+ case OpCode::Id::IADD_R:
+ case OpCode::Id::IADD_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.alu.saturate_d, "IADD saturation not implemented");
+
+ op_a = GetOperandAbsNegInteger(op_a, false, instr.alu_integer.negate_a, true);
+ op_b = GetOperandAbsNegInteger(op_b, false, instr.alu_integer.negate_b, true);
+
+ const Node value = Operation(OperationCode::IAdd, PRECISE, op_a, op_b);
+
+ SetInternalFlagsFromInteger(bb, value, instr.op_32.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::IADD3_C:
+ case OpCode::Id::IADD3_R:
+ case OpCode::Id::IADD3_IMM: {
+ Node op_c = GetRegister(instr.gpr39);
+
+ const auto ApplyHeight = [&](IAdd3Height height, Node value) {
+ switch (height) {
+ case IAdd3Height::None:
+ return value;
+ case IAdd3Height::LowerHalfWord:
+ return BitfieldExtract(value, 0, 16);
+ case IAdd3Height::UpperHalfWord:
+ return BitfieldExtract(value, 16, 16);
+ default:
+ UNIMPLEMENTED_MSG("Unhandled IADD3 height: {}", static_cast<u32>(height));
+ return Immediate(0);
+ }
+ };
+
+ if (opcode->get().GetId() == OpCode::Id::IADD3_R) {
+ op_a = ApplyHeight(instr.iadd3.height_a, op_a);
+ op_b = ApplyHeight(instr.iadd3.height_b, op_b);
+ op_c = ApplyHeight(instr.iadd3.height_c, op_c);
+ }
+
+ op_a = GetOperandAbsNegInteger(op_a, false, instr.iadd3.neg_a, true);
+ op_b = GetOperandAbsNegInteger(op_b, false, instr.iadd3.neg_b, true);
+ op_c = GetOperandAbsNegInteger(op_c, false, instr.iadd3.neg_c, true);
+
+ const Node value = [&]() {
+ const Node add_ab = Operation(OperationCode::IAdd, NO_PRECISE, op_a, op_b);
+ if (opcode->get().GetId() != OpCode::Id::IADD3_R) {
+ return Operation(OperationCode::IAdd, NO_PRECISE, add_ab, op_c);
+ }
+ const Node shifted = [&]() {
+ switch (instr.iadd3.mode) {
+ case Tegra::Shader::IAdd3Mode::RightShift:
+ // TODO(tech4me): According to
+ // https://envytools.readthedocs.io/en/latest/hw/graph/maxwell/cuda/int.html?highlight=iadd3
+ // The addition between op_a and op_b should be done in uint33, more
+ // investigation required
+ return Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, add_ab,
+ Immediate(16));
+ case Tegra::Shader::IAdd3Mode::LeftShift:
+ return Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, add_ab,
+ Immediate(16));
+ default:
+ return add_ab;
+ }
+ }();
+ return Operation(OperationCode::IAdd, NO_PRECISE, shifted, op_c);
+ }();
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::ISCADD_C:
+ case OpCode::Id::ISCADD_R:
+ case OpCode::Id::ISCADD_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in ISCADD is not implemented");
+
+ op_a = GetOperandAbsNegInteger(op_a, false, instr.alu_integer.negate_a, true);
+ op_b = GetOperandAbsNegInteger(op_b, false, instr.alu_integer.negate_b, true);
+
+ const Node shift = Immediate(static_cast<u32>(instr.alu_integer.shift_amount));
+ const Node shifted_a = Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, op_a, shift);
+ const Node value = Operation(OperationCode::IAdd, NO_PRECISE, shifted_a, op_b);
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::POPC_C:
+ case OpCode::Id::POPC_R:
+ case OpCode::Id::POPC_IMM: {
+ if (instr.popc.invert) {
+ op_b = Operation(OperationCode::IBitwiseNot, NO_PRECISE, op_b);
+ }
+ const Node value = Operation(OperationCode::IBitCount, PRECISE, op_b);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::SEL_C:
+ case OpCode::Id::SEL_R:
+ case OpCode::Id::SEL_IMM: {
+ const Node condition = GetPredicate(instr.sel.pred, instr.sel.neg_pred != 0);
+ const Node value = Operation(OperationCode::Select, PRECISE, condition, op_a, op_b);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::LOP_C:
+ case OpCode::Id::LOP_R:
+ case OpCode::Id::LOP_IMM: {
+ if (instr.alu.lop.invert_a)
+ op_a = Operation(OperationCode::IBitwiseNot, NO_PRECISE, op_a);
+ if (instr.alu.lop.invert_b)
+ op_b = Operation(OperationCode::IBitwiseNot, NO_PRECISE, op_b);
+
+ WriteLogicOperation(bb, instr.gpr0, instr.alu.lop.operation, op_a, op_b,
+ instr.alu.lop.pred_result_mode, instr.alu.lop.pred48,
+ instr.generates_cc);
+ break;
+ }
+ case OpCode::Id::LOP3_C:
+ case OpCode::Id::LOP3_R:
+ case OpCode::Id::LOP3_IMM: {
+ const Node op_c = GetRegister(instr.gpr39);
+ const Node lut = [&]() {
+ if (opcode->get().GetId() == OpCode::Id::LOP3_R) {
+ return Immediate(instr.alu.lop3.GetImmLut28());
+ } else {
+ return Immediate(instr.alu.lop3.GetImmLut48());
+ }
+ }();
+
+ WriteLop3Instruction(bb, instr.gpr0, op_a, op_b, op_c, lut, instr.generates_cc);
+ break;
+ }
+ case OpCode::Id::IMNMX_C:
+ case OpCode::Id::IMNMX_R:
+ case OpCode::Id::IMNMX_IMM: {
+ UNIMPLEMENTED_IF(instr.imnmx.exchange != Tegra::Shader::IMinMaxExchange::None);
+
+ const bool is_signed = instr.imnmx.is_signed;
+
+ const Node condition = GetPredicate(instr.imnmx.pred, instr.imnmx.negate_pred != 0);
+ const Node min = SignedOperation(OperationCode::IMin, is_signed, NO_PRECISE, op_a, op_b);
+ const Node max = SignedOperation(OperationCode::IMax, is_signed, NO_PRECISE, op_a, op_b);
+ const Node value = Operation(OperationCode::Select, NO_PRECISE, condition, min, max);
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::LEA_R2:
+ case OpCode::Id::LEA_R1:
+ case OpCode::Id::LEA_IMM:
+ case OpCode::Id::LEA_RZ:
+ case OpCode::Id::LEA_HI: {
+ const auto [op_a, op_b, op_c] = [&]() -> std::tuple<Node, Node, Node> {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::LEA_R2: {
+ return {GetRegister(instr.gpr20), GetRegister(instr.gpr39),
+ Immediate(static_cast<u32>(instr.lea.r2.entry_a))};
+ }
+
+ case OpCode::Id::LEA_R1: {
+ const bool neg = instr.lea.r1.neg != 0;
+ return {GetOperandAbsNegInteger(GetRegister(instr.gpr8), false, neg, true),
+ GetRegister(instr.gpr20),
+ Immediate(static_cast<u32>(instr.lea.r1.entry_a))};
+ }
+
+ case OpCode::Id::LEA_IMM: {
+ const bool neg = instr.lea.imm.neg != 0;
+ return {Immediate(static_cast<u32>(instr.lea.imm.entry_a)),
+ GetOperandAbsNegInteger(GetRegister(instr.gpr8), false, neg, true),
+ Immediate(static_cast<u32>(instr.lea.imm.entry_b))};
+ }
+
+ case OpCode::Id::LEA_RZ: {
+ const bool neg = instr.lea.rz.neg != 0;
+ return {GetConstBuffer(instr.lea.rz.cb_index, instr.lea.rz.cb_offset),
+ GetOperandAbsNegInteger(GetRegister(instr.gpr8), false, neg, true),
+ Immediate(static_cast<u32>(instr.lea.rz.entry_a))};
+ }
+
+ case OpCode::Id::LEA_HI:
+ default:
+ UNIMPLEMENTED_MSG("Unhandled LEA subinstruction: {}", opcode->get().GetName());
+
+ return {Immediate(static_cast<u32>(instr.lea.imm.entry_a)), GetRegister(instr.gpr8),
+ Immediate(static_cast<u32>(instr.lea.imm.entry_b))};
+ }
+ }();
+
+ UNIMPLEMENTED_IF_MSG(instr.lea.pred48 != static_cast<u64>(Pred::UnusedIndex),
+ "Unhandled LEA Predicate");
+
+ const Node shifted_c =
+ Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, Immediate(1), op_c);
+ const Node mul_bc = Operation(OperationCode::IMul, NO_PRECISE, op_b, shifted_c);
+ const Node value = Operation(OperationCode::IAdd, NO_PRECISE, op_a, mul_bc);
+
+ SetRegister(bb, instr.gpr0, value);
+
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled ArithmeticInteger instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+void ShaderIR::WriteLop3Instruction(BasicBlock& bb, Register dest, Node op_a, Node op_b, Node op_c,
+ Node imm_lut, bool sets_cc) {
+ constexpr u32 lop_iterations = 32;
+ const Node one = Immediate(1);
+ const Node two = Immediate(2);
+
+ Node value{};
+ for (u32 i = 0; i < lop_iterations; ++i) {
+ const Node shift_amount = Immediate(i);
+
+ const Node a = Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, op_c, shift_amount);
+ const Node pack_0 = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, a, one);
+
+ const Node b = Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, op_b, shift_amount);
+ const Node c = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, b, one);
+ const Node pack_1 = Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, c, one);
+
+ const Node d = Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, op_a, shift_amount);
+ const Node e = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, d, one);
+ const Node pack_2 = Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, e, two);
+
+ const Node pack_01 = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, pack_0, pack_1);
+ const Node pack_012 = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, pack_01, pack_2);
+
+ const Node shifted_bit =
+ Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, imm_lut, pack_012);
+ const Node bit = Operation(OperationCode::IBitwiseAnd, NO_PRECISE, shifted_bit, one);
+
+ const Node right =
+ Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, bit, shift_amount);
+
+ if (i > 0) {
+ value = Operation(OperationCode::IBitwiseOr, NO_PRECISE, value, right);
+ } else {
+ value = right;
+ }
+ }
+
+ SetInternalFlagsFromInteger(bb, value, sets_cc);
+ SetRegister(bb, dest, value);
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/arithmetic_integer_immediate.cpp b/src/video_core/shader/decode/arithmetic_integer_immediate.cpp
new file mode 100644
index 000000000..b26a6e473
--- /dev/null
+++ b/src/video_core/shader/decode/arithmetic_integer_immediate.cpp
@@ -0,0 +1,96 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::LogicOperation;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+using Tegra::Shader::PredicateResultMode;
+using Tegra::Shader::Register;
+
+u32 ShaderIR::DecodeArithmeticIntegerImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ Node op_a = GetRegister(instr.gpr8);
+ Node op_b = Immediate(static_cast<s32>(instr.alu.imm20_32));
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::IADD32I: {
+ UNIMPLEMENTED_IF_MSG(instr.iadd32i.saturate, "IADD32I saturation is not implemented");
+
+ op_a = GetOperandAbsNegInteger(op_a, false, instr.iadd32i.negate_a, true);
+
+ const Node value = Operation(OperationCode::IAdd, PRECISE, op_a, op_b);
+
+ SetInternalFlagsFromInteger(bb, value, instr.op_32.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::LOP32I: {
+ if (instr.alu.lop32i.invert_a)
+ op_a = Operation(OperationCode::IBitwiseNot, NO_PRECISE, op_a);
+
+ if (instr.alu.lop32i.invert_b)
+ op_b = Operation(OperationCode::IBitwiseNot, NO_PRECISE, op_b);
+
+ WriteLogicOperation(bb, instr.gpr0, instr.alu.lop32i.operation, op_a, op_b,
+ PredicateResultMode::None, Pred::UnusedIndex, instr.op_32.generates_cc);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled ArithmeticIntegerImmediate instruction: {}",
+ opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+void ShaderIR::WriteLogicOperation(BasicBlock& bb, Register dest, LogicOperation logic_op,
+ Node op_a, Node op_b, PredicateResultMode predicate_mode,
+ Pred predicate, bool sets_cc) {
+ const Node result = [&]() {
+ switch (logic_op) {
+ case LogicOperation::And:
+ return Operation(OperationCode::IBitwiseAnd, PRECISE, op_a, op_b);
+ case LogicOperation::Or:
+ return Operation(OperationCode::IBitwiseOr, PRECISE, op_a, op_b);
+ case LogicOperation::Xor:
+ return Operation(OperationCode::IBitwiseXor, PRECISE, op_a, op_b);
+ case LogicOperation::PassB:
+ return op_b;
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented logic operation={}", static_cast<u32>(logic_op));
+ return Immediate(0);
+ }
+ }();
+
+ SetInternalFlagsFromInteger(bb, result, sets_cc);
+ SetRegister(bb, dest, result);
+
+ // Write the predicate value depending on the predicate mode.
+ switch (predicate_mode) {
+ case PredicateResultMode::None:
+ // Do nothing.
+ return;
+ case PredicateResultMode::NotZero: {
+ // Set the predicate to true if the result is not zero.
+ const Node compare = Operation(OperationCode::LogicalINotEqual, result, Immediate(0));
+ SetPredicate(bb, static_cast<u64>(predicate), compare);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented predicate result mode: {}",
+ static_cast<u32>(predicate_mode));
+ }
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/bfe.cpp b/src/video_core/shader/decode/bfe.cpp
new file mode 100644
index 000000000..0734141b0
--- /dev/null
+++ b/src/video_core/shader/decode/bfe.cpp
@@ -0,0 +1,49 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeBfe(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF(instr.bfe.negate_b);
+
+ Node op_a = GetRegister(instr.gpr8);
+ op_a = GetOperandAbsNegInteger(op_a, false, instr.bfe.negate_a, false);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::BFE_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in BFE is not implemented");
+
+ const Node inner_shift_imm = Immediate(static_cast<u32>(instr.bfe.GetLeftShiftValue()));
+ const Node outer_shift_imm =
+ Immediate(static_cast<u32>(instr.bfe.GetLeftShiftValue() + instr.bfe.shift_position));
+
+ const Node inner_shift =
+ Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, op_a, inner_shift_imm);
+ const Node outer_shift =
+ Operation(OperationCode::ILogicalShiftRight, NO_PRECISE, inner_shift, outer_shift_imm);
+
+ SetInternalFlagsFromInteger(bb, outer_shift, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, outer_shift);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled BFE instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/bfi.cpp b/src/video_core/shader/decode/bfi.cpp
new file mode 100644
index 000000000..942d6729d
--- /dev/null
+++ b/src/video_core/shader/decode/bfi.cpp
@@ -0,0 +1,41 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeBfi(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const auto [base, packed_shift] = [&]() -> std::tuple<Node, Node> {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::BFI_IMM_R:
+ return {GetRegister(instr.gpr39), Immediate(instr.alu.GetSignedImm20_20())};
+ default:
+ UNREACHABLE();
+ return {Immediate(0), Immediate(0)};
+ }
+ }();
+ const Node insert = GetRegister(instr.gpr8);
+ const Node offset = BitfieldExtract(packed_shift, 0, 8);
+ const Node bits = BitfieldExtract(packed_shift, 8, 8);
+
+ const Node value =
+ Operation(OperationCode::UBitfieldInsert, PRECISE, base, insert, offset, bits);
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/conversion.cpp b/src/video_core/shader/decode/conversion.cpp
new file mode 100644
index 000000000..ee18d3a99
--- /dev/null
+++ b/src/video_core/shader/decode/conversion.cpp
@@ -0,0 +1,149 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Register;
+
+u32 ShaderIR::DecodeConversion(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::I2I_R: {
+ UNIMPLEMENTED_IF(instr.conversion.selector);
+
+ const bool input_signed = instr.conversion.is_input_signed;
+ const bool output_signed = instr.conversion.is_output_signed;
+
+ Node value = GetRegister(instr.gpr20);
+ value = ConvertIntegerSize(value, instr.conversion.src_size, input_signed);
+
+ value = GetOperandAbsNegInteger(value, instr.conversion.abs_a, instr.conversion.negate_a,
+ input_signed);
+ if (input_signed != output_signed) {
+ value = SignedOperation(OperationCode::ICastUnsigned, output_signed, NO_PRECISE, value);
+ }
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::I2F_R:
+ case OpCode::Id::I2F_C: {
+ UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
+ UNIMPLEMENTED_IF(instr.conversion.selector);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in I2F is not implemented");
+
+ Node value = [&]() {
+ if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+ const bool input_signed = instr.conversion.is_input_signed;
+ value = ConvertIntegerSize(value, instr.conversion.src_size, input_signed);
+ value = GetOperandAbsNegInteger(value, instr.conversion.abs_a, false, input_signed);
+ value = SignedOperation(OperationCode::FCastInteger, input_signed, PRECISE, value);
+ value = GetOperandAbsNegFloat(value, false, instr.conversion.negate_a);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::F2F_R:
+ case OpCode::Id::F2F_C: {
+ UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
+ UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in F2F is not implemented");
+
+ Node value = [&]() {
+ if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ value = GetOperandAbsNegFloat(value, instr.conversion.abs_a, instr.conversion.negate_a);
+
+ value = [&]() {
+ switch (instr.conversion.f2f.rounding) {
+ case Tegra::Shader::F2fRoundingOp::None:
+ return value;
+ case Tegra::Shader::F2fRoundingOp::Round:
+ return Operation(OperationCode::FRoundEven, PRECISE, value);
+ case Tegra::Shader::F2fRoundingOp::Floor:
+ return Operation(OperationCode::FFloor, PRECISE, value);
+ case Tegra::Shader::F2fRoundingOp::Ceil:
+ return Operation(OperationCode::FCeil, PRECISE, value);
+ case Tegra::Shader::F2fRoundingOp::Trunc:
+ return Operation(OperationCode::FTrunc, PRECISE, value);
+ }
+ UNIMPLEMENTED_MSG("Unimplemented F2F rounding mode {}",
+ static_cast<u32>(instr.conversion.f2f.rounding.Value()));
+ return Immediate(0);
+ }();
+ value = GetSaturatedFloat(value, instr.alu.saturate_d);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::F2I_R:
+ case OpCode::Id::F2I_C: {
+ UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in F2I is not implemented");
+ Node value = [&]() {
+ if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ value = GetOperandAbsNegFloat(value, instr.conversion.abs_a, instr.conversion.negate_a);
+
+ value = [&]() {
+ switch (instr.conversion.f2i.rounding) {
+ case Tegra::Shader::F2iRoundingOp::None:
+ return value;
+ case Tegra::Shader::F2iRoundingOp::Floor:
+ return Operation(OperationCode::FFloor, PRECISE, value);
+ case Tegra::Shader::F2iRoundingOp::Ceil:
+ return Operation(OperationCode::FCeil, PRECISE, value);
+ case Tegra::Shader::F2iRoundingOp::Trunc:
+ return Operation(OperationCode::FTrunc, PRECISE, value);
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented F2I rounding mode {}",
+ static_cast<u32>(instr.conversion.f2i.rounding.Value()));
+ return Immediate(0);
+ }
+ }();
+ const bool is_signed = instr.conversion.is_output_signed;
+ value = SignedOperation(OperationCode::ICastFloat, is_signed, PRECISE, value);
+ value = ConvertIntegerSize(value, instr.conversion.dest_size, is_signed);
+
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled conversion instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/decode_integer_set.cpp b/src/video_core/shader/decode/decode_integer_set.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/src/video_core/shader/decode/decode_integer_set.cpp
diff --git a/src/video_core/shader/decode/ffma.cpp b/src/video_core/shader/decode/ffma.cpp
new file mode 100644
index 000000000..be8dc2230
--- /dev/null
+++ b/src/video_core/shader/decode/ffma.cpp
@@ -0,0 +1,59 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeFfma(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF_MSG(instr.ffma.cc != 0, "FFMA cc not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.ffma.tab5980_0 != 1, "FFMA tab5980_0({}) not implemented",
+ instr.ffma.tab5980_0.Value()); // Seems to be 1 by default based on SMO
+ UNIMPLEMENTED_IF_MSG(instr.ffma.tab5980_1 != 0, "FFMA tab5980_1({}) not implemented",
+ instr.ffma.tab5980_1.Value());
+
+ const Node op_a = GetRegister(instr.gpr8);
+
+ auto [op_b, op_c] = [&]() -> std::tuple<Node, Node> {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::FFMA_CR: {
+ return {GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset),
+ GetRegister(instr.gpr39)};
+ }
+ case OpCode::Id::FFMA_RR:
+ return {GetRegister(instr.gpr20), GetRegister(instr.gpr39)};
+ case OpCode::Id::FFMA_RC: {
+ return {GetRegister(instr.gpr39),
+ GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset)};
+ }
+ case OpCode::Id::FFMA_IMM:
+ return {GetImmediate19(instr), GetRegister(instr.gpr39)};
+ default:
+ UNIMPLEMENTED_MSG("Unhandled FFMA instruction: {}", opcode->get().GetName());
+ return {Immediate(0), Immediate(0)};
+ }
+ }();
+
+ op_b = GetOperandAbsNegFloat(op_b, false, instr.ffma.negate_b);
+ op_c = GetOperandAbsNegFloat(op_c, false, instr.ffma.negate_c);
+
+ Node value = Operation(OperationCode::FFma, PRECISE, op_a, op_b, op_c);
+ value = GetSaturatedFloat(value, instr.alu.saturate_d);
+
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/float_set.cpp b/src/video_core/shader/decode/float_set.cpp
new file mode 100644
index 000000000..ba846f1bd
--- /dev/null
+++ b/src/video_core/shader/decode/float_set.cpp
@@ -0,0 +1,58 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeFloatSet(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a = GetOperandAbsNegFloat(GetRegister(instr.gpr8), instr.fset.abs_a != 0,
+ instr.fset.neg_a != 0);
+
+ Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return GetImmediate19(instr);
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ op_b = GetOperandAbsNegFloat(op_b, instr.fset.abs_b != 0, instr.fset.neg_b != 0);
+
+ // The fset instruction sets a register to 1.0 or -1 (depending on the bf bit) if the
+ // condition is true, and to 0 otherwise.
+ const Node second_pred = GetPredicate(instr.fset.pred39, instr.fset.neg_pred != 0);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.fset.op);
+ const Node first_pred = GetPredicateComparisonFloat(instr.fset.cond, op_a, op_b);
+
+ const Node predicate = Operation(combiner, first_pred, second_pred);
+
+ const Node true_value = instr.fset.bf ? Immediate(1.0f) : Immediate(-1);
+ const Node false_value = instr.fset.bf ? Immediate(0.0f) : Immediate(0);
+ const Node value =
+ Operation(OperationCode::Select, PRECISE, predicate, true_value, false_value);
+
+ if (instr.fset.bf) {
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ } else {
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ }
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/float_set_predicate.cpp b/src/video_core/shader/decode/float_set_predicate.cpp
new file mode 100644
index 000000000..e88b04d18
--- /dev/null
+++ b/src/video_core/shader/decode/float_set_predicate.cpp
@@ -0,0 +1,56 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+
+u32 ShaderIR::DecodeFloatSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a = GetOperandAbsNegFloat(GetRegister(instr.gpr8), instr.fsetp.abs_a != 0,
+ instr.fsetp.neg_a != 0);
+ Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return GetImmediate19(instr);
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+ op_b = GetOperandAbsNegFloat(op_b, instr.fsetp.abs_b, false);
+
+ // We can't use the constant predicate as destination.
+ ASSERT(instr.fsetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+
+ const Node predicate = GetPredicateComparisonFloat(instr.fsetp.cond, op_a, op_b);
+ const Node second_pred = GetPredicate(instr.fsetp.pred39, instr.fsetp.neg_pred != 0);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.fsetp.op);
+ const Node value = Operation(combiner, predicate, second_pred);
+
+ // Set the primary predicate to the result of Predicate OP SecondPredicate
+ SetPredicate(bb, instr.fsetp.pred3, value);
+
+ if (instr.fsetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
+ // if enabled
+ const Node negated_pred = Operation(OperationCode::LogicalNegate, predicate);
+ const Node second_value = Operation(combiner, negated_pred, second_pred);
+ SetPredicate(bb, instr.fsetp.pred0, second_value);
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/half_set.cpp b/src/video_core/shader/decode/half_set.cpp
new file mode 100644
index 000000000..dfd7cb98f
--- /dev/null
+++ b/src/video_core/shader/decode/half_set.cpp
@@ -0,0 +1,67 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <array>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeHalfSet(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF(instr.hset2.ftz != 0);
+
+ // instr.hset2.type_a
+ // instr.hset2.type_b
+ Node op_a = GetRegister(instr.gpr8);
+ Node op_b = [&]() {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HSET2_R:
+ return GetRegister(instr.gpr20);
+ default:
+ UNREACHABLE();
+ return Immediate(0);
+ }
+ }();
+
+ op_a = GetOperandAbsNegHalf(op_a, instr.hset2.abs_a, instr.hset2.negate_a);
+ op_b = GetOperandAbsNegHalf(op_b, instr.hset2.abs_b, instr.hset2.negate_b);
+
+ const Node second_pred = GetPredicate(instr.hset2.pred39, instr.hset2.neg_pred);
+
+ MetaHalfArithmetic meta{false, {instr.hset2.type_a, instr.hset2.type_b}};
+ const Node comparison_pair = GetPredicateComparisonHalf(instr.hset2.cond, meta, op_a, op_b);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.hset2.op);
+
+ // HSET2 operates on each half float in the pack.
+ std::array<Node, 2> values;
+ for (u32 i = 0; i < 2; ++i) {
+ const u32 raw_value = instr.hset2.bf ? 0x3c00 : 0xffff;
+ const Node true_value = Immediate(raw_value << (i * 16));
+ const Node false_value = Immediate(0);
+
+ const Node comparison =
+ Operation(OperationCode::LogicalPick2, comparison_pair, Immediate(i));
+ const Node predicate = Operation(combiner, comparison, second_pred);
+
+ values[i] =
+ Operation(OperationCode::Select, NO_PRECISE, predicate, true_value, false_value);
+ }
+
+ const Node value = Operation(OperationCode::UBitwiseOr, NO_PRECISE, values[0], values[1]);
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/half_set_predicate.cpp b/src/video_core/shader/decode/half_set_predicate.cpp
new file mode 100644
index 000000000..53c44ae5a
--- /dev/null
+++ b/src/video_core/shader/decode/half_set_predicate.cpp
@@ -0,0 +1,62 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+
+u32 ShaderIR::DecodeHalfSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF(instr.hsetp2.ftz != 0);
+
+ Node op_a = GetRegister(instr.gpr8);
+ op_a = GetOperandAbsNegHalf(op_a, instr.hsetp2.abs_a, instr.hsetp2.negate_a);
+
+ const Node op_b = [&]() {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HSETP2_R:
+ return GetOperandAbsNegHalf(GetRegister(instr.gpr20), instr.hsetp2.abs_a,
+ instr.hsetp2.negate_b);
+ default:
+ UNREACHABLE();
+ return Immediate(0);
+ }
+ }();
+
+ // We can't use the constant predicate as destination.
+ ASSERT(instr.hsetp2.pred3 != static_cast<u64>(Pred::UnusedIndex));
+
+ const Node second_pred = GetPredicate(instr.hsetp2.pred39, instr.hsetp2.neg_pred != 0);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.hsetp2.op);
+ const OperationCode pair_combiner =
+ instr.hsetp2.h_and ? OperationCode::LogicalAll2 : OperationCode::LogicalAny2;
+
+ MetaHalfArithmetic meta = {false, {instr.hsetp2.type_a, instr.hsetp2.type_b}};
+ const Node comparison = GetPredicateComparisonHalf(instr.hsetp2.cond, meta, op_a, op_b);
+ const Node first_pred = Operation(pair_combiner, comparison);
+
+ // Set the primary predicate to the result of Predicate OP SecondPredicate
+ const Node value = Operation(combiner, first_pred, second_pred);
+ SetPredicate(bb, instr.hsetp2.pred3, value);
+
+ if (instr.hsetp2.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ // Set the secondary predicate to the result of !Predicate OP SecondPredicate, if enabled
+ const Node negated_pred = Operation(OperationCode::LogicalNegate, first_pred);
+ SetPredicate(bb, instr.hsetp2.pred0, Operation(combiner, negated_pred, second_pred));
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/hfma2.cpp b/src/video_core/shader/decode/hfma2.cpp
new file mode 100644
index 000000000..4a6b945f9
--- /dev/null
+++ b/src/video_core/shader/decode/hfma2.cpp
@@ -0,0 +1,76 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <tuple>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::HalfPrecision;
+using Tegra::Shader::HalfType;
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeHfma2(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ if (opcode->get().GetId() == OpCode::Id::HFMA2_RR) {
+ UNIMPLEMENTED_IF(instr.hfma2.rr.precision != HalfPrecision::None);
+ } else {
+ UNIMPLEMENTED_IF(instr.hfma2.precision != HalfPrecision::None);
+ }
+
+ constexpr auto identity = HalfType::H0_H1;
+
+ const HalfType type_a = instr.hfma2.type_a;
+ const Node op_a = GetRegister(instr.gpr8);
+
+ bool neg_b{}, neg_c{};
+ auto [saturate, type_b, op_b, type_c,
+ op_c] = [&]() -> std::tuple<bool, HalfType, Node, HalfType, Node> {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::HFMA2_CR:
+ neg_b = instr.hfma2.negate_b;
+ neg_c = instr.hfma2.negate_c;
+ return {instr.hfma2.saturate, instr.hfma2.type_b,
+ GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset), instr.hfma2.type_reg39,
+ GetRegister(instr.gpr39)};
+ case OpCode::Id::HFMA2_RC:
+ neg_b = instr.hfma2.negate_b;
+ neg_c = instr.hfma2.negate_c;
+ return {instr.hfma2.saturate, instr.hfma2.type_reg39, GetRegister(instr.gpr39),
+ instr.hfma2.type_b, GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset)};
+ case OpCode::Id::HFMA2_RR:
+ neg_b = instr.hfma2.rr.negate_b;
+ neg_c = instr.hfma2.rr.negate_c;
+ return {instr.hfma2.rr.saturate, instr.hfma2.type_b, GetRegister(instr.gpr20),
+ instr.hfma2.rr.type_c, GetRegister(instr.gpr39)};
+ case OpCode::Id::HFMA2_IMM_R:
+ neg_c = instr.hfma2.negate_c;
+ return {instr.hfma2.saturate, identity, UnpackHalfImmediate(instr, true),
+ instr.hfma2.type_reg39, GetRegister(instr.gpr39)};
+ default:
+ return {false, identity, Immediate(0), identity, Immediate(0)};
+ }
+ }();
+ UNIMPLEMENTED_IF_MSG(saturate, "HFMA2 saturation is not implemented");
+
+ op_b = GetOperandAbsNegHalf(op_b, false, neg_b);
+ op_c = GetOperandAbsNegHalf(op_c, false, neg_c);
+
+ MetaHalfArithmetic meta{true, {type_a, type_b, type_c}};
+ Node value = Operation(OperationCode::HFma, meta, op_a, op_b, op_c);
+ value = HalfMerge(GetRegister(instr.gpr0), value, instr.hfma2.merge);
+
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/integer_set.cpp b/src/video_core/shader/decode/integer_set.cpp
new file mode 100644
index 000000000..85e67b03b
--- /dev/null
+++ b/src/video_core/shader/decode/integer_set.cpp
@@ -0,0 +1,50 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeIntegerSet(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a = GetRegister(instr.gpr8);
+ const Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return Immediate(instr.alu.GetSignedImm20_20());
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ // The iset instruction sets a register to 1.0 or -1 (depending on the bf bit) if the condition
+ // is true, and to 0 otherwise.
+ const Node second_pred = GetPredicate(instr.iset.pred39, instr.iset.neg_pred != 0);
+ const Node first_pred =
+ GetPredicateComparisonInteger(instr.iset.cond, instr.iset.is_signed, op_a, op_b);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.iset.op);
+
+ const Node predicate = Operation(combiner, first_pred, second_pred);
+
+ const Node true_value = instr.iset.bf ? Immediate(1.0f) : Immediate(-1);
+ const Node false_value = instr.iset.bf ? Immediate(0.0f) : Immediate(0);
+ const Node value =
+ Operation(OperationCode::Select, PRECISE, predicate, true_value, false_value);
+
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/integer_set_predicate.cpp b/src/video_core/shader/decode/integer_set_predicate.cpp
new file mode 100644
index 000000000..c8b105a08
--- /dev/null
+++ b/src/video_core/shader/decode/integer_set_predicate.cpp
@@ -0,0 +1,53 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+
+u32 ShaderIR::DecodeIntegerSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a = GetRegister(instr.gpr8);
+
+ const Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return Immediate(instr.alu.GetSignedImm20_20());
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ // We can't use the constant predicate as destination.
+ ASSERT(instr.isetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+
+ const Node second_pred = GetPredicate(instr.isetp.pred39, instr.isetp.neg_pred != 0);
+ const Node predicate =
+ GetPredicateComparisonInteger(instr.isetp.cond, instr.isetp.is_signed, op_a, op_b);
+
+ // Set the primary predicate to the result of Predicate OP SecondPredicate
+ const OperationCode combiner = GetPredicateCombiner(instr.isetp.op);
+ const Node value = Operation(combiner, predicate, second_pred);
+ SetPredicate(bb, instr.isetp.pred3, value);
+
+ if (instr.isetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ // Set the secondary predicate to the result of !Predicate OP SecondPredicate, if enabled
+ const Node negated_pred = Operation(OperationCode::LogicalNegate, predicate);
+ SetPredicate(bb, instr.isetp.pred0, Operation(combiner, negated_pred, second_pred));
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/memory.cpp b/src/video_core/shader/decode/memory.cpp
new file mode 100644
index 000000000..04cb386b7
--- /dev/null
+++ b/src/video_core/shader/decode/memory.cpp
@@ -0,0 +1,737 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <vector>
+#include <fmt/format.h>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Attribute;
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Register;
+using Tegra::Shader::TextureMiscMode;
+using Tegra::Shader::TextureProcessMode;
+using Tegra::Shader::TextureType;
+
+static std::size_t GetCoordCount(TextureType texture_type) {
+ switch (texture_type) {
+ case TextureType::Texture1D:
+ return 1;
+ case TextureType::Texture2D:
+ return 2;
+ case TextureType::Texture3D:
+ case TextureType::TextureCube:
+ return 3;
+ default:
+ UNIMPLEMENTED_MSG("Unhandled texture type: {}", static_cast<u32>(texture_type));
+ return 0;
+ }
+}
+
+u32 ShaderIR::DecodeMemory(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::LD_A: {
+ // Note: Shouldn't this be interp mode flat? As in no interpolation made.
+ UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
+ "Indirect attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
+ "Unaligned attribute loads are not supported");
+
+ Tegra::Shader::IpaMode input_mode{Tegra::Shader::IpaInterpMode::Perspective,
+ Tegra::Shader::IpaSampleMode::Default};
+
+ u64 next_element = instr.attribute.fmt20.element;
+ auto next_index = static_cast<u64>(instr.attribute.fmt20.index.Value());
+
+ const auto LoadNextElement = [&](u32 reg_offset) {
+ const Node buffer = GetRegister(instr.gpr39);
+ const Node attribute = GetInputAttribute(static_cast<Attribute::Index>(next_index),
+ next_element, input_mode, buffer);
+
+ SetRegister(bb, instr.gpr0.Value() + reg_offset, attribute);
+
+ // Load the next attribute element into the following register. If the element
+ // to load goes beyond the vec4 size, load the first element of the next
+ // attribute.
+ next_element = (next_element + 1) % 4;
+ next_index = next_index + (next_element == 0 ? 1 : 0);
+ };
+
+ const u32 num_words = static_cast<u32>(instr.attribute.fmt20.size.Value()) + 1;
+ for (u32 reg_offset = 0; reg_offset < num_words; ++reg_offset) {
+ LoadNextElement(reg_offset);
+ }
+ break;
+ }
+ case OpCode::Id::LD_C: {
+ UNIMPLEMENTED_IF(instr.ld_c.unknown != 0);
+
+ Node index = GetRegister(instr.gpr8);
+
+ const Node op_a =
+ GetConstBufferIndirect(instr.cbuf36.index, instr.cbuf36.offset + 0, index);
+
+ switch (instr.ld_c.type.Value()) {
+ case Tegra::Shader::UniformType::Single:
+ SetRegister(bb, instr.gpr0, op_a);
+ break;
+
+ case Tegra::Shader::UniformType::Double: {
+ const Node op_b =
+ GetConstBufferIndirect(instr.cbuf36.index, instr.cbuf36.offset + 4, index);
+
+ SetTemporal(bb, 0, op_a);
+ SetTemporal(bb, 1, op_b);
+ SetRegister(bb, instr.gpr0, GetTemporal(0));
+ SetRegister(bb, instr.gpr0.Value() + 1, GetTemporal(1));
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled type: {}", static_cast<unsigned>(instr.ld_c.type.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::LD_L: {
+ UNIMPLEMENTED_IF_MSG(instr.ld_l.unknown == 1, "LD_L Unhandled mode: {}",
+ static_cast<unsigned>(instr.ld_l.unknown.Value()));
+
+ const Node index = Operation(OperationCode::IAdd, GetRegister(instr.gpr8),
+ Immediate(static_cast<s32>(instr.smem_imm)));
+ const Node lmem = GetLocalMemory(index);
+
+ switch (instr.ldst_sl.type.Value()) {
+ case Tegra::Shader::StoreType::Bytes32:
+ SetRegister(bb, instr.gpr0, lmem);
+ break;
+ default:
+ UNIMPLEMENTED_MSG("LD_L Unhandled type: {}",
+ static_cast<unsigned>(instr.ldst_sl.type.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::LDG: {
+ const u32 count = [&]() {
+ switch (instr.ldg.type) {
+ case Tegra::Shader::UniformType::Single:
+ return 1;
+ case Tegra::Shader::UniformType::Double:
+ return 2;
+ case Tegra::Shader::UniformType::Quad:
+ case Tegra::Shader::UniformType::UnsignedQuad:
+ return 4;
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented LDG size!");
+ return 1;
+ }
+ }();
+
+ const Node addr_register = GetRegister(instr.gpr8);
+ const Node base_address = TrackCbuf(addr_register, code, static_cast<s64>(code.size()));
+ const auto cbuf = std::get_if<CbufNode>(base_address);
+ ASSERT(cbuf != nullptr);
+ const auto cbuf_offset_imm = std::get_if<ImmediateNode>(cbuf->GetOffset());
+ ASSERT(cbuf_offset_imm != nullptr);
+ const auto cbuf_offset = cbuf_offset_imm->GetValue() * 4;
+
+ bb.push_back(Comment(
+ fmt::format("Base address is c[0x{:x}][0x{:x}]", cbuf->GetIndex(), cbuf_offset)));
+
+ const GlobalMemoryBase descriptor{cbuf->GetIndex(), cbuf_offset};
+ used_global_memory_bases.insert(descriptor);
+
+ const Node immediate_offset =
+ Immediate(static_cast<u32>(instr.ldg.immediate_offset.Value()));
+ const Node base_real_address =
+ Operation(OperationCode::UAdd, NO_PRECISE, immediate_offset, addr_register);
+
+ for (u32 i = 0; i < count; ++i) {
+ const Node it_offset = Immediate(i * 4);
+ const Node real_address =
+ Operation(OperationCode::UAdd, NO_PRECISE, base_real_address, it_offset);
+ const Node gmem = StoreNode(GmemNode(real_address, base_address, descriptor));
+
+ SetTemporal(bb, i, gmem);
+ }
+ for (u32 i = 0; i < count; ++i) {
+ SetRegister(bb, instr.gpr0.Value() + i, GetTemporal(i));
+ }
+ break;
+ }
+ case OpCode::Id::ST_A: {
+ UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
+ "Indirect attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
+ "Unaligned attribute loads are not supported");
+
+ u64 next_element = instr.attribute.fmt20.element;
+ auto next_index = static_cast<u64>(instr.attribute.fmt20.index.Value());
+
+ const auto StoreNextElement = [&](u32 reg_offset) {
+ const auto dest = GetOutputAttribute(static_cast<Attribute::Index>(next_index),
+ next_element, GetRegister(instr.gpr39));
+ const auto src = GetRegister(instr.gpr0.Value() + reg_offset);
+
+ bb.push_back(Operation(OperationCode::Assign, dest, src));
+
+ // Load the next attribute element into the following register. If the element
+ // to load goes beyond the vec4 size, load the first element of the next
+ // attribute.
+ next_element = (next_element + 1) % 4;
+ next_index = next_index + (next_element == 0 ? 1 : 0);
+ };
+
+ const u32 num_words = static_cast<u32>(instr.attribute.fmt20.size.Value()) + 1;
+ for (u32 reg_offset = 0; reg_offset < num_words; ++reg_offset) {
+ StoreNextElement(reg_offset);
+ }
+
+ break;
+ }
+ case OpCode::Id::ST_L: {
+ UNIMPLEMENTED_IF_MSG(instr.st_l.unknown == 0, "ST_L Unhandled mode: {}",
+ static_cast<u32>(instr.st_l.unknown.Value()));
+
+ const Node index = Operation(OperationCode::IAdd, NO_PRECISE, GetRegister(instr.gpr8),
+ Immediate(static_cast<s32>(instr.smem_imm)));
+
+ switch (instr.ldst_sl.type.Value()) {
+ case Tegra::Shader::StoreType::Bytes32:
+ SetLocalMemory(bb, index, GetRegister(instr.gpr0));
+ break;
+ default:
+ UNIMPLEMENTED_MSG("ST_L Unhandled type: {}",
+ static_cast<u32>(instr.ldst_sl.type.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::TEX: {
+ UNIMPLEMENTED_IF_MSG(instr.tex.UsesMiscMode(TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+
+ if (instr.tex.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TEX.NODEP implementation is incomplete");
+ }
+
+ const TextureType texture_type{instr.tex.texture_type};
+ const bool is_array = instr.tex.array != 0;
+ const bool depth_compare = instr.tex.UsesMiscMode(TextureMiscMode::DC);
+ const auto process_mode = instr.tex.GetTextureProcessMode();
+ WriteTexInstructionFloat(
+ bb, instr, GetTexCode(instr, texture_type, process_mode, depth_compare, is_array));
+ break;
+ }
+ case OpCode::Id::TEXS: {
+ const TextureType texture_type{instr.texs.GetTextureType()};
+ const bool is_array{instr.texs.IsArrayTexture()};
+ const bool depth_compare = instr.texs.UsesMiscMode(TextureMiscMode::DC);
+ const auto process_mode = instr.texs.GetTextureProcessMode();
+
+ if (instr.texs.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TEXS.NODEP implementation is incomplete");
+ }
+
+ const Node4 components =
+ GetTexsCode(instr, texture_type, process_mode, depth_compare, is_array);
+
+ if (instr.texs.fp32_flag) {
+ WriteTexsInstructionFloat(bb, instr, components);
+ } else {
+ WriteTexsInstructionHalfFloat(bb, instr, components);
+ }
+ break;
+ }
+ case OpCode::Id::TLD4: {
+ ASSERT(instr.tld4.array == 0);
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(TextureMiscMode::NDV),
+ "NDV is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(TextureMiscMode::PTP),
+ "PTP is not implemented");
+
+ if (instr.tld4.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TLD4.NODEP implementation is incomplete");
+ }
+
+ const auto texture_type = instr.tld4.texture_type.Value();
+ const bool depth_compare = instr.tld4.UsesMiscMode(TextureMiscMode::DC);
+ const bool is_array = instr.tld4.array != 0;
+ WriteTexInstructionFloat(bb, instr,
+ GetTld4Code(instr, texture_type, depth_compare, is_array));
+ break;
+ }
+ case OpCode::Id::TLD4S: {
+ UNIMPLEMENTED_IF_MSG(instr.tld4s.UsesMiscMode(TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+
+ if (instr.tld4s.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TLD4S.NODEP implementation is incomplete");
+ }
+
+ const bool depth_compare = instr.tld4s.UsesMiscMode(TextureMiscMode::DC);
+ const Node op_a = GetRegister(instr.gpr8);
+ const Node op_b = GetRegister(instr.gpr20);
+
+ std::vector<Node> coords;
+
+ // TODO(Subv): Figure out how the sampler type is encoded in the TLD4S instruction.
+ if (depth_compare) {
+ // Note: TLD4S coordinate encoding works just like TEXS's
+ const Node op_y = GetRegister(instr.gpr8.Value() + 1);
+ coords.push_back(op_a);
+ coords.push_back(op_y);
+ coords.push_back(op_b);
+ } else {
+ coords.push_back(op_a);
+ coords.push_back(op_b);
+ }
+ const auto num_coords = static_cast<u32>(coords.size());
+ coords.push_back(Immediate(static_cast<u32>(instr.tld4s.component)));
+
+ const auto& sampler =
+ GetSampler(instr.sampler, TextureType::Texture2D, false, depth_compare);
+
+ Node4 values;
+ for (u32 element = 0; element < values.size(); ++element) {
+ auto params = coords;
+ MetaTexture meta{sampler, element, num_coords};
+ values[element] =
+ Operation(OperationCode::F4TextureGather, std::move(meta), std::move(params));
+ }
+
+ WriteTexsInstructionFloat(bb, instr, values);
+ break;
+ }
+ case OpCode::Id::TXQ: {
+ if (instr.txq.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TXQ.NODEP implementation is incomplete");
+ }
+
+ // TODO: The new commits on the texture refactor, change the way samplers work.
+ // Sadly, not all texture instructions specify the type of texture their sampler
+ // uses. This must be fixed at a later instance.
+ const auto& sampler =
+ GetSampler(instr.sampler, Tegra::Shader::TextureType::Texture2D, false, false);
+
+ switch (instr.txq.query_type) {
+ case Tegra::Shader::TextureQueryType::Dimension: {
+ for (u32 element = 0; element < 4; ++element) {
+ MetaTexture meta{sampler, element};
+ const Node value = Operation(OperationCode::F4TextureQueryDimensions,
+ std::move(meta), GetRegister(instr.gpr8));
+ SetTemporal(bb, element, value);
+ }
+ for (u32 i = 0; i < 4; ++i) {
+ SetRegister(bb, instr.gpr0.Value() + i, GetTemporal(i));
+ }
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled texture query type: {}",
+ static_cast<u32>(instr.txq.query_type.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::TMML: {
+ UNIMPLEMENTED_IF_MSG(instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
+ "NDV is not implemented");
+
+ if (instr.tmml.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TMML.NODEP implementation is incomplete");
+ }
+
+ auto texture_type = instr.tmml.texture_type.Value();
+ const bool is_array = instr.tmml.array != 0;
+ const auto& sampler = GetSampler(instr.sampler, texture_type, is_array, false);
+
+ std::vector<Node> coords;
+
+ // TODO: Add coordinates for different samplers once other texture types are implemented.
+ switch (texture_type) {
+ case TextureType::Texture1D:
+ coords.push_back(GetRegister(instr.gpr8));
+ break;
+ case TextureType::Texture2D:
+ coords.push_back(GetRegister(instr.gpr8.Value() + 0));
+ coords.push_back(GetRegister(instr.gpr8.Value() + 1));
+ break;
+ default:
+ UNIMPLEMENTED_MSG("Unhandled texture type {}", static_cast<u32>(texture_type));
+
+ // Fallback to interpreting as a 2D texture for now
+ coords.push_back(GetRegister(instr.gpr8.Value() + 0));
+ coords.push_back(GetRegister(instr.gpr8.Value() + 1));
+ texture_type = TextureType::Texture2D;
+ }
+
+ for (u32 element = 0; element < 2; ++element) {
+ auto params = coords;
+ MetaTexture meta_texture{sampler, element, static_cast<u32>(coords.size())};
+ const Node value =
+ Operation(OperationCode::F4TextureQueryLod, meta_texture, std::move(params));
+ SetTemporal(bb, element, value);
+ }
+ for (u32 element = 0; element < 2; ++element) {
+ SetRegister(bb, instr.gpr0.Value() + element, GetTemporal(element));
+ }
+
+ break;
+ }
+ case OpCode::Id::TLDS: {
+ const Tegra::Shader::TextureType texture_type{instr.tlds.GetTextureType()};
+ const bool is_array{instr.tlds.IsArrayTexture()};
+
+ UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(TextureMiscMode::MZ), "MZ is not implemented");
+
+ if (instr.tlds.UsesMiscMode(TextureMiscMode::NODEP)) {
+ LOG_WARNING(HW_GPU, "TMML.NODEP implementation is incomplete");
+ }
+
+ WriteTexsInstructionFloat(bb, instr, GetTldsCode(instr, texture_type, is_array));
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled memory instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+const Sampler& ShaderIR::GetSampler(const Tegra::Shader::Sampler& sampler, TextureType type,
+ bool is_array, bool is_shadow) {
+ const auto offset = static_cast<std::size_t>(sampler.index.Value());
+
+ // If this sampler has already been used, return the existing mapping.
+ const auto itr =
+ std::find_if(used_samplers.begin(), used_samplers.end(),
+ [&](const Sampler& entry) { return entry.GetOffset() == offset; });
+ if (itr != used_samplers.end()) {
+ ASSERT(itr->GetType() == type && itr->IsArray() == is_array &&
+ itr->IsShadow() == is_shadow);
+ return *itr;
+ }
+
+ // Otherwise create a new mapping for this sampler
+ const std::size_t next_index = used_samplers.size();
+ const Sampler entry{offset, next_index, type, is_array, is_shadow};
+ return *used_samplers.emplace(entry).first;
+}
+
+void ShaderIR::WriteTexInstructionFloat(BasicBlock& bb, Instruction instr,
+ const Node4& components) {
+ u32 dest_elem = 0;
+ for (u32 elem = 0; elem < 4; ++elem) {
+ if (!instr.tex.IsComponentEnabled(elem)) {
+ // Skip disabled components
+ continue;
+ }
+ SetTemporal(bb, dest_elem++, components[elem]);
+ }
+ // After writing values in temporals, move them to the real registers
+ for (u32 i = 0; i < dest_elem; ++i) {
+ SetRegister(bb, instr.gpr0.Value() + i, GetTemporal(i));
+ }
+}
+
+void ShaderIR::WriteTexsInstructionFloat(BasicBlock& bb, Instruction instr,
+ const Node4& components) {
+ // TEXS has two destination registers and a swizzle. The first two elements in the swizzle
+ // go into gpr0+0 and gpr0+1, and the rest goes into gpr28+0 and gpr28+1
+
+ u32 dest_elem = 0;
+ for (u32 component = 0; component < 4; ++component) {
+ if (!instr.texs.IsComponentEnabled(component))
+ continue;
+ SetTemporal(bb, dest_elem++, components[component]);
+ }
+
+ for (u32 i = 0; i < dest_elem; ++i) {
+ if (i < 2) {
+ // Write the first two swizzle components to gpr0 and gpr0+1
+ SetRegister(bb, instr.gpr0.Value() + i % 2, GetTemporal(i));
+ } else {
+ ASSERT(instr.texs.HasTwoDestinations());
+ // Write the rest of the swizzle components to gpr28 and gpr28+1
+ SetRegister(bb, instr.gpr28.Value() + i % 2, GetTemporal(i));
+ }
+ }
+}
+
+void ShaderIR::WriteTexsInstructionHalfFloat(BasicBlock& bb, Instruction instr,
+ const Node4& components) {
+ // TEXS.F16 destionation registers are packed in two registers in pairs (just like any half
+ // float instruction).
+
+ Node4 values;
+ u32 dest_elem = 0;
+ for (u32 component = 0; component < 4; ++component) {
+ if (!instr.texs.IsComponentEnabled(component))
+ continue;
+ values[dest_elem++] = components[component];
+ }
+ if (dest_elem == 0)
+ return;
+
+ std::generate(values.begin() + dest_elem, values.end(), [&]() { return Immediate(0); });
+
+ const Node first_value = Operation(OperationCode::HPack2, values[0], values[1]);
+ if (dest_elem <= 2) {
+ SetRegister(bb, instr.gpr0, first_value);
+ return;
+ }
+
+ SetTemporal(bb, 0, first_value);
+ SetTemporal(bb, 1, Operation(OperationCode::HPack2, values[2], values[3]));
+
+ SetRegister(bb, instr.gpr0, GetTemporal(0));
+ SetRegister(bb, instr.gpr28, GetTemporal(1));
+}
+
+Node4 ShaderIR::GetTextureCode(Instruction instr, TextureType texture_type,
+ TextureProcessMode process_mode, bool depth_compare, bool is_array,
+ std::size_t array_offset, std::size_t bias_offset,
+ std::vector<Node>&& coords) {
+ UNIMPLEMENTED_IF_MSG(
+ (texture_type == TextureType::Texture3D && (is_array || depth_compare)) ||
+ (texture_type == TextureType::TextureCube && is_array && depth_compare),
+ "This method is not supported.");
+
+ const auto& sampler = GetSampler(instr.sampler, texture_type, is_array, depth_compare);
+
+ const bool lod_needed = process_mode == TextureProcessMode::LZ ||
+ process_mode == TextureProcessMode::LL ||
+ process_mode == TextureProcessMode::LLA;
+
+ // LOD selection (either via bias or explicit textureLod) not supported in GL for
+ // sampler2DArrayShadow and samplerCubeArrayShadow.
+ const bool gl_lod_supported =
+ !((texture_type == Tegra::Shader::TextureType::Texture2D && is_array && depth_compare) ||
+ (texture_type == Tegra::Shader::TextureType::TextureCube && is_array && depth_compare));
+
+ const OperationCode read_method =
+ lod_needed && gl_lod_supported ? OperationCode::F4TextureLod : OperationCode::F4Texture;
+
+ UNIMPLEMENTED_IF(process_mode != TextureProcessMode::None && !gl_lod_supported);
+
+ std::optional<u32> array_offset_value;
+ if (is_array)
+ array_offset_value = static_cast<u32>(array_offset);
+
+ const auto coords_count = static_cast<u32>(coords.size());
+
+ if (process_mode != TextureProcessMode::None && gl_lod_supported) {
+ if (process_mode == TextureProcessMode::LZ) {
+ coords.push_back(Immediate(0.0f));
+ } else {
+ // If present, lod or bias are always stored in the register indexed by the gpr20
+ // field with an offset depending on the usage of the other registers
+ coords.push_back(GetRegister(instr.gpr20.Value() + bias_offset));
+ }
+ }
+
+ Node4 values;
+ for (u32 element = 0; element < values.size(); ++element) {
+ auto params = coords;
+ MetaTexture meta{sampler, element, coords_count, array_offset_value};
+ values[element] = Operation(read_method, std::move(meta), std::move(params));
+ }
+
+ return values;
+}
+
+Node4 ShaderIR::GetTexCode(Instruction instr, TextureType texture_type,
+ TextureProcessMode process_mode, bool depth_compare, bool is_array) {
+ const bool lod_bias_enabled =
+ (process_mode != TextureProcessMode::None && process_mode != TextureProcessMode::LZ);
+
+ const auto [coord_count, total_coord_count] = ValidateAndGetCoordinateElement(
+ texture_type, depth_compare, is_array, lod_bias_enabled, 4, 5);
+ // If enabled arrays index is always stored in the gpr8 field
+ const u64 array_register = instr.gpr8.Value();
+ // First coordinate index is the gpr8 or gpr8 + 1 when arrays are used
+ const u64 coord_register = array_register + (is_array ? 1 : 0);
+
+ std::vector<Node> coords;
+ for (std::size_t i = 0; i < coord_count; ++i) {
+ coords.push_back(GetRegister(coord_register + i));
+ }
+ // 1D.DC in opengl the 2nd component is ignored.
+ if (depth_compare && !is_array && texture_type == TextureType::Texture1D) {
+ coords.push_back(Immediate(0.0f));
+ }
+ std::size_t array_offset{};
+ if (is_array) {
+ array_offset = coords.size();
+ coords.push_back(GetRegister(array_register));
+ }
+ if (depth_compare) {
+ // Depth is always stored in the register signaled by gpr20
+ // or in the next register if lod or bias are used
+ const u64 depth_register = instr.gpr20.Value() + (lod_bias_enabled ? 1 : 0);
+ coords.push_back(GetRegister(depth_register));
+ }
+ // Fill ignored coordinates
+ while (coords.size() < total_coord_count) {
+ coords.push_back(Immediate(0));
+ }
+
+ return GetTextureCode(instr, texture_type, process_mode, depth_compare, is_array, array_offset,
+ 0, std::move(coords));
+}
+
+Node4 ShaderIR::GetTexsCode(Instruction instr, TextureType texture_type,
+ TextureProcessMode process_mode, bool depth_compare, bool is_array) {
+ const bool lod_bias_enabled =
+ (process_mode != TextureProcessMode::None && process_mode != TextureProcessMode::LZ);
+
+ const auto [coord_count, total_coord_count] = ValidateAndGetCoordinateElement(
+ texture_type, depth_compare, is_array, lod_bias_enabled, 4, 4);
+ // If enabled arrays index is always stored in the gpr8 field
+ const u64 array_register = instr.gpr8.Value();
+ // First coordinate index is stored in gpr8 field or (gpr8 + 1) when arrays are used
+ const u64 coord_register = array_register + (is_array ? 1 : 0);
+ const u64 last_coord_register =
+ (is_array || !(lod_bias_enabled || depth_compare) || (coord_count > 2))
+ ? static_cast<u64>(instr.gpr20.Value())
+ : coord_register + 1;
+
+ std::vector<Node> coords;
+ for (std::size_t i = 0; i < coord_count; ++i) {
+ const bool last = (i == (coord_count - 1)) && (coord_count > 1);
+ coords.push_back(GetRegister(last ? last_coord_register : coord_register + i));
+ }
+
+ std::size_t array_offset{};
+ if (is_array) {
+ array_offset = coords.size();
+ coords.push_back(GetRegister(array_register));
+ }
+ if (depth_compare) {
+ // Depth is always stored in the register signaled by gpr20
+ // or in the next register if lod or bias are used
+ const u64 depth_register = instr.gpr20.Value() + (lod_bias_enabled ? 1 : 0);
+ coords.push_back(GetRegister(depth_register));
+ }
+ // Fill ignored coordinates
+ while (coords.size() < total_coord_count) {
+ coords.push_back(Immediate(0));
+ }
+
+ return GetTextureCode(instr, texture_type, process_mode, depth_compare, is_array, array_offset,
+ (coord_count > 2 ? 1 : 0), std::move(coords));
+}
+
+Node4 ShaderIR::GetTld4Code(Instruction instr, TextureType texture_type, bool depth_compare,
+ bool is_array) {
+ const std::size_t coord_count = GetCoordCount(texture_type);
+ const std::size_t total_coord_count = coord_count + (is_array ? 1 : 0);
+ const std::size_t total_reg_count = total_coord_count + (depth_compare ? 1 : 0);
+
+ // If enabled arrays index is always stored in the gpr8 field
+ const u64 array_register = instr.gpr8.Value();
+ // First coordinate index is the gpr8 or gpr8 + 1 when arrays are used
+ const u64 coord_register = array_register + (is_array ? 1 : 0);
+
+ std::vector<Node> coords;
+
+ for (size_t i = 0; i < coord_count; ++i) {
+ coords.push_back(GetRegister(coord_register + i));
+ }
+ std::optional<u32> array_offset;
+ if (is_array) {
+ array_offset = static_cast<u32>(coords.size());
+ coords.push_back(GetRegister(array_register));
+ }
+
+ const auto& sampler = GetSampler(instr.sampler, texture_type, is_array, depth_compare);
+
+ Node4 values;
+ for (u32 element = 0; element < values.size(); ++element) {
+ auto params = coords;
+ MetaTexture meta{sampler, element, static_cast<u32>(coords.size()), array_offset};
+ values[element] =
+ Operation(OperationCode::F4TextureGather, std::move(meta), std::move(params));
+ }
+
+ return values;
+}
+
+Node4 ShaderIR::GetTldsCode(Instruction instr, TextureType texture_type, bool is_array) {
+ const std::size_t type_coord_count = GetCoordCount(texture_type);
+ const std::size_t total_coord_count = type_coord_count + (is_array ? 1 : 0);
+ const bool lod_enabled = instr.tlds.GetTextureProcessMode() == TextureProcessMode::LL;
+
+ // If enabled arrays index is always stored in the gpr8 field
+ const u64 array_register = instr.gpr8.Value();
+ // if is array gpr20 is used
+ const u64 coord_register = is_array ? instr.gpr20.Value() : instr.gpr8.Value();
+
+ const u64 last_coord_register =
+ ((type_coord_count > 2) || (type_coord_count == 2 && !lod_enabled)) && !is_array
+ ? static_cast<u64>(instr.gpr20.Value())
+ : coord_register + 1;
+
+ std::vector<Node> coords;
+
+ for (std::size_t i = 0; i < type_coord_count; ++i) {
+ const bool last = (i == (type_coord_count - 1)) && (type_coord_count > 1);
+ coords.push_back(GetRegister(last ? last_coord_register : coord_register + i));
+ }
+ std::optional<u32> array_offset;
+ if (is_array) {
+ array_offset = static_cast<u32>(coords.size());
+ coords.push_back(GetRegister(array_register));
+ }
+ const auto coords_count = static_cast<u32>(coords.size());
+
+ if (lod_enabled) {
+ // When lod is used always is in grp20
+ coords.push_back(GetRegister(instr.gpr20));
+ } else {
+ coords.push_back(Immediate(0));
+ }
+
+ const auto& sampler = GetSampler(instr.sampler, texture_type, is_array, false);
+
+ Node4 values;
+ for (u32 element = 0; element < values.size(); ++element) {
+ auto params = coords;
+ MetaTexture meta{sampler, element, coords_count, array_offset};
+ values[element] =
+ Operation(OperationCode::F4TexelFetch, std::move(meta), std::move(params));
+ }
+ return values;
+}
+
+std::tuple<std::size_t, std::size_t> ShaderIR::ValidateAndGetCoordinateElement(
+ TextureType texture_type, bool depth_compare, bool is_array, bool lod_bias_enabled,
+ std::size_t max_coords, std::size_t max_inputs) {
+ const std::size_t coord_count = GetCoordCount(texture_type);
+
+ std::size_t total_coord_count = coord_count + (is_array ? 1 : 0) + (depth_compare ? 1 : 0);
+ const std::size_t total_reg_count = total_coord_count + (lod_bias_enabled ? 1 : 0);
+ if (total_coord_count > max_coords || total_reg_count > max_inputs) {
+ UNIMPLEMENTED_MSG("Unsupported Texture operation");
+ total_coord_count = std::min(total_coord_count, max_coords);
+ }
+ // 1D.DC OpenGL is using a vec3 but 2nd component is ignored later.
+ total_coord_count +=
+ (depth_compare && !is_array && texture_type == TextureType::Texture1D) ? 1 : 0;
+
+ return {coord_count, total_coord_count};
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/other.cpp b/src/video_core/shader/decode/other.cpp
new file mode 100644
index 000000000..c1e5f4efb
--- /dev/null
+++ b/src/video_core/shader/decode/other.cpp
@@ -0,0 +1,178 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::ConditionCode;
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Register;
+
+u32 ShaderIR::DecodeOther(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::EXIT: {
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T, "EXIT condition code used: {}",
+ static_cast<u32>(cc));
+
+ switch (instr.flow.cond) {
+ case Tegra::Shader::FlowCondition::Always:
+ bb.push_back(Operation(OperationCode::Exit));
+ if (instr.pred.pred_index == static_cast<u64>(Tegra::Shader::Pred::UnusedIndex)) {
+ // If this is an unconditional exit then just end processing here,
+ // otherwise we have to account for the possibility of the condition
+ // not being met, so continue processing the next instruction.
+ pc = MAX_PROGRAM_LENGTH - 1;
+ }
+ break;
+
+ case Tegra::Shader::FlowCondition::Fcsm_Tr:
+ // TODO(bunnei): What is this used for? If we assume this conditon is not
+ // satisifed, dual vertex shaders in Farming Simulator make more sense
+ UNIMPLEMENTED_MSG("Skipping unknown FlowCondition::Fcsm_Tr");
+ break;
+
+ default:
+ UNIMPLEMENTED_MSG("Unhandled flow condition: {}",
+ static_cast<u32>(instr.flow.cond.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::KIL: {
+ UNIMPLEMENTED_IF(instr.flow.cond != Tegra::Shader::FlowCondition::Always);
+
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T, "KIL condition code used: {}",
+ static_cast<u32>(cc));
+
+ bb.push_back(Operation(OperationCode::Discard));
+ break;
+ }
+ case OpCode::Id::MOV_SYS: {
+ switch (instr.sys20) {
+ case Tegra::Shader::SystemVariable::InvocationInfo: {
+ LOG_WARNING(HW_GPU, "MOV_SYS instruction with InvocationInfo is incomplete");
+ SetRegister(bb, instr.gpr0, Immediate(0u));
+ break;
+ }
+ case Tegra::Shader::SystemVariable::Ydirection: {
+ // Config pack's third value is Y_NEGATE's state.
+ SetRegister(bb, instr.gpr0, Operation(OperationCode::YNegate));
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled system move: {}", static_cast<u32>(instr.sys20.Value()));
+ }
+ break;
+ }
+ case OpCode::Id::BRA: {
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "BRA with constant buffers are not implemented");
+
+ const u32 target = pc + instr.bra.GetBranchTarget();
+ const Node branch = Operation(OperationCode::Branch, Immediate(target));
+
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ if (cc != Tegra::Shader::ConditionCode::T) {
+ bb.push_back(Conditional(GetConditionCode(cc), {branch}));
+ } else {
+ bb.push_back(branch);
+ }
+ break;
+ }
+ case OpCode::Id::SSY: {
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer flow is not supported");
+
+ // The SSY opcode tells the GPU where to re-converge divergent execution paths, it sets the
+ // target of the jump that the SYNC instruction will make. The SSY opcode has a similar
+ // structure to the BRA opcode.
+ const u32 target = pc + instr.bra.GetBranchTarget();
+ bb.push_back(Operation(OperationCode::PushFlowStack, Immediate(target)));
+ break;
+ }
+ case OpCode::Id::PBK: {
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer PBK is not supported");
+
+ // PBK pushes to a stack the address where BRK will jump to. This shares stack with SSY but
+ // using SYNC on a PBK address will kill the shader execution. We don't emulate this because
+ // it's very unlikely a driver will emit such invalid shader.
+ const u32 target = pc + instr.bra.GetBranchTarget();
+ bb.push_back(Operation(OperationCode::PushFlowStack, Immediate(target)));
+ break;
+ }
+ case OpCode::Id::SYNC: {
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T, "SYNC condition code used: {}",
+ static_cast<u32>(cc));
+
+ // The SYNC opcode jumps to the address previously set by the SSY opcode
+ bb.push_back(Operation(OperationCode::PopFlowStack));
+ break;
+ }
+ case OpCode::Id::BRK: {
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T, "BRK condition code used: {}",
+ static_cast<u32>(cc));
+
+ // The BRK opcode jumps to the address previously set by the PBK opcode
+ bb.push_back(Operation(OperationCode::PopFlowStack));
+ break;
+ }
+ case OpCode::Id::IPA: {
+ const auto& attribute = instr.attribute.fmt28;
+ const Tegra::Shader::IpaMode input_mode{instr.ipa.interp_mode.Value(),
+ instr.ipa.sample_mode.Value()};
+
+ const Node attr = GetInputAttribute(attribute.index, attribute.element, input_mode);
+ const Node value = GetSaturatedFloat(attr, instr.ipa.saturate);
+
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::OUT_R: {
+ UNIMPLEMENTED_IF_MSG(instr.gpr20.Value() != Register::ZeroIndex,
+ "Stream buffer is not supported");
+
+ if (instr.out.emit) {
+ // gpr0 is used to store the next address and gpr8 contains the address to emit.
+ // Hardware uses pointers here but we just ignore it
+ bb.push_back(Operation(OperationCode::EmitVertex));
+ SetRegister(bb, instr.gpr0, Immediate(0));
+ }
+ if (instr.out.cut) {
+ bb.push_back(Operation(OperationCode::EndPrimitive));
+ }
+ break;
+ }
+ case OpCode::Id::ISBERD: {
+ UNIMPLEMENTED_IF(instr.isberd.o != 0);
+ UNIMPLEMENTED_IF(instr.isberd.skew != 0);
+ UNIMPLEMENTED_IF(instr.isberd.shift != Tegra::Shader::IsberdShift::None);
+ UNIMPLEMENTED_IF(instr.isberd.mode != Tegra::Shader::IsberdMode::None);
+ LOG_WARNING(HW_GPU, "ISBERD instruction is incomplete");
+ SetRegister(bb, instr.gpr0, GetRegister(instr.gpr8));
+ break;
+ }
+ case OpCode::Id::DEPBAR: {
+ LOG_WARNING(HW_GPU, "DEPBAR instruction is stubbed");
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/predicate_set_predicate.cpp b/src/video_core/shader/decode/predicate_set_predicate.cpp
new file mode 100644
index 000000000..1717f0653
--- /dev/null
+++ b/src/video_core/shader/decode/predicate_set_predicate.cpp
@@ -0,0 +1,67 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+
+u32 ShaderIR::DecodePredicateSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::PSETP: {
+ const Node op_a = GetPredicate(instr.psetp.pred12, instr.psetp.neg_pred12 != 0);
+ const Node op_b = GetPredicate(instr.psetp.pred29, instr.psetp.neg_pred29 != 0);
+
+ // We can't use the constant predicate as destination.
+ ASSERT(instr.psetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+
+ const Node second_pred = GetPredicate(instr.psetp.pred39, instr.psetp.neg_pred39 != 0);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.psetp.op);
+ const Node predicate = Operation(combiner, op_a, op_b);
+
+ // Set the primary predicate to the result of Predicate OP SecondPredicate
+ SetPredicate(bb, instr.psetp.pred3, Operation(combiner, predicate, second_pred));
+
+ if (instr.psetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ // Set the secondary predicate to the result of !Predicate OP SecondPredicate, if
+ // enabled
+ SetPredicate(bb, instr.psetp.pred0,
+ Operation(combiner, Operation(OperationCode::LogicalNegate, predicate),
+ second_pred));
+ }
+ break;
+ }
+ case OpCode::Id::CSETP: {
+ const Node pred = GetPredicate(instr.csetp.pred39, instr.csetp.neg_pred39 != 0);
+ const Node condition_code = GetConditionCode(instr.csetp.cc);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.csetp.op);
+
+ if (instr.csetp.pred3 != static_cast<u64>(Pred::UnusedIndex)) {
+ SetPredicate(bb, instr.csetp.pred3, Operation(combiner, condition_code, pred));
+ }
+ if (instr.csetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ const Node neg_cc = Operation(OperationCode::LogicalNegate, condition_code);
+ SetPredicate(bb, instr.csetp.pred0, Operation(combiner, neg_cc, pred));
+ }
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled predicate instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/predicate_set_register.cpp b/src/video_core/shader/decode/predicate_set_register.cpp
new file mode 100644
index 000000000..8bd15fb00
--- /dev/null
+++ b/src/video_core/shader/decode/predicate_set_register.cpp
@@ -0,0 +1,46 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodePredicateSetRegister(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in PSET is not implemented");
+
+ const Node op_a = GetPredicate(instr.pset.pred12, instr.pset.neg_pred12 != 0);
+ const Node op_b = GetPredicate(instr.pset.pred29, instr.pset.neg_pred29 != 0);
+ const Node first_pred = Operation(GetPredicateCombiner(instr.pset.cond), op_a, op_b);
+
+ const Node second_pred = GetPredicate(instr.pset.pred39, instr.pset.neg_pred39 != 0);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.pset.op);
+ const Node predicate = Operation(combiner, first_pred, second_pred);
+
+ const Node true_value = instr.pset.bf ? Immediate(1.0f) : Immediate(0xffffffff);
+ const Node false_value = instr.pset.bf ? Immediate(0.0f) : Immediate(0);
+ const Node value =
+ Operation(OperationCode::Select, PRECISE, predicate, true_value, false_value);
+
+ if (instr.pset.bf) {
+ SetInternalFlagsFromFloat(bb, value, instr.generates_cc);
+ } else {
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ }
+ SetRegister(bb, instr.gpr0, value);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/register_set_predicate.cpp b/src/video_core/shader/decode/register_set_predicate.cpp
new file mode 100644
index 000000000..bdb4424a6
--- /dev/null
+++ b/src/video_core/shader/decode/register_set_predicate.cpp
@@ -0,0 +1,51 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeRegisterSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF(instr.r2p.mode != Tegra::Shader::R2pMode::Pr);
+
+ const Node apply_mask = [&]() {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::R2P_IMM:
+ return Immediate(static_cast<u32>(instr.r2p.immediate_mask));
+ default:
+ UNREACHABLE();
+ return Immediate(static_cast<u32>(instr.r2p.immediate_mask));
+ }
+ }();
+ const Node mask = GetRegister(instr.gpr8);
+ const auto offset = static_cast<u32>(instr.r2p.byte) * 8;
+
+ constexpr u32 programmable_preds = 7;
+ for (u64 pred = 0; pred < programmable_preds; ++pred) {
+ const auto shift = static_cast<u32>(pred);
+
+ const Node apply_compare = BitfieldExtract(apply_mask, shift, 1);
+ const Node condition =
+ Operation(OperationCode::LogicalUNotEqual, apply_compare, Immediate(0));
+
+ const Node value_compare = BitfieldExtract(mask, offset + shift, 1);
+ const Node value = Operation(OperationCode::LogicalUNotEqual, value_compare, Immediate(0));
+
+ const Node code = Operation(OperationCode::LogicalAssign, GetPredicate(pred), value);
+ bb.push_back(Conditional(condition, {code}));
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/shift.cpp b/src/video_core/shader/decode/shift.cpp
new file mode 100644
index 000000000..85026bb37
--- /dev/null
+++ b/src/video_core/shader/decode/shift.cpp
@@ -0,0 +1,55 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeShift(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a = GetRegister(instr.gpr8);
+ const Node op_b = [&]() {
+ if (instr.is_b_imm) {
+ return Immediate(instr.alu.GetSignedImm20_20());
+ } else if (instr.is_b_gpr) {
+ return GetRegister(instr.gpr20);
+ } else {
+ return GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset);
+ }
+ }();
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::SHR_C:
+ case OpCode::Id::SHR_R:
+ case OpCode::Id::SHR_IMM: {
+ const Node value = SignedOperation(OperationCode::IArithmeticShiftRight,
+ instr.shift.is_signed, PRECISE, op_a, op_b);
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::SHL_C:
+ case OpCode::Id::SHL_R:
+ case OpCode::Id::SHL_IMM: {
+ const Node value = Operation(OperationCode::ILogicalShiftLeft, PRECISE, op_a, op_b);
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled shift instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/video.cpp b/src/video_core/shader/decode/video.cpp
new file mode 100644
index 000000000..c3432356d
--- /dev/null
+++ b/src/video_core/shader/decode/video.cpp
@@ -0,0 +1,111 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+using Tegra::Shader::Pred;
+using Tegra::Shader::VideoType;
+using Tegra::Shader::VmadShr;
+
+u32 ShaderIR::DecodeVideo(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ const Node op_a =
+ GetVideoOperand(GetRegister(instr.gpr8), instr.video.is_byte_chunk_a, instr.video.signed_a,
+ instr.video.type_a, instr.video.byte_height_a);
+ const Node op_b = [&]() {
+ if (instr.video.use_register_b) {
+ return GetVideoOperand(GetRegister(instr.gpr20), instr.video.is_byte_chunk_b,
+ instr.video.signed_b, instr.video.type_b,
+ instr.video.byte_height_b);
+ }
+ if (instr.video.signed_b) {
+ const auto imm = static_cast<s16>(instr.alu.GetImm20_16());
+ return Immediate(static_cast<u32>(imm));
+ } else {
+ return Immediate(instr.alu.GetImm20_16());
+ }
+ }();
+
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::VMAD: {
+ const bool result_signed = instr.video.signed_a == 1 || instr.video.signed_b == 1;
+ const Node op_c = GetRegister(instr.gpr39);
+
+ Node value = SignedOperation(OperationCode::IMul, result_signed, NO_PRECISE, op_a, op_b);
+ value = SignedOperation(OperationCode::IAdd, result_signed, NO_PRECISE, value, op_c);
+
+ if (instr.vmad.shr == VmadShr::Shr7 || instr.vmad.shr == VmadShr::Shr15) {
+ const Node shift = Immediate(instr.vmad.shr == VmadShr::Shr7 ? 7 : 15);
+ value =
+ SignedOperation(OperationCode::IArithmeticShiftRight, result_signed, value, shift);
+ }
+
+ SetInternalFlagsFromInteger(bb, value, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, value);
+ break;
+ }
+ case OpCode::Id::VSETP: {
+ // We can't use the constant predicate as destination.
+ ASSERT(instr.vsetp.pred3 != static_cast<u64>(Pred::UnusedIndex));
+
+ const bool sign = instr.video.signed_a == 1 || instr.video.signed_b == 1;
+ const Node first_pred = GetPredicateComparisonInteger(instr.vsetp.cond, sign, op_a, op_b);
+ const Node second_pred = GetPredicate(instr.vsetp.pred39, false);
+
+ const OperationCode combiner = GetPredicateCombiner(instr.vsetp.op);
+
+ // Set the primary predicate to the result of Predicate OP SecondPredicate
+ SetPredicate(bb, instr.vsetp.pred3, Operation(combiner, first_pred, second_pred));
+
+ if (instr.vsetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
+ // Set the secondary predicate to the result of !Predicate OP SecondPredicate,
+ // if enabled
+ const Node negate_pred = Operation(OperationCode::LogicalNegate, first_pred);
+ SetPredicate(bb, instr.vsetp.pred0, Operation(combiner, negate_pred, second_pred));
+ }
+ break;
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled video instruction: {}", opcode->get().GetName());
+ }
+
+ return pc;
+}
+
+Node ShaderIR::GetVideoOperand(Node op, bool is_chunk, bool is_signed,
+ Tegra::Shader::VideoType type, u64 byte_height) {
+ if (!is_chunk) {
+ return BitfieldExtract(op, static_cast<u32>(byte_height * 8), 8);
+ }
+ const Node zero = Immediate(0);
+
+ switch (type) {
+ case Tegra::Shader::VideoType::Size16_Low:
+ return BitfieldExtract(op, 0, 16);
+ case Tegra::Shader::VideoType::Size16_High:
+ return BitfieldExtract(op, 16, 16);
+ case Tegra::Shader::VideoType::Size32:
+ // TODO(Rodrigo): From my hardware tests it becomes a bit "mad" when this type is used
+ // (1 * 1 + 0 == 0x5b800000). Until a better explanation is found: abort.
+ UNIMPLEMENTED();
+ return zero;
+ case Tegra::Shader::VideoType::Invalid:
+ UNREACHABLE_MSG("Invalid instruction encoding");
+ return zero;
+ default:
+ UNREACHABLE();
+ return zero;
+ }
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/decode/xmad.cpp b/src/video_core/shader/decode/xmad.cpp
new file mode 100644
index 000000000..0cd9cd1cc
--- /dev/null
+++ b/src/video_core/shader/decode/xmad.cpp
@@ -0,0 +1,97 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Instruction;
+using Tegra::Shader::OpCode;
+
+u32 ShaderIR::DecodeXmad(BasicBlock& bb, const BasicBlock& code, u32 pc) {
+ const Instruction instr = {program_code[pc]};
+ const auto opcode = OpCode::Decode(instr);
+
+ UNIMPLEMENTED_IF(instr.xmad.sign_a);
+ UNIMPLEMENTED_IF(instr.xmad.sign_b);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in XMAD is not implemented");
+
+ Node op_a = GetRegister(instr.gpr8);
+
+ // TODO(bunnei): Needs to be fixed once op_a or op_b is signed
+ UNIMPLEMENTED_IF(instr.xmad.sign_a != instr.xmad.sign_b);
+ const bool is_signed_a = instr.xmad.sign_a == 1;
+ const bool is_signed_b = instr.xmad.sign_b == 1;
+ const bool is_signed_c = is_signed_a;
+
+ auto [is_merge, op_b, op_c] = [&]() -> std::tuple<bool, Node, Node> {
+ switch (opcode->get().GetId()) {
+ case OpCode::Id::XMAD_CR:
+ return {instr.xmad.merge_56, GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset),
+ GetRegister(instr.gpr39)};
+ case OpCode::Id::XMAD_RR:
+ return {instr.xmad.merge_37, GetRegister(instr.gpr20), GetRegister(instr.gpr39)};
+ case OpCode::Id::XMAD_RC:
+ return {false, GetRegister(instr.gpr39),
+ GetConstBuffer(instr.cbuf34.index, instr.cbuf34.offset)};
+ case OpCode::Id::XMAD_IMM:
+ return {instr.xmad.merge_37, Immediate(static_cast<u32>(instr.xmad.imm20_16)),
+ GetRegister(instr.gpr39)};
+ }
+ UNIMPLEMENTED_MSG("Unhandled XMAD instruction: {}", opcode->get().GetName());
+ return {false, Immediate(0), Immediate(0)};
+ }();
+
+ op_a = BitfieldExtract(op_a, instr.xmad.high_a ? 16 : 0, 16);
+
+ const Node original_b = op_b;
+ op_b = BitfieldExtract(op_b, instr.xmad.high_b ? 16 : 0, 16);
+
+ // TODO(Rodrigo): Use an appropiate sign for this operation
+ Node product = Operation(OperationCode::IMul, NO_PRECISE, op_a, op_b);
+ if (instr.xmad.product_shift_left) {
+ product = Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, product, Immediate(16));
+ }
+
+ const Node original_c = op_c;
+ op_c = [&]() {
+ switch (instr.xmad.mode) {
+ case Tegra::Shader::XmadMode::None:
+ return original_c;
+ case Tegra::Shader::XmadMode::CLo:
+ return BitfieldExtract(original_c, 0, 16);
+ case Tegra::Shader::XmadMode::CHi:
+ return BitfieldExtract(original_c, 16, 16);
+ case Tegra::Shader::XmadMode::CBcc: {
+ const Node shifted_b = SignedOperation(OperationCode::ILogicalShiftLeft, is_signed_b,
+ NO_PRECISE, original_b, Immediate(16));
+ return SignedOperation(OperationCode::IAdd, is_signed_c, NO_PRECISE, original_c,
+ shifted_b);
+ }
+ default:
+ UNIMPLEMENTED_MSG("Unhandled XMAD mode: {}", static_cast<u32>(instr.xmad.mode.Value()));
+ return Immediate(0);
+ }
+ }();
+
+ // TODO(Rodrigo): Use an appropiate sign for this operation
+ Node sum = Operation(OperationCode::IAdd, product, op_c);
+ if (is_merge) {
+ const Node a = BitfieldExtract(sum, 0, 16);
+ const Node b =
+ Operation(OperationCode::ILogicalShiftLeft, NO_PRECISE, original_b, Immediate(16));
+ sum = Operation(OperationCode::IBitwiseOr, NO_PRECISE, a, b);
+ }
+
+ SetInternalFlagsFromInteger(bb, sum, instr.generates_cc);
+ SetRegister(bb, instr.gpr0, sum);
+
+ return pc;
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/shader_ir.cpp b/src/video_core/shader/shader_ir.cpp
new file mode 100644
index 000000000..d7747103e
--- /dev/null
+++ b/src/video_core/shader/shader_ir.cpp
@@ -0,0 +1,444 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <cmath>
+#include <unordered_map>
+
+#include "common/assert.h"
+#include "common/common_types.h"
+#include "common/logging/log.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+using Tegra::Shader::Attribute;
+using Tegra::Shader::Instruction;
+using Tegra::Shader::IpaMode;
+using Tegra::Shader::Pred;
+using Tegra::Shader::PredCondition;
+using Tegra::Shader::PredOperation;
+using Tegra::Shader::Register;
+
+Node ShaderIR::StoreNode(NodeData&& node_data) {
+ auto store = std::make_unique<NodeData>(node_data);
+ const Node node = store.get();
+ stored_nodes.push_back(std::move(store));
+ return node;
+}
+
+Node ShaderIR::Conditional(Node condition, std::vector<Node>&& code) {
+ return StoreNode(ConditionalNode(condition, std::move(code)));
+}
+
+Node ShaderIR::Comment(const std::string& text) {
+ return StoreNode(CommentNode(text));
+}
+
+Node ShaderIR::Immediate(u32 value) {
+ return StoreNode(ImmediateNode(value));
+}
+
+Node ShaderIR::GetRegister(Register reg) {
+ if (reg != Register::ZeroIndex) {
+ used_registers.insert(static_cast<u32>(reg));
+ }
+ return StoreNode(GprNode(reg));
+}
+
+Node ShaderIR::GetImmediate19(Instruction instr) {
+ return Immediate(instr.alu.GetImm20_19());
+}
+
+Node ShaderIR::GetImmediate32(Instruction instr) {
+ return Immediate(instr.alu.GetImm20_32());
+}
+
+Node ShaderIR::GetConstBuffer(u64 index_, u64 offset_) {
+ const auto index = static_cast<u32>(index_);
+ const auto offset = static_cast<u32>(offset_);
+
+ const auto [entry, is_new] = used_cbufs.try_emplace(index);
+ entry->second.MarkAsUsed(offset);
+
+ return StoreNode(CbufNode(index, Immediate(offset)));
+}
+
+Node ShaderIR::GetConstBufferIndirect(u64 index_, u64 offset_, Node node) {
+ const auto index = static_cast<u32>(index_);
+ const auto offset = static_cast<u32>(offset_);
+
+ const auto [entry, is_new] = used_cbufs.try_emplace(index);
+ entry->second.MarkAsUsedIndirect();
+
+ const Node final_offset = Operation(OperationCode::UAdd, NO_PRECISE, node, Immediate(offset));
+ return StoreNode(CbufNode(index, final_offset));
+}
+
+Node ShaderIR::GetPredicate(u64 pred_, bool negated) {
+ const auto pred = static_cast<Pred>(pred_);
+ if (pred != Pred::UnusedIndex && pred != Pred::NeverExecute) {
+ used_predicates.insert(pred);
+ }
+
+ return StoreNode(PredicateNode(pred, negated));
+}
+
+Node ShaderIR::GetPredicate(bool immediate) {
+ return GetPredicate(static_cast<u64>(immediate ? Pred::UnusedIndex : Pred::NeverExecute));
+}
+
+Node ShaderIR::GetInputAttribute(Attribute::Index index, u64 element,
+ const Tegra::Shader::IpaMode& input_mode, Node buffer) {
+ const auto [entry, is_new] =
+ used_input_attributes.emplace(std::make_pair(index, std::set<Tegra::Shader::IpaMode>{}));
+ entry->second.insert(input_mode);
+
+ return StoreNode(AbufNode(index, static_cast<u32>(element), input_mode, buffer));
+}
+
+Node ShaderIR::GetOutputAttribute(Attribute::Index index, u64 element, Node buffer) {
+ if (index == Attribute::Index::ClipDistances0123 ||
+ index == Attribute::Index::ClipDistances4567) {
+ const auto clip_index =
+ static_cast<u32>((index == Attribute::Index::ClipDistances4567 ? 1 : 0) + element);
+ used_clip_distances.at(clip_index) = true;
+ }
+ used_output_attributes.insert(index);
+
+ return StoreNode(AbufNode(index, static_cast<u32>(element), buffer));
+}
+
+Node ShaderIR::GetInternalFlag(InternalFlag flag, bool negated) {
+ const Node node = StoreNode(InternalFlagNode(flag));
+ if (negated) {
+ return Operation(OperationCode::LogicalNegate, node);
+ }
+ return node;
+}
+
+Node ShaderIR::GetLocalMemory(Node address) {
+ return StoreNode(LmemNode(address));
+}
+
+Node ShaderIR::GetTemporal(u32 id) {
+ return GetRegister(Register::ZeroIndex + 1 + id);
+}
+
+Node ShaderIR::GetOperandAbsNegFloat(Node value, bool absolute, bool negate) {
+ if (absolute) {
+ value = Operation(OperationCode::FAbsolute, NO_PRECISE, value);
+ }
+ if (negate) {
+ value = Operation(OperationCode::FNegate, NO_PRECISE, value);
+ }
+ return value;
+}
+
+Node ShaderIR::GetSaturatedFloat(Node value, bool saturate) {
+ if (!saturate) {
+ return value;
+ }
+ const Node positive_zero = Immediate(std::copysignf(0, 1));
+ const Node positive_one = Immediate(1.0f);
+ return Operation(OperationCode::FClamp, NO_PRECISE, value, positive_zero, positive_one);
+}
+
+Node ShaderIR::ConvertIntegerSize(Node value, Tegra::Shader::Register::Size size, bool is_signed) {
+ switch (size) {
+ case Register::Size::Byte:
+ value = SignedOperation(OperationCode::ILogicalShiftLeft, is_signed, NO_PRECISE, value,
+ Immediate(24));
+ value = SignedOperation(OperationCode::IArithmeticShiftRight, is_signed, NO_PRECISE, value,
+ Immediate(24));
+ return value;
+ case Register::Size::Short:
+ value = SignedOperation(OperationCode::ILogicalShiftLeft, is_signed, NO_PRECISE, value,
+ Immediate(16));
+ value = SignedOperation(OperationCode::IArithmeticShiftRight, is_signed, NO_PRECISE, value,
+ Immediate(16));
+ case Register::Size::Word:
+ // Default - do nothing
+ return value;
+ default:
+ UNREACHABLE_MSG("Unimplemented conversion size: {}", static_cast<u32>(size));
+ return value;
+ }
+}
+
+Node ShaderIR::GetOperandAbsNegInteger(Node value, bool absolute, bool negate, bool is_signed) {
+ if (!is_signed) {
+ // Absolute or negate on an unsigned is pointless
+ return value;
+ }
+ if (absolute) {
+ value = Operation(OperationCode::IAbsolute, NO_PRECISE, value);
+ }
+ if (negate) {
+ value = Operation(OperationCode::INegate, NO_PRECISE, value);
+ }
+ return value;
+}
+
+Node ShaderIR::UnpackHalfImmediate(Instruction instr, bool has_negation) {
+ const Node value = Immediate(instr.half_imm.PackImmediates());
+ if (!has_negation) {
+ return value;
+ }
+ const Node first_negate = GetPredicate(instr.half_imm.first_negate != 0);
+ const Node second_negate = GetPredicate(instr.half_imm.second_negate != 0);
+
+ return Operation(OperationCode::HNegate, HALF_NO_PRECISE, value, first_negate, second_negate);
+}
+
+Node ShaderIR::HalfMerge(Node dest, Node src, Tegra::Shader::HalfMerge merge) {
+ switch (merge) {
+ case Tegra::Shader::HalfMerge::H0_H1:
+ return src;
+ case Tegra::Shader::HalfMerge::F32:
+ return Operation(OperationCode::HMergeF32, src);
+ case Tegra::Shader::HalfMerge::Mrg_H0:
+ return Operation(OperationCode::HMergeH0, dest, src);
+ case Tegra::Shader::HalfMerge::Mrg_H1:
+ return Operation(OperationCode::HMergeH1, dest, src);
+ }
+ UNREACHABLE();
+ return src;
+}
+
+Node ShaderIR::GetOperandAbsNegHalf(Node value, bool absolute, bool negate) {
+ if (absolute) {
+ value = Operation(OperationCode::HAbsolute, HALF_NO_PRECISE, value);
+ }
+ if (negate) {
+ value = Operation(OperationCode::HNegate, HALF_NO_PRECISE, value, GetPredicate(true),
+ GetPredicate(true));
+ }
+ return value;
+}
+
+Node ShaderIR::GetPredicateComparisonFloat(PredCondition condition, Node op_a, Node op_b) {
+ static const std::unordered_map<PredCondition, OperationCode> PredicateComparisonTable = {
+ {PredCondition::LessThan, OperationCode::LogicalFLessThan},
+ {PredCondition::Equal, OperationCode::LogicalFEqual},
+ {PredCondition::LessEqual, OperationCode::LogicalFLessEqual},
+ {PredCondition::GreaterThan, OperationCode::LogicalFGreaterThan},
+ {PredCondition::NotEqual, OperationCode::LogicalFNotEqual},
+ {PredCondition::GreaterEqual, OperationCode::LogicalFGreaterEqual},
+ {PredCondition::LessThanWithNan, OperationCode::LogicalFLessThan},
+ {PredCondition::NotEqualWithNan, OperationCode::LogicalFNotEqual},
+ {PredCondition::LessEqualWithNan, OperationCode::LogicalFLessEqual},
+ {PredCondition::GreaterThanWithNan, OperationCode::LogicalFGreaterThan},
+ {PredCondition::GreaterEqualWithNan, OperationCode::LogicalFGreaterEqual}};
+
+ const auto comparison{PredicateComparisonTable.find(condition)};
+ UNIMPLEMENTED_IF_MSG(comparison == PredicateComparisonTable.end(),
+ "Unknown predicate comparison operation");
+
+ Node predicate = Operation(comparison->second, NO_PRECISE, op_a, op_b);
+
+ if (condition == PredCondition::LessThanWithNan ||
+ condition == PredCondition::NotEqualWithNan ||
+ condition == PredCondition::LessEqualWithNan ||
+ condition == PredCondition::GreaterThanWithNan ||
+ condition == PredCondition::GreaterEqualWithNan) {
+
+ predicate = Operation(OperationCode::LogicalOr, predicate,
+ Operation(OperationCode::LogicalFIsNan, op_a));
+ predicate = Operation(OperationCode::LogicalOr, predicate,
+ Operation(OperationCode::LogicalFIsNan, op_b));
+ }
+
+ return predicate;
+}
+
+Node ShaderIR::GetPredicateComparisonInteger(PredCondition condition, bool is_signed, Node op_a,
+ Node op_b) {
+ static const std::unordered_map<PredCondition, OperationCode> PredicateComparisonTable = {
+ {PredCondition::LessThan, OperationCode::LogicalILessThan},
+ {PredCondition::Equal, OperationCode::LogicalIEqual},
+ {PredCondition::LessEqual, OperationCode::LogicalILessEqual},
+ {PredCondition::GreaterThan, OperationCode::LogicalIGreaterThan},
+ {PredCondition::NotEqual, OperationCode::LogicalINotEqual},
+ {PredCondition::GreaterEqual, OperationCode::LogicalIGreaterEqual},
+ {PredCondition::LessThanWithNan, OperationCode::LogicalILessThan},
+ {PredCondition::NotEqualWithNan, OperationCode::LogicalINotEqual},
+ {PredCondition::LessEqualWithNan, OperationCode::LogicalILessEqual},
+ {PredCondition::GreaterThanWithNan, OperationCode::LogicalIGreaterThan},
+ {PredCondition::GreaterEqualWithNan, OperationCode::LogicalIGreaterEqual}};
+
+ const auto comparison{PredicateComparisonTable.find(condition)};
+ UNIMPLEMENTED_IF_MSG(comparison == PredicateComparisonTable.end(),
+ "Unknown predicate comparison operation");
+
+ Node predicate = SignedOperation(comparison->second, is_signed, NO_PRECISE, op_a, op_b);
+
+ UNIMPLEMENTED_IF_MSG(condition == PredCondition::LessThanWithNan ||
+ condition == PredCondition::NotEqualWithNan ||
+ condition == PredCondition::LessEqualWithNan ||
+ condition == PredCondition::GreaterThanWithNan ||
+ condition == PredCondition::GreaterEqualWithNan,
+ "NaN comparisons for integers are not implemented");
+ return predicate;
+}
+
+Node ShaderIR::GetPredicateComparisonHalf(Tegra::Shader::PredCondition condition,
+ const MetaHalfArithmetic& meta, Node op_a, Node op_b) {
+
+ UNIMPLEMENTED_IF_MSG(condition == PredCondition::LessThanWithNan ||
+ condition == PredCondition::NotEqualWithNan ||
+ condition == PredCondition::LessEqualWithNan ||
+ condition == PredCondition::GreaterThanWithNan ||
+ condition == PredCondition::GreaterEqualWithNan,
+ "Unimplemented NaN comparison for half floats");
+
+ static const std::unordered_map<PredCondition, OperationCode> PredicateComparisonTable = {
+ {PredCondition::LessThan, OperationCode::Logical2HLessThan},
+ {PredCondition::Equal, OperationCode::Logical2HEqual},
+ {PredCondition::LessEqual, OperationCode::Logical2HLessEqual},
+ {PredCondition::GreaterThan, OperationCode::Logical2HGreaterThan},
+ {PredCondition::NotEqual, OperationCode::Logical2HNotEqual},
+ {PredCondition::GreaterEqual, OperationCode::Logical2HGreaterEqual},
+ {PredCondition::LessThanWithNan, OperationCode::Logical2HLessThan},
+ {PredCondition::NotEqualWithNan, OperationCode::Logical2HNotEqual},
+ {PredCondition::LessEqualWithNan, OperationCode::Logical2HLessEqual},
+ {PredCondition::GreaterThanWithNan, OperationCode::Logical2HGreaterThan},
+ {PredCondition::GreaterEqualWithNan, OperationCode::Logical2HGreaterEqual}};
+
+ const auto comparison{PredicateComparisonTable.find(condition)};
+ UNIMPLEMENTED_IF_MSG(comparison == PredicateComparisonTable.end(),
+ "Unknown predicate comparison operation");
+
+ const Node predicate = Operation(comparison->second, meta, op_a, op_b);
+
+ return predicate;
+}
+
+OperationCode ShaderIR::GetPredicateCombiner(PredOperation operation) {
+ static const std::unordered_map<PredOperation, OperationCode> PredicateOperationTable = {
+ {PredOperation::And, OperationCode::LogicalAnd},
+ {PredOperation::Or, OperationCode::LogicalOr},
+ {PredOperation::Xor, OperationCode::LogicalXor},
+ };
+
+ const auto op = PredicateOperationTable.find(operation);
+ UNIMPLEMENTED_IF_MSG(op == PredicateOperationTable.end(), "Unknown predicate operation");
+ return op->second;
+}
+
+Node ShaderIR::GetConditionCode(Tegra::Shader::ConditionCode cc) {
+ switch (cc) {
+ case Tegra::Shader::ConditionCode::NEU:
+ return GetInternalFlag(InternalFlag::Zero, true);
+ default:
+ UNIMPLEMENTED_MSG("Unimplemented condition code: {}", static_cast<u32>(cc));
+ return GetPredicate(static_cast<u64>(Pred::NeverExecute));
+ }
+}
+
+void ShaderIR::SetRegister(BasicBlock& bb, Register dest, Node src) {
+ bb.push_back(Operation(OperationCode::Assign, GetRegister(dest), src));
+}
+
+void ShaderIR::SetPredicate(BasicBlock& bb, u64 dest, Node src) {
+ bb.push_back(Operation(OperationCode::LogicalAssign, GetPredicate(dest), src));
+}
+
+void ShaderIR::SetInternalFlag(BasicBlock& bb, InternalFlag flag, Node value) {
+ bb.push_back(Operation(OperationCode::LogicalAssign, GetInternalFlag(flag), value));
+}
+
+void ShaderIR::SetLocalMemory(BasicBlock& bb, Node address, Node value) {
+ bb.push_back(Operation(OperationCode::Assign, GetLocalMemory(address), value));
+}
+
+void ShaderIR::SetTemporal(BasicBlock& bb, u32 id, Node value) {
+ SetRegister(bb, Register::ZeroIndex + 1 + id, value);
+}
+
+void ShaderIR::SetInternalFlagsFromFloat(BasicBlock& bb, Node value, bool sets_cc) {
+ if (!sets_cc) {
+ return;
+ }
+ const Node zerop = Operation(OperationCode::LogicalFEqual, value, Immediate(0.0f));
+ SetInternalFlag(bb, InternalFlag::Zero, zerop);
+ LOG_WARNING(HW_GPU, "Condition codes implementation is incomplete");
+}
+
+void ShaderIR::SetInternalFlagsFromInteger(BasicBlock& bb, Node value, bool sets_cc) {
+ if (!sets_cc) {
+ return;
+ }
+ const Node zerop = Operation(OperationCode::LogicalIEqual, value, Immediate(0));
+ SetInternalFlag(bb, InternalFlag::Zero, zerop);
+ LOG_WARNING(HW_GPU, "Condition codes implementation is incomplete");
+}
+
+Node ShaderIR::BitfieldExtract(Node value, u32 offset, u32 bits) {
+ return Operation(OperationCode::UBitfieldExtract, NO_PRECISE, value, Immediate(offset),
+ Immediate(bits));
+}
+
+/*static*/ OperationCode ShaderIR::SignedToUnsignedCode(OperationCode operation_code,
+ bool is_signed) {
+ if (is_signed) {
+ return operation_code;
+ }
+ switch (operation_code) {
+ case OperationCode::FCastInteger:
+ return OperationCode::FCastUInteger;
+ case OperationCode::IAdd:
+ return OperationCode::UAdd;
+ case OperationCode::IMul:
+ return OperationCode::UMul;
+ case OperationCode::IDiv:
+ return OperationCode::UDiv;
+ case OperationCode::IMin:
+ return OperationCode::UMin;
+ case OperationCode::IMax:
+ return OperationCode::UMax;
+ case OperationCode::ICastFloat:
+ return OperationCode::UCastFloat;
+ case OperationCode::ICastUnsigned:
+ return OperationCode::UCastSigned;
+ case OperationCode::ILogicalShiftLeft:
+ return OperationCode::ULogicalShiftLeft;
+ case OperationCode::ILogicalShiftRight:
+ return OperationCode::ULogicalShiftRight;
+ case OperationCode::IArithmeticShiftRight:
+ return OperationCode::UArithmeticShiftRight;
+ case OperationCode::IBitwiseAnd:
+ return OperationCode::UBitwiseAnd;
+ case OperationCode::IBitwiseOr:
+ return OperationCode::UBitwiseOr;
+ case OperationCode::IBitwiseXor:
+ return OperationCode::UBitwiseXor;
+ case OperationCode::IBitwiseNot:
+ return OperationCode::UBitwiseNot;
+ case OperationCode::IBitfieldInsert:
+ return OperationCode::UBitfieldInsert;
+ case OperationCode::IBitCount:
+ return OperationCode::UBitCount;
+ case OperationCode::LogicalILessThan:
+ return OperationCode::LogicalULessThan;
+ case OperationCode::LogicalIEqual:
+ return OperationCode::LogicalUEqual;
+ case OperationCode::LogicalILessEqual:
+ return OperationCode::LogicalULessEqual;
+ case OperationCode::LogicalIGreaterThan:
+ return OperationCode::LogicalUGreaterThan;
+ case OperationCode::LogicalINotEqual:
+ return OperationCode::LogicalUNotEqual;
+ case OperationCode::LogicalIGreaterEqual:
+ return OperationCode::LogicalUGreaterEqual;
+ case OperationCode::INegate:
+ UNREACHABLE_MSG("Can't negate an unsigned integer");
+ case OperationCode::IAbsolute:
+ UNREACHABLE_MSG("Can't apply absolute to an unsigned integer");
+ }
+ UNREACHABLE_MSG("Unknown signed operation with code={}", static_cast<u32>(operation_code));
+ return {};
+}
+
+} // namespace VideoCommon::Shader \ No newline at end of file
diff --git a/src/video_core/shader/shader_ir.h b/src/video_core/shader/shader_ir.h
new file mode 100644
index 000000000..c4ecb2e3c
--- /dev/null
+++ b/src/video_core/shader/shader_ir.h
@@ -0,0 +1,823 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <array>
+#include <cstring>
+#include <map>
+#include <set>
+#include <string>
+#include <tuple>
+#include <variant>
+#include <vector>
+
+#include "common/common_types.h"
+#include "video_core/engines/maxwell_3d.h"
+#include "video_core/engines/shader_bytecode.h"
+#include "video_core/engines/shader_header.h"
+
+namespace VideoCommon::Shader {
+
+class OperationNode;
+class ConditionalNode;
+class GprNode;
+class ImmediateNode;
+class InternalFlagNode;
+class PredicateNode;
+class AbufNode; ///< Attribute buffer
+class CbufNode; ///< Constant buffer
+class LmemNode; ///< Local memory
+class GmemNode; ///< Global memory
+class CommentNode;
+
+using ProgramCode = std::vector<u64>;
+
+using NodeData =
+ std::variant<OperationNode, ConditionalNode, GprNode, ImmediateNode, InternalFlagNode,
+ PredicateNode, AbufNode, CbufNode, LmemNode, GmemNode, CommentNode>;
+using Node = const NodeData*;
+using Node4 = std::array<Node, 4>;
+using BasicBlock = std::vector<Node>;
+
+constexpr u32 MAX_PROGRAM_LENGTH = 0x1000;
+
+enum class OperationCode {
+ Assign, /// (float& dest, float src) -> void
+
+ Select, /// (MetaArithmetic, bool pred, float a, float b) -> float
+
+ FAdd, /// (MetaArithmetic, float a, float b) -> float
+ FMul, /// (MetaArithmetic, float a, float b) -> float
+ FDiv, /// (MetaArithmetic, float a, float b) -> float
+ FFma, /// (MetaArithmetic, float a, float b, float c) -> float
+ FNegate, /// (MetaArithmetic, float a) -> float
+ FAbsolute, /// (MetaArithmetic, float a) -> float
+ FClamp, /// (MetaArithmetic, float value, float min, float max) -> float
+ FMin, /// (MetaArithmetic, float a, float b) -> float
+ FMax, /// (MetaArithmetic, float a, float b) -> float
+ FCos, /// (MetaArithmetic, float a) -> float
+ FSin, /// (MetaArithmetic, float a) -> float
+ FExp2, /// (MetaArithmetic, float a) -> float
+ FLog2, /// (MetaArithmetic, float a) -> float
+ FInverseSqrt, /// (MetaArithmetic, float a) -> float
+ FSqrt, /// (MetaArithmetic, float a) -> float
+ FRoundEven, /// (MetaArithmetic, float a) -> float
+ FFloor, /// (MetaArithmetic, float a) -> float
+ FCeil, /// (MetaArithmetic, float a) -> float
+ FTrunc, /// (MetaArithmetic, float a) -> float
+ FCastInteger, /// (MetaArithmetic, int a) -> float
+ FCastUInteger, /// (MetaArithmetic, uint a) -> float
+
+ IAdd, /// (MetaArithmetic, int a, int b) -> int
+ IMul, /// (MetaArithmetic, int a, int b) -> int
+ IDiv, /// (MetaArithmetic, int a, int b) -> int
+ INegate, /// (MetaArithmetic, int a) -> int
+ IAbsolute, /// (MetaArithmetic, int a) -> int
+ IMin, /// (MetaArithmetic, int a, int b) -> int
+ IMax, /// (MetaArithmetic, int a, int b) -> int
+ ICastFloat, /// (MetaArithmetic, float a) -> int
+ ICastUnsigned, /// (MetaArithmetic, uint a) -> int
+ ILogicalShiftLeft, /// (MetaArithmetic, int a, uint b) -> int
+ ILogicalShiftRight, /// (MetaArithmetic, int a, uint b) -> int
+ IArithmeticShiftRight, /// (MetaArithmetic, int a, uint b) -> int
+ IBitwiseAnd, /// (MetaArithmetic, int a, int b) -> int
+ IBitwiseOr, /// (MetaArithmetic, int a, int b) -> int
+ IBitwiseXor, /// (MetaArithmetic, int a, int b) -> int
+ IBitwiseNot, /// (MetaArithmetic, int a) -> int
+ IBitfieldInsert, /// (MetaArithmetic, int base, int insert, int offset, int bits) -> int
+ IBitfieldExtract, /// (MetaArithmetic, int value, int offset, int offset) -> int
+ IBitCount, /// (MetaArithmetic, int) -> int
+
+ UAdd, /// (MetaArithmetic, uint a, uint b) -> uint
+ UMul, /// (MetaArithmetic, uint a, uint b) -> uint
+ UDiv, /// (MetaArithmetic, uint a, uint b) -> uint
+ UMin, /// (MetaArithmetic, uint a, uint b) -> uint
+ UMax, /// (MetaArithmetic, uint a, uint b) -> uint
+ UCastFloat, /// (MetaArithmetic, float a) -> uint
+ UCastSigned, /// (MetaArithmetic, int a) -> uint
+ ULogicalShiftLeft, /// (MetaArithmetic, uint a, uint b) -> uint
+ ULogicalShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
+ UArithmeticShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
+ UBitwiseAnd, /// (MetaArithmetic, uint a, uint b) -> uint
+ UBitwiseOr, /// (MetaArithmetic, uint a, uint b) -> uint
+ UBitwiseXor, /// (MetaArithmetic, uint a, uint b) -> uint
+ UBitwiseNot, /// (MetaArithmetic, uint a) -> uint
+ UBitfieldInsert, /// (MetaArithmetic, uint base, uint insert, int offset, int bits) -> uint
+ UBitfieldExtract, /// (MetaArithmetic, uint value, int offset, int offset) -> uint
+ UBitCount, /// (MetaArithmetic, uint) -> uint
+
+ HAdd, /// (MetaHalfArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
+ HMul, /// (MetaHalfArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
+ HFma, /// (MetaHalfArithmetic, f16vec2 a, f16vec2 b, f16vec2 c) -> f16vec2
+ HAbsolute, /// (f16vec2 a) -> f16vec2
+ HNegate, /// (f16vec2 a, bool first, bool second) -> f16vec2
+ HMergeF32, /// (f16vec2 src) -> float
+ HMergeH0, /// (f16vec2 dest, f16vec2 src) -> f16vec2
+ HMergeH1, /// (f16vec2 dest, f16vec2 src) -> f16vec2
+ HPack2, /// (float a, float b) -> f16vec2
+
+ LogicalAssign, /// (bool& dst, bool src) -> void
+ LogicalAnd, /// (bool a, bool b) -> bool
+ LogicalOr, /// (bool a, bool b) -> bool
+ LogicalXor, /// (bool a, bool b) -> bool
+ LogicalNegate, /// (bool a) -> bool
+ LogicalPick2, /// (bool2 pair, uint index) -> bool
+ LogicalAll2, /// (bool2 a) -> bool
+ LogicalAny2, /// (bool2 a) -> bool
+
+ LogicalFLessThan, /// (float a, float b) -> bool
+ LogicalFEqual, /// (float a, float b) -> bool
+ LogicalFLessEqual, /// (float a, float b) -> bool
+ LogicalFGreaterThan, /// (float a, float b) -> bool
+ LogicalFNotEqual, /// (float a, float b) -> bool
+ LogicalFGreaterEqual, /// (float a, float b) -> bool
+ LogicalFIsNan, /// (float a) -> bool
+
+ LogicalILessThan, /// (int a, int b) -> bool
+ LogicalIEqual, /// (int a, int b) -> bool
+ LogicalILessEqual, /// (int a, int b) -> bool
+ LogicalIGreaterThan, /// (int a, int b) -> bool
+ LogicalINotEqual, /// (int a, int b) -> bool
+ LogicalIGreaterEqual, /// (int a, int b) -> bool
+
+ LogicalULessThan, /// (uint a, uint b) -> bool
+ LogicalUEqual, /// (uint a, uint b) -> bool
+ LogicalULessEqual, /// (uint a, uint b) -> bool
+ LogicalUGreaterThan, /// (uint a, uint b) -> bool
+ LogicalUNotEqual, /// (uint a, uint b) -> bool
+ LogicalUGreaterEqual, /// (uint a, uint b) -> bool
+
+ Logical2HLessThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+ Logical2HEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+ Logical2HLessEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+ Logical2HGreaterThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+ Logical2HNotEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+ Logical2HGreaterEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
+
+ F4Texture, /// (MetaTexture, float[N] coords, float[M] params) -> float4
+ F4TextureLod, /// (MetaTexture, float[N] coords, float[M] params) -> float4
+ F4TextureGather, /// (MetaTexture, float[N] coords, float[M] params) -> float4
+ F4TextureQueryDimensions, /// (MetaTexture, float a) -> float4
+ F4TextureQueryLod, /// (MetaTexture, float[N] coords) -> float4
+ F4TexelFetch, /// (MetaTexture, int[N], int) -> float4
+
+ Branch, /// (uint branch_target) -> void
+ PushFlowStack, /// (uint branch_target) -> void
+ PopFlowStack, /// () -> void
+ Exit, /// () -> void
+ Discard, /// () -> void
+
+ EmitVertex, /// () -> void
+ EndPrimitive, /// () -> void
+
+ YNegate, /// () -> float
+
+ Amount,
+};
+
+enum class InternalFlag {
+ Zero = 0,
+ Sign = 1,
+ Carry = 2,
+ Overflow = 3,
+ Amount = 4,
+};
+
+/// Describes the behaviour of code path of a given entry point and a return point.
+enum class ExitMethod {
+ Undetermined, ///< Internal value. Only occur when analyzing JMP loop.
+ AlwaysReturn, ///< All code paths reach the return point.
+ Conditional, ///< Code path reaches the return point or an END instruction conditionally.
+ AlwaysEnd, ///< All code paths reach a END instruction.
+};
+
+class Sampler {
+public:
+ explicit Sampler(std::size_t offset, std::size_t index, Tegra::Shader::TextureType type,
+ bool is_array, bool is_shadow)
+ : offset{offset}, index{index}, type{type}, is_array{is_array}, is_shadow{is_shadow} {}
+
+ std::size_t GetOffset() const {
+ return offset;
+ }
+
+ std::size_t GetIndex() const {
+ return index;
+ }
+
+ Tegra::Shader::TextureType GetType() const {
+ return type;
+ }
+
+ bool IsArray() const {
+ return is_array;
+ }
+
+ bool IsShadow() const {
+ return is_shadow;
+ }
+
+ bool operator<(const Sampler& rhs) const {
+ return std::tie(offset, index, type, is_array, is_shadow) <
+ std::tie(rhs.offset, rhs.index, rhs.type, rhs.is_array, rhs.is_shadow);
+ }
+
+private:
+ /// Offset in TSC memory from which to read the sampler object, as specified by the sampling
+ /// instruction.
+ std::size_t offset{};
+ std::size_t index{}; ///< Value used to index into the generated GLSL sampler array.
+ Tegra::Shader::TextureType type{}; ///< The type used to sample this texture (Texture2D, etc)
+ bool is_array{}; ///< Whether the texture is being sampled as an array texture or not.
+ bool is_shadow{}; ///< Whether the texture is being sampled as a depth texture or not.
+};
+
+class ConstBuffer {
+public:
+ void MarkAsUsed(u64 offset) {
+ max_offset = std::max(max_offset, static_cast<u32>(offset));
+ }
+
+ void MarkAsUsedIndirect() {
+ is_indirect = true;
+ }
+
+ bool IsIndirect() const {
+ return is_indirect;
+ }
+
+ u32 GetSize() const {
+ return max_offset + 1;
+ }
+
+private:
+ u32 max_offset{};
+ bool is_indirect{};
+};
+
+struct GlobalMemoryBase {
+ u32 cbuf_index{};
+ u32 cbuf_offset{};
+
+ bool operator<(const GlobalMemoryBase& rhs) const {
+ return std::tie(cbuf_index, cbuf_offset) < std::tie(rhs.cbuf_index, rhs.cbuf_offset);
+ }
+};
+
+struct MetaArithmetic {
+ bool precise{};
+};
+
+struct MetaHalfArithmetic {
+ bool precise{};
+ std::array<Tegra::Shader::HalfType, 3> types = {Tegra::Shader::HalfType::H0_H1,
+ Tegra::Shader::HalfType::H0_H1,
+ Tegra::Shader::HalfType::H0_H1};
+};
+
+struct MetaTexture {
+ const Sampler& sampler;
+ u32 element{};
+ u32 coords_count{};
+ std::optional<u32> array_index;
+};
+
+constexpr MetaArithmetic PRECISE = {true};
+constexpr MetaArithmetic NO_PRECISE = {false};
+constexpr MetaHalfArithmetic HALF_NO_PRECISE = {false};
+
+using Meta = std::variant<MetaArithmetic, MetaHalfArithmetic, MetaTexture>;
+
+/// Holds any kind of operation that can be done in the IR
+class OperationNode final {
+public:
+ template <typename... T>
+ explicit constexpr OperationNode(OperationCode code) : code{code}, meta{} {}
+
+ template <typename... T>
+ explicit constexpr OperationNode(OperationCode code, Meta&& meta)
+ : code{code}, meta{std::move(meta)} {}
+
+ template <typename... T>
+ explicit constexpr OperationNode(OperationCode code, const T*... operands)
+ : OperationNode(code, {}, operands...) {}
+
+ template <typename... T>
+ explicit constexpr OperationNode(OperationCode code, Meta&& meta, const T*... operands_)
+ : code{code}, meta{std::move(meta)} {
+
+ auto operands_list = {operands_...};
+ for (auto& operand : operands_list) {
+ operands.push_back(operand);
+ }
+ }
+
+ explicit OperationNode(OperationCode code, Meta&& meta, std::vector<Node>&& operands)
+ : code{code}, meta{meta}, operands{std::move(operands)} {}
+
+ explicit OperationNode(OperationCode code, std::vector<Node>&& operands)
+ : code{code}, meta{}, operands{std::move(operands)} {}
+
+ OperationCode GetCode() const {
+ return code;
+ }
+
+ const Meta& GetMeta() const {
+ return meta;
+ }
+
+ std::size_t GetOperandsCount() const {
+ return operands.size();
+ }
+
+ Node operator[](std::size_t operand_index) const {
+ return operands.at(operand_index);
+ }
+
+private:
+ const OperationCode code;
+ const Meta meta;
+ std::vector<Node> operands;
+};
+
+/// Encloses inside any kind of node that returns a boolean conditionally-executed code
+class ConditionalNode final {
+public:
+ explicit ConditionalNode(Node condition, std::vector<Node>&& code)
+ : condition{condition}, code{std::move(code)} {}
+
+ Node GetCondition() const {
+ return condition;
+ }
+
+ const std::vector<Node>& GetCode() const {
+ return code;
+ }
+
+private:
+ const Node condition; ///< Condition to be satisfied
+ std::vector<Node> code; ///< Code to execute
+};
+
+/// A general purpose register
+class GprNode final {
+public:
+ explicit constexpr GprNode(Tegra::Shader::Register index) : index{index} {}
+
+ u32 GetIndex() const {
+ return static_cast<u32>(index);
+ }
+
+private:
+ const Tegra::Shader::Register index;
+};
+
+/// A 32-bits value that represents an immediate value
+class ImmediateNode final {
+public:
+ explicit constexpr ImmediateNode(u32 value) : value{value} {}
+
+ u32 GetValue() const {
+ return value;
+ }
+
+private:
+ const u32 value;
+};
+
+/// One of Maxwell's internal flags
+class InternalFlagNode final {
+public:
+ explicit constexpr InternalFlagNode(InternalFlag flag) : flag{flag} {}
+
+ InternalFlag GetFlag() const {
+ return flag;
+ }
+
+private:
+ const InternalFlag flag;
+};
+
+/// A predicate register, it can be negated without additional nodes
+class PredicateNode final {
+public:
+ explicit constexpr PredicateNode(Tegra::Shader::Pred index, bool negated)
+ : index{index}, negated{negated} {}
+
+ Tegra::Shader::Pred GetIndex() const {
+ return index;
+ }
+
+ bool IsNegated() const {
+ return negated;
+ }
+
+private:
+ const Tegra::Shader::Pred index;
+ const bool negated;
+};
+
+/// Attribute buffer memory (known as attributes or varyings in GLSL terms)
+class AbufNode final {
+public:
+ explicit constexpr AbufNode(Tegra::Shader::Attribute::Index index, u32 element,
+ const Tegra::Shader::IpaMode& input_mode, Node buffer = {})
+ : input_mode{input_mode}, buffer{buffer}, index{index}, element{element} {}
+
+ explicit constexpr AbufNode(Tegra::Shader::Attribute::Index index, u32 element,
+ Node buffer = {})
+ : input_mode{}, buffer{buffer}, index{index}, element{element} {}
+
+ Tegra::Shader::IpaMode GetInputMode() const {
+ return input_mode;
+ }
+
+ Tegra::Shader::Attribute::Index GetIndex() const {
+ return index;
+ }
+
+ u32 GetElement() const {
+ return element;
+ }
+
+ Node GetBuffer() const {
+ return buffer;
+ }
+
+private:
+ const Tegra::Shader::IpaMode input_mode;
+ const Node buffer;
+ const Tegra::Shader::Attribute::Index index;
+ const u32 element;
+};
+
+/// Constant buffer node, usually mapped to uniform buffers in GLSL
+class CbufNode final {
+public:
+ explicit constexpr CbufNode(u32 index, Node offset) : index{index}, offset{offset} {}
+
+ u32 GetIndex() const {
+ return index;
+ }
+
+ Node GetOffset() const {
+ return offset;
+ }
+
+private:
+ const u32 index;
+ const Node offset;
+};
+
+/// Local memory node
+class LmemNode final {
+public:
+ explicit constexpr LmemNode(Node address) : address{address} {}
+
+ Node GetAddress() const {
+ return address;
+ }
+
+private:
+ const Node address;
+};
+
+/// Global memory node
+class GmemNode final {
+public:
+ explicit constexpr GmemNode(Node real_address, Node base_address,
+ const GlobalMemoryBase& descriptor)
+ : real_address{real_address}, base_address{base_address}, descriptor{descriptor} {}
+
+ Node GetRealAddress() const {
+ return real_address;
+ }
+
+ Node GetBaseAddress() const {
+ return base_address;
+ }
+
+ const GlobalMemoryBase& GetDescriptor() const {
+ return descriptor;
+ }
+
+private:
+ const Node real_address;
+ const Node base_address;
+ const GlobalMemoryBase descriptor;
+};
+
+/// Commentary, can be dropped
+class CommentNode final {
+public:
+ explicit CommentNode(std::string text) : text{std::move(text)} {}
+
+ const std::string& GetText() const {
+ return text;
+ }
+
+private:
+ std::string text;
+};
+
+class ShaderIR final {
+public:
+ explicit ShaderIR(const ProgramCode& program_code, u32 main_offset)
+ : program_code{program_code}, main_offset{main_offset} {
+
+ Decode();
+ }
+
+ const std::map<u32, BasicBlock>& GetBasicBlocks() const {
+ return basic_blocks;
+ }
+
+ const std::set<u32>& GetRegisters() const {
+ return used_registers;
+ }
+
+ const std::set<Tegra::Shader::Pred>& GetPredicates() const {
+ return used_predicates;
+ }
+
+ const std::map<Tegra::Shader::Attribute::Index, std::set<Tegra::Shader::IpaMode>>&
+ GetInputAttributes() const {
+ return used_input_attributes;
+ }
+
+ const std::set<Tegra::Shader::Attribute::Index>& GetOutputAttributes() const {
+ return used_output_attributes;
+ }
+
+ const std::map<u32, ConstBuffer>& GetConstantBuffers() const {
+ return used_cbufs;
+ }
+
+ const std::set<Sampler>& GetSamplers() const {
+ return used_samplers;
+ }
+
+ const std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances>& GetClipDistances()
+ const {
+ return used_clip_distances;
+ }
+
+ const std::set<GlobalMemoryBase>& GetGlobalMemoryBases() const {
+ return used_global_memory_bases;
+ }
+
+ std::size_t GetLength() const {
+ return static_cast<std::size_t>(coverage_end * sizeof(u64));
+ }
+
+ const Tegra::Shader::Header& GetHeader() const {
+ return header;
+ }
+
+private:
+ void Decode();
+
+ ExitMethod Scan(u32 begin, u32 end, std::set<u32>& labels);
+
+ BasicBlock DecodeRange(u32 begin, u32 end);
+
+ /**
+ * Decodes a single instruction from Tegra to IR.
+ * @param bb Basic block where the nodes will be written to.
+ * @param pc Program counter. Offset to decode.
+ * @return Next address to decode.
+ */
+ u32 DecodeInstr(BasicBlock& bb, u32 pc);
+
+ u32 DecodeArithmetic(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeArithmeticImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeBfe(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeBfi(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeShift(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeArithmeticInteger(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeArithmeticIntegerImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeArithmeticHalf(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeArithmeticHalfImmediate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeFfma(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeHfma2(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeConversion(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeMemory(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeFloatSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeIntegerSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeHalfSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodePredicateSetRegister(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodePredicateSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeRegisterSetPredicate(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeFloatSet(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeIntegerSet(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeHalfSet(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeVideo(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeXmad(BasicBlock& bb, const BasicBlock& code, u32 pc);
+ u32 DecodeOther(BasicBlock& bb, const BasicBlock& code, u32 pc);
+
+ /// Internalizes node's data and returns a managed pointer to a clone of that node
+ Node StoreNode(NodeData&& node_data);
+
+ /// Creates a conditional node
+ Node Conditional(Node condition, std::vector<Node>&& code);
+ /// Creates a commentary
+ Node Comment(const std::string& text);
+ /// Creates an u32 immediate
+ Node Immediate(u32 value);
+ /// Creates a s32 immediate
+ Node Immediate(s32 value) {
+ return Immediate(static_cast<u32>(value));
+ }
+ /// Creates a f32 immediate
+ Node Immediate(f32 value) {
+ u32 integral;
+ std::memcpy(&integral, &value, sizeof(u32));
+ return Immediate(integral);
+ }
+
+ /// Generates a node for a passed register.
+ Node GetRegister(Tegra::Shader::Register reg);
+ /// Generates a node representing a 19-bit immediate value
+ Node GetImmediate19(Tegra::Shader::Instruction instr);
+ /// Generates a node representing a 32-bit immediate value
+ Node GetImmediate32(Tegra::Shader::Instruction instr);
+ /// Generates a node representing a constant buffer
+ Node GetConstBuffer(u64 index, u64 offset);
+ /// Generates a node representing a constant buffer with a variadic offset
+ Node GetConstBufferIndirect(u64 index, u64 offset, Node node);
+ /// Generates a node for a passed predicate. It can be optionally negated
+ Node GetPredicate(u64 pred, bool negated = false);
+ /// Generates a predicate node for an immediate true or false value
+ Node GetPredicate(bool immediate);
+ /// Generates a node representing an input attribute. Keeps track of used attributes.
+ Node GetInputAttribute(Tegra::Shader::Attribute::Index index, u64 element,
+ const Tegra::Shader::IpaMode& input_mode, Node buffer = {});
+ /// Generates a node representing an output attribute. Keeps track of used attributes.
+ Node GetOutputAttribute(Tegra::Shader::Attribute::Index index, u64 element, Node buffer);
+ /// Generates a node representing an internal flag
+ Node GetInternalFlag(InternalFlag flag, bool negated = false);
+ /// Generates a node representing a local memory address
+ Node GetLocalMemory(Node address);
+ /// Generates a temporal, internally it uses a post-RZ register
+ Node GetTemporal(u32 id);
+
+ /// Sets a register. src value must be a number-evaluated node.
+ void SetRegister(BasicBlock& bb, Tegra::Shader::Register dest, Node src);
+ /// Sets a predicate. src value must be a bool-evaluated node
+ void SetPredicate(BasicBlock& bb, u64 dest, Node src);
+ /// Sets an internal flag. src value must be a bool-evaluated node
+ void SetInternalFlag(BasicBlock& bb, InternalFlag flag, Node value);
+ /// Sets a local memory address. address and value must be a number-evaluated node
+ void SetLocalMemory(BasicBlock& bb, Node address, Node value);
+ /// Sets a temporal. Internally it uses a post-RZ register
+ void SetTemporal(BasicBlock& bb, u32 id, Node value);
+
+ /// Sets internal flags from a float
+ void SetInternalFlagsFromFloat(BasicBlock& bb, Node value, bool sets_cc = true);
+ /// Sets internal flags from an integer
+ void SetInternalFlagsFromInteger(BasicBlock& bb, Node value, bool sets_cc = true);
+
+ /// Conditionally absolute/negated float. Absolute is applied first
+ Node GetOperandAbsNegFloat(Node value, bool absolute, bool negate);
+ /// Conditionally saturates a float
+ Node GetSaturatedFloat(Node value, bool saturate = true);
+
+ /// Converts an integer to different sizes.
+ Node ConvertIntegerSize(Node value, Tegra::Shader::Register::Size size, bool is_signed);
+ /// Conditionally absolute/negated integer. Absolute is applied first
+ Node GetOperandAbsNegInteger(Node value, bool absolute, bool negate, bool is_signed);
+
+ /// Unpacks a half immediate from an instruction
+ Node UnpackHalfImmediate(Tegra::Shader::Instruction instr, bool has_negation);
+ /// Merges a half pair into another value
+ Node HalfMerge(Node dest, Node src, Tegra::Shader::HalfMerge merge);
+ /// Conditionally absolute/negated half float pair. Absolute is applied first
+ Node GetOperandAbsNegHalf(Node value, bool absolute, bool negate);
+
+ /// Returns a predicate comparing two floats
+ Node GetPredicateComparisonFloat(Tegra::Shader::PredCondition condition, Node op_a, Node op_b);
+ /// Returns a predicate comparing two integers
+ Node GetPredicateComparisonInteger(Tegra::Shader::PredCondition condition, bool is_signed,
+ Node op_a, Node op_b);
+ /// Returns a predicate comparing two half floats. meta consumes how both pairs will be compared
+ Node GetPredicateComparisonHalf(Tegra::Shader::PredCondition condition,
+ const MetaHalfArithmetic& meta, Node op_a, Node op_b);
+
+ /// Returns a predicate combiner operation
+ OperationCode GetPredicateCombiner(Tegra::Shader::PredOperation operation);
+
+ /// Returns a condition code evaluated from internal flags
+ Node GetConditionCode(Tegra::Shader::ConditionCode cc);
+
+ /// Accesses a texture sampler
+ const Sampler& GetSampler(const Tegra::Shader::Sampler& sampler,
+ Tegra::Shader::TextureType type, bool is_array, bool is_shadow);
+
+ /// Extracts a sequence of bits from a node
+ Node BitfieldExtract(Node value, u32 offset, u32 bits);
+
+ void WriteTexInstructionFloat(BasicBlock& bb, Tegra::Shader::Instruction instr,
+ const Node4& components);
+
+ void WriteTexsInstructionFloat(BasicBlock& bb, Tegra::Shader::Instruction instr,
+ const Node4& components);
+ void WriteTexsInstructionHalfFloat(BasicBlock& bb, Tegra::Shader::Instruction instr,
+ const Node4& components);
+
+ Node4 GetTexCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
+ Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
+ bool is_array);
+
+ Node4 GetTexsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
+ Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
+ bool is_array);
+
+ Node4 GetTld4Code(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
+ bool depth_compare, bool is_array);
+
+ Node4 GetTldsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
+ bool is_array);
+
+ std::tuple<std::size_t, std::size_t> ValidateAndGetCoordinateElement(
+ Tegra::Shader::TextureType texture_type, bool depth_compare, bool is_array,
+ bool lod_bias_enabled, std::size_t max_coords, std::size_t max_inputs);
+
+ Node4 GetTextureCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
+ Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
+ bool is_array, std::size_t array_offset, std::size_t bias_offset,
+ std::vector<Node>&& coords);
+
+ Node GetVideoOperand(Node op, bool is_chunk, bool is_signed, Tegra::Shader::VideoType type,
+ u64 byte_height);
+
+ void WriteLogicOperation(BasicBlock& bb, Tegra::Shader::Register dest,
+ Tegra::Shader::LogicOperation logic_op, Node op_a, Node op_b,
+ Tegra::Shader::PredicateResultMode predicate_mode,
+ Tegra::Shader::Pred predicate, bool sets_cc);
+ void WriteLop3Instruction(BasicBlock& bb, Tegra::Shader::Register dest, Node op_a, Node op_b,
+ Node op_c, Node imm_lut, bool sets_cc);
+
+ Node TrackCbuf(Node tracked, const BasicBlock& code, s64 cursor);
+
+ std::pair<Node, s64> TrackRegister(const GprNode* tracked, const BasicBlock& code, s64 cursor);
+
+ template <typename... T>
+ Node Operation(OperationCode code, const T*... operands) {
+ return StoreNode(OperationNode(code, operands...));
+ }
+
+ template <typename... T>
+ Node Operation(OperationCode code, Meta&& meta, const T*... operands) {
+ return StoreNode(OperationNode(code, std::move(meta), operands...));
+ }
+
+ template <typename... T>
+ Node Operation(OperationCode code, std::vector<Node>&& operands) {
+ return StoreNode(OperationNode(code, std::move(operands)));
+ }
+
+ template <typename... T>
+ Node Operation(OperationCode code, Meta&& meta, std::vector<Node>&& operands) {
+ return StoreNode(OperationNode(code, std::move(meta), std::move(operands)));
+ }
+
+ template <typename... T>
+ Node SignedOperation(OperationCode code, bool is_signed, const T*... operands) {
+ return StoreNode(OperationNode(SignedToUnsignedCode(code, is_signed), operands...));
+ }
+
+ template <typename... T>
+ Node SignedOperation(OperationCode code, bool is_signed, Meta&& meta, const T*... operands) {
+ return StoreNode(
+ OperationNode(SignedToUnsignedCode(code, is_signed), std::move(meta), operands...));
+ }
+
+ static OperationCode SignedToUnsignedCode(OperationCode operation_code, bool is_signed);
+
+ const ProgramCode& program_code;
+ const u32 main_offset;
+
+ u32 coverage_begin{};
+ u32 coverage_end{};
+ std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
+
+ std::map<u32, BasicBlock> basic_blocks;
+
+ std::vector<std::unique_ptr<NodeData>> stored_nodes;
+
+ std::set<u32> used_registers;
+ std::set<Tegra::Shader::Pred> used_predicates;
+ std::map<Tegra::Shader::Attribute::Index, std::set<Tegra::Shader::IpaMode>>
+ used_input_attributes;
+ std::set<Tegra::Shader::Attribute::Index> used_output_attributes;
+ std::map<u32, ConstBuffer> used_cbufs;
+ std::set<Sampler> used_samplers;
+ std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances> used_clip_distances{};
+ std::set<GlobalMemoryBase> used_global_memory_bases;
+
+ Tegra::Shader::Header header;
+};
+
+} // namespace VideoCommon::Shader
diff --git a/src/video_core/shader/track.cpp b/src/video_core/shader/track.cpp
new file mode 100644
index 000000000..d6d29ee9f
--- /dev/null
+++ b/src/video_core/shader/track.cpp
@@ -0,0 +1,76 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <utility>
+#include <variant>
+
+#include "video_core/shader/shader_ir.h"
+
+namespace VideoCommon::Shader {
+
+namespace {
+std::pair<Node, s64> FindOperation(const BasicBlock& code, s64 cursor,
+ OperationCode operation_code) {
+ for (; cursor >= 0; --cursor) {
+ const Node node = code[cursor];
+ if (const auto operation = std::get_if<OperationNode>(node)) {
+ if (operation->GetCode() == operation_code)
+ return {node, cursor};
+ }
+ }
+ return {};
+}
+} // namespace
+
+Node ShaderIR::TrackCbuf(Node tracked, const BasicBlock& code, s64 cursor) {
+ if (const auto cbuf = std::get_if<CbufNode>(tracked)) {
+ // Cbuf found, but it has to be immediate
+ return std::holds_alternative<ImmediateNode>(*cbuf->GetOffset()) ? tracked : nullptr;
+ }
+ if (const auto gpr = std::get_if<GprNode>(tracked)) {
+ if (gpr->GetIndex() == Tegra::Shader::Register::ZeroIndex) {
+ return nullptr;
+ }
+ // Reduce the cursor in one to avoid infinite loops when the instruction sets the same
+ // register that it uses as operand
+ const auto [source, new_cursor] = TrackRegister(gpr, code, cursor - 1);
+ if (!source) {
+ return nullptr;
+ }
+ return TrackCbuf(source, code, new_cursor);
+ }
+ if (const auto operation = std::get_if<OperationNode>(tracked)) {
+ for (std::size_t i = 0; i < operation->GetOperandsCount(); ++i) {
+ if (const auto found = TrackCbuf((*operation)[i], code, cursor)) {
+ // Cbuf found in operand
+ return found;
+ }
+ }
+ return nullptr;
+ }
+ return nullptr;
+}
+
+std::pair<Node, s64> ShaderIR::TrackRegister(const GprNode* tracked, const BasicBlock& code,
+ s64 cursor) {
+ for (; cursor >= 0; --cursor) {
+ const auto [found_node, new_cursor] = FindOperation(code, cursor, OperationCode::Assign);
+ if (!found_node) {
+ return {};
+ }
+ const auto operation = std::get_if<OperationNode>(found_node);
+ ASSERT(operation);
+
+ const auto& target = (*operation)[0];
+ if (const auto gpr_target = std::get_if<GprNode>(target)) {
+ if (gpr_target->GetIndex() == tracked->GetIndex()) {
+ return {(*operation)[1], new_cursor};
+ }
+ }
+ }
+ return {};
+}
+
+} // namespace VideoCommon::Shader
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
index 9582dd2ca..2f6612a35 100644
--- a/src/video_core/surface.cpp
+++ b/src/video_core/surface.cpp
@@ -50,6 +50,24 @@ bool SurfaceTargetIsLayered(SurfaceTarget target) {
}
}
+bool SurfaceTargetIsArray(SurfaceTarget target) {
+ switch (target) {
+ case SurfaceTarget::Texture1D:
+ case SurfaceTarget::Texture2D:
+ case SurfaceTarget::Texture3D:
+ case SurfaceTarget::TextureCubemap:
+ return false;
+ case SurfaceTarget::Texture1DArray:
+ case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
+ return true;
+ default:
+ LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
+ UNREACHABLE();
+ return false;
+ }
+}
+
PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format) {
switch (format) {
case Tegra::DepthFormat::S8_Z24_UNORM:
@@ -65,6 +83,7 @@ PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format) {
default:
LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
UNREACHABLE();
+ return PixelFormat::S8Z24;
}
}
@@ -141,6 +160,7 @@ PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format)
default:
LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
UNREACHABLE();
+ return PixelFormat::RGBA8_SRGB;
}
}
@@ -194,11 +214,14 @@ PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
UNREACHABLE();
case Tegra::Texture::TextureFormat::G8R8:
+ // TextureFormat::G8R8 is actually ordered red then green, as such we can use
+ // PixelFormat::RG8U and PixelFormat::RG8S. This was tested with The Legend of Zelda: Breath
+ // of the Wild, which uses this format to render the hearts on the UI.
switch (component_type) {
case Tegra::Texture::ComponentType::UNORM:
- return PixelFormat::G8R8U;
+ return PixelFormat::RG8U;
case Tegra::Texture::ComponentType::SNORM:
- return PixelFormat::G8R8S;
+ return PixelFormat::RG8S;
}
LOG_CRITICAL(HW_GPU, "Unimplemented component_type={}", static_cast<u32>(component_type));
UNREACHABLE();
@@ -327,6 +350,7 @@ PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
LOG_CRITICAL(HW_GPU, "Unimplemented format={}, component_type={}", static_cast<u32>(format),
static_cast<u32>(component_type));
UNREACHABLE();
+ return PixelFormat::ABGR8U;
}
}
@@ -346,6 +370,7 @@ ComponentType ComponentTypeFromTexture(Tegra::Texture::ComponentType type) {
default:
LOG_CRITICAL(HW_GPU, "Unimplemented component type={}", static_cast<u32>(type));
UNREACHABLE();
+ return ComponentType::UNorm;
}
}
@@ -393,6 +418,7 @@ ComponentType ComponentTypeFromRenderTarget(Tegra::RenderTargetFormat format) {
default:
LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
UNREACHABLE();
+ return ComponentType::UNorm;
}
}
@@ -403,6 +429,7 @@ PixelFormat PixelFormatFromGPUPixelFormat(Tegra::FramebufferConfig::PixelFormat
default:
LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
UNREACHABLE();
+ return PixelFormat::ABGR8U;
}
}
@@ -418,6 +445,7 @@ ComponentType ComponentTypeFromDepthFormat(Tegra::DepthFormat format) {
default:
LOG_CRITICAL(HW_GPU, "Unimplemented format={}", static_cast<u32>(format));
UNREACHABLE();
+ return ComponentType::UNorm;
}
}
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
index 0dd3eb2e4..edd3816ba 100644
--- a/src/video_core/surface.h
+++ b/src/video_core/surface.h
@@ -38,57 +38,55 @@ enum class PixelFormat {
BC6H_UF16 = 20,
BC6H_SF16 = 21,
ASTC_2D_4X4 = 22,
- G8R8U = 23,
- G8R8S = 24,
- BGRA8 = 25,
- RGBA32F = 26,
- RG32F = 27,
- R32F = 28,
- R16F = 29,
- R16U = 30,
- R16S = 31,
- R16UI = 32,
- R16I = 33,
- RG16 = 34,
- RG16F = 35,
- RG16UI = 36,
- RG16I = 37,
- RG16S = 38,
- RGB32F = 39,
- RGBA8_SRGB = 40,
- RG8U = 41,
- RG8S = 42,
- RG32UI = 43,
- R32UI = 44,
- ASTC_2D_8X8 = 45,
- ASTC_2D_8X5 = 46,
- ASTC_2D_5X4 = 47,
- BGRA8_SRGB = 48,
- DXT1_SRGB = 49,
- DXT23_SRGB = 50,
- DXT45_SRGB = 51,
- BC7U_SRGB = 52,
- ASTC_2D_4X4_SRGB = 53,
- ASTC_2D_8X8_SRGB = 54,
- ASTC_2D_8X5_SRGB = 55,
- ASTC_2D_5X4_SRGB = 56,
- ASTC_2D_5X5 = 57,
- ASTC_2D_5X5_SRGB = 58,
- ASTC_2D_10X8 = 59,
- ASTC_2D_10X8_SRGB = 60,
+ BGRA8 = 23,
+ RGBA32F = 24,
+ RG32F = 25,
+ R32F = 26,
+ R16F = 27,
+ R16U = 28,
+ R16S = 29,
+ R16UI = 30,
+ R16I = 31,
+ RG16 = 32,
+ RG16F = 33,
+ RG16UI = 34,
+ RG16I = 35,
+ RG16S = 36,
+ RGB32F = 37,
+ RGBA8_SRGB = 38,
+ RG8U = 39,
+ RG8S = 40,
+ RG32UI = 41,
+ R32UI = 42,
+ ASTC_2D_8X8 = 43,
+ ASTC_2D_8X5 = 44,
+ ASTC_2D_5X4 = 45,
+ BGRA8_SRGB = 46,
+ DXT1_SRGB = 47,
+ DXT23_SRGB = 48,
+ DXT45_SRGB = 49,
+ BC7U_SRGB = 50,
+ ASTC_2D_4X4_SRGB = 51,
+ ASTC_2D_8X8_SRGB = 52,
+ ASTC_2D_8X5_SRGB = 53,
+ ASTC_2D_5X4_SRGB = 54,
+ ASTC_2D_5X5 = 55,
+ ASTC_2D_5X5_SRGB = 56,
+ ASTC_2D_10X8 = 57,
+ ASTC_2D_10X8_SRGB = 58,
MaxColorFormat,
// Depth formats
- Z32F = 61,
- Z16 = 62,
+ Z32F = 59,
+ Z16 = 60,
MaxDepthFormat,
// DepthStencil formats
- Z24S8 = 63,
- S8Z24 = 64,
- Z32FS8 = 65,
+ Z24S8 = 61,
+ S8Z24 = 62,
+ Z32FS8 = 63,
MaxDepthStencilFormat,
@@ -125,6 +123,73 @@ enum class SurfaceTarget {
TextureCubeArray,
};
+constexpr std::array<u32, MaxPixelFormat> compression_factor_table = {{
+ 1, // ABGR8U
+ 1, // ABGR8S
+ 1, // ABGR8UI
+ 1, // B5G6R5U
+ 1, // A2B10G10R10U
+ 1, // A1B5G5R5U
+ 1, // R8U
+ 1, // R8UI
+ 1, // RGBA16F
+ 1, // RGBA16U
+ 1, // RGBA16UI
+ 1, // R11FG11FB10F
+ 1, // RGBA32UI
+ 4, // DXT1
+ 4, // DXT23
+ 4, // DXT45
+ 4, // DXN1
+ 4, // DXN2UNORM
+ 4, // DXN2SNORM
+ 4, // BC7U
+ 4, // BC6H_UF16
+ 4, // BC6H_SF16
+ 4, // ASTC_2D_4X4
+ 1, // BGRA8
+ 1, // RGBA32F
+ 1, // RG32F
+ 1, // R32F
+ 1, // R16F
+ 1, // R16U
+ 1, // R16S
+ 1, // R16UI
+ 1, // R16I
+ 1, // RG16
+ 1, // RG16F
+ 1, // RG16UI
+ 1, // RG16I
+ 1, // RG16S
+ 1, // RGB32F
+ 1, // RGBA8_SRGB
+ 1, // RG8U
+ 1, // RG8S
+ 1, // RG32UI
+ 1, // R32UI
+ 4, // ASTC_2D_8X8
+ 4, // ASTC_2D_8X5
+ 4, // ASTC_2D_5X4
+ 1, // BGRA8_SRGB
+ 4, // DXT1_SRGB
+ 4, // DXT23_SRGB
+ 4, // DXT45_SRGB
+ 4, // BC7U_SRGB
+ 4, // ASTC_2D_4X4_SRGB
+ 4, // ASTC_2D_8X8_SRGB
+ 4, // ASTC_2D_8X5_SRGB
+ 4, // ASTC_2D_5X4_SRGB
+ 4, // ASTC_2D_5X5
+ 4, // ASTC_2D_5X5_SRGB
+ 4, // ASTC_2D_10X8
+ 4, // ASTC_2D_10X8_SRGB
+ 1, // Z32F
+ 1, // Z16
+ 1, // Z24S8
+ 1, // S8Z24
+ 1, // Z32FS8
+}};
+
/**
* Gets the compression factor for the specified PixelFormat. This applies to just the
* "compressed width" and "compressed height", not the overall compression factor of a
@@ -135,304 +200,231 @@ static constexpr u32 GetCompressionFactor(PixelFormat format) {
if (format == PixelFormat::Invalid)
return 0;
- constexpr std::array<u32, MaxPixelFormat> compression_factor_table = {{
- 1, // ABGR8U
- 1, // ABGR8S
- 1, // ABGR8UI
- 1, // B5G6R5U
- 1, // A2B10G10R10U
- 1, // A1B5G5R5U
- 1, // R8U
- 1, // R8UI
- 1, // RGBA16F
- 1, // RGBA16U
- 1, // RGBA16UI
- 1, // R11FG11FB10F
- 1, // RGBA32UI
- 4, // DXT1
- 4, // DXT23
- 4, // DXT45
- 4, // DXN1
- 4, // DXN2UNORM
- 4, // DXN2SNORM
- 4, // BC7U
- 4, // BC6H_UF16
- 4, // BC6H_SF16
- 4, // ASTC_2D_4X4
- 1, // G8R8U
- 1, // G8R8S
- 1, // BGRA8
- 1, // RGBA32F
- 1, // RG32F
- 1, // R32F
- 1, // R16F
- 1, // R16U
- 1, // R16S
- 1, // R16UI
- 1, // R16I
- 1, // RG16
- 1, // RG16F
- 1, // RG16UI
- 1, // RG16I
- 1, // RG16S
- 1, // RGB32F
- 1, // RGBA8_SRGB
- 1, // RG8U
- 1, // RG8S
- 1, // RG32UI
- 1, // R32UI
- 4, // ASTC_2D_8X8
- 4, // ASTC_2D_8X5
- 4, // ASTC_2D_5X4
- 1, // BGRA8_SRGB
- 4, // DXT1_SRGB
- 4, // DXT23_SRGB
- 4, // DXT45_SRGB
- 4, // BC7U_SRGB
- 4, // ASTC_2D_4X4_SRGB
- 4, // ASTC_2D_8X8_SRGB
- 4, // ASTC_2D_8X5_SRGB
- 4, // ASTC_2D_5X4_SRGB
- 4, // ASTC_2D_5X5
- 4, // ASTC_2D_5X5_SRGB
- 4, // ASTC_2D_10X8
- 4, // ASTC_2D_10X8_SRGB
- 1, // Z32F
- 1, // Z16
- 1, // Z24S8
- 1, // S8Z24
- 1, // Z32FS8
- }};
-
ASSERT(static_cast<std::size_t>(format) < compression_factor_table.size());
return compression_factor_table[static_cast<std::size_t>(format)];
}
+constexpr std::array<u32, MaxPixelFormat> block_width_table = {{
+ 1, // ABGR8U
+ 1, // ABGR8S
+ 1, // ABGR8UI
+ 1, // B5G6R5U
+ 1, // A2B10G10R10U
+ 1, // A1B5G5R5U
+ 1, // R8U
+ 1, // R8UI
+ 1, // RGBA16F
+ 1, // RGBA16U
+ 1, // RGBA16UI
+ 1, // R11FG11FB10F
+ 1, // RGBA32UI
+ 4, // DXT1
+ 4, // DXT23
+ 4, // DXT45
+ 4, // DXN1
+ 4, // DXN2UNORM
+ 4, // DXN2SNORM
+ 4, // BC7U
+ 4, // BC6H_UF16
+ 4, // BC6H_SF16
+ 4, // ASTC_2D_4X4
+ 1, // BGRA8
+ 1, // RGBA32F
+ 1, // RG32F
+ 1, // R32F
+ 1, // R16F
+ 1, // R16U
+ 1, // R16S
+ 1, // R16UI
+ 1, // R16I
+ 1, // RG16
+ 1, // RG16F
+ 1, // RG16UI
+ 1, // RG16I
+ 1, // RG16S
+ 1, // RGB32F
+ 1, // RGBA8_SRGB
+ 1, // RG8U
+ 1, // RG8S
+ 1, // RG32UI
+ 1, // R32UI
+ 8, // ASTC_2D_8X8
+ 8, // ASTC_2D_8X5
+ 5, // ASTC_2D_5X4
+ 1, // BGRA8_SRGB
+ 4, // DXT1_SRGB
+ 4, // DXT23_SRGB
+ 4, // DXT45_SRGB
+ 4, // BC7U_SRGB
+ 4, // ASTC_2D_4X4_SRGB
+ 8, // ASTC_2D_8X8_SRGB
+ 8, // ASTC_2D_8X5_SRGB
+ 5, // ASTC_2D_5X4_SRGB
+ 5, // ASTC_2D_5X5
+ 5, // ASTC_2D_5X5_SRGB
+ 10, // ASTC_2D_10X8
+ 10, // ASTC_2D_10X8_SRGB
+ 1, // Z32F
+ 1, // Z16
+ 1, // Z24S8
+ 1, // S8Z24
+ 1, // Z32FS8
+}};
+
static constexpr u32 GetDefaultBlockWidth(PixelFormat format) {
if (format == PixelFormat::Invalid)
return 0;
- constexpr std::array<u32, MaxPixelFormat> block_width_table = {{
- 1, // ABGR8U
- 1, // ABGR8S
- 1, // ABGR8UI
- 1, // B5G6R5U
- 1, // A2B10G10R10U
- 1, // A1B5G5R5U
- 1, // R8U
- 1, // R8UI
- 1, // RGBA16F
- 1, // RGBA16U
- 1, // RGBA16UI
- 1, // R11FG11FB10F
- 1, // RGBA32UI
- 4, // DXT1
- 4, // DXT23
- 4, // DXT45
- 4, // DXN1
- 4, // DXN2UNORM
- 4, // DXN2SNORM
- 4, // BC7U
- 4, // BC6H_UF16
- 4, // BC6H_SF16
- 4, // ASTC_2D_4X4
- 1, // G8R8U
- 1, // G8R8S
- 1, // BGRA8
- 1, // RGBA32F
- 1, // RG32F
- 1, // R32F
- 1, // R16F
- 1, // R16U
- 1, // R16S
- 1, // R16UI
- 1, // R16I
- 1, // RG16
- 1, // RG16F
- 1, // RG16UI
- 1, // RG16I
- 1, // RG16S
- 1, // RGB32F
- 1, // RGBA8_SRGB
- 1, // RG8U
- 1, // RG8S
- 1, // RG32UI
- 1, // R32UI
- 8, // ASTC_2D_8X8
- 8, // ASTC_2D_8X5
- 5, // ASTC_2D_5X4
- 1, // BGRA8_SRGB
- 4, // DXT1_SRGB
- 4, // DXT23_SRGB
- 4, // DXT45_SRGB
- 4, // BC7U_SRGB
- 4, // ASTC_2D_4X4_SRGB
- 8, // ASTC_2D_8X8_SRGB
- 8, // ASTC_2D_8X5_SRGB
- 5, // ASTC_2D_5X4_SRGB
- 5, // ASTC_2D_5X5
- 5, // ASTC_2D_5X5_SRGB
- 10, // ASTC_2D_10X8
- 10, // ASTC_2D_10X8_SRGB
- 1, // Z32F
- 1, // Z16
- 1, // Z24S8
- 1, // S8Z24
- 1, // Z32FS8
- }};
+
ASSERT(static_cast<std::size_t>(format) < block_width_table.size());
return block_width_table[static_cast<std::size_t>(format)];
}
+constexpr std::array<u32, MaxPixelFormat> block_height_table = {{
+ 1, // ABGR8U
+ 1, // ABGR8S
+ 1, // ABGR8UI
+ 1, // B5G6R5U
+ 1, // A2B10G10R10U
+ 1, // A1B5G5R5U
+ 1, // R8U
+ 1, // R8UI
+ 1, // RGBA16F
+ 1, // RGBA16U
+ 1, // RGBA16UI
+ 1, // R11FG11FB10F
+ 1, // RGBA32UI
+ 4, // DXT1
+ 4, // DXT23
+ 4, // DXT45
+ 4, // DXN1
+ 4, // DXN2UNORM
+ 4, // DXN2SNORM
+ 4, // BC7U
+ 4, // BC6H_UF16
+ 4, // BC6H_SF16
+ 4, // ASTC_2D_4X4
+ 1, // BGRA8
+ 1, // RGBA32F
+ 1, // RG32F
+ 1, // R32F
+ 1, // R16F
+ 1, // R16U
+ 1, // R16S
+ 1, // R16UI
+ 1, // R16I
+ 1, // RG16
+ 1, // RG16F
+ 1, // RG16UI
+ 1, // RG16I
+ 1, // RG16S
+ 1, // RGB32F
+ 1, // RGBA8_SRGB
+ 1, // RG8U
+ 1, // RG8S
+ 1, // RG32UI
+ 1, // R32UI
+ 8, // ASTC_2D_8X8
+ 5, // ASTC_2D_8X5
+ 4, // ASTC_2D_5X4
+ 1, // BGRA8_SRGB
+ 4, // DXT1_SRGB
+ 4, // DXT23_SRGB
+ 4, // DXT45_SRGB
+ 4, // BC7U_SRGB
+ 4, // ASTC_2D_4X4_SRGB
+ 8, // ASTC_2D_8X8_SRGB
+ 5, // ASTC_2D_8X5_SRGB
+ 4, // ASTC_2D_5X4_SRGB
+ 5, // ASTC_2D_5X5
+ 5, // ASTC_2D_5X5_SRGB
+ 8, // ASTC_2D_10X8
+ 8, // ASTC_2D_10X8_SRGB
+ 1, // Z32F
+ 1, // Z16
+ 1, // Z24S8
+ 1, // S8Z24
+ 1, // Z32FS8
+}};
+
static constexpr u32 GetDefaultBlockHeight(PixelFormat format) {
if (format == PixelFormat::Invalid)
return 0;
- constexpr std::array<u32, MaxPixelFormat> block_height_table = {{
- 1, // ABGR8U
- 1, // ABGR8S
- 1, // ABGR8UI
- 1, // B5G6R5U
- 1, // A2B10G10R10U
- 1, // A1B5G5R5U
- 1, // R8U
- 1, // R8UI
- 1, // RGBA16F
- 1, // RGBA16U
- 1, // RGBA16UI
- 1, // R11FG11FB10F
- 1, // RGBA32UI
- 4, // DXT1
- 4, // DXT23
- 4, // DXT45
- 4, // DXN1
- 4, // DXN2UNORM
- 4, // DXN2SNORM
- 4, // BC7U
- 4, // BC6H_UF16
- 4, // BC6H_SF16
- 4, // ASTC_2D_4X4
- 1, // G8R8U
- 1, // G8R8S
- 1, // BGRA8
- 1, // RGBA32F
- 1, // RG32F
- 1, // R32F
- 1, // R16F
- 1, // R16U
- 1, // R16S
- 1, // R16UI
- 1, // R16I
- 1, // RG16
- 1, // RG16F
- 1, // RG16UI
- 1, // RG16I
- 1, // RG16S
- 1, // RGB32F
- 1, // RGBA8_SRGB
- 1, // RG8U
- 1, // RG8S
- 1, // RG32UI
- 1, // R32UI
- 8, // ASTC_2D_8X8
- 5, // ASTC_2D_8X5
- 4, // ASTC_2D_5X4
- 1, // BGRA8_SRGB
- 4, // DXT1_SRGB
- 4, // DXT23_SRGB
- 4, // DXT45_SRGB
- 4, // BC7U_SRGB
- 4, // ASTC_2D_4X4_SRGB
- 8, // ASTC_2D_8X8_SRGB
- 5, // ASTC_2D_8X5_SRGB
- 4, // ASTC_2D_5X4_SRGB
- 5, // ASTC_2D_5X5
- 5, // ASTC_2D_5X5_SRGB
- 8, // ASTC_2D_10X8
- 8, // ASTC_2D_10X8_SRGB
- 1, // Z32F
- 1, // Z16
- 1, // Z24S8
- 1, // S8Z24
- 1, // Z32FS8
- }};
-
ASSERT(static_cast<std::size_t>(format) < block_height_table.size());
return block_height_table[static_cast<std::size_t>(format)];
}
+constexpr std::array<u32, MaxPixelFormat> bpp_table = {{
+ 32, // ABGR8U
+ 32, // ABGR8S
+ 32, // ABGR8UI
+ 16, // B5G6R5U
+ 32, // A2B10G10R10U
+ 16, // A1B5G5R5U
+ 8, // R8U
+ 8, // R8UI
+ 64, // RGBA16F
+ 64, // RGBA16U
+ 64, // RGBA16UI
+ 32, // R11FG11FB10F
+ 128, // RGBA32UI
+ 64, // DXT1
+ 128, // DXT23
+ 128, // DXT45
+ 64, // DXN1
+ 128, // DXN2UNORM
+ 128, // DXN2SNORM
+ 128, // BC7U
+ 128, // BC6H_UF16
+ 128, // BC6H_SF16
+ 128, // ASTC_2D_4X4
+ 32, // BGRA8
+ 128, // RGBA32F
+ 64, // RG32F
+ 32, // R32F
+ 16, // R16F
+ 16, // R16U
+ 16, // R16S
+ 16, // R16UI
+ 16, // R16I
+ 32, // RG16
+ 32, // RG16F
+ 32, // RG16UI
+ 32, // RG16I
+ 32, // RG16S
+ 96, // RGB32F
+ 32, // RGBA8_SRGB
+ 16, // RG8U
+ 16, // RG8S
+ 64, // RG32UI
+ 32, // R32UI
+ 128, // ASTC_2D_8X8
+ 128, // ASTC_2D_8X5
+ 128, // ASTC_2D_5X4
+ 32, // BGRA8_SRGB
+ 64, // DXT1_SRGB
+ 128, // DXT23_SRGB
+ 128, // DXT45_SRGB
+ 128, // BC7U
+ 128, // ASTC_2D_4X4_SRGB
+ 128, // ASTC_2D_8X8_SRGB
+ 128, // ASTC_2D_8X5_SRGB
+ 128, // ASTC_2D_5X4_SRGB
+ 128, // ASTC_2D_5X5
+ 128, // ASTC_2D_5X5_SRGB
+ 128, // ASTC_2D_10X8
+ 128, // ASTC_2D_10X8_SRGB
+ 32, // Z32F
+ 16, // Z16
+ 32, // Z24S8
+ 32, // S8Z24
+ 64, // Z32FS8
+}};
+
static constexpr u32 GetFormatBpp(PixelFormat format) {
if (format == PixelFormat::Invalid)
return 0;
- constexpr std::array<u32, MaxPixelFormat> bpp_table = {{
- 32, // ABGR8U
- 32, // ABGR8S
- 32, // ABGR8UI
- 16, // B5G6R5U
- 32, // A2B10G10R10U
- 16, // A1B5G5R5U
- 8, // R8U
- 8, // R8UI
- 64, // RGBA16F
- 64, // RGBA16U
- 64, // RGBA16UI
- 32, // R11FG11FB10F
- 128, // RGBA32UI
- 64, // DXT1
- 128, // DXT23
- 128, // DXT45
- 64, // DXN1
- 128, // DXN2UNORM
- 128, // DXN2SNORM
- 128, // BC7U
- 128, // BC6H_UF16
- 128, // BC6H_SF16
- 128, // ASTC_2D_4X4
- 16, // G8R8U
- 16, // G8R8S
- 32, // BGRA8
- 128, // RGBA32F
- 64, // RG32F
- 32, // R32F
- 16, // R16F
- 16, // R16U
- 16, // R16S
- 16, // R16UI
- 16, // R16I
- 32, // RG16
- 32, // RG16F
- 32, // RG16UI
- 32, // RG16I
- 32, // RG16S
- 96, // RGB32F
- 32, // RGBA8_SRGB
- 16, // RG8U
- 16, // RG8S
- 64, // RG32UI
- 32, // R32UI
- 128, // ASTC_2D_8X8
- 128, // ASTC_2D_8X5
- 128, // ASTC_2D_5X4
- 32, // BGRA8_SRGB
- 64, // DXT1_SRGB
- 128, // DXT23_SRGB
- 128, // DXT45_SRGB
- 128, // BC7U
- 128, // ASTC_2D_4X4_SRGB
- 128, // ASTC_2D_8X8_SRGB
- 128, // ASTC_2D_8X5_SRGB
- 128, // ASTC_2D_5X4_SRGB
- 128, // ASTC_2D_5X5
- 128, // ASTC_2D_5X5_SRGB
- 128, // ASTC_2D_10X8
- 128, // ASTC_2D_10X8_SRGB
- 32, // Z32F
- 16, // Z16
- 32, // Z24S8
- 32, // S8Z24
- 64, // Z32FS8
- }};
-
ASSERT(static_cast<std::size_t>(format) < bpp_table.size());
return bpp_table[static_cast<std::size_t>(format)];
}
@@ -449,6 +441,8 @@ SurfaceTarget SurfaceTargetFromTextureType(Tegra::Texture::TextureType texture_t
bool SurfaceTargetIsLayered(SurfaceTarget target);
+bool SurfaceTargetIsArray(SurfaceTarget target);
+
PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format);
PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format);
diff --git a/src/video_core/textures/decoders.cpp b/src/video_core/textures/decoders.cpp
index bbae9285f..5db75de22 100644
--- a/src/video_core/textures/decoders.cpp
+++ b/src/video_core/textures/decoders.cpp
@@ -226,7 +226,7 @@ u32 BytesPerPixel(TextureFormat format) {
return 8;
default:
UNIMPLEMENTED_MSG("Format not implemented");
- break;
+ return 1;
}
}
diff --git a/src/video_core/video_core.cpp b/src/video_core/video_core.cpp
index 07e3a7d24..0b8ccdd44 100644
--- a/src/video_core/video_core.cpp
+++ b/src/video_core/video_core.cpp
@@ -3,6 +3,8 @@
// Refer to the license.txt file included.
#include <memory>
+#include "core/core.h"
+#include "core/settings.h"
#include "video_core/renderer_base.h"
#include "video_core/renderer_opengl/renderer_opengl.h"
#include "video_core/video_core.h"
@@ -13,4 +15,11 @@ std::unique_ptr<RendererBase> CreateRenderer(Core::Frontend::EmuWindow& emu_wind
return std::make_unique<OpenGL::RendererOpenGL>(emu_window);
}
+u16 GetResolutionScaleFactor(const RendererBase& renderer) {
+ return static_cast<u16>(
+ Settings::values.resolution_factor
+ ? Settings::values.resolution_factor
+ : renderer.GetRenderWindow().GetFramebufferLayout().GetScalingRatio());
+}
+
} // namespace VideoCore
diff --git a/src/video_core/video_core.h b/src/video_core/video_core.h
index f79f85dfe..5b373bcb1 100644
--- a/src/video_core/video_core.h
+++ b/src/video_core/video_core.h
@@ -22,4 +22,6 @@ class RendererBase;
*/
std::unique_ptr<RendererBase> CreateRenderer(Core::Frontend::EmuWindow& emu_window);
+u16 GetResolutionScaleFactor(const RendererBase& renderer);
+
} // namespace VideoCore
diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt
index cfca8f4a8..4cab599b4 100644
--- a/src/yuzu/CMakeLists.txt
+++ b/src/yuzu/CMakeLists.txt
@@ -7,8 +7,12 @@ add_executable(yuzu
Info.plist
about_dialog.cpp
about_dialog.h
+ applets/profile_select.cpp
+ applets/profile_select.h
applets/software_keyboard.cpp
applets/software_keyboard.h
+ applets/web_browser.cpp
+ applets/web_browser.h
bootmanager.cpp
bootmanager.h
compatibility_list.cpp
@@ -31,10 +35,16 @@ add_executable(yuzu
configuration/configure_input.h
configuration/configure_input_player.cpp
configuration/configure_input_player.h
+ configuration/configure_input_simple.cpp
+ configuration/configure_input_simple.h
configuration/configure_mouse_advanced.cpp
configuration/configure_mouse_advanced.h
+ configuration/configure_profile_manager.cpp
+ configuration/configure_profile_manager.h
configuration/configure_system.cpp
configuration/configure_system.h
+ configuration/configure_per_general.cpp
+ configuration/configure_per_general.h
configuration/configure_touchscreen_advanced.cpp
configuration/configure_touchscreen_advanced.h
configuration/configure_web.cpp
@@ -58,6 +68,8 @@ add_executable(yuzu
game_list_p.h
game_list_worker.cpp
game_list_worker.h
+ loading_screen.cpp
+ loading_screen.h
hotkeys.cpp
hotkeys.h
main.cpp
@@ -85,13 +97,17 @@ set(UIS
configuration/configure_graphics.ui
configuration/configure_input.ui
configuration/configure_input_player.ui
+ configuration/configure_input_simple.ui
configuration/configure_mouse_advanced.ui
+ configuration/configure_per_general.ui
+ configuration/configure_profile_manager.ui
configuration/configure_system.ui
configuration/configure_touchscreen_advanced.ui
configuration/configure_web.ui
+ compatdb.ui
hotkeys.ui
+ loading_screen.ui
main.ui
- compatdb.ui
)
file(GLOB COMPAT_LIST
@@ -146,6 +162,11 @@ if (USE_DISCORD_PRESENCE)
target_compile_definitions(yuzu PRIVATE -DUSE_DISCORD_PRESENCE)
endif()
+if (YUZU_USE_QT_WEB_ENGINE)
+ target_link_libraries(yuzu PRIVATE Qt5::WebEngineCore Qt5::WebEngineWidgets)
+ target_compile_definitions(yuzu PRIVATE -DYUZU_USE_QT_WEB_ENGINE)
+endif ()
+
if(UNIX AND NOT APPLE)
install(TARGETS yuzu RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
endif()
diff --git a/src/yuzu/applets/profile_select.cpp b/src/yuzu/applets/profile_select.cpp
new file mode 100644
index 000000000..5c1b65a2c
--- /dev/null
+++ b/src/yuzu/applets/profile_select.cpp
@@ -0,0 +1,168 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <mutex>
+#include <QDialogButtonBox>
+#include <QLabel>
+#include <QLineEdit>
+#include <QScrollArea>
+#include <QStandardItemModel>
+#include <QVBoxLayout>
+#include "common/file_util.h"
+#include "common/string_util.h"
+#include "core/hle/lock.h"
+#include "yuzu/applets/profile_select.h"
+#include "yuzu/main.h"
+
+// Same backup JPEG used by acc IProfile::GetImage if no jpeg found
+constexpr std::array<u8, 107> backup_jpeg{
+ 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02,
+ 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x06, 0x06, 0x05,
+ 0x06, 0x09, 0x08, 0x0a, 0x0a, 0x09, 0x08, 0x09, 0x09, 0x0a, 0x0c, 0x0f, 0x0c, 0x0a, 0x0b, 0x0e,
+ 0x0b, 0x09, 0x09, 0x0d, 0x11, 0x0d, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x10, 0x0a, 0x0c, 0x12, 0x13,
+ 0x12, 0x10, 0x13, 0x0f, 0x10, 0x10, 0x10, 0xff, 0xc9, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01,
+ 0x01, 0x01, 0x11, 0x00, 0xff, 0xcc, 0x00, 0x06, 0x00, 0x10, 0x10, 0x05, 0xff, 0xda, 0x00, 0x08,
+ 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0xd2, 0xcf, 0x20, 0xff, 0xd9,
+};
+
+QString FormatUserEntryText(const QString& username, Service::Account::UUID uuid) {
+ return QtProfileSelectionDialog::tr(
+ "%1\n%2", "%1 is the profile username, %2 is the formatted UUID (e.g. "
+ "00112233-4455-6677-8899-AABBCCDDEEFF))")
+ .arg(username, QString::fromStdString(uuid.FormatSwitch()));
+}
+
+QString GetImagePath(Service::Account::UUID uuid) {
+ const auto path = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
+ "/system/save/8000000000000010/su/avators/" + uuid.FormatSwitch() + ".jpg";
+ return QString::fromStdString(path);
+}
+
+QPixmap GetIcon(Service::Account::UUID uuid) {
+ QPixmap icon{GetImagePath(uuid)};
+
+ if (!icon) {
+ icon.fill(Qt::black);
+ icon.loadFromData(backup_jpeg.data(), static_cast<u32>(backup_jpeg.size()));
+ }
+
+ return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
+}
+
+QtProfileSelectionDialog::QtProfileSelectionDialog(QWidget* parent)
+ : QDialog(parent), profile_manager(std::make_unique<Service::Account::ProfileManager>()) {
+ outer_layout = new QVBoxLayout;
+
+ instruction_label = new QLabel(tr("Select a user:"));
+
+ scroll_area = new QScrollArea;
+
+ buttons = new QDialogButtonBox;
+ buttons->addButton(tr("Cancel"), QDialogButtonBox::RejectRole);
+ buttons->addButton(tr("OK"), QDialogButtonBox::AcceptRole);
+
+ connect(buttons, &QDialogButtonBox::accepted, this, &QtProfileSelectionDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, this, &QtProfileSelectionDialog::reject);
+
+ outer_layout->addWidget(instruction_label);
+ outer_layout->addWidget(scroll_area);
+ outer_layout->addWidget(buttons);
+
+ layout = new QVBoxLayout;
+ tree_view = new QTreeView;
+ item_model = new QStandardItemModel(tree_view);
+ tree_view->setModel(item_model);
+
+ tree_view->setAlternatingRowColors(true);
+ tree_view->setSelectionMode(QHeaderView::SingleSelection);
+ tree_view->setSelectionBehavior(QHeaderView::SelectRows);
+ tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setSortingEnabled(true);
+ tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
+ tree_view->setUniformRowHeights(true);
+ tree_view->setIconSize({64, 64});
+ tree_view->setContextMenuPolicy(Qt::NoContextMenu);
+
+ item_model->insertColumns(0, 1);
+ item_model->setHeaderData(0, Qt::Horizontal, "Users");
+
+ // We must register all custom types with the Qt Automoc system so that we are able to use it
+ // with signals/slots. In this case, QList falls under the umbrells of custom types.
+ qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
+
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(0);
+ layout->addWidget(tree_view);
+
+ scroll_area->setLayout(layout);
+
+ connect(tree_view, &QTreeView::clicked, this, &QtProfileSelectionDialog::SelectUser);
+
+ const auto& profiles = profile_manager->GetAllUsers();
+ for (const auto& user : profiles) {
+ Service::Account::ProfileBase profile;
+ if (!profile_manager->GetProfileBase(user, profile))
+ continue;
+
+ const auto username = Common::StringFromFixedZeroTerminatedBuffer(
+ reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
+
+ list_items.push_back(QList<QStandardItem*>{new QStandardItem{
+ GetIcon(user), FormatUserEntryText(QString::fromStdString(username), user)}});
+ }
+
+ for (const auto& item : list_items)
+ item_model->appendRow(item);
+
+ setLayout(outer_layout);
+ setWindowTitle(tr("Profile Selector"));
+ resize(550, 400);
+}
+
+QtProfileSelectionDialog::~QtProfileSelectionDialog() = default;
+
+void QtProfileSelectionDialog::accept() {
+ ok = true;
+ QDialog::accept();
+}
+
+void QtProfileSelectionDialog::reject() {
+ ok = false;
+ user_index = 0;
+ QDialog::reject();
+}
+
+bool QtProfileSelectionDialog::GetStatus() const {
+ return ok;
+}
+
+u32 QtProfileSelectionDialog::GetIndex() const {
+ return user_index;
+}
+
+void QtProfileSelectionDialog::SelectUser(const QModelIndex& index) {
+ user_index = index.row();
+}
+
+QtProfileSelector::QtProfileSelector(GMainWindow& parent) {
+ connect(this, &QtProfileSelector::MainWindowSelectProfile, &parent,
+ &GMainWindow::ProfileSelectorSelectProfile, Qt::QueuedConnection);
+ connect(&parent, &GMainWindow::ProfileSelectorFinishedSelection, this,
+ &QtProfileSelector::MainWindowFinishedSelection, Qt::DirectConnection);
+}
+
+QtProfileSelector::~QtProfileSelector() = default;
+
+void QtProfileSelector::SelectProfile(
+ std::function<void(std::optional<Service::Account::UUID>)> callback) const {
+ this->callback = std::move(callback);
+ emit MainWindowSelectProfile();
+}
+
+void QtProfileSelector::MainWindowFinishedSelection(std::optional<Service::Account::UUID> uuid) {
+ // Acquire the HLE mutex
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ callback(uuid);
+}
diff --git a/src/yuzu/applets/profile_select.h b/src/yuzu/applets/profile_select.h
new file mode 100644
index 000000000..868573324
--- /dev/null
+++ b/src/yuzu/applets/profile_select.h
@@ -0,0 +1,73 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <vector>
+#include <QDialog>
+#include <QList>
+#include "core/frontend/applets/profile_select.h"
+
+class GMainWindow;
+class QDialogButtonBox;
+class QGraphicsScene;
+class QLabel;
+class QScrollArea;
+class QStandardItem;
+class QStandardItemModel;
+class QTreeView;
+class QVBoxLayout;
+
+class QtProfileSelectionDialog final : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit QtProfileSelectionDialog(QWidget* parent);
+ ~QtProfileSelectionDialog() override;
+
+ void accept() override;
+ void reject() override;
+
+ bool GetStatus() const;
+ u32 GetIndex() const;
+
+private:
+ bool ok = false;
+ u32 user_index = 0;
+
+ void SelectUser(const QModelIndex& index);
+
+ QVBoxLayout* layout;
+ QTreeView* tree_view;
+ QStandardItemModel* item_model;
+ QGraphicsScene* scene;
+
+ std::vector<QList<QStandardItem*>> list_items;
+
+ QVBoxLayout* outer_layout;
+ QLabel* instruction_label;
+ QScrollArea* scroll_area;
+ QDialogButtonBox* buttons;
+
+ std::unique_ptr<Service::Account::ProfileManager> profile_manager;
+};
+
+class QtProfileSelector final : public QObject, public Core::Frontend::ProfileSelectApplet {
+ Q_OBJECT
+
+public:
+ explicit QtProfileSelector(GMainWindow& parent);
+ ~QtProfileSelector() override;
+
+ void SelectProfile(
+ std::function<void(std::optional<Service::Account::UUID>)> callback) const override;
+
+signals:
+ void MainWindowSelectProfile() const;
+
+private:
+ void MainWindowFinishedSelection(std::optional<Service::Account::UUID> uuid);
+
+ mutable std::function<void(std::optional<Service::Account::UUID>)> callback;
+};
diff --git a/src/yuzu/applets/web_browser.cpp b/src/yuzu/applets/web_browser.cpp
new file mode 100644
index 000000000..6a9138d53
--- /dev/null
+++ b/src/yuzu/applets/web_browser.cpp
@@ -0,0 +1,113 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <mutex>
+
+#include <QKeyEvent>
+
+#include "core/hle/lock.h"
+#include "yuzu/applets/web_browser.h"
+#include "yuzu/main.h"
+
+#ifdef YUZU_USE_QT_WEB_ENGINE
+
+constexpr char NX_SHIM_INJECT_SCRIPT[] = R"(
+ window.nx = {};
+ window.nx.playReport = {};
+ window.nx.playReport.setCounterSetIdentifier = function () {
+ console.log("nx.playReport.setCounterSetIdentifier called - unimplemented");
+ };
+
+ window.nx.playReport.incrementCounter = function () {
+ console.log("nx.playReport.incrementCounter called - unimplemented");
+ };
+
+ window.nx.footer = {};
+ window.nx.footer.unsetAssign = function () {
+ console.log("nx.footer.unsetAssign called - unimplemented");
+ };
+
+ var yuzu_key_callbacks = [];
+ window.nx.footer.setAssign = function(key, discard1, func, discard2) {
+ switch (key) {
+ case 'A':
+ yuzu_key_callbacks[0] = func;
+ break;
+ case 'B':
+ yuzu_key_callbacks[1] = func;
+ break;
+ case 'X':
+ yuzu_key_callbacks[2] = func;
+ break;
+ case 'Y':
+ yuzu_key_callbacks[3] = func;
+ break;
+ case 'L':
+ yuzu_key_callbacks[6] = func;
+ break;
+ case 'R':
+ yuzu_key_callbacks[7] = func;
+ break;
+ }
+ };
+
+ var applet_done = false;
+ window.nx.endApplet = function() {
+ applet_done = true;
+ };
+)";
+
+QString GetNXShimInjectionScript() {
+ return QString::fromStdString(NX_SHIM_INJECT_SCRIPT);
+}
+
+NXInputWebEngineView::NXInputWebEngineView(QWidget* parent) : QWebEngineView(parent) {}
+
+void NXInputWebEngineView::keyPressEvent(QKeyEvent* event) {
+ parent()->event(event);
+}
+
+void NXInputWebEngineView::keyReleaseEvent(QKeyEvent* event) {
+ parent()->event(event);
+}
+
+#endif
+
+QtWebBrowser::QtWebBrowser(GMainWindow& main_window) {
+ connect(this, &QtWebBrowser::MainWindowOpenPage, &main_window, &GMainWindow::WebBrowserOpenPage,
+ Qt::QueuedConnection);
+ connect(&main_window, &GMainWindow::WebBrowserUnpackRomFS, this,
+ &QtWebBrowser::MainWindowUnpackRomFS, Qt::QueuedConnection);
+ connect(&main_window, &GMainWindow::WebBrowserFinishedBrowsing, this,
+ &QtWebBrowser::MainWindowFinishedBrowsing, Qt::QueuedConnection);
+}
+
+QtWebBrowser::~QtWebBrowser() = default;
+
+void QtWebBrowser::OpenPage(std::string_view url, std::function<void()> unpack_romfs_callback,
+ std::function<void()> finished_callback) {
+ this->unpack_romfs_callback = std::move(unpack_romfs_callback);
+ this->finished_callback = std::move(finished_callback);
+
+ const auto index = url.find('?');
+ if (index == std::string::npos) {
+ emit MainWindowOpenPage(url, "");
+ } else {
+ const auto front = url.substr(0, index);
+ const auto back = url.substr(index);
+ emit MainWindowOpenPage(front, back);
+ }
+}
+
+void QtWebBrowser::MainWindowUnpackRomFS() {
+ // Acquire the HLE mutex
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ unpack_romfs_callback();
+}
+
+void QtWebBrowser::MainWindowFinishedBrowsing() {
+ // Acquire the HLE mutex
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ finished_callback();
+}
diff --git a/src/yuzu/applets/web_browser.h b/src/yuzu/applets/web_browser.h
new file mode 100644
index 000000000..1a3d67353
--- /dev/null
+++ b/src/yuzu/applets/web_browser.h
@@ -0,0 +1,52 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <functional>
+#include <QObject>
+
+#ifdef YUZU_USE_QT_WEB_ENGINE
+#include <QWebEngineView>
+#endif
+
+#include "core/frontend/applets/web_browser.h"
+
+class GMainWindow;
+
+#ifdef YUZU_USE_QT_WEB_ENGINE
+
+QString GetNXShimInjectionScript();
+
+class NXInputWebEngineView : public QWebEngineView {
+public:
+ explicit NXInputWebEngineView(QWidget* parent = nullptr);
+
+protected:
+ void keyPressEvent(QKeyEvent* event) override;
+ void keyReleaseEvent(QKeyEvent* event) override;
+};
+
+#endif
+
+class QtWebBrowser final : public QObject, public Core::Frontend::WebBrowserApplet {
+ Q_OBJECT
+
+public:
+ explicit QtWebBrowser(GMainWindow& main_window);
+ ~QtWebBrowser() override;
+
+ void OpenPage(std::string_view url, std::function<void()> unpack_romfs_callback,
+ std::function<void()> finished_callback) override;
+
+signals:
+ void MainWindowOpenPage(std::string_view filename, std::string_view additional_args) const;
+
+private:
+ void MainWindowUnpackRomFS();
+ void MainWindowFinishedBrowsing();
+
+ std::function<void()> unpack_romfs_callback;
+ std::function<void()> finished_callback;
+};
diff --git a/src/yuzu/bootmanager.cpp b/src/yuzu/bootmanager.cpp
index 384e17921..f74cb693a 100644
--- a/src/yuzu/bootmanager.cpp
+++ b/src/yuzu/bootmanager.cpp
@@ -3,9 +3,7 @@
#include <QKeyEvent>
#include <QScreen>
#include <QWindow>
-
#include <fmt/format.h>
-
#include "common/microprofile.h"
#include "common/scm_rev.h"
#include "core/core.h"
@@ -14,7 +12,10 @@
#include "input_common/keyboard.h"
#include "input_common/main.h"
#include "input_common/motion_emu.h"
+#include "video_core/renderer_base.h"
+#include "video_core/video_core.h"
#include "yuzu/bootmanager.h"
+#include "yuzu/main.h"
EmuThread::EmuThread(GRenderWindow* render_window) : render_window(render_window) {}
@@ -112,6 +113,8 @@ GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread)
InputCommon::Init();
InputCommon::StartJoystickEventHandler();
+ connect(this, &GRenderWindow::FirstFrameDisplayed, static_cast<GMainWindow*>(parent),
+ &GMainWindow::OnLoadComplete);
}
GRenderWindow::~GRenderWindow() {
@@ -139,6 +142,10 @@ void GRenderWindow::SwapBuffers() {
child->makeCurrent();
child->swapBuffers();
+ if (!first_frame) {
+ emit FirstFrameDisplayed();
+ first_frame = true;
+ }
}
void GRenderWindow::MakeCurrent() {
@@ -307,6 +314,8 @@ void GRenderWindow::InitRenderTarget() {
delete layout();
}
+ first_frame = false;
+
// TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
// WA_DontShowOnScreen, WA_DeleteOnClose
QGLFormat fmt;
@@ -333,6 +342,22 @@ void GRenderWindow::InitRenderTarget() {
BackupGeometry();
}
+void GRenderWindow::CaptureScreenshot(u16 res_scale, const QString& screenshot_path) {
+ auto& renderer = Core::System::GetInstance().Renderer();
+
+ if (!res_scale)
+ res_scale = VideoCore::GetResolutionScaleFactor(renderer);
+
+ const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
+ screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
+ renderer.RequestScreenshot(screenshot_image.bits(),
+ [=] {
+ screenshot_image.mirrored(false, true).save(screenshot_path);
+ LOG_INFO(Frontend, "The screenshot is saved.");
+ },
+ layout);
+}
+
void GRenderWindow::OnMinimalClientAreaChangeRequest(
const std::pair<unsigned, unsigned>& minimal_size) {
setMinimumSize(minimal_size.first, minimal_size.second);
diff --git a/src/yuzu/bootmanager.h b/src/yuzu/bootmanager.h
index 873985564..d1f37e503 100644
--- a/src/yuzu/bootmanager.h
+++ b/src/yuzu/bootmanager.h
@@ -8,6 +8,7 @@
#include <condition_variable>
#include <mutex>
#include <QGLWidget>
+#include <QImage>
#include <QThread>
#include "common/thread.h"
#include "core/core.h"
@@ -139,6 +140,8 @@ public:
void InitRenderTarget();
+ void CaptureScreenshot(u16 res_scale, const QString& screenshot_path);
+
public slots:
void moveContext(); // overridden
@@ -149,6 +152,7 @@ public slots:
signals:
/// Emitted when the window is closed
void Closed();
+ void FirstFrameDisplayed();
private:
std::pair<unsigned, unsigned> ScaleTouch(const QPointF pos) const;
@@ -165,6 +169,11 @@ private:
EmuThread* emu_thread;
+ /// Temporary storage of the screenshot taken
+ QImage screenshot_image;
+
+ bool first_frame = false;
+
protected:
void showEvent(QShowEvent* event) override;
};
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index 83ebbd1fe..ddf4cf552 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -4,6 +4,7 @@
#include <QSettings>
#include "common/file_util.h"
+#include "configure_input_simple.h"
#include "core/hle/service/acc/profile_manager.h"
#include "core/hle/service/hid/controllers/npad.h"
#include "input_common/main.h"
@@ -206,60 +207,57 @@ const std::array<int, Settings::NativeKeyboard::NumKeyboardMods> Config::default
void Config::ReadPlayerValues() {
for (std::size_t p = 0; p < Settings::values.players.size(); ++p) {
- Settings::values.players[p].connected =
- qt_config->value(QString("player_%1_connected").arg(p), false).toBool();
+ auto& player = Settings::values.players[p];
- Settings::values.players[p].type = static_cast<Settings::ControllerType>(
+ player.connected = qt_config->value(QString("player_%1_connected").arg(p), false).toBool();
+
+ player.type = static_cast<Settings::ControllerType>(
qt_config
->value(QString("player_%1_type").arg(p),
static_cast<u8>(Settings::ControllerType::DualJoycon))
.toUInt());
- Settings::values.players[p].body_color_left =
- qt_config
- ->value(QString("player_%1_body_color_left").arg(p),
- Settings::JOYCON_BODY_NEON_BLUE)
- .toUInt();
- Settings::values.players[p].body_color_right =
- qt_config
- ->value(QString("player_%1_body_color_right").arg(p),
- Settings::JOYCON_BODY_NEON_RED)
- .toUInt();
- Settings::values.players[p].button_color_left =
- qt_config
- ->value(QString("player_%1_button_color_left").arg(p),
- Settings::JOYCON_BUTTONS_NEON_BLUE)
- .toUInt();
- Settings::values.players[p].button_color_right =
- qt_config
- ->value(QString("player_%1_button_color_right").arg(p),
- Settings::JOYCON_BUTTONS_NEON_RED)
- .toUInt();
+ player.body_color_left = qt_config
+ ->value(QString("player_%1_body_color_left").arg(p),
+ Settings::JOYCON_BODY_NEON_BLUE)
+ .toUInt();
+ player.body_color_right = qt_config
+ ->value(QString("player_%1_body_color_right").arg(p),
+ Settings::JOYCON_BODY_NEON_RED)
+ .toUInt();
+ player.button_color_left = qt_config
+ ->value(QString("player_%1_button_color_left").arg(p),
+ Settings::JOYCON_BUTTONS_NEON_BLUE)
+ .toUInt();
+ player.button_color_right = qt_config
+ ->value(QString("player_%1_button_color_right").arg(p),
+ Settings::JOYCON_BUTTONS_NEON_RED)
+ .toUInt();
for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]);
- Settings::values.players[p].buttons[i] =
+ player.buttons[i] =
qt_config
->value(QString("player_%1_").arg(p) + Settings::NativeButton::mapping[i],
QString::fromStdString(default_param))
.toString()
.toStdString();
- if (Settings::values.players[p].buttons[i].empty())
- Settings::values.players[p].buttons[i] = default_param;
+ if (player.buttons[i].empty())
+ player.buttons[i] = default_param;
}
for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
std::string default_param = InputCommon::GenerateAnalogParamFromKeys(
default_analogs[i][0], default_analogs[i][1], default_analogs[i][2],
default_analogs[i][3], default_analogs[i][4], 0.5f);
- Settings::values.players[p].analogs[i] =
+ player.analogs[i] =
qt_config
->value(QString("player_%1_").arg(p) + Settings::NativeAnalog::mapping[i],
QString::fromStdString(default_param))
.toString()
.toStdString();
- if (Settings::values.players[p].analogs[i].empty())
- Settings::values.players[p].analogs[i] = default_param;
+ if (player.analogs[i].empty())
+ player.analogs[i] = default_param;
}
}
@@ -342,6 +340,13 @@ void Config::ReadTouchscreenValues() {
qt_config->endGroup();
}
+void Config::ApplyDefaultProfileIfInputInvalid() {
+ if (!std::any_of(Settings::values.players.begin(), Settings::values.players.end(),
+ [](const Settings::PlayerInput& in) { return in.connected; })) {
+ ApplyInputProfileConfiguration(UISettings::values.profile_index);
+ }
+}
+
void Config::ReadValues() {
qt_config->beginGroup("Controls");
@@ -414,13 +419,21 @@ void Config::ReadValues() {
Settings::values.language_index = qt_config->value("language_index", 1).toInt();
- const auto enabled = qt_config->value("rng_seed_enabled", false).toBool();
- if (enabled) {
+ const auto rng_seed_enabled = qt_config->value("rng_seed_enabled", false).toBool();
+ if (rng_seed_enabled) {
Settings::values.rng_seed = qt_config->value("rng_seed", 0).toULongLong();
} else {
Settings::values.rng_seed = std::nullopt;
}
+ const auto custom_rtc_enabled = qt_config->value("custom_rtc_enabled", false).toBool();
+ if (custom_rtc_enabled) {
+ Settings::values.custom_rtc =
+ std::chrono::seconds(qt_config->value("custom_rtc", 0).toULongLong());
+ } else {
+ Settings::values.custom_rtc = std::nullopt;
+ }
+
qt_config->endGroup();
qt_config->beginGroup("Miscellaneous");
@@ -444,10 +457,29 @@ void Config::ReadValues() {
Settings::values.yuzu_token = qt_config->value("yuzu_token").toString().toStdString();
qt_config->endGroup();
+ const auto size = qt_config->beginReadArray("DisabledAddOns");
+ for (int i = 0; i < size; ++i) {
+ qt_config->setArrayIndex(i);
+ const auto title_id = qt_config->value("title_id", 0).toULongLong();
+ std::vector<std::string> out;
+ const auto d_size = qt_config->beginReadArray("disabled");
+ for (int j = 0; j < d_size; ++j) {
+ qt_config->setArrayIndex(j);
+ out.push_back(qt_config->value("d", "").toString().toStdString());
+ }
+ qt_config->endArray();
+ Settings::values.disabled_addons.insert_or_assign(title_id, out);
+ }
+ qt_config->endArray();
+
qt_config->beginGroup("UI");
UISettings::values.theme = qt_config->value("theme", UISettings::themes[0].second).toString();
UISettings::values.enable_discord_presence =
qt_config->value("enable_discord_presence", true).toBool();
+ UISettings::values.screenshot_resolution_factor =
+ static_cast<u16>(qt_config->value("screenshot_resolution_factor", 0).toUInt());
+ UISettings::values.select_user_on_boot =
+ qt_config->value("select_user_on_boot", false).toBool();
qt_config->beginGroup("UIGameList");
UISettings::values.show_unknown = qt_config->value("show_unknown", true).toBool();
@@ -506,35 +538,36 @@ void Config::ReadValues() {
UISettings::values.first_start = qt_config->value("firstStart", true).toBool();
UISettings::values.callout_flags = qt_config->value("calloutFlags", 0).toUInt();
UISettings::values.show_console = qt_config->value("showConsole", false).toBool();
+ UISettings::values.profile_index = qt_config->value("profileIndex", 0).toUInt();
+
+ ApplyDefaultProfileIfInputInvalid();
qt_config->endGroup();
}
void Config::SavePlayerValues() {
- for (int p = 0; p < Settings::values.players.size(); ++p) {
- qt_config->setValue(QString("player_%1_connected").arg(p),
- Settings::values.players[p].connected);
- qt_config->setValue(QString("player_%1_type").arg(p),
- static_cast<u8>(Settings::values.players[p].type));
-
- qt_config->setValue(QString("player_%1_body_color_left").arg(p),
- Settings::values.players[p].body_color_left);
- qt_config->setValue(QString("player_%1_body_color_right").arg(p),
- Settings::values.players[p].body_color_right);
+ for (std::size_t p = 0; p < Settings::values.players.size(); ++p) {
+ const auto& player = Settings::values.players[p];
+
+ qt_config->setValue(QString("player_%1_connected").arg(p), player.connected);
+ qt_config->setValue(QString("player_%1_type").arg(p), static_cast<u8>(player.type));
+
+ qt_config->setValue(QString("player_%1_body_color_left").arg(p), player.body_color_left);
+ qt_config->setValue(QString("player_%1_body_color_right").arg(p), player.body_color_right);
qt_config->setValue(QString("player_%1_button_color_left").arg(p),
- Settings::values.players[p].button_color_left);
+ player.button_color_left);
qt_config->setValue(QString("player_%1_button_color_right").arg(p),
- Settings::values.players[p].button_color_right);
+ player.button_color_right);
for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
qt_config->setValue(QString("player_%1_").arg(p) +
QString::fromStdString(Settings::NativeButton::mapping[i]),
- QString::fromStdString(Settings::values.players[p].buttons[i]));
+ QString::fromStdString(player.buttons[i]));
}
for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
qt_config->setValue(QString("player_%1_").arg(p) +
QString::fromStdString(Settings::NativeAnalog::mapping[i]),
- QString::fromStdString(Settings::values.players[p].analogs[i]));
+ QString::fromStdString(player.analogs[i]));
}
}
}
@@ -628,6 +661,11 @@ void Config::SaveValues() {
qt_config->setValue("rng_seed_enabled", Settings::values.rng_seed.has_value());
qt_config->setValue("rng_seed", Settings::values.rng_seed.value_or(0));
+ qt_config->setValue("custom_rtc_enabled", Settings::values.custom_rtc.has_value());
+ qt_config->setValue("custom_rtc",
+ QVariant::fromValue<long long>(
+ Settings::values.custom_rtc.value_or(std::chrono::seconds{}).count()));
+
qt_config->endGroup();
qt_config->beginGroup("Miscellaneous");
@@ -650,9 +688,27 @@ void Config::SaveValues() {
qt_config->setValue("yuzu_token", QString::fromStdString(Settings::values.yuzu_token));
qt_config->endGroup();
+ qt_config->beginWriteArray("DisabledAddOns");
+ int i = 0;
+ for (const auto& elem : Settings::values.disabled_addons) {
+ qt_config->setArrayIndex(i);
+ qt_config->setValue("title_id", QVariant::fromValue<u64>(elem.first));
+ qt_config->beginWriteArray("disabled");
+ for (std::size_t j = 0; j < elem.second.size(); ++j) {
+ qt_config->setArrayIndex(static_cast<int>(j));
+ qt_config->setValue("d", QString::fromStdString(elem.second[j]));
+ }
+ qt_config->endArray();
+ ++i;
+ }
+ qt_config->endArray();
+
qt_config->beginGroup("UI");
qt_config->setValue("theme", UISettings::values.theme);
qt_config->setValue("enable_discord_presence", UISettings::values.enable_discord_presence);
+ qt_config->setValue("screenshot_resolution_factor",
+ UISettings::values.screenshot_resolution_factor);
+ qt_config->setValue("select_user_on_boot", UISettings::values.select_user_on_boot);
qt_config->beginGroup("UIGameList");
qt_config->setValue("show_unknown", UISettings::values.show_unknown);
@@ -674,6 +730,7 @@ void Config::SaveValues() {
qt_config->beginGroup("Paths");
qt_config->setValue("romsPath", UISettings::values.roms_path);
qt_config->setValue("symbolsPath", UISettings::values.symbols_path);
+ qt_config->setValue("screenshotPath", UISettings::values.screenshot_path);
qt_config->setValue("gameListRootDir", UISettings::values.gamedir);
qt_config->setValue("gameListDeepScan", UISettings::values.gamedir_deepscan);
qt_config->setValue("recentFiles", UISettings::values.recent_files);
@@ -695,6 +752,7 @@ void Config::SaveValues() {
qt_config->setValue("firstStart", UISettings::values.first_start);
qt_config->setValue("calloutFlags", UISettings::values.callout_flags);
qt_config->setValue("showConsole", UISettings::values.show_console);
+ qt_config->setValue("profileIndex", UISettings::values.profile_index);
qt_config->endGroup();
}
diff --git a/src/yuzu/configuration/config.h b/src/yuzu/configuration/config.h
index a1c27bbf9..e73ad19bb 100644
--- a/src/yuzu/configuration/config.h
+++ b/src/yuzu/configuration/config.h
@@ -34,6 +34,7 @@ private:
void ReadKeyboardValues();
void ReadMouseValues();
void ReadTouchscreenValues();
+ void ApplyDefaultProfileIfInputInvalid();
void SaveValues();
void SavePlayerValues();
diff --git a/src/yuzu/configuration/configure.ui b/src/yuzu/configuration/configure.ui
index 9b297df28..3f03f0b77 100644
--- a/src/yuzu/configuration/configure.ui
+++ b/src/yuzu/configuration/configure.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>461</width>
- <height>500</height>
+ <width>382</width>
+ <height>241</height>
</rect>
</property>
<property name="windowTitle">
@@ -15,51 +15,76 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
- <widget class="QTabWidget" name="tabWidget">
- <property name="currentIndex">
- <number>0</number>
- </property>
- <widget class="ConfigureGeneral" name="generalTab">
- <attribute name="title">
- <string>General</string>
- </attribute>
- </widget>
- <widget class="ConfigureGameList" name="gameListTab">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QListWidget" name="selectorList">
+ <property name="minimumSize">
+ <size>
+ <width>150</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>150</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QTabWidget" name="tabWidget">
+ <property name="currentIndex">
+ <number>0</number>
+ </property>
+ <widget class="ConfigureGeneral" name="generalTab">
<attribute name="title">
- <string>Game List</string>
+ <string>General</string>
</attribute>
- </widget>
- <widget class="ConfigureSystem" name="systemTab">
- <attribute name="title">
- <string>System</string>
- </attribute>
- </widget>
- <widget class="ConfigureInput" name="inputTab">
- <attribute name="title">
- <string>Input</string>
- </attribute>
- </widget>
- <widget class="ConfigureGraphics" name="graphicsTab">
- <attribute name="title">
- <string>Graphics</string>
- </attribute>
- </widget>
- <widget class="ConfigureAudio" name="audioTab">
- <attribute name="title">
- <string>Audio</string>
- </attribute>
- </widget>
- <widget class="ConfigureDebug" name="debugTab">
- <attribute name="title">
- <string>Debug</string>
- </attribute>
- </widget>
- <widget class="ConfigureWeb" name="webTab">
+ </widget>
+ <widget class="ConfigureGameList" name="gameListTab">
+ <attribute name="title">
+ <string>Game List</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureSystem" name="systemTab">
+ <attribute name="title">
+ <string>System</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureProfileManager" name="profileManagerTab">
+ <attribute name="title">
+ <string>Profiles</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureInputSimple" name="inputTab">
+ <attribute name="title">
+ <string>Input</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureGraphics" name="graphicsTab">
+ <attribute name="title">
+ <string>Graphics</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureAudio" name="audioTab">
+ <attribute name="title">
+ <string>Audio</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureDebug" name="debugTab">
+ <attribute name="title">
+ <string>Debug</string>
+ </attribute>
+ </widget>
+ <widget class="ConfigureWeb" name="webTab">
<attribute name="title">
- <string>Web</string>
+ <string>Web</string>
</attribute>
+ </widget>
</widget>
- </widget>
+ </item>
+ </layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
@@ -77,12 +102,6 @@
<header>configuration/configure_general.h</header>
<container>1</container>
</customwidget>
- <customwidget>
- <class>ConfigureGameList</class>
- <extends>QWidget</extends>
- <header>configuration/configure_gamelist.h</header>
- <container>1</container>
- </customwidget>
<customwidget>
<class>ConfigureSystem</class>
<extends>QWidget</extends>
@@ -90,6 +109,12 @@
<container>1</container>
</customwidget>
<customwidget>
+ <class>ConfigureProfileManager</class>
+ <extends>QWidget</extends>
+ <header>configuration/configure_profile_manager.h</header>
+ <container>1</container>
+ </customwidget>
+ <customwidget>
<class>ConfigureAudio</class>
<extends>QWidget</extends>
<header>configuration/configure_audio.h</header>
@@ -102,23 +127,29 @@
<container>1</container>
</customwidget>
<customwidget>
- <class>ConfigureInput</class>
+ <class>ConfigureGraphics</class>
<extends>QWidget</extends>
- <header>configuration/configure_input.h</header>
+ <header>configuration/configure_graphics.h</header>
<container>1</container>
</customwidget>
<customwidget>
- <class>ConfigureGraphics</class>
+ <class>ConfigureWeb</class>
<extends>QWidget</extends>
- <header>configuration/configure_graphics.h</header>
+ <header>configuration/configure_web.h</header>
+ <container>1</container>
+ </customwidget>
+ <customwidget>
+ <class>ConfigureGameList</class>
+ <extends>QWidget</extends>
+ <header>configuration/configure_gamelist.h</header>
+ <container>1</container>
+ </customwidget>
+ <customwidget>
+ <class>ConfigureInputSimple</class>
+ <extends>QWidget</extends>
+ <header>configuration/configure_input_simple.h</header>
<container>1</container>
</customwidget>
- <customwidget>
- <class>ConfigureWeb</class>
- <extends>QWidget</extends>
- <header>configuration/configure_web.h</header>
- <container>1</container>
- </customwidget>
</customwidgets>
<resources/>
<connections>
diff --git a/src/yuzu/configuration/configure_audio.cpp b/src/yuzu/configuration/configure_audio.cpp
index eb1da0f9e..5d9ccc6e8 100644
--- a/src/yuzu/configuration/configure_audio.cpp
+++ b/src/yuzu/configuration/configure_audio.cpp
@@ -17,8 +17,8 @@ ConfigureAudio::ConfigureAudio(QWidget* parent)
ui->output_sink_combo_box->clear();
ui->output_sink_combo_box->addItem("auto");
- for (const auto& sink_detail : AudioCore::g_sink_details) {
- ui->output_sink_combo_box->addItem(sink_detail.id);
+ for (const char* id : AudioCore::GetSinkIDs()) {
+ ui->output_sink_combo_box->addItem(id);
}
connect(ui->volume_slider, &QSlider::valueChanged, this,
@@ -97,8 +97,7 @@ void ConfigureAudio::updateAudioDevices(int sink_index) {
ui->audio_device_combo_box->addItem(AudioCore::auto_device_name);
const std::string sink_id = ui->output_sink_combo_box->itemText(sink_index).toStdString();
- const std::vector<std::string> device_list = AudioCore::GetSinkDetails(sink_id).list_devices();
- for (const auto& device : device_list) {
+ for (const auto& device : AudioCore::GetDeviceListForSink(sink_id)) {
ui->audio_device_combo_box->addItem(QString::fromStdString(device));
}
}
diff --git a/src/yuzu/configuration/configure_audio.h b/src/yuzu/configuration/configure_audio.h
index 207f9dfb3..8771421c0 100644
--- a/src/yuzu/configuration/configure_audio.h
+++ b/src/yuzu/configuration/configure_audio.h
@@ -16,15 +16,14 @@ class ConfigureAudio : public QWidget {
public:
explicit ConfigureAudio(QWidget* parent = nullptr);
- ~ConfigureAudio();
+ ~ConfigureAudio() override;
void applyConfiguration();
void retranslateUi();
-public slots:
+private:
void updateAudioDevices(int sink_index);
-private:
void setConfiguration();
void setOutputSinkFromSinkID();
void setAudioDeviceFromDeviceID();
diff --git a/src/yuzu/configuration/configure_debug.cpp b/src/yuzu/configuration/configure_debug.cpp
index aa7de7b54..550cf9dca 100644
--- a/src/yuzu/configuration/configure_debug.cpp
+++ b/src/yuzu/configuration/configure_debug.cpp
@@ -7,7 +7,6 @@
#include "common/file_util.h"
#include "common/logging/backend.h"
#include "common/logging/filter.h"
-#include "common/logging/log.h"
#include "core/core.h"
#include "core/settings.h"
#include "ui_configure_debug.h"
diff --git a/src/yuzu/configuration/configure_debug.h b/src/yuzu/configuration/configure_debug.h
index d167eb996..c6420b18c 100644
--- a/src/yuzu/configuration/configure_debug.h
+++ b/src/yuzu/configuration/configure_debug.h
@@ -16,13 +16,12 @@ class ConfigureDebug : public QWidget {
public:
explicit ConfigureDebug(QWidget* parent = nullptr);
- ~ConfigureDebug();
+ ~ConfigureDebug() override;
void applyConfiguration();
private:
void setConfiguration();
-private:
std::unique_ptr<Ui::ConfigureDebug> ui;
};
diff --git a/src/yuzu/configuration/configure_dialog.cpp b/src/yuzu/configuration/configure_dialog.cpp
index 3905423e9..777050405 100644
--- a/src/yuzu/configuration/configure_dialog.cpp
+++ b/src/yuzu/configuration/configure_dialog.cpp
@@ -2,6 +2,8 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <QHash>
+#include <QListWidgetItem>
#include "core/settings.h"
#include "ui_configure.h"
#include "yuzu/configuration/config.h"
@@ -13,6 +15,13 @@ ConfigureDialog::ConfigureDialog(QWidget* parent, const HotkeyRegistry& registry
ui->setupUi(this);
ui->generalTab->PopulateHotkeyList(registry);
this->setConfiguration();
+ this->PopulateSelectionList();
+ connect(ui->selectorList, &QListWidget::itemSelectionChanged, this,
+ &ConfigureDialog::UpdateVisibleTabs);
+
+ adjustSize();
+
+ ui->selectorList->setCurrentRow(0);
}
ConfigureDialog::~ConfigureDialog() = default;
@@ -23,10 +32,50 @@ void ConfigureDialog::applyConfiguration() {
ui->generalTab->applyConfiguration();
ui->gameListTab->applyConfiguration();
ui->systemTab->applyConfiguration();
+ ui->profileManagerTab->applyConfiguration();
ui->inputTab->applyConfiguration();
ui->graphicsTab->applyConfiguration();
ui->audioTab->applyConfiguration();
ui->debugTab->applyConfiguration();
ui->webTab->applyConfiguration();
Settings::Apply();
+ Settings::LogSettings();
+}
+
+void ConfigureDialog::PopulateSelectionList() {
+ const std::array<std::pair<QString, QStringList>, 4> items{
+ {{tr("General"), {tr("General"), tr("Web"), tr("Debug"), tr("Game List")}},
+ {tr("System"), {tr("System"), tr("Profiles"), tr("Audio")}},
+ {tr("Graphics"), {tr("Graphics")}},
+ {tr("Controls"), {tr("Input")}}}};
+
+ for (const auto& entry : items) {
+ auto* const item = new QListWidgetItem(entry.first);
+ item->setData(Qt::UserRole, entry.second);
+
+ ui->selectorList->addItem(item);
+ }
+}
+
+void ConfigureDialog::UpdateVisibleTabs() {
+ const auto items = ui->selectorList->selectedItems();
+ if (items.isEmpty())
+ return;
+
+ const std::map<QString, QWidget*> widgets = {{tr("General"), ui->generalTab},
+ {tr("System"), ui->systemTab},
+ {tr("Profiles"), ui->profileManagerTab},
+ {tr("Input"), ui->inputTab},
+ {tr("Graphics"), ui->graphicsTab},
+ {tr("Audio"), ui->audioTab},
+ {tr("Debug"), ui->debugTab},
+ {tr("Web"), ui->webTab},
+ {tr("Game List"), ui->gameListTab}};
+
+ ui->tabWidget->clear();
+
+ const QStringList tabs = items[0]->data(Qt::UserRole).toStringList();
+
+ for (const auto& tab : tabs)
+ ui->tabWidget->addTab(widgets.find(tab)->second, tab);
}
diff --git a/src/yuzu/configuration/configure_dialog.h b/src/yuzu/configuration/configure_dialog.h
index bbbdacc29..243d9fa09 100644
--- a/src/yuzu/configuration/configure_dialog.h
+++ b/src/yuzu/configuration/configure_dialog.h
@@ -18,13 +18,14 @@ class ConfigureDialog : public QDialog {
public:
explicit ConfigureDialog(QWidget* parent, const HotkeyRegistry& registry);
- ~ConfigureDialog();
+ ~ConfigureDialog() override;
void applyConfiguration();
private:
void setConfiguration();
+ void UpdateVisibleTabs();
+ void PopulateSelectionList();
-private:
std::unique_ptr<Ui::ConfigureDialog> ui;
};
diff --git a/src/yuzu/configuration/configure_gamelist.h b/src/yuzu/configuration/configure_gamelist.h
index bbf7e25f1..bf3f1cdfa 100644
--- a/src/yuzu/configuration/configure_gamelist.h
+++ b/src/yuzu/configuration/configure_gamelist.h
@@ -16,7 +16,7 @@ class ConfigureGameList : public QWidget {
public:
explicit ConfigureGameList(QWidget* parent = nullptr);
- ~ConfigureGameList();
+ ~ConfigureGameList() override;
void applyConfiguration();
diff --git a/src/yuzu/configuration/configure_general.cpp b/src/yuzu/configuration/configure_general.cpp
index 92a441308..4116b6cd7 100644
--- a/src/yuzu/configuration/configure_general.cpp
+++ b/src/yuzu/configuration/configure_general.cpp
@@ -30,6 +30,7 @@ ConfigureGeneral::~ConfigureGeneral() = default;
void ConfigureGeneral::setConfiguration() {
ui->toggle_deepscan->setChecked(UISettings::values.gamedir_deepscan);
ui->toggle_check_exit->setChecked(UISettings::values.confirm_before_closing);
+ ui->toggle_user_on_boot->setChecked(UISettings::values.select_user_on_boot);
ui->theme_combobox->setCurrentIndex(ui->theme_combobox->findData(UISettings::values.theme));
ui->use_cpu_jit->setChecked(Settings::values.use_cpu_jit);
ui->enable_nfc->setChecked(Settings::values.enable_nfc);
@@ -42,6 +43,7 @@ void ConfigureGeneral::PopulateHotkeyList(const HotkeyRegistry& registry) {
void ConfigureGeneral::applyConfiguration() {
UISettings::values.gamedir_deepscan = ui->toggle_deepscan->isChecked();
UISettings::values.confirm_before_closing = ui->toggle_check_exit->isChecked();
+ UISettings::values.select_user_on_boot = ui->toggle_user_on_boot->isChecked();
UISettings::values.theme =
ui->theme_combobox->itemData(ui->theme_combobox->currentIndex()).toString();
diff --git a/src/yuzu/configuration/configure_general.h b/src/yuzu/configuration/configure_general.h
index 4770034cc..59738af40 100644
--- a/src/yuzu/configuration/configure_general.h
+++ b/src/yuzu/configuration/configure_general.h
@@ -18,7 +18,7 @@ class ConfigureGeneral : public QWidget {
public:
explicit ConfigureGeneral(QWidget* parent = nullptr);
- ~ConfigureGeneral();
+ ~ConfigureGeneral() override;
void PopulateHotkeyList(const HotkeyRegistry& registry);
void applyConfiguration();
diff --git a/src/yuzu/configuration/configure_general.ui b/src/yuzu/configuration/configure_general.ui
index bf37446c6..dff0ad5d0 100644
--- a/src/yuzu/configuration/configure_general.ui
+++ b/src/yuzu/configuration/configure_general.ui
@@ -38,6 +38,13 @@
</property>
</widget>
</item>
+ <item>
+ <widget class="QCheckBox" name="toggle_user_on_boot">
+ <property name="text">
+ <string>Prompt for user on game boot</string>
+ </property>
+ </widget>
+ </item>
</layout>
</item>
</layout>
diff --git a/src/yuzu/configuration/configure_graphics.h b/src/yuzu/configuration/configure_graphics.h
index 9bda26fd6..d6ffc6fde 100644
--- a/src/yuzu/configuration/configure_graphics.h
+++ b/src/yuzu/configuration/configure_graphics.h
@@ -16,14 +16,13 @@ class ConfigureGraphics : public QWidget {
public:
explicit ConfigureGraphics(QWidget* parent = nullptr);
- ~ConfigureGraphics();
+ ~ConfigureGraphics() override;
void applyConfiguration();
private:
void setConfiguration();
-private:
std::unique_ptr<Ui::ConfigureGraphics> ui;
QColor bg_color;
};
diff --git a/src/yuzu/configuration/configure_input.cpp b/src/yuzu/configuration/configure_input.cpp
index ec46dc4e3..f39d57998 100644
--- a/src/yuzu/configuration/configure_input.cpp
+++ b/src/yuzu/configuration/configure_input.cpp
@@ -20,6 +20,33 @@
#include "yuzu/configuration/configure_input_player.h"
#include "yuzu/configuration/configure_mouse_advanced.h"
+void OnDockedModeChanged(bool last_state, bool new_state) {
+ if (last_state == new_state) {
+ return;
+ }
+
+ Core::System& system{Core::System::GetInstance()};
+ if (!system.IsPoweredOn()) {
+ return;
+ }
+ Service::SM::ServiceManager& sm = system.ServiceManager();
+
+ // Message queue is shared between these services, we just need to signal an operation
+ // change to one and it will handle both automatically
+ auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
+ auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
+ bool has_signalled = false;
+
+ if (applet_oe != nullptr) {
+ applet_oe->GetMessageQueue()->OperationModeChanged();
+ has_signalled = true;
+ }
+
+ if (applet_ae != nullptr && !has_signalled) {
+ applet_ae->GetMessageQueue()->OperationModeChanged();
+ }
+}
+
namespace {
template <typename Dialog, typename... Args>
void CallConfigureDialog(ConfigureInput& parent, Args&&... args) {
@@ -34,7 +61,7 @@ void CallConfigureDialog(ConfigureInput& parent, Args&&... args) {
} // Anonymous namespace
ConfigureInput::ConfigureInput(QWidget* parent)
- : QWidget(parent), ui(std::make_unique<Ui::ConfigureInput>()) {
+ : QDialog(parent), ui(std::make_unique<Ui::ConfigureInput>()) {
ui->setupUi(this);
players_controller = {
@@ -88,32 +115,7 @@ ConfigureInput::ConfigureInput(QWidget* parent)
[this] { CallConfigureDialog<ConfigureTouchscreenAdvanced>(*this); });
}
-void ConfigureInput::OnDockedModeChanged(bool last_state, bool new_state) {
- if (last_state == new_state) {
- return;
- }
-
- Core::System& system{Core::System::GetInstance()};
- if (!system.IsPoweredOn()) {
- return;
- }
- Service::SM::ServiceManager& sm = system.ServiceManager();
-
- // Message queue is shared between these services, we just need to signal an operation
- // change to one and it will handle both automatically
- auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
- auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
- bool has_signalled = false;
-
- if (applet_oe != nullptr) {
- applet_oe->GetMessageQueue()->OperationModeChanged();
- has_signalled = true;
- }
-
- if (applet_ae != nullptr && !has_signalled) {
- applet_ae->GetMessageQueue()->OperationModeChanged();
- }
-}
+ConfigureInput::~ConfigureInput() = default;
void ConfigureInput::applyConfiguration() {
for (std::size_t i = 0; i < players_controller.size(); ++i) {
diff --git a/src/yuzu/configuration/configure_input.h b/src/yuzu/configuration/configure_input.h
index e8723dfcb..b8e62cc2b 100644
--- a/src/yuzu/configuration/configure_input.h
+++ b/src/yuzu/configuration/configure_input.h
@@ -7,8 +7,8 @@
#include <array>
#include <memory>
+#include <QDialog>
#include <QKeyEvent>
-#include <QWidget>
#include "ui_configure_input.h"
@@ -20,11 +20,14 @@ namespace Ui {
class ConfigureInput;
}
-class ConfigureInput : public QWidget {
+void OnDockedModeChanged(bool last_state, bool new_state);
+
+class ConfigureInput : public QDialog {
Q_OBJECT
public:
explicit ConfigureInput(QWidget* parent = nullptr);
+ ~ConfigureInput() override;
/// Save all button configurations to settings file
void applyConfiguration();
@@ -32,8 +35,6 @@ public:
private:
void updateUIEnabled();
- void OnDockedModeChanged(bool last_state, bool new_state);
-
/// Load configuration settings.
void loadConfiguration();
/// Restore all buttons to their default values.
diff --git a/src/yuzu/configuration/configure_input.ui b/src/yuzu/configuration/configure_input.ui
index dae8277bc..0a2d9f024 100644
--- a/src/yuzu/configuration/configure_input.ui
+++ b/src/yuzu/configuration/configure_input.ui
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ConfigureInput</class>
- <widget class="QWidget" name="ConfigureInput">
+ <widget class="QDialog" name="ConfigureInput">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
- <width>473</width>
- <height>685</height>
+ <width>384</width>
+ <height>576</height>
</rect>
</property>
<property name="windowTitle">
@@ -478,6 +478,13 @@
</property>
</spacer>
</item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
</layout>
</item>
</layout>
@@ -485,5 +492,38 @@
</layout>
</widget>
<resources/>
- <connections/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ConfigureInput</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>294</x>
+ <y>553</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>191</x>
+ <y>287</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ConfigureInput</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>294</x>
+ <y>553</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>191</x>
+ <y>287</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
</ui>
diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp
index 7dadd83c1..c5a245ebe 100644
--- a/src/yuzu/configuration/configure_input_player.cpp
+++ b/src/yuzu/configuration/configure_input_player.cpp
@@ -6,6 +6,8 @@
#include <memory>
#include <utility>
#include <QColorDialog>
+#include <QGridLayout>
+#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QTimer>
diff --git a/src/yuzu/configuration/configure_input_player.h b/src/yuzu/configuration/configure_input_player.h
index 7a53f6715..ade8d4435 100644
--- a/src/yuzu/configuration/configure_input_player.h
+++ b/src/yuzu/configuration/configure_input_player.h
@@ -11,17 +11,21 @@
#include <string>
#include <QDialog>
-#include <QKeyEvent>
#include "common/param_package.h"
#include "core/settings.h"
-#include "input_common/main.h"
#include "ui_configure_input.h"
+class QKeyEvent;
class QPushButton;
class QString;
class QTimer;
+namespace InputCommon::Polling {
+class DevicePoller;
+enum class DeviceType;
+} // namespace InputCommon::Polling
+
namespace Ui {
class ConfigureInputPlayer;
}
diff --git a/src/yuzu/configuration/configure_input_simple.cpp b/src/yuzu/configuration/configure_input_simple.cpp
new file mode 100644
index 000000000..07d71e9d1
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_simple.cpp
@@ -0,0 +1,137 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <array>
+#include <tuple>
+
+#include "ui_configure_input_simple.h"
+#include "yuzu/configuration/configure_input.h"
+#include "yuzu/configuration/configure_input_player.h"
+#include "yuzu/configuration/configure_input_simple.h"
+#include "yuzu/ui_settings.h"
+
+namespace {
+
+template <typename Dialog, typename... Args>
+void CallConfigureDialog(ConfigureInputSimple* caller, Args&&... args) {
+ caller->applyConfiguration();
+ Dialog dialog(caller, std::forward<Args>(args)...);
+
+ const auto res = dialog.exec();
+ if (res == QDialog::Accepted) {
+ dialog.applyConfiguration();
+ }
+}
+
+// OnProfileSelect functions should (when applicable):
+// - Set controller types
+// - Set controller enabled
+// - Set docked mode
+// - Set advanced controller config/enabled (i.e. debug, kbd, mouse, touch)
+//
+// OnProfileSelect function should NOT however:
+// - Reset any button mappings
+// - Open any dialogs
+// - Block in any way
+
+constexpr std::size_t HANDHELD_INDEX = 8;
+
+void HandheldOnProfileSelect() {
+ Settings::values.players[HANDHELD_INDEX].connected = true;
+ Settings::values.players[HANDHELD_INDEX].type = Settings::ControllerType::DualJoycon;
+
+ for (std::size_t player = 0; player < HANDHELD_INDEX; ++player) {
+ Settings::values.players[player].connected = false;
+ }
+
+ Settings::values.use_docked_mode = false;
+ Settings::values.keyboard_enabled = false;
+ Settings::values.mouse_enabled = false;
+ Settings::values.debug_pad_enabled = false;
+ Settings::values.touchscreen.enabled = true;
+}
+
+void DualJoyconsDockedOnProfileSelect() {
+ Settings::values.players[0].connected = true;
+ Settings::values.players[0].type = Settings::ControllerType::DualJoycon;
+
+ for (std::size_t player = 1; player <= HANDHELD_INDEX; ++player) {
+ Settings::values.players[player].connected = false;
+ }
+
+ Settings::values.use_docked_mode = true;
+ Settings::values.keyboard_enabled = false;
+ Settings::values.mouse_enabled = false;
+ Settings::values.debug_pad_enabled = false;
+ Settings::values.touchscreen.enabled = false;
+}
+
+// Name, OnProfileSelect (called when selected in drop down), OnConfigure (called when configure
+// is clicked)
+using InputProfile = std::tuple<const char*, void (*)(), void (*)(ConfigureInputSimple*)>;
+
+constexpr std::array<InputProfile, 3> INPUT_PROFILES{{
+ {QT_TR_NOOP("Single Player - Handheld - Undocked"), HandheldOnProfileSelect,
+ [](ConfigureInputSimple* caller) {
+ CallConfigureDialog<ConfigureInputPlayer>(caller, HANDHELD_INDEX, false);
+ }},
+ {QT_TR_NOOP("Single Player - Dual Joycons - Docked"), DualJoyconsDockedOnProfileSelect,
+ [](ConfigureInputSimple* caller) {
+ CallConfigureDialog<ConfigureInputPlayer>(caller, 1, false);
+ }},
+ {QT_TR_NOOP("Custom"), [] {}, CallConfigureDialog<ConfigureInput>},
+}};
+
+} // namespace
+
+void ApplyInputProfileConfiguration(int profile_index) {
+ std::get<1>(
+ INPUT_PROFILES.at(std::min(profile_index, static_cast<int>(INPUT_PROFILES.size() - 1))))();
+}
+
+ConfigureInputSimple::ConfigureInputSimple(QWidget* parent)
+ : QWidget(parent), ui(std::make_unique<Ui::ConfigureInputSimple>()) {
+ ui->setupUi(this);
+
+ for (const auto& profile : INPUT_PROFILES) {
+ const QString label = tr(std::get<0>(profile));
+ ui->profile_combobox->addItem(label, label);
+ }
+
+ connect(ui->profile_combobox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ &ConfigureInputSimple::OnSelectProfile);
+ connect(ui->profile_configure, &QPushButton::pressed, this, &ConfigureInputSimple::OnConfigure);
+
+ this->loadConfiguration();
+}
+
+ConfigureInputSimple::~ConfigureInputSimple() = default;
+
+void ConfigureInputSimple::applyConfiguration() {
+ auto index = ui->profile_combobox->currentIndex();
+ // Make the stored index for "Custom" very large so that if new profiles are added it
+ // doesn't change.
+ if (index >= static_cast<int>(INPUT_PROFILES.size() - 1))
+ index = std::numeric_limits<int>::max();
+
+ UISettings::values.profile_index = index;
+}
+
+void ConfigureInputSimple::loadConfiguration() {
+ const auto index = UISettings::values.profile_index;
+ if (index >= static_cast<int>(INPUT_PROFILES.size()) || index < 0)
+ ui->profile_combobox->setCurrentIndex(static_cast<int>(INPUT_PROFILES.size() - 1));
+ else
+ ui->profile_combobox->setCurrentIndex(index);
+}
+
+void ConfigureInputSimple::OnSelectProfile(int index) {
+ const auto old_docked = Settings::values.use_docked_mode;
+ ApplyInputProfileConfiguration(index);
+ OnDockedModeChanged(old_docked, Settings::values.use_docked_mode);
+}
+
+void ConfigureInputSimple::OnConfigure() {
+ std::get<2>(INPUT_PROFILES.at(ui->profile_combobox->currentIndex()))(this);
+}
diff --git a/src/yuzu/configuration/configure_input_simple.h b/src/yuzu/configuration/configure_input_simple.h
new file mode 100644
index 000000000..5b6b69994
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_simple.h
@@ -0,0 +1,40 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+
+#include <QWidget>
+
+class QPushButton;
+class QString;
+class QTimer;
+
+namespace Ui {
+class ConfigureInputSimple;
+}
+
+// Used by configuration loader to apply a profile if the input is invalid.
+void ApplyInputProfileConfiguration(int profile_index);
+
+class ConfigureInputSimple : public QWidget {
+ Q_OBJECT
+
+public:
+ explicit ConfigureInputSimple(QWidget* parent = nullptr);
+ ~ConfigureInputSimple() override;
+
+ /// Save all button configurations to settings file
+ void applyConfiguration();
+
+private:
+ /// Load configuration settings.
+ void loadConfiguration();
+
+ void OnSelectProfile(int index);
+ void OnConfigure();
+
+ std::unique_ptr<Ui::ConfigureInputSimple> ui;
+};
diff --git a/src/yuzu/configuration/configure_input_simple.ui b/src/yuzu/configuration/configure_input_simple.ui
new file mode 100644
index 000000000..c4889caa9
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_simple.ui
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigureInputSimple</class>
+ <widget class="QWidget" name="ConfigureInputSimple">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>473</width>
+ <height>685</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>ConfigureInputSimple</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
+ <property name="title">
+ <string>Profile</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="1" column="2">
+ <widget class="QPushButton" name="profile_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="3">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="1">
+ <widget class="QComboBox" name="profile_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>250</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1" colspan="2">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Choose a controller configuration:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/yuzu/configuration/configure_per_general.cpp b/src/yuzu/configuration/configure_per_general.cpp
new file mode 100644
index 000000000..022b94609
--- /dev/null
+++ b/src/yuzu/configuration/configure_per_general.cpp
@@ -0,0 +1,169 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <memory>
+#include <utility>
+
+#include <QHeaderView>
+#include <QMenu>
+#include <QStandardItemModel>
+#include <QString>
+#include <QTimer>
+#include <QTreeView>
+
+#include "core/file_sys/control_metadata.h"
+#include "core/file_sys/patch_manager.h"
+#include "core/file_sys/xts_archive.h"
+#include "core/loader/loader.h"
+#include "ui_configure_per_general.h"
+#include "yuzu/configuration/config.h"
+#include "yuzu/configuration/configure_input.h"
+#include "yuzu/configuration/configure_per_general.h"
+#include "yuzu/ui_settings.h"
+#include "yuzu/util/util.h"
+
+ConfigurePerGameGeneral::ConfigurePerGameGeneral(QWidget* parent, u64 title_id)
+ : QDialog(parent), ui(std::make_unique<Ui::ConfigurePerGameGeneral>()), title_id(title_id) {
+
+ ui->setupUi(this);
+ setFocusPolicy(Qt::ClickFocus);
+ setWindowTitle(tr("Properties"));
+
+ layout = new QVBoxLayout;
+ tree_view = new QTreeView;
+ item_model = new QStandardItemModel(tree_view);
+ tree_view->setModel(item_model);
+ tree_view->setAlternatingRowColors(true);
+ tree_view->setSelectionMode(QHeaderView::SingleSelection);
+ tree_view->setSelectionBehavior(QHeaderView::SelectRows);
+ tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setSortingEnabled(true);
+ tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
+ tree_view->setUniformRowHeights(true);
+ tree_view->setContextMenuPolicy(Qt::NoContextMenu);
+
+ item_model->insertColumns(0, 2);
+ item_model->setHeaderData(0, Qt::Horizontal, tr("Patch Name"));
+ item_model->setHeaderData(1, Qt::Horizontal, tr("Version"));
+
+ // We must register all custom types with the Qt Automoc system so that we are able to use it
+ // with signals/slots. In this case, QList falls under the umbrells of custom types.
+ qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
+
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(0);
+ layout->addWidget(tree_view);
+
+ ui->scrollArea->setLayout(layout);
+
+ scene = new QGraphicsScene;
+ ui->icon_view->setScene(scene);
+
+ connect(item_model, &QStandardItemModel::itemChanged,
+ [] { UISettings::values.is_game_list_reload_pending.exchange(true); });
+
+ this->loadConfiguration();
+}
+
+ConfigurePerGameGeneral::~ConfigurePerGameGeneral() = default;
+
+void ConfigurePerGameGeneral::applyConfiguration() {
+ std::vector<std::string> disabled_addons;
+
+ for (const auto& item : list_items) {
+ const auto disabled = item.front()->checkState() == Qt::Unchecked;
+ if (disabled)
+ disabled_addons.push_back(item.front()->text().toStdString());
+ }
+
+ Settings::values.disabled_addons[title_id] = disabled_addons;
+}
+
+void ConfigurePerGameGeneral::loadFromFile(FileSys::VirtualFile file) {
+ this->file = std::move(file);
+ this->loadConfiguration();
+}
+
+void ConfigurePerGameGeneral::loadConfiguration() {
+ if (file == nullptr)
+ return;
+
+ const auto loader = Loader::GetLoader(file);
+
+ ui->display_title_id->setText(fmt::format("{:016X}", title_id).c_str());
+
+ FileSys::PatchManager pm{title_id};
+ const auto control = pm.GetControlMetadata();
+
+ if (control.first != nullptr) {
+ ui->display_version->setText(QString::fromStdString(control.first->GetVersionString()));
+ ui->display_name->setText(QString::fromStdString(control.first->GetApplicationName()));
+ ui->display_developer->setText(QString::fromStdString(control.first->GetDeveloperName()));
+ } else {
+ std::string title;
+ if (loader->ReadTitle(title) == Loader::ResultStatus::Success)
+ ui->display_name->setText(QString::fromStdString(title));
+
+ FileSys::NACP nacp;
+ if (loader->ReadControlData(nacp) == Loader::ResultStatus::Success)
+ ui->display_developer->setText(QString::fromStdString(nacp.GetDeveloperName()));
+
+ ui->display_version->setText(QStringLiteral("1.0.0"));
+ }
+
+ if (control.second != nullptr) {
+ scene->clear();
+
+ QPixmap map;
+ const auto bytes = control.second->ReadAllBytes();
+ map.loadFromData(bytes.data(), static_cast<u32>(bytes.size()));
+
+ scene->addPixmap(map.scaled(ui->icon_view->width(), ui->icon_view->height(),
+ Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
+ } else {
+ std::vector<u8> bytes;
+ if (loader->ReadIcon(bytes) == Loader::ResultStatus::Success) {
+ scene->clear();
+
+ QPixmap map;
+ map.loadFromData(bytes.data(), static_cast<u32>(bytes.size()));
+
+ scene->addPixmap(map.scaled(ui->icon_view->width(), ui->icon_view->height(),
+ Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
+ }
+ }
+
+ FileSys::VirtualFile update_raw;
+ loader->ReadUpdateRaw(update_raw);
+
+ const auto& disabled = Settings::values.disabled_addons[title_id];
+
+ for (const auto& patch : pm.GetPatchVersionNames(update_raw)) {
+ QStandardItem* first_item = new QStandardItem;
+ const auto name = QString::fromStdString(patch.first).replace("[D] ", "");
+ first_item->setText(name);
+ first_item->setCheckable(true);
+
+ const auto patch_disabled =
+ std::find(disabled.begin(), disabled.end(), name.toStdString()) != disabled.end();
+
+ first_item->setCheckState(patch_disabled ? Qt::Unchecked : Qt::Checked);
+
+ list_items.push_back(QList<QStandardItem*>{
+ first_item, new QStandardItem{QString::fromStdString(patch.second)}});
+ item_model->appendRow(list_items.back());
+ }
+
+ tree_view->setColumnWidth(0, 5 * tree_view->width() / 16);
+
+ ui->display_filename->setText(QString::fromStdString(file->GetName()));
+
+ ui->display_format->setText(
+ QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())));
+
+ const auto valueText = ReadableByteSize(file->GetSize());
+ ui->display_size->setText(valueText);
+}
diff --git a/src/yuzu/configuration/configure_per_general.h b/src/yuzu/configuration/configure_per_general.h
new file mode 100644
index 000000000..f8a7d5326
--- /dev/null
+++ b/src/yuzu/configuration/configure_per_general.h
@@ -0,0 +1,50 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+#include <vector>
+
+#include <QDialog>
+#include <QList>
+
+#include "core/file_sys/vfs_types.h"
+
+class QGraphicsScene;
+class QStandardItem;
+class QStandardItemModel;
+class QTreeView;
+class QVBoxLayout;
+
+namespace Ui {
+class ConfigurePerGameGeneral;
+}
+
+class ConfigurePerGameGeneral : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit ConfigurePerGameGeneral(QWidget* parent, u64 title_id);
+ ~ConfigurePerGameGeneral() override;
+
+ /// Save all button configurations to settings file
+ void applyConfiguration();
+
+ void loadFromFile(FileSys::VirtualFile file);
+
+private:
+ std::unique_ptr<Ui::ConfigurePerGameGeneral> ui;
+ FileSys::VirtualFile file;
+ u64 title_id;
+
+ QVBoxLayout* layout;
+ QTreeView* tree_view;
+ QStandardItemModel* item_model;
+ QGraphicsScene* scene;
+
+ std::vector<QList<QStandardItem*>> list_items;
+
+ void loadConfiguration();
+};
diff --git a/src/yuzu/configuration/configure_per_general.ui b/src/yuzu/configuration/configure_per_general.ui
new file mode 100644
index 000000000..8fdd96fa4
--- /dev/null
+++ b/src/yuzu/configuration/configure_per_general.ui
@@ -0,0 +1,276 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigurePerGameGeneral</class>
+ <widget class="QDialog" name="ConfigurePerGameGeneral">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>520</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>ConfigurePerGameGeneral</string>
+ </property>
+ <layout class="QHBoxLayout" name="HorizontalLayout">
+ <item>
+ <layout class="QVBoxLayout" name="VerticalLayout">
+ <item>
+ <widget class="QGroupBox" name="GeneralGroupBox">
+ <property name="title">
+ <string>Info</string>
+ </property>
+ <layout class="QHBoxLayout" name="GeneralHorizontalLayout">
+ <item>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="6" column="1" colspan="2">
+ <widget class="QLineEdit" name="display_filename">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="display_name">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>Developer</string>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="1" colspan="2">
+ <widget class="QLineEdit" name="display_size">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Name</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="0">
+ <widget class="QLabel" name="label_7">
+ <property name="text">
+ <string>Filename</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Version</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Format</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="display_version">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="1">
+ <widget class="QLineEdit" name="display_format">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="0">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>Size</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="display_developer">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Title ID</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLineEdit" name="display_title_id">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2" rowspan="5">
+ <widget class="QGraphicsView" name="icon_view">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Maximum" vsizetype="Maximum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>128</width>
+ <height>128</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>128</width>
+ <height>128</height>
+ </size>
+ </property>
+ <property name="verticalScrollBarPolicy">
+ <enum>Qt::ScrollBarAlwaysOff</enum>
+ </property>
+ <property name="horizontalScrollBarPolicy">
+ <enum>Qt::ScrollBarAlwaysOff</enum>
+ </property>
+ <property name="sizeAdjustPolicy">
+ <enum>QAbstractScrollArea::AdjustToContents</enum>
+ </property>
+ <property name="interactive">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="PerformanceGroupBox">
+ <property name="title">
+ <string>Add-Ons</string>
+ </property>
+ <layout class="QHBoxLayout" name="PerformanceHorizontalLayout">
+ <item>
+ <widget class="QScrollArea" name="scrollArea">
+ <property name="widgetResizable">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>350</width>
+ <height>169</height>
+ </rect>
+ </property>
+ </widget>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="PerformanceVerticalLayout"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ConfigurePerGameGeneral</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>269</x>
+ <y>567</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>269</x>
+ <y>294</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ConfigurePerGameGeneral</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>269</x>
+ <y>567</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>269</x>
+ <y>294</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/yuzu/configuration/configure_profile_manager.cpp b/src/yuzu/configuration/configure_profile_manager.cpp
new file mode 100644
index 000000000..41663e39a
--- /dev/null
+++ b/src/yuzu/configuration/configure_profile_manager.cpp
@@ -0,0 +1,300 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <QFileDialog>
+#include <QGraphicsItem>
+#include <QGraphicsScene>
+#include <QHeaderView>
+#include <QMessageBox>
+#include <QStandardItemModel>
+#include <QTreeView>
+#include <QVBoxLayout>
+#include "common/assert.h"
+#include "common/file_util.h"
+#include "common/string_util.h"
+#include "core/core.h"
+#include "core/hle/service/acc/profile_manager.h"
+#include "core/settings.h"
+#include "ui_configure_profile_manager.h"
+#include "yuzu/configuration/configure_profile_manager.h"
+#include "yuzu/util/limitable_input_dialog.h"
+
+namespace {
+// Same backup JPEG used by acc IProfile::GetImage if no jpeg found
+constexpr std::array<u8, 107> backup_jpeg{
+ 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02,
+ 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x06, 0x06, 0x05,
+ 0x06, 0x09, 0x08, 0x0a, 0x0a, 0x09, 0x08, 0x09, 0x09, 0x0a, 0x0c, 0x0f, 0x0c, 0x0a, 0x0b, 0x0e,
+ 0x0b, 0x09, 0x09, 0x0d, 0x11, 0x0d, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x10, 0x0a, 0x0c, 0x12, 0x13,
+ 0x12, 0x10, 0x13, 0x0f, 0x10, 0x10, 0x10, 0xff, 0xc9, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01,
+ 0x01, 0x01, 0x11, 0x00, 0xff, 0xcc, 0x00, 0x06, 0x00, 0x10, 0x10, 0x05, 0xff, 0xda, 0x00, 0x08,
+ 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0xd2, 0xcf, 0x20, 0xff, 0xd9,
+};
+
+QString GetImagePath(Service::Account::UUID uuid) {
+ const auto path = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
+ "/system/save/8000000000000010/su/avators/" + uuid.FormatSwitch() + ".jpg";
+ return QString::fromStdString(path);
+}
+
+QString GetAccountUsername(const Service::Account::ProfileManager& manager,
+ Service::Account::UUID uuid) {
+ Service::Account::ProfileBase profile;
+ if (!manager.GetProfileBase(uuid, profile)) {
+ return {};
+ }
+
+ const auto text = Common::StringFromFixedZeroTerminatedBuffer(
+ reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
+ return QString::fromStdString(text);
+}
+
+QString FormatUserEntryText(const QString& username, Service::Account::UUID uuid) {
+ return ConfigureProfileManager::tr("%1\n%2",
+ "%1 is the profile username, %2 is the formatted UUID (e.g. "
+ "00112233-4455-6677-8899-AABBCCDDEEFF))")
+ .arg(username, QString::fromStdString(uuid.FormatSwitch()));
+}
+
+QPixmap GetIcon(Service::Account::UUID uuid) {
+ QPixmap icon{GetImagePath(uuid)};
+
+ if (!icon) {
+ icon.fill(Qt::black);
+ icon.loadFromData(backup_jpeg.data(), static_cast<u32>(backup_jpeg.size()));
+ }
+
+ return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
+}
+
+QString GetProfileUsernameFromUser(QWidget* parent, const QString& description_text) {
+ return LimitableInputDialog::GetText(parent, ConfigureProfileManager::tr("Enter Username"),
+ description_text, 1,
+ static_cast<int>(Service::Account::profile_username_size));
+}
+} // Anonymous namespace
+
+ConfigureProfileManager ::ConfigureProfileManager(QWidget* parent)
+ : QWidget(parent), ui(new Ui::ConfigureProfileManager),
+ profile_manager(std::make_unique<Service::Account::ProfileManager>()) {
+ ui->setupUi(this);
+
+ layout = new QVBoxLayout;
+ tree_view = new QTreeView;
+ item_model = new QStandardItemModel(tree_view);
+ tree_view->setModel(item_model);
+
+ tree_view->setAlternatingRowColors(true);
+ tree_view->setSelectionMode(QHeaderView::SingleSelection);
+ tree_view->setSelectionBehavior(QHeaderView::SelectRows);
+ tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
+ tree_view->setSortingEnabled(true);
+ tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
+ tree_view->setUniformRowHeights(true);
+ tree_view->setIconSize({64, 64});
+ tree_view->setContextMenuPolicy(Qt::NoContextMenu);
+
+ item_model->insertColumns(0, 1);
+ item_model->setHeaderData(0, Qt::Horizontal, "Users");
+
+ // We must register all custom types with the Qt Automoc system so that we are able to use it
+ // with signals/slots. In this case, QList falls under the umbrells of custom types.
+ qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
+
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->setSpacing(0);
+ layout->addWidget(tree_view);
+
+ ui->scrollArea->setLayout(layout);
+
+ connect(tree_view, &QTreeView::clicked, this, &ConfigureProfileManager::SelectUser);
+
+ connect(ui->pm_add, &QPushButton::pressed, this, &ConfigureProfileManager::AddUser);
+ connect(ui->pm_rename, &QPushButton::pressed, this, &ConfigureProfileManager::RenameUser);
+ connect(ui->pm_remove, &QPushButton::pressed, this, &ConfigureProfileManager::DeleteUser);
+ connect(ui->pm_set_image, &QPushButton::pressed, this, &ConfigureProfileManager::SetUserImage);
+
+ scene = new QGraphicsScene;
+ ui->current_user_icon->setScene(scene);
+
+ this->setConfiguration();
+}
+
+ConfigureProfileManager::~ConfigureProfileManager() = default;
+
+void ConfigureProfileManager::setConfiguration() {
+ enabled = !Core::System::GetInstance().IsPoweredOn();
+ item_model->removeRows(0, item_model->rowCount());
+ list_items.clear();
+
+ PopulateUserList();
+ UpdateCurrentUser();
+}
+
+void ConfigureProfileManager::PopulateUserList() {
+ const auto& profiles = profile_manager->GetAllUsers();
+ for (const auto& user : profiles) {
+ Service::Account::ProfileBase profile;
+ if (!profile_manager->GetProfileBase(user, profile))
+ continue;
+
+ const auto username = Common::StringFromFixedZeroTerminatedBuffer(
+ reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
+
+ list_items.push_back(QList<QStandardItem*>{new QStandardItem{
+ GetIcon(user), FormatUserEntryText(QString::fromStdString(username), user)}});
+ }
+
+ for (const auto& item : list_items)
+ item_model->appendRow(item);
+}
+
+void ConfigureProfileManager::UpdateCurrentUser() {
+ ui->pm_add->setEnabled(profile_manager->GetUserCount() < Service::Account::MAX_USERS);
+
+ const auto& current_user = profile_manager->GetUser(Settings::values.current_user);
+ ASSERT(current_user);
+ const auto username = GetAccountUsername(*profile_manager, *current_user);
+
+ scene->clear();
+ scene->addPixmap(
+ GetIcon(*current_user).scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
+ ui->current_user_username->setText(username);
+}
+
+void ConfigureProfileManager::applyConfiguration() {
+ if (!enabled)
+ return;
+
+ Settings::Apply();
+}
+
+void ConfigureProfileManager::SelectUser(const QModelIndex& index) {
+ Settings::values.current_user =
+ std::clamp<s32>(index.row(), 0, static_cast<s32>(profile_manager->GetUserCount() - 1));
+
+ UpdateCurrentUser();
+
+ ui->pm_remove->setEnabled(profile_manager->GetUserCount() >= 2);
+ ui->pm_rename->setEnabled(true);
+ ui->pm_set_image->setEnabled(true);
+}
+
+void ConfigureProfileManager::AddUser() {
+ const auto username =
+ GetProfileUsernameFromUser(this, tr("Enter a username for the new user:"));
+ if (username.isEmpty()) {
+ return;
+ }
+
+ const auto uuid = Service::Account::UUID::Generate();
+ profile_manager->CreateNewUser(uuid, username.toStdString());
+
+ item_model->appendRow(new QStandardItem{GetIcon(uuid), FormatUserEntryText(username, uuid)});
+}
+
+void ConfigureProfileManager::RenameUser() {
+ const auto user = tree_view->currentIndex().row();
+ const auto uuid = profile_manager->GetUser(user);
+ ASSERT(uuid);
+
+ Service::Account::ProfileBase profile;
+ if (!profile_manager->GetProfileBase(*uuid, profile))
+ return;
+
+ const auto new_username = GetProfileUsernameFromUser(this, tr("Enter a new username:"));
+ if (new_username.isEmpty()) {
+ return;
+ }
+
+ const auto username_std = new_username.toStdString();
+ std::fill(profile.username.begin(), profile.username.end(), '\0');
+ std::copy(username_std.begin(), username_std.end(), profile.username.begin());
+
+ profile_manager->SetProfileBase(*uuid, profile);
+
+ item_model->setItem(
+ user, 0,
+ new QStandardItem{GetIcon(*uuid),
+ FormatUserEntryText(QString::fromStdString(username_std), *uuid)});
+ UpdateCurrentUser();
+}
+
+void ConfigureProfileManager::DeleteUser() {
+ const auto index = tree_view->currentIndex().row();
+ const auto uuid = profile_manager->GetUser(index);
+ ASSERT(uuid);
+ const auto username = GetAccountUsername(*profile_manager, *uuid);
+
+ const auto confirm = QMessageBox::question(
+ this, tr("Confirm Delete"),
+ tr("You are about to delete user with name \"%1\". Are you sure?").arg(username));
+
+ if (confirm == QMessageBox::No)
+ return;
+
+ if (Settings::values.current_user == tree_view->currentIndex().row())
+ Settings::values.current_user = 0;
+ UpdateCurrentUser();
+
+ if (!profile_manager->RemoveUser(*uuid))
+ return;
+
+ item_model->removeRows(tree_view->currentIndex().row(), 1);
+ tree_view->clearSelection();
+
+ ui->pm_remove->setEnabled(false);
+ ui->pm_rename->setEnabled(false);
+}
+
+void ConfigureProfileManager::SetUserImage() {
+ const auto index = tree_view->currentIndex().row();
+ const auto uuid = profile_manager->GetUser(index);
+ ASSERT(uuid);
+
+ const auto file = QFileDialog::getOpenFileName(this, tr("Select User Image"), QString(),
+ tr("JPEG Images (*.jpg *.jpeg)"));
+
+ if (file.isEmpty()) {
+ return;
+ }
+
+ const auto image_path = GetImagePath(*uuid);
+ if (QFile::exists(image_path) && !QFile::remove(image_path)) {
+ QMessageBox::warning(
+ this, tr("Error deleting image"),
+ tr("Error occurred attempting to overwrite previous image at: %1.").arg(image_path));
+ return;
+ }
+
+ const auto raw_path = QString::fromStdString(
+ FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) + "/system/save/8000000000000010");
+ const QFileInfo raw_info{raw_path};
+ if (raw_info.exists() && !raw_info.isDir() && !QFile::remove(raw_path)) {
+ QMessageBox::warning(this, tr("Error deleting file"),
+ tr("Unable to delete existing file: %1.").arg(raw_path));
+ return;
+ }
+
+ const QString absolute_dst_path = QFileInfo{image_path}.absolutePath();
+ if (!QDir{raw_path}.mkpath(absolute_dst_path)) {
+ QMessageBox::warning(
+ this, tr("Error creating user image directory"),
+ tr("Unable to create directory %1 for storing user images.").arg(absolute_dst_path));
+ return;
+ }
+
+ if (!QFile::copy(file, image_path)) {
+ QMessageBox::warning(this, tr("Error copying user image"),
+ tr("Unable to copy image from %1 to %2").arg(file, image_path));
+ return;
+ }
+
+ const auto username = GetAccountUsername(*profile_manager, *uuid);
+ item_model->setItem(index, 0,
+ new QStandardItem{GetIcon(*uuid), FormatUserEntryText(username, *uuid)});
+ UpdateCurrentUser();
+}
diff --git a/src/yuzu/configuration/configure_profile_manager.h b/src/yuzu/configuration/configure_profile_manager.h
new file mode 100644
index 000000000..7fe95a2a8
--- /dev/null
+++ b/src/yuzu/configuration/configure_profile_manager.h
@@ -0,0 +1,57 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+
+#include <QList>
+#include <QWidget>
+
+class QGraphicsScene;
+class QStandardItem;
+class QStandardItemModel;
+class QTreeView;
+class QVBoxLayout;
+
+namespace Service::Account {
+class ProfileManager;
+}
+
+namespace Ui {
+class ConfigureProfileManager;
+}
+
+class ConfigureProfileManager : public QWidget {
+ Q_OBJECT
+
+public:
+ explicit ConfigureProfileManager(QWidget* parent = nullptr);
+ ~ConfigureProfileManager() override;
+
+ void applyConfiguration();
+ void setConfiguration();
+
+private:
+ void PopulateUserList();
+ void UpdateCurrentUser();
+
+ void SelectUser(const QModelIndex& index);
+ void AddUser();
+ void RenameUser();
+ void DeleteUser();
+ void SetUserImage();
+
+ QVBoxLayout* layout;
+ QTreeView* tree_view;
+ QStandardItemModel* item_model;
+ QGraphicsScene* scene;
+
+ std::vector<QList<QStandardItem*>> list_items;
+
+ std::unique_ptr<Ui::ConfigureProfileManager> ui;
+ bool enabled = false;
+
+ std::unique_ptr<Service::Account::ProfileManager> profile_manager;
+};
diff --git a/src/yuzu/configuration/configure_profile_manager.ui b/src/yuzu/configuration/configure_profile_manager.ui
new file mode 100644
index 000000000..dedba4998
--- /dev/null
+++ b/src/yuzu/configuration/configure_profile_manager.ui
@@ -0,0 +1,172 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigureProfileManager</class>
+ <widget class="QWidget" name="ConfigureProfileManager">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>366</width>
+ <height>483</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
+ <property name="title">
+ <string>Profile Manager</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <property name="sizeConstraint">
+ <enum>QLayout::SetNoConstraint</enum>
+ </property>
+ <item row="0" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Current User</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGraphicsView" name="current_user_icon">
+ <property name="minimumSize">
+ <size>
+ <width>48</width>
+ <height>48</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>48</width>
+ <height>48</height>
+ </size>
+ </property>
+ <property name="verticalScrollBarPolicy">
+ <enum>Qt::ScrollBarAlwaysOff</enum>
+ </property>
+ <property name="horizontalScrollBarPolicy">
+ <enum>Qt::ScrollBarAlwaysOff</enum>
+ </property>
+ <property name="interactive">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="current_user_username">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Username</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0">
+ <widget class="QScrollArea" name="scrollArea">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="widgetResizable">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="QPushButton" name="pm_set_image">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Set Image</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="pm_add">
+ <property name="text">
+ <string>Add</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="pm_rename">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Rename</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="pm_remove">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="label_disable_info">
+ <property name="text">
+ <string>Profile management is available only when game is not running.</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/yuzu/configuration/configure_system.cpp b/src/yuzu/configuration/configure_system.cpp
index ab5d46492..10645a2b3 100644
--- a/src/yuzu/configuration/configure_system.cpp
+++ b/src/yuzu/configuration/configure_system.cpp
@@ -2,24 +2,19 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
-#include <algorithm>
+#include <array>
+#include <chrono>
+#include <optional>
+
#include <QFileDialog>
#include <QGraphicsItem>
-#include <QGraphicsScene>
-#include <QHeaderView>
#include <QMessageBox>
-#include <QStandardItemModel>
-#include <QTreeView>
-#include <QVBoxLayout>
#include "common/assert.h"
#include "common/file_util.h"
-#include "common/string_util.h"
#include "core/core.h"
-#include "core/hle/service/acc/profile_manager.h"
#include "core/settings.h"
#include "ui_configure_system.h"
#include "yuzu/configuration/configure_system.h"
-#include "yuzu/util/limitable_input_dialog.h"
namespace {
constexpr std::array<int, 12> days_in_month = {{
@@ -36,64 +31,9 @@ constexpr std::array<int, 12> days_in_month = {{
30,
31,
}};
-
-// Same backup JPEG used by acc IProfile::GetImage if no jpeg found
-constexpr std::array<u8, 107> backup_jpeg{
- 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02,
- 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x06, 0x06, 0x05,
- 0x06, 0x09, 0x08, 0x0a, 0x0a, 0x09, 0x08, 0x09, 0x09, 0x0a, 0x0c, 0x0f, 0x0c, 0x0a, 0x0b, 0x0e,
- 0x0b, 0x09, 0x09, 0x0d, 0x11, 0x0d, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x10, 0x0a, 0x0c, 0x12, 0x13,
- 0x12, 0x10, 0x13, 0x0f, 0x10, 0x10, 0x10, 0xff, 0xc9, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01,
- 0x01, 0x01, 0x11, 0x00, 0xff, 0xcc, 0x00, 0x06, 0x00, 0x10, 0x10, 0x05, 0xff, 0xda, 0x00, 0x08,
- 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0xd2, 0xcf, 0x20, 0xff, 0xd9,
-};
-
-QString GetImagePath(Service::Account::UUID uuid) {
- const auto path = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
- "/system/save/8000000000000010/su/avators/" + uuid.FormatSwitch() + ".jpg";
- return QString::fromStdString(path);
-}
-
-QString GetAccountUsername(const Service::Account::ProfileManager& manager,
- Service::Account::UUID uuid) {
- Service::Account::ProfileBase profile;
- if (!manager.GetProfileBase(uuid, profile)) {
- return {};
- }
-
- const auto text = Common::StringFromFixedZeroTerminatedBuffer(
- reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
- return QString::fromStdString(text);
-}
-
-QString FormatUserEntryText(const QString& username, Service::Account::UUID uuid) {
- return ConfigureSystem::tr("%1\n%2",
- "%1 is the profile username, %2 is the formatted UUID (e.g. "
- "00112233-4455-6677-8899-AABBCCDDEEFF))")
- .arg(username, QString::fromStdString(uuid.FormatSwitch()));
-}
-
-QPixmap GetIcon(Service::Account::UUID uuid) {
- QPixmap icon{GetImagePath(uuid)};
-
- if (!icon) {
- icon.fill(Qt::black);
- icon.loadFromData(backup_jpeg.data(), static_cast<u32>(backup_jpeg.size()));
- }
-
- return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
-}
-
-QString GetProfileUsernameFromUser(QWidget* parent, const QString& description_text) {
- return LimitableInputDialog::GetText(parent, ConfigureSystem::tr("Enter Username"),
- description_text, 1,
- static_cast<int>(Service::Account::profile_username_size));
-}
} // Anonymous namespace
-ConfigureSystem::ConfigureSystem(QWidget* parent)
- : QWidget(parent), ui(new Ui::ConfigureSystem),
- profile_manager(std::make_unique<Service::Account::ProfileManager>()) {
+ConfigureSystem::ConfigureSystem(QWidget* parent) : QWidget(parent), ui(new Ui::ConfigureSystem) {
ui->setupUi(this);
connect(ui->combo_birthmonth,
static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
@@ -101,50 +41,17 @@ ConfigureSystem::ConfigureSystem(QWidget* parent)
connect(ui->button_regenerate_console_id, &QPushButton::clicked, this,
&ConfigureSystem::RefreshConsoleID);
- layout = new QVBoxLayout;
- tree_view = new QTreeView;
- item_model = new QStandardItemModel(tree_view);
- tree_view->setModel(item_model);
-
- tree_view->setAlternatingRowColors(true);
- tree_view->setSelectionMode(QHeaderView::SingleSelection);
- tree_view->setSelectionBehavior(QHeaderView::SelectRows);
- tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
- tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
- tree_view->setSortingEnabled(true);
- tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
- tree_view->setUniformRowHeights(true);
- tree_view->setIconSize({64, 64});
- tree_view->setContextMenuPolicy(Qt::NoContextMenu);
-
- item_model->insertColumns(0, 1);
- item_model->setHeaderData(0, Qt::Horizontal, "Users");
-
- // We must register all custom types with the Qt Automoc system so that we are able to use it
- // with signals/slots. In this case, QList falls under the umbrells of custom types.
- qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
-
- layout->setContentsMargins(0, 0, 0, 0);
- layout->setSpacing(0);
- layout->addWidget(tree_view);
-
- ui->scrollArea->setLayout(layout);
-
- connect(tree_view, &QTreeView::clicked, this, &ConfigureSystem::SelectUser);
-
- connect(ui->pm_add, &QPushButton::pressed, this, &ConfigureSystem::AddUser);
- connect(ui->pm_rename, &QPushButton::pressed, this, &ConfigureSystem::RenameUser);
- connect(ui->pm_remove, &QPushButton::pressed, this, &ConfigureSystem::DeleteUser);
- connect(ui->pm_set_image, &QPushButton::pressed, this, &ConfigureSystem::SetUserImage);
-
connect(ui->rng_seed_checkbox, &QCheckBox::stateChanged, this, [this](bool checked) {
ui->rng_seed_edit->setEnabled(checked);
if (!checked)
ui->rng_seed_edit->setText(QStringLiteral("00000000"));
});
- scene = new QGraphicsScene;
- ui->current_user_icon->setScene(scene);
+ connect(ui->custom_rtc_checkbox, &QCheckBox::stateChanged, this, [this](bool checked) {
+ ui->custom_rtc_edit->setEnabled(checked);
+ if (!checked)
+ ui->custom_rtc_edit->setDateTime(QDateTime::currentDateTime());
+ });
this->setConfiguration();
}
@@ -156,49 +63,19 @@ void ConfigureSystem::setConfiguration() {
ui->combo_language->setCurrentIndex(Settings::values.language_index);
- item_model->removeRows(0, item_model->rowCount());
- list_items.clear();
-
- PopulateUserList();
- UpdateCurrentUser();
-
ui->rng_seed_checkbox->setChecked(Settings::values.rng_seed.has_value());
ui->rng_seed_edit->setEnabled(Settings::values.rng_seed.has_value());
const auto rng_seed =
QString("%1").arg(Settings::values.rng_seed.value_or(0), 8, 16, QLatin1Char{'0'}).toUpper();
ui->rng_seed_edit->setText(rng_seed);
-}
-
-void ConfigureSystem::PopulateUserList() {
- const auto& profiles = profile_manager->GetAllUsers();
- for (const auto& user : profiles) {
- Service::Account::ProfileBase profile;
- if (!profile_manager->GetProfileBase(user, profile))
- continue;
-
- const auto username = Common::StringFromFixedZeroTerminatedBuffer(
- reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
-
- list_items.push_back(QList<QStandardItem*>{new QStandardItem{
- GetIcon(user), FormatUserEntryText(QString::fromStdString(username), user)}});
- }
-
- for (const auto& item : list_items)
- item_model->appendRow(item);
-}
-void ConfigureSystem::UpdateCurrentUser() {
- ui->pm_add->setEnabled(profile_manager->GetUserCount() < Service::Account::MAX_USERS);
+ ui->custom_rtc_checkbox->setChecked(Settings::values.custom_rtc.has_value());
+ ui->custom_rtc_edit->setEnabled(Settings::values.custom_rtc.has_value());
- const auto& current_user = profile_manager->GetUser(Settings::values.current_user);
- ASSERT(current_user);
- const auto username = GetAccountUsername(*profile_manager, *current_user);
-
- scene->clear();
- scene->addPixmap(
- GetIcon(*current_user).scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
- ui->current_user_username->setText(username);
+ const auto rtc_time = Settings::values.custom_rtc.value_or(
+ std::chrono::seconds(QDateTime::currentSecsSinceEpoch()));
+ ui->custom_rtc_edit->setDateTime(QDateTime::fromSecsSinceEpoch(rtc_time.count()));
}
void ConfigureSystem::ReadSystemSettings() {}
@@ -214,6 +91,12 @@ void ConfigureSystem::applyConfiguration() {
else
Settings::values.rng_seed = std::nullopt;
+ if (ui->custom_rtc_checkbox->isChecked())
+ Settings::values.custom_rtc =
+ std::chrono::seconds(ui->custom_rtc_edit->dateTime().toSecsSinceEpoch());
+ else
+ Settings::values.custom_rtc = std::nullopt;
+
Settings::Apply();
}
@@ -256,130 +139,3 @@ void ConfigureSystem::RefreshConsoleID() {
ui->label_console_id->setText(
tr("Console ID: 0x%1").arg(QString::number(console_id, 16).toUpper()));
}
-
-void ConfigureSystem::SelectUser(const QModelIndex& index) {
- Settings::values.current_user =
- std::clamp<s32>(index.row(), 0, static_cast<s32>(profile_manager->GetUserCount() - 1));
-
- UpdateCurrentUser();
-
- ui->pm_remove->setEnabled(profile_manager->GetUserCount() >= 2);
- ui->pm_rename->setEnabled(true);
- ui->pm_set_image->setEnabled(true);
-}
-
-void ConfigureSystem::AddUser() {
- const auto username =
- GetProfileUsernameFromUser(this, tr("Enter a username for the new user:"));
- if (username.isEmpty()) {
- return;
- }
-
- const auto uuid = Service::Account::UUID::Generate();
- profile_manager->CreateNewUser(uuid, username.toStdString());
-
- item_model->appendRow(new QStandardItem{GetIcon(uuid), FormatUserEntryText(username, uuid)});
-}
-
-void ConfigureSystem::RenameUser() {
- const auto user = tree_view->currentIndex().row();
- const auto uuid = profile_manager->GetUser(user);
- ASSERT(uuid);
-
- Service::Account::ProfileBase profile;
- if (!profile_manager->GetProfileBase(*uuid, profile))
- return;
-
- const auto new_username = GetProfileUsernameFromUser(this, tr("Enter a new username:"));
- if (new_username.isEmpty()) {
- return;
- }
-
- const auto username_std = new_username.toStdString();
- std::fill(profile.username.begin(), profile.username.end(), '\0');
- std::copy(username_std.begin(), username_std.end(), profile.username.begin());
-
- profile_manager->SetProfileBase(*uuid, profile);
-
- item_model->setItem(
- user, 0,
- new QStandardItem{GetIcon(*uuid),
- FormatUserEntryText(QString::fromStdString(username_std), *uuid)});
- UpdateCurrentUser();
-}
-
-void ConfigureSystem::DeleteUser() {
- const auto index = tree_view->currentIndex().row();
- const auto uuid = profile_manager->GetUser(index);
- ASSERT(uuid);
- const auto username = GetAccountUsername(*profile_manager, *uuid);
-
- const auto confirm = QMessageBox::question(
- this, tr("Confirm Delete"),
- tr("You are about to delete user with name \"%1\". Are you sure?").arg(username));
-
- if (confirm == QMessageBox::No)
- return;
-
- if (Settings::values.current_user == tree_view->currentIndex().row())
- Settings::values.current_user = 0;
- UpdateCurrentUser();
-
- if (!profile_manager->RemoveUser(*uuid))
- return;
-
- item_model->removeRows(tree_view->currentIndex().row(), 1);
- tree_view->clearSelection();
-
- ui->pm_remove->setEnabled(false);
- ui->pm_rename->setEnabled(false);
-}
-
-void ConfigureSystem::SetUserImage() {
- const auto index = tree_view->currentIndex().row();
- const auto uuid = profile_manager->GetUser(index);
- ASSERT(uuid);
-
- const auto file = QFileDialog::getOpenFileName(this, tr("Select User Image"), QString(),
- tr("JPEG Images (*.jpg *.jpeg)"));
-
- if (file.isEmpty()) {
- return;
- }
-
- const auto image_path = GetImagePath(*uuid);
- if (QFile::exists(image_path) && !QFile::remove(image_path)) {
- QMessageBox::warning(
- this, tr("Error deleting image"),
- tr("Error occurred attempting to overwrite previous image at: %1.").arg(image_path));
- return;
- }
-
- const auto raw_path = QString::fromStdString(
- FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) + "/system/save/8000000000000010");
- const QFileInfo raw_info{raw_path};
- if (raw_info.exists() && !raw_info.isDir() && !QFile::remove(raw_path)) {
- QMessageBox::warning(this, tr("Error deleting file"),
- tr("Unable to delete existing file: %1.").arg(raw_path));
- return;
- }
-
- const QString absolute_dst_path = QFileInfo{image_path}.absolutePath();
- if (!QDir{raw_path}.mkpath(absolute_dst_path)) {
- QMessageBox::warning(
- this, tr("Error creating user image directory"),
- tr("Unable to create directory %1 for storing user images.").arg(absolute_dst_path));
- return;
- }
-
- if (!QFile::copy(file, image_path)) {
- QMessageBox::warning(this, tr("Error copying user image"),
- tr("Unable to copy image from %1 to %2").arg(file, image_path));
- return;
- }
-
- const auto username = GetAccountUsername(*profile_manager, *uuid);
- item_model->setItem(index, 0,
- new QStandardItem{GetIcon(*uuid), FormatUserEntryText(username, *uuid)});
- UpdateCurrentUser();
-}
diff --git a/src/yuzu/configuration/configure_system.h b/src/yuzu/configuration/configure_system.h
index 07764e1f7..cf1e54de5 100644
--- a/src/yuzu/configuration/configure_system.h
+++ b/src/yuzu/configuration/configure_system.h
@@ -9,16 +9,6 @@
#include <QList>
#include <QWidget>
-class QGraphicsScene;
-class QStandardItem;
-class QStandardItemModel;
-class QTreeView;
-class QVBoxLayout;
-
-namespace Service::Account {
-class ProfileManager;
-}
-
namespace Ui {
class ConfigureSystem;
}
@@ -39,21 +29,6 @@ private:
void UpdateBirthdayComboBox(int birthmonth_index);
void RefreshConsoleID();
- void PopulateUserList();
- void UpdateCurrentUser();
- void SelectUser(const QModelIndex& index);
- void AddUser();
- void RenameUser();
- void DeleteUser();
- void SetUserImage();
-
- QVBoxLayout* layout;
- QTreeView* tree_view;
- QStandardItemModel* item_model;
- QGraphicsScene* scene;
-
- std::vector<QList<QStandardItem*>> list_items;
-
std::unique_ptr<Ui::ConfigureSystem> ui;
bool enabled = false;
@@ -61,6 +36,4 @@ private:
int birthday = 0;
int language_index = 0;
int sound_index = 0;
-
- std::unique_ptr<Service::Account::ProfileManager> profile_manager;
};
diff --git a/src/yuzu/configuration/configure_system.ui b/src/yuzu/configuration/configure_system.ui
index a91580893..073327298 100644
--- a/src/yuzu/configuration/configure_system.ui
+++ b/src/yuzu/configuration/configure_system.ui
@@ -22,6 +22,13 @@
<string>System Settings</string>
</property>
<layout class="QGridLayout" name="gridLayout">
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_sound">
+ <property name="text">
+ <string>Sound output mode</string>
+ </property>
+ </widget>
+ </item>
<item row="1" column="1">
<widget class="QComboBox" name="combo_language">
<property name="toolTip">
@@ -114,27 +121,6 @@
</item>
</widget>
</item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_console_id">
- <property name="text">
- <string>Console ID:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_sound">
- <property name="text">
- <string>Sound output mode</string>
- </property>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QLabel" name="label_birthday">
- <property name="text">
- <string>Birthday</string>
- </property>
- </widget>
- </item>
<item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_birthday2">
<item>
@@ -206,6 +192,20 @@
</item>
</layout>
</item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_console_id">
+ <property name="text">
+ <string>Console ID:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_birthday">
+ <property name="text">
+ <string>Birthday</string>
+ </property>
+ </widget>
+ </item>
<item row="3" column="1">
<widget class="QPushButton" name="button_regenerate_console_id">
<property name="sizePolicy">
@@ -241,21 +241,21 @@
</item>
</widget>
</item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_language">
+ <item row="5" column="0">
+ <widget class="QCheckBox" name="rng_seed_checkbox">
<property name="text">
- <string>Language</string>
+ <string>RNG Seed</string>
</property>
</widget>
</item>
- <item row="4" column="0">
- <widget class="QCheckBox" name="rng_seed_checkbox">
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_language">
<property name="text">
- <string>RNG Seed</string>
+ <string>Language</string>
</property>
</widget>
</item>
- <item row="4" column="1">
+ <item row="5" column="1">
<widget class="QLineEdit" name="rng_seed_edit">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
@@ -276,147 +276,44 @@
</property>
</widget>
</item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="gridGroupBox">
- <property name="title">
- <string>Profile Manager</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_2">
- <property name="sizeConstraint">
- <enum>QLayout::SetNoConstraint</enum>
- </property>
- <item row="0" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="label">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Current User</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QGraphicsView" name="current_user_icon">
- <property name="minimumSize">
- <size>
- <width>48</width>
- <height>48</height>
- </size>
- </property>
- <property name="maximumSize">
- <size>
- <width>48</width>
- <height>48</height>
- </size>
- </property>
- <property name="verticalScrollBarPolicy">
- <enum>Qt::ScrollBarAlwaysOff</enum>
- </property>
- <property name="horizontalScrollBarPolicy">
- <enum>Qt::ScrollBarAlwaysOff</enum>
- </property>
- <property name="interactive">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="current_user_username">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Username</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0">
- <widget class="QScrollArea" name="scrollArea">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
+ <item row="4" column="0">
+ <widget class="QCheckBox" name="custom_rtc_checkbox">
+ <property name="text">
+ <string>Custom RTC</string>
</property>
- <property name="frameShape">
- <enum>QFrame::StyledPanel</enum>
+ </widget>
+ </item>
+ <item row="4" column="1">
+ <widget class="QDateTimeEdit" name="custom_rtc_edit">
+ <property name="minimumDate">
+ <date>
+ <year>1970</year>
+ <month>1</month>
+ <day>1</day>
+ </date>
</property>
- <property name="widgetResizable">
- <bool>false</bool>
+ <property name="displayFormat">
+ <string>d MMM yyyy h:mm:ss AP</string>
</property>
</widget>
</item>
- <item row="2" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <widget class="QPushButton" name="pm_set_image">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Set Image</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="pm_add">
- <property name="text">
- <string>Add</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="pm_rename">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Rename</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="pm_remove">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Remove</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
</layout>
</widget>
</item>
<item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
<widget class="QLabel" name="label_disable_info">
<property name="text">
<string>System settings are available only when game is not running.</string>
diff --git a/src/yuzu/configuration/configure_touchscreen_advanced.h b/src/yuzu/configuration/configure_touchscreen_advanced.h
index 41cd255fb..3d0772c87 100644
--- a/src/yuzu/configuration/configure_touchscreen_advanced.h
+++ b/src/yuzu/configuration/configure_touchscreen_advanced.h
@@ -6,8 +6,6 @@
#include <memory>
#include <QDialog>
-#include <QWidget>
-#include "yuzu/configuration/config.h"
namespace Ui {
class ConfigureTouchscreenAdvanced;
diff --git a/src/yuzu/configuration/configure_web.cpp b/src/yuzu/configuration/configure_web.cpp
index 3c2ccb76f..18566d028 100644
--- a/src/yuzu/configuration/configure_web.cpp
+++ b/src/yuzu/configuration/configure_web.cpp
@@ -89,12 +89,11 @@ void ConfigureWeb::OnLoginChanged() {
void ConfigureWeb::VerifyLogin() {
ui->button_verify_login->setDisabled(true);
- ui->button_verify_login->setText(tr("Verifying"));
- verify_watcher.setFuture(
- QtConcurrent::run([this, username = ui->edit_username->text().toStdString(),
- token = ui->edit_token->text().toStdString()]() {
- return Core::VerifyLogin(username, token);
- }));
+ ui->button_verify_login->setText(tr("Verifying..."));
+ verify_watcher.setFuture(QtConcurrent::run([username = ui->edit_username->text().toStdString(),
+ token = ui->edit_token->text().toStdString()] {
+ return Core::VerifyLogin(username, token);
+ }));
}
void ConfigureWeb::OnLoginVerified() {
diff --git a/src/yuzu/configuration/configure_web.h b/src/yuzu/configuration/configure_web.h
index 7741ab95d..7752ae4a1 100644
--- a/src/yuzu/configuration/configure_web.h
+++ b/src/yuzu/configuration/configure_web.h
@@ -17,18 +17,17 @@ class ConfigureWeb : public QWidget {
public:
explicit ConfigureWeb(QWidget* parent = nullptr);
- ~ConfigureWeb();
+ ~ConfigureWeb() override;
void applyConfiguration();
void retranslateUi();
-public slots:
+private:
void RefreshTelemetryID();
void OnLoginChanged();
void VerifyLogin();
void OnLoginVerified();
-private:
void setConfiguration();
bool user_verified = true;
diff --git a/src/yuzu/debugger/graphics/graphics_surface.cpp b/src/yuzu/debugger/graphics/graphics_surface.cpp
index 707747422..209798521 100644
--- a/src/yuzu/debugger/graphics/graphics_surface.cpp
+++ b/src/yuzu/debugger/graphics/graphics_surface.cpp
@@ -30,6 +30,7 @@ static Tegra::Texture::TextureFormat ConvertToTextureFormat(
return Tegra::Texture::TextureFormat::A2B10G10R10;
default:
UNIMPLEMENTED_MSG("Unimplemented RT format");
+ return Tegra::Texture::TextureFormat::A8R8G8B8;
}
}
diff --git a/src/yuzu/debugger/wait_tree.cpp b/src/yuzu/debugger/wait_tree.cpp
index 0c831c9f4..0c0864742 100644
--- a/src/yuzu/debugger/wait_tree.cpp
+++ b/src/yuzu/debugger/wait_tree.cpp
@@ -7,10 +7,10 @@
#include "common/assert.h"
#include "core/core.h"
-#include "core/hle/kernel/event.h"
#include "core/hle/kernel/handle_table.h"
#include "core/hle/kernel/mutex.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/readable_event.h"
#include "core/hle/kernel/scheduler.h"
#include "core/hle/kernel/thread.h"
#include "core/hle/kernel/timer.h"
@@ -75,7 +75,7 @@ std::vector<std::unique_ptr<WaitTreeThread>> WaitTreeItem::MakeThreadItemList()
return item_list;
}
-WaitTreeText::WaitTreeText(const QString& t) : text(t) {}
+WaitTreeText::WaitTreeText(QString t) : text(std::move(t)) {}
WaitTreeText::~WaitTreeText() = default;
QString WaitTreeText::GetText() const {
@@ -153,8 +153,8 @@ QString WaitTreeWaitObject::GetText() const {
std::unique_ptr<WaitTreeWaitObject> WaitTreeWaitObject::make(const Kernel::WaitObject& object) {
switch (object.GetHandleType()) {
- case Kernel::HandleType::Event:
- return std::make_unique<WaitTreeEvent>(static_cast<const Kernel::Event&>(object));
+ case Kernel::HandleType::ReadableEvent:
+ return std::make_unique<WaitTreeEvent>(static_cast<const Kernel::ReadableEvent&>(object));
case Kernel::HandleType::Timer:
return std::make_unique<WaitTreeTimer>(static_cast<const Kernel::Timer&>(object));
case Kernel::HandleType::Thread:
@@ -182,8 +182,6 @@ QString WaitTreeWaitObject::GetResetTypeQString(Kernel::ResetType reset_type) {
return tr("one shot");
case Kernel::ResetType::Sticky:
return tr("sticky");
- case Kernel::ResetType::Pulse:
- return tr("pulse");
}
UNREACHABLE();
return {};
@@ -221,6 +219,9 @@ QString WaitTreeThread::GetText() const {
case Kernel::ThreadStatus::Ready:
status = tr("ready");
break;
+ case Kernel::ThreadStatus::Paused:
+ status = tr("paused");
+ break;
case Kernel::ThreadStatus::WaitHLEEvent:
status = tr("waiting for HLE return");
break;
@@ -262,6 +263,8 @@ QColor WaitTreeThread::GetColor() const {
return QColor(Qt::GlobalColor::darkGreen);
case Kernel::ThreadStatus::Ready:
return QColor(Qt::GlobalColor::darkBlue);
+ case Kernel::ThreadStatus::Paused:
+ return QColor(Qt::GlobalColor::lightGray);
case Kernel::ThreadStatus::WaitHLEEvent:
case Kernel::ThreadStatus::WaitIPC:
return QColor(Qt::GlobalColor::darkRed);
@@ -288,8 +291,8 @@ std::vector<std::unique_ptr<WaitTreeItem>> WaitTreeThread::GetChildren() const {
QString processor;
switch (thread.GetProcessorID()) {
- case Kernel::ThreadProcessorId::THREADPROCESSORID_DEFAULT:
- processor = tr("default");
+ case Kernel::ThreadProcessorId::THREADPROCESSORID_IDEAL:
+ processor = tr("ideal");
break;
case Kernel::ThreadProcessorId::THREADPROCESSORID_0:
case Kernel::ThreadProcessorId::THREADPROCESSORID_1:
@@ -332,7 +335,7 @@ std::vector<std::unique_ptr<WaitTreeItem>> WaitTreeThread::GetChildren() const {
return list;
}
-WaitTreeEvent::WaitTreeEvent(const Kernel::Event& object) : WaitTreeWaitObject(object) {}
+WaitTreeEvent::WaitTreeEvent(const Kernel::ReadableEvent& object) : WaitTreeWaitObject(object) {}
WaitTreeEvent::~WaitTreeEvent() = default;
std::vector<std::unique_ptr<WaitTreeItem>> WaitTreeEvent::GetChildren() const {
@@ -340,7 +343,8 @@ std::vector<std::unique_ptr<WaitTreeItem>> WaitTreeEvent::GetChildren() const {
list.push_back(std::make_unique<WaitTreeText>(
tr("reset type = %1")
- .arg(GetResetTypeQString(static_cast<const Kernel::Event&>(object).GetResetType()))));
+ .arg(GetResetTypeQString(
+ static_cast<const Kernel::ReadableEvent&>(object).GetResetType()))));
return list;
}
diff --git a/src/yuzu/debugger/wait_tree.h b/src/yuzu/debugger/wait_tree.h
index 331f89885..e639ef412 100644
--- a/src/yuzu/debugger/wait_tree.h
+++ b/src/yuzu/debugger/wait_tree.h
@@ -17,8 +17,8 @@
class EmuThread;
namespace Kernel {
+class ReadableEvent;
class WaitObject;
-class Event;
class Thread;
class Timer;
} // namespace Kernel
@@ -52,7 +52,7 @@ private:
class WaitTreeText : public WaitTreeItem {
Q_OBJECT
public:
- explicit WaitTreeText(const QString& text);
+ explicit WaitTreeText(QString text);
~WaitTreeText() override;
QString GetText() const override;
@@ -144,7 +144,7 @@ public:
class WaitTreeEvent : public WaitTreeWaitObject {
Q_OBJECT
public:
- explicit WaitTreeEvent(const Kernel::Event& object);
+ explicit WaitTreeEvent(const Kernel::ReadableEvent& object);
~WaitTreeEvent() override;
std::vector<std::unique_ptr<WaitTreeItem>> GetChildren() const override;
diff --git a/src/yuzu/game_list.cpp b/src/yuzu/game_list.cpp
index 11a8c390b..c0e3c5fa9 100644
--- a/src/yuzu/game_list.cpp
+++ b/src/yuzu/game_list.cpp
@@ -214,6 +214,7 @@ GameList::GameList(FileSys::VirtualFilesystem vfs, GMainWindow* parent)
tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
tree_view->setUniformRowHeights(true);
tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
+ tree_view->setStyleSheet("QTreeView{ border: none; }");
item_model->insertColumns(0, UISettings::values.show_add_ons ? COLUMN_COUNT : COLUMN_COUNT - 1);
item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
@@ -332,6 +333,8 @@ void GameList::PopupContextMenu(const QPoint& menu_location) {
QAction* dump_romfs = context_menu.addAction(tr("Dump RomFS"));
QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard"));
QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
+ context_menu.addSeparator();
+ QAction* properties = context_menu.addAction(tr("Properties"));
open_save_location->setEnabled(program_id != 0);
auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
@@ -345,6 +348,7 @@ void GameList::PopupContextMenu(const QPoint& menu_location) {
connect(copy_tid, &QAction::triggered, [&]() { emit CopyTIDRequested(program_id); });
connect(navigate_to_gamedb_entry, &QAction::triggered,
[&]() { emit NavigateToGamedbEntryRequested(program_id, compatibility_list); });
+ connect(properties, &QAction::triggered, [&]() { emit OpenPerGameGeneralRequested(path); });
context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
}
@@ -372,7 +376,7 @@ void GameList::LoadCompatibilityList() {
QJsonDocument json = QJsonDocument::fromJson(string_content.toUtf8());
QJsonArray arr = json.array();
- for (const QJsonValueRef& value : arr) {
+ for (const QJsonValueRef value : arr) {
QJsonObject game = value.toObject();
if (game.contains("compatibility") && game["compatibility"].isDouble()) {
@@ -380,7 +384,7 @@ void GameList::LoadCompatibilityList() {
QString directory = game["directory"].toString();
QJsonArray ids = game["releases"].toArray();
- for (const QJsonValueRef& id_ref : ids) {
+ for (const QJsonValueRef id_ref : ids) {
QJsonObject id_object = id_ref.toObject();
QString id = id_object["id"].toString();
compatibility_list.emplace(
diff --git a/src/yuzu/game_list.h b/src/yuzu/game_list.h
index 05e115e19..b317eb2fc 100644
--- a/src/yuzu/game_list.h
+++ b/src/yuzu/game_list.h
@@ -70,6 +70,7 @@ signals:
void CopyTIDRequested(u64 program_id);
void NavigateToGamedbEntryRequested(u64 program_id,
const CompatibilityList& compatibility_list);
+ void OpenPerGameGeneralRequested(const std::string& file);
private slots:
void onTextChanged(const QString& newText);
diff --git a/src/yuzu/game_list_worker.cpp b/src/yuzu/game_list_worker.cpp
index 362902e46..b37710f59 100644
--- a/src/yuzu/game_list_worker.cpp
+++ b/src/yuzu/game_list_worker.cpp
@@ -62,7 +62,7 @@ QString FormatPatchNameVersions(const FileSys::PatchManager& patch_manager,
FileSys::VirtualFile update_raw;
loader.ReadUpdateRaw(update_raw);
for (const auto& kv : patch_manager.GetPatchVersionNames(update_raw)) {
- const bool is_update = kv.first == "Update";
+ const bool is_update = kv.first == "Update" || kv.first == "[D] Update";
if (!updatable && is_update) {
continue;
}
@@ -86,6 +86,37 @@ QString FormatPatchNameVersions(const FileSys::PatchManager& patch_manager,
out.chop(1);
return out;
}
+
+QList<QStandardItem*> MakeGameListEntry(const std::string& path, const std::string& name,
+ const std::vector<u8>& icon, Loader::AppLoader& loader,
+ u64 program_id, const CompatibilityList& compatibility_list,
+ const FileSys::PatchManager& patch) {
+ const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
+
+ // The game list uses this as compatibility number for untested games
+ QString compatibility{"99"};
+ if (it != compatibility_list.end()) {
+ compatibility = it->second.first;
+ }
+
+ const auto file_type = loader.GetFileType();
+ const auto file_type_string = QString::fromStdString(Loader::GetFileTypeString(file_type));
+
+ QList<QStandardItem*> list{
+ new GameListItemPath(FormatGameName(path), icon, QString::fromStdString(name),
+ file_type_string, program_id),
+ new GameListItemCompat(compatibility),
+ new GameListItem(file_type_string),
+ new GameListItemSize(FileUtil::GetSize(path)),
+ };
+
+ if (UISettings::values.show_add_ons) {
+ list.insert(
+ 2, new GameListItem(FormatPatchNameVersions(patch, loader, loader.IsRomFSUpdatable())));
+ }
+
+ return list;
+}
} // Anonymous namespace
GameListWorker::GameListWorker(FileSys::VirtualFilesystem vfs, QString dir_path, bool deep_scan,
@@ -97,11 +128,11 @@ GameListWorker::~GameListWorker() = default;
void GameListWorker::AddInstalledTitlesToGameList() {
const auto cache = Service::FileSystem::GetUnionContents();
- const auto installed_games = cache->ListEntriesFilter(FileSys::TitleType::Application,
- FileSys::ContentRecordType::Program);
+ const auto installed_games = cache.ListEntriesFilter(FileSys::TitleType::Application,
+ FileSys::ContentRecordType::Program);
for (const auto& game : installed_games) {
- const auto file = cache->GetEntryUnparsed(game);
+ const auto file = cache.GetEntryUnparsed(game);
std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(file);
if (!loader)
continue;
@@ -112,40 +143,19 @@ void GameListWorker::AddInstalledTitlesToGameList() {
loader->ReadProgramId(program_id);
const FileSys::PatchManager patch{program_id};
- const auto control = cache->GetEntry(game.title_id, FileSys::ContentRecordType::Control);
+ const auto control = cache.GetEntry(game.title_id, FileSys::ContentRecordType::Control);
if (control != nullptr)
GetMetadataFromControlNCA(patch, *control, icon, name);
- auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
-
- // The game list uses this as compatibility number for untested games
- QString compatibility("99");
- if (it != compatibility_list.end())
- compatibility = it->second.first;
-
- QList<QStandardItem*> list{
- new GameListItemPath(
- FormatGameName(file->GetFullPath()), icon, QString::fromStdString(name),
- QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
- program_id),
- new GameListItemCompat(compatibility),
- new GameListItem(
- QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
- new GameListItemSize(file->GetSize()),
- };
-
- if (UISettings::values.show_add_ons) {
- list.insert(2, new GameListItem(FormatPatchNameVersions(patch, *loader)));
- }
-
- emit EntryReady(list);
+ emit EntryReady(MakeGameListEntry(file->GetFullPath(), name, icon, *loader, program_id,
+ compatibility_list, patch));
}
- const auto control_data = cache->ListEntriesFilter(FileSys::TitleType::Application,
- FileSys::ContentRecordType::Control);
+ const auto control_data = cache.ListEntriesFilter(FileSys::TitleType::Application,
+ FileSys::ContentRecordType::Control);
for (const auto& entry : control_data) {
- auto nca = cache->GetEntry(entry);
+ auto nca = cache.GetEntry(entry);
if (nca != nullptr) {
nca_control_map.insert_or_assign(entry.title_id, std::move(nca));
}
@@ -155,14 +165,14 @@ void GameListWorker::AddInstalledTitlesToGameList() {
void GameListWorker::FillControlMap(const std::string& dir_path) {
const auto nca_control_callback = [this](u64* num_entries_out, const std::string& directory,
const std::string& virtual_name) -> bool {
- std::string physical_name = directory + DIR_SEP + virtual_name;
-
- if (stop_processing)
- return false; // Breaks the callback loop.
+ if (stop_processing) {
+ // Breaks the callback loop
+ return false;
+ }
- bool is_dir = FileUtil::IsDirectory(physical_name);
- QFileInfo file_info(physical_name.c_str());
- if (!is_dir && file_info.suffix().toStdString() == "nca") {
+ const std::string physical_name = directory + DIR_SEP + virtual_name;
+ const QFileInfo file_info(QString::fromStdString(physical_name));
+ if (!file_info.isDir() && file_info.suffix() == QStringLiteral("nca")) {
auto nca =
std::make_unique<FileSys::NCA>(vfs->OpenFile(physical_name, FileSys::Mode::Read));
if (nca->GetType() == FileSys::NCAContentType::Control) {
@@ -179,20 +189,25 @@ void GameListWorker::FillControlMap(const std::string& dir_path) {
void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsigned int recursion) {
const auto callback = [this, recursion](u64* num_entries_out, const std::string& directory,
const std::string& virtual_name) -> bool {
- std::string physical_name = directory + DIR_SEP + virtual_name;
-
- if (stop_processing)
- return false; // Breaks the callback loop.
+ if (stop_processing) {
+ // Breaks the callback loop.
+ return false;
+ }
- bool is_dir = FileUtil::IsDirectory(physical_name);
+ const std::string physical_name = directory + DIR_SEP + virtual_name;
+ const bool is_dir = FileUtil::IsDirectory(physical_name);
if (!is_dir &&
(HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
- std::unique_ptr<Loader::AppLoader> loader =
- Loader::GetLoader(vfs->OpenFile(physical_name, FileSys::Mode::Read));
- if (!loader || ((loader->GetFileType() == Loader::FileType::Unknown ||
- loader->GetFileType() == Loader::FileType::Error) &&
- !UISettings::values.show_unknown))
+ auto loader = Loader::GetLoader(vfs->OpenFile(physical_name, FileSys::Mode::Read));
+ if (!loader) {
return true;
+ }
+
+ const auto file_type = loader->GetFileType();
+ if ((file_type == Loader::FileType::Unknown || file_type == Loader::FileType::Error) &&
+ !UISettings::values.show_unknown) {
+ return true;
+ }
std::vector<u8> icon;
const auto res1 = loader->ReadIcon(icon);
@@ -214,30 +229,8 @@ void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsign
}
}
- auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
-
- // The game list uses this as compatibility number for untested games
- QString compatibility("99");
- if (it != compatibility_list.end())
- compatibility = it->second.first;
-
- QList<QStandardItem*> list{
- new GameListItemPath(
- FormatGameName(physical_name), icon, QString::fromStdString(name),
- QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
- program_id),
- new GameListItemCompat(compatibility),
- new GameListItem(
- QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
- new GameListItemSize(FileUtil::GetSize(physical_name)),
- };
-
- if (UISettings::values.show_add_ons) {
- list.insert(2, new GameListItem(FormatPatchNameVersions(
- patch, *loader, loader->IsRomFSUpdatable())));
- }
-
- emit EntryReady(std::move(list));
+ emit EntryReady(MakeGameListEntry(physical_name, name, icon, *loader, program_id,
+ compatibility_list, patch));
} else if (is_dir && recursion > 0) {
watch_list.append(QString::fromStdString(physical_name));
AddFstEntriesToGameList(physical_name, recursion - 1);
diff --git a/src/yuzu/loading_screen.cpp b/src/yuzu/loading_screen.cpp
new file mode 100644
index 000000000..907aac4f1
--- /dev/null
+++ b/src/yuzu/loading_screen.cpp
@@ -0,0 +1,213 @@
+// Copyright 2019 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <unordered_map>
+#include <QBuffer>
+#include <QByteArray>
+#include <QGraphicsOpacityEffect>
+#include <QHBoxLayout>
+#include <QIODevice>
+#include <QImage>
+#include <QLabel>
+#include <QPainter>
+#include <QPalette>
+#include <QPixmap>
+#include <QProgressBar>
+#include <QPropertyAnimation>
+#include <QStyleOption>
+#include <QTime>
+#include <QtConcurrent/QtConcurrentRun>
+#include "common/logging/log.h"
+#include "core/loader/loader.h"
+#include "ui_loading_screen.h"
+#include "video_core/rasterizer_interface.h"
+#include "yuzu/loading_screen.h"
+
+// Mingw seems to not have QMovie at all. If QMovie is missing then use a single frame instead of an
+// showing the full animation
+#if !YUZU_QT_MOVIE_MISSING
+#include <QMovie>
+#endif
+
+constexpr const char PROGRESSBAR_STYLE_PREPARE[] = R"(
+QProgressBar {}
+QProgressBar::chunk {})";
+
+constexpr const char PROGRESSBAR_STYLE_DECOMPILE[] = R"(
+QProgressBar {
+ background-color: black;
+ border: 2px solid white;
+ border-radius: 4px;
+ padding: 2px;
+}
+QProgressBar::chunk {
+ background-color: #0ab9e6;
+})";
+
+constexpr const char PROGRESSBAR_STYLE_BUILD[] = R"(
+QProgressBar {
+ background-color: black;
+ border: 2px solid white;
+ border-radius: 4px;
+ padding: 2px;
+}
+QProgressBar::chunk {
+ background-color: #ff3c28;
+})";
+
+constexpr const char PROGRESSBAR_STYLE_COMPLETE[] = R"(
+QProgressBar {
+ background-color: #0ab9e6;
+ border: 2px solid white;
+ border-radius: 4px;
+ padding: 2px;
+}
+QProgressBar::chunk {
+ background-color: #ff3c28;
+})";
+
+LoadingScreen::LoadingScreen(QWidget* parent)
+ : QWidget(parent), ui(std::make_unique<Ui::LoadingScreen>()),
+ previous_stage(VideoCore::LoadCallbackStage::Complete) {
+ ui->setupUi(this);
+ setMinimumSize(1280, 720);
+
+ // Create a fade out effect to hide this loading screen widget.
+ // When fading opacity, it will fade to the parent widgets background color, which is why we
+ // create an internal widget named fade_widget that we use the effect on, while keeping the
+ // loading screen widget's background color black. This way we can create a fade to black effect
+ opacity_effect = new QGraphicsOpacityEffect(this);
+ opacity_effect->setOpacity(1);
+ ui->fade_parent->setGraphicsEffect(opacity_effect);
+ fadeout_animation = std::make_unique<QPropertyAnimation>(opacity_effect, "opacity");
+ fadeout_animation->setDuration(500);
+ fadeout_animation->setStartValue(1);
+ fadeout_animation->setEndValue(0);
+ fadeout_animation->setEasingCurve(QEasingCurve::OutBack);
+
+ // After the fade completes, hide the widget and reset the opacity
+ connect(fadeout_animation.get(), &QPropertyAnimation::finished, [this] {
+ hide();
+ opacity_effect->setOpacity(1);
+ emit Hidden();
+ });
+ connect(this, &LoadingScreen::LoadProgress, this, &LoadingScreen::OnLoadProgress,
+ Qt::QueuedConnection);
+ qRegisterMetaType<VideoCore::LoadCallbackStage>();
+
+ stage_translations = {
+ {VideoCore::LoadCallbackStage::Prepare, tr("Loading...")},
+ {VideoCore::LoadCallbackStage::Decompile, tr("Preparing Shaders %1 / %2")},
+ {VideoCore::LoadCallbackStage::Build, tr("Loading Shaders %1 / %2")},
+ {VideoCore::LoadCallbackStage::Complete, tr("Launching...")},
+ };
+ progressbar_style = {
+ {VideoCore::LoadCallbackStage::Prepare, PROGRESSBAR_STYLE_PREPARE},
+ {VideoCore::LoadCallbackStage::Decompile, PROGRESSBAR_STYLE_DECOMPILE},
+ {VideoCore::LoadCallbackStage::Build, PROGRESSBAR_STYLE_BUILD},
+ {VideoCore::LoadCallbackStage::Complete, PROGRESSBAR_STYLE_COMPLETE},
+ };
+}
+
+LoadingScreen::~LoadingScreen() = default;
+
+void LoadingScreen::Prepare(Loader::AppLoader& loader) {
+ std::vector<u8> buffer;
+ if (loader.ReadBanner(buffer) == Loader::ResultStatus::Success) {
+#ifdef YUZU_QT_MOVIE_MISSING
+ QPixmap map;
+ map.loadFromData(buffer.data(), buffer.size());
+ ui->banner->setPixmap(map);
+#else
+ backing_mem = std::make_unique<QByteArray>(reinterpret_cast<char*>(buffer.data()),
+ static_cast<int>(buffer.size()));
+ backing_buf = std::make_unique<QBuffer>(backing_mem.get());
+ backing_buf->open(QIODevice::ReadOnly);
+ animation = std::make_unique<QMovie>(backing_buf.get(), QByteArray());
+ animation->start();
+ ui->banner->setMovie(animation.get());
+#endif
+ buffer.clear();
+ }
+ if (loader.ReadLogo(buffer) == Loader::ResultStatus::Success) {
+ QPixmap map;
+ map.loadFromData(buffer.data(), static_cast<uint>(buffer.size()));
+ ui->logo->setPixmap(map);
+ }
+
+ slow_shader_compile_start = false;
+ OnLoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
+}
+
+void LoadingScreen::OnLoadComplete() {
+ fadeout_animation->start(QPropertyAnimation::KeepWhenStopped);
+}
+
+void LoadingScreen::OnLoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value,
+ std::size_t total) {
+ using namespace std::chrono;
+ auto now = high_resolution_clock::now();
+ // reset the timer if the stage changes
+ if (stage != previous_stage) {
+ ui->progress_bar->setStyleSheet(progressbar_style[stage]);
+ // Hide the progress bar during the prepare stage
+ if (stage == VideoCore::LoadCallbackStage::Prepare) {
+ ui->progress_bar->hide();
+ } else {
+ ui->progress_bar->show();
+ }
+ previous_stage = stage;
+ // reset back to fast shader compiling since the stage changed
+ slow_shader_compile_start = false;
+ }
+ // update the max of the progress bar if the number of shaders change
+ if (total != previous_total) {
+ ui->progress_bar->setMaximum(static_cast<int>(total));
+ previous_total = total;
+ }
+
+ QString estimate;
+ // If theres a drastic slowdown in the rate, then display an estimate
+ if (now - previous_time > milliseconds{50} || slow_shader_compile_start) {
+ if (!slow_shader_compile_start) {
+ slow_shader_start = high_resolution_clock::now();
+ slow_shader_compile_start = true;
+ slow_shader_first_value = value;
+ }
+ // only calculate an estimate time after a second has passed since stage change
+ auto diff = duration_cast<milliseconds>(now - slow_shader_start);
+ if (diff > seconds{1}) {
+ auto eta_mseconds =
+ static_cast<long>(static_cast<double>(total - slow_shader_first_value) /
+ (value - slow_shader_first_value) * diff.count());
+ estimate =
+ tr("Estimated Time %1")
+ .arg(QTime(0, 0, 0, 0)
+ .addMSecs(std::max<long>(eta_mseconds - diff.count() + 1000, 1000))
+ .toString("mm:ss"));
+ }
+ }
+
+ // update labels and progress bar
+ ui->stage->setText(stage_translations[stage].arg(value).arg(total));
+ ui->value->setText(estimate);
+ ui->progress_bar->setValue(static_cast<int>(value));
+ previous_time = now;
+}
+
+void LoadingScreen::paintEvent(QPaintEvent* event) {
+ QStyleOption opt;
+ opt.init(this);
+ QPainter p(this);
+ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
+ QWidget::paintEvent(event);
+}
+
+void LoadingScreen::Clear() {
+#ifndef YUZU_QT_MOVIE_MISSING
+ animation.reset();
+ backing_buf.reset();
+ backing_mem.reset();
+#endif
+}
diff --git a/src/yuzu/loading_screen.h b/src/yuzu/loading_screen.h
new file mode 100644
index 000000000..801d08e1a
--- /dev/null
+++ b/src/yuzu/loading_screen.h
@@ -0,0 +1,92 @@
+// Copyright 2019 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <chrono>
+#include <memory>
+#include <QString>
+#include <QWidget>
+
+#if !QT_CONFIG(movie)
+#define YUZU_QT_MOVIE_MISSING 1
+#endif
+
+namespace Loader {
+class AppLoader;
+}
+
+namespace Ui {
+class LoadingScreen;
+}
+
+namespace VideoCore {
+enum class LoadCallbackStage;
+}
+
+class QBuffer;
+class QByteArray;
+class QGraphicsOpacityEffect;
+class QMovie;
+class QPropertyAnimation;
+
+class LoadingScreen : public QWidget {
+ Q_OBJECT
+
+public:
+ explicit LoadingScreen(QWidget* parent = nullptr);
+
+ ~LoadingScreen();
+
+ /// Call before showing the loading screen to load the widgets with the logo and banner for the
+ /// currently loaded application.
+ void Prepare(Loader::AppLoader& loader);
+
+ /// After the loading screen is hidden, the owner of this class can call this to clean up any
+ /// used resources such as the logo and banner.
+ void Clear();
+
+ /// Slot used to update the status of the progress bar
+ void OnLoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total);
+
+ /// Hides the LoadingScreen with a fade out effect
+ void OnLoadComplete();
+
+ // In order to use a custom widget with a stylesheet, you need to override the paintEvent
+ // See https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget
+ void paintEvent(QPaintEvent* event) override;
+
+signals:
+ void LoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total);
+ /// Signals that this widget is completely hidden now and should be replaced with the other
+ /// widget
+ void Hidden();
+
+private:
+#ifndef YUZU_QT_MOVIE_MISSING
+ std::unique_ptr<QMovie> animation;
+ std::unique_ptr<QBuffer> backing_buf;
+ std::unique_ptr<QByteArray> backing_mem;
+#endif
+ std::unique_ptr<Ui::LoadingScreen> ui;
+ std::size_t previous_total = 0;
+ VideoCore::LoadCallbackStage previous_stage;
+
+ QGraphicsOpacityEffect* opacity_effect = nullptr;
+ std::unique_ptr<QPropertyAnimation> fadeout_animation;
+
+ // Definitions for the differences in text and styling for each stage
+ std::unordered_map<VideoCore::LoadCallbackStage, const char*> progressbar_style;
+ std::unordered_map<VideoCore::LoadCallbackStage, QString> stage_translations;
+
+ // newly generated shaders are added to the end of the file, so when loading and compiling
+ // shaders, it will start quickly but end slow if new shaders were added since previous launch.
+ // These variables are used to detect the change in speed so we can generate an ETA
+ bool slow_shader_compile_start = false;
+ std::chrono::high_resolution_clock::time_point slow_shader_start;
+ std::chrono::high_resolution_clock::time_point previous_time;
+ std::size_t slow_shader_first_value = 0;
+};
+
+Q_DECLARE_METATYPE(VideoCore::LoadCallbackStage);
diff --git a/src/yuzu/loading_screen.ui b/src/yuzu/loading_screen.ui
new file mode 100644
index 000000000..a67d273fd
--- /dev/null
+++ b/src/yuzu/loading_screen.ui
@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>LoadingScreen</class>
+ <widget class="QWidget" name="LoadingScreen">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>746</width>
+ <height>495</height>
+ </rect>
+ </property>
+ <property name="styleSheet">
+ <string notr="true">background-color: rgb(0, 0, 0);</string>
+ </property>
+ <layout class="QVBoxLayout">
+ <property name="spacing">
+ <number>0</number>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QWidget" name="fade_parent" native="true">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <property name="spacing">
+ <number>0</number>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item alignment="Qt::AlignLeft|Qt::AlignTop">
+ <widget class="QLabel" name="logo">
+ <property name="text">
+ <string/>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
+ </property>
+ <property name="margin">
+ <number>30</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout" stretch="1,0,1">
+ <property name="spacing">
+ <number>15</number>
+ </property>
+ <property name="sizeConstraint">
+ <enum>QLayout::SetNoConstraint</enum>
+ </property>
+ <item alignment="Qt::AlignHCenter|Qt::AlignBottom">
+ <widget class="QLabel" name="stage">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="styleSheet">
+ <string notr="true">background-color: black; color: white;
+font: 75 20pt &quot;Arial&quot;;</string>
+ </property>
+ <property name="text">
+ <string>Loading Shaders 387 / 1628</string>
+ </property>
+ </widget>
+ </item>
+ <item alignment="Qt::AlignHCenter|Qt::AlignTop">
+ <widget class="QProgressBar" name="progress_bar">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>500</width>
+ <height>40</height>
+ </size>
+ </property>
+ <property name="styleSheet">
+ <string notr="true">QProgressBar {
+color: white;
+border: 2px solid white;
+outline-color: black;
+border-radius: 20px;
+}
+QProgressBar::chunk {
+background-color: white;
+border-radius: 15px;
+}</string>
+ </property>
+ <property name="value">
+ <number>50</number>
+ </property>
+ <property name="textVisible">
+ <bool>false</bool>
+ </property>
+ <property name="format">
+ <string>Loading Shaders %v out of %m</string>
+ </property>
+ </widget>
+ </item>
+ <item alignment="Qt::AlignHCenter|Qt::AlignTop">
+ <widget class="QLabel" name="value">
+ <property name="toolTip">
+ <string notr="true"/>
+ </property>
+ <property name="styleSheet">
+ <string notr="true">background-color: black; color: white;
+font: 75 15pt &quot;Arial&quot;;</string>
+ </property>
+ <property name="text">
+ <string>Stage 1 of 2. Estimate Time 5m 4s</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item alignment="Qt::AlignRight|Qt::AlignBottom">
+ <widget class="QLabel" name="banner">
+ <property name="styleSheet">
+ <string notr="true">background-color: black;</string>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="margin">
+ <number>30</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index 93bf117c8..ab403b3ac 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -8,11 +8,17 @@
#include <thread>
// VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
+#include "applets/profile_select.h"
#include "applets/software_keyboard.h"
+#include "applets/web_browser.h"
+#include "configuration/configure_per_general.h"
#include "core/file_sys/vfs.h"
#include "core/file_sys/vfs_real.h"
+#include "core/frontend/scope_acquire_window_context.h"
#include "core/hle/service/acc/profile_manager.h"
#include "core/hle/service/am/applets/applets.h"
+#include "core/hle/service/hid/controllers/npad.h"
+#include "core/hle/service/hid/hid.h"
// These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
// defines.
@@ -87,6 +93,7 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual
#include "yuzu/game_list.h"
#include "yuzu/game_list_p.h"
#include "yuzu/hotkeys.h"
+#include "yuzu/loading_screen.h"
#include "yuzu/main.h"
#include "yuzu/ui_settings.h"
@@ -94,6 +101,14 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual
#include "yuzu/discord_impl.h"
#endif
+#ifdef YUZU_USE_QT_WEB_ENGINE
+#include <QWebEngineProfile>
+#include <QWebEngineScript>
+#include <QWebEngineScriptCollection>
+#include <QWebEngineSettings>
+#include <QWebEngineView>
+#endif
+
#ifdef QT_STATICPLUGIN
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#endif
@@ -207,6 +222,28 @@ GMainWindow::~GMainWindow() {
delete render_window;
}
+void GMainWindow::ProfileSelectorSelectProfile() {
+ QtProfileSelectionDialog dialog(this);
+ dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
+ Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
+ dialog.setWindowModality(Qt::WindowModal);
+ dialog.exec();
+
+ if (!dialog.GetStatus()) {
+ emit ProfileSelectorFinishedSelection(std::nullopt);
+ return;
+ }
+
+ Service::Account::ProfileManager manager;
+ const auto uuid = manager.GetUser(dialog.GetIndex());
+ if (!uuid.has_value()) {
+ emit ProfileSelectorFinishedSelection(std::nullopt);
+ return;
+ }
+
+ emit ProfileSelectorFinishedSelection(uuid);
+}
+
void GMainWindow::SoftwareKeyboardGetText(
const Core::Frontend::SoftwareKeyboardParameters& parameters) {
QtSoftwareKeyboardDialog dialog(this, parameters);
@@ -228,6 +265,144 @@ void GMainWindow::SoftwareKeyboardInvokeCheckDialog(std::u16string error_message
emit SoftwareKeyboardFinishedCheckDialog();
}
+#ifdef YUZU_USE_QT_WEB_ENGINE
+
+void GMainWindow::WebBrowserOpenPage(std::string_view filename, std::string_view additional_args) {
+ NXInputWebEngineView web_browser_view(this);
+
+ // Scope to contain the QProgressDialog for initalization
+ {
+ QProgressDialog progress(this);
+ progress.setMinimumDuration(200);
+ progress.setLabelText(tr("Loading Web Applet..."));
+ progress.setRange(0, 4);
+ progress.setValue(0);
+ progress.show();
+
+ auto future = QtConcurrent::run([this] { emit WebBrowserUnpackRomFS(); });
+
+ while (!future.isFinished())
+ QApplication::processEvents();
+
+ progress.setValue(1);
+
+ // Load the special shim script to handle input and exit.
+ QWebEngineScript nx_shim;
+ nx_shim.setSourceCode(GetNXShimInjectionScript());
+ nx_shim.setWorldId(QWebEngineScript::MainWorld);
+ nx_shim.setName("nx_inject.js");
+ nx_shim.setInjectionPoint(QWebEngineScript::DocumentCreation);
+ nx_shim.setRunsOnSubFrames(true);
+ web_browser_view.page()->profile()->scripts()->insert(nx_shim);
+
+ web_browser_view.load(
+ QUrl(QUrl::fromLocalFile(QString::fromStdString(std::string(filename))).toString() +
+ QString::fromStdString(std::string(additional_args))));
+
+ progress.setValue(2);
+
+ render_window->hide();
+ web_browser_view.setFocus();
+
+ const auto& layout = render_window->GetFramebufferLayout();
+ web_browser_view.resize(layout.screen.GetWidth(), layout.screen.GetHeight());
+ web_browser_view.move(layout.screen.left, layout.screen.top + menuBar()->height());
+ web_browser_view.setZoomFactor(static_cast<qreal>(layout.screen.GetWidth()) /
+ Layout::ScreenUndocked::Width);
+ web_browser_view.settings()->setAttribute(
+ QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
+
+ web_browser_view.show();
+
+ progress.setValue(3);
+
+ QApplication::processEvents();
+
+ progress.setValue(4);
+ }
+
+ bool finished = false;
+ QAction* exit_action = new QAction(tr("Exit Web Applet"), this);
+ connect(exit_action, &QAction::triggered, this, [&finished] { finished = true; });
+ ui.menubar->addAction(exit_action);
+
+ auto& npad =
+ Core::System::GetInstance()
+ .ServiceManager()
+ .GetService<Service::HID::Hid>("hid")
+ ->GetAppletResource()
+ ->GetController<Service::HID::Controller_NPad>(Service::HID::HidController::NPad);
+
+ const auto fire_js_keypress = [&web_browser_view](u32 key_code) {
+ web_browser_view.page()->runJavaScript(
+ QStringLiteral("document.dispatchEvent(new KeyboardEvent('keydown', {'key': %1}));")
+ .arg(QString::fromStdString(std::to_string(key_code))));
+ };
+
+ bool running_exit_check = false;
+ while (!finished) {
+ QApplication::processEvents();
+
+ if (!running_exit_check) {
+ web_browser_view.page()->runJavaScript(QStringLiteral("applet_done;"),
+ [&](const QVariant& res) {
+ running_exit_check = false;
+ if (res.toBool())
+ finished = true;
+ });
+ running_exit_check = true;
+ }
+
+ const auto input = npad.GetAndResetPressState();
+ for (std::size_t i = 0; i < Settings::NativeButton::NumButtons; ++i) {
+ if ((input & (1 << i)) != 0) {
+ LOG_DEBUG(Frontend, "firing input for button id={:02X}", i);
+ web_browser_view.page()->runJavaScript(
+ QStringLiteral("yuzu_key_callbacks[%1]();").arg(i));
+ }
+ }
+
+ if (input & 0x00888000) // RStick Down | LStick Down | DPad Down
+ fire_js_keypress(40); // Down Arrow Key
+ else if (input & 0x00444000) // RStick Right | LStick Right | DPad Right
+ fire_js_keypress(39); // Right Arrow Key
+ else if (input & 0x00222000) // RStick Up | LStick Up | DPad Up
+ fire_js_keypress(38); // Up Arrow Key
+ else if (input & 0x00111000) // RStick Left | LStick Left | DPad Left
+ fire_js_keypress(37); // Left Arrow Key
+ else if (input & 0x00000001) // A Button
+ fire_js_keypress(13); // Enter Key
+ }
+
+ web_browser_view.hide();
+ render_window->show();
+ render_window->setFocus();
+ ui.menubar->removeAction(exit_action);
+
+ // Needed to update render window focus/show and remove menubar action
+ QApplication::processEvents();
+ emit WebBrowserFinishedBrowsing();
+}
+
+#else
+
+void GMainWindow::WebBrowserOpenPage(std::string_view filename, std::string_view additional_args) {
+ QMessageBox::warning(
+ this, tr("Web Applet"),
+ tr("This version of yuzu was built without QtWebEngine support, meaning that yuzu cannot "
+ "properly display the game manual or web page requested."),
+ QMessageBox::Ok, QMessageBox::Ok);
+
+ LOG_INFO(Frontend,
+ "(STUBBED) called - Missing QtWebEngine dependency needed to open website page at "
+ "'{}' with arguments '{}'!",
+ filename, additional_args);
+
+ emit WebBrowserFinishedBrowsing();
+}
+
+#endif
+
void GMainWindow::InitializeWidgets() {
#ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
ui.action_Report_Compatibility->setVisible(true);
@@ -238,6 +413,17 @@ void GMainWindow::InitializeWidgets() {
game_list = new GameList(vfs, this);
ui.horizontalLayout->addWidget(game_list);
+ loading_screen = new LoadingScreen(this);
+ loading_screen->hide();
+ ui.horizontalLayout->addWidget(loading_screen);
+ connect(loading_screen, &LoadingScreen::Hidden, [&] {
+ loading_screen->Clear();
+ if (emulation_running) {
+ render_window->show();
+ render_window->setFocus();
+ }
+ });
+
// Create status bar
message_label = new QLabel();
// Configured separately for left alignment
@@ -334,6 +520,9 @@ void GMainWindow::InitializeHotkeys() {
Qt::ApplicationShortcut);
hotkey_registry.RegisterHotkey("Main Window", "Load Amiibo", QKeySequence(Qt::Key_F2),
Qt::ApplicationShortcut);
+ hotkey_registry.RegisterHotkey("Main Window", "Capture Screenshot",
+ QKeySequence(QKeySequence::Print));
+
hotkey_registry.LoadHotkeys();
connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
@@ -393,6 +582,12 @@ void GMainWindow::InitializeHotkeys() {
OnLoadAmiibo();
}
});
+ connect(hotkey_registry.GetHotkey("Main Window", "Capture Screenshot", this),
+ &QShortcut::activated, this, [&] {
+ if (emu_thread->IsRunning()) {
+ OnCaptureScreenshot();
+ }
+ });
}
void GMainWindow::SetDefaultUIGeometry() {
@@ -441,6 +636,8 @@ void GMainWindow::ConnectWidgetEvents() {
connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
&GMainWindow::OnGameListNavigateToGamedbEntry);
+ connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
+ &GMainWindow::OnGameListOpenPerGameProperties);
connect(this, &GMainWindow::EmulationStarting, render_window,
&GRenderWindow::OnEmulationStarting);
@@ -488,6 +685,10 @@ void GMainWindow::ConnectMenuEvents() {
hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
+ // Movie
+ connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
+ &GMainWindow::OnCaptureScreenshot);
+
// Help
connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
connect(ui.action_Rederive, &QAction::triggered, this,
@@ -518,6 +719,8 @@ void GMainWindow::OnDisplayTitleBars(bool show) {
QStringList GMainWindow::GetUnsupportedGLExtensions() {
QStringList unsupported_ext;
+ if (!GLAD_GL_ARB_direct_state_access)
+ unsupported_ext.append("ARB_direct_state_access");
if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
@@ -545,13 +748,15 @@ bool GMainWindow::LoadROM(const QString& filename) {
ShutdownGame();
render_window->InitRenderTarget();
- render_window->MakeCurrent();
- if (!gladLoadGL()) {
- QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
- tr("Your GPU may not support OpenGL 4.3, or you do not "
- "have the latest graphics driver."));
- return false;
+ {
+ Core::Frontend::ScopeAcquireWindowContext acquire_context{*render_window};
+ if (!gladLoadGL()) {
+ QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
+ tr("Your GPU may not support OpenGL 4.3, or you do not "
+ "have the latest graphics driver."));
+ return false;
+ }
}
QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
@@ -569,7 +774,9 @@ bool GMainWindow::LoadROM(const QString& filename) {
system.SetGPUDebugContext(debug_context);
+ system.SetProfileSelector(std::make_unique<QtProfileSelector>(*this));
system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
+ system.SetWebBrowser(std::make_unique<QtWebBrowser>(*this));
const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
@@ -590,8 +797,6 @@ bool GMainWindow::LoadROM(const QString& filename) {
"wiki</a>. This message will not be shown again."));
}
- render_window->DoneCurrent();
-
if (result != Core::System::ResultStatus::Success) {
switch (result) {
case Core::System::ResultStatus::ErrorGetLoader:
@@ -645,10 +850,26 @@ bool GMainWindow::LoadROM(const QString& filename) {
return true;
}
+void GMainWindow::SelectAndSetCurrentUser() {
+ QtProfileSelectionDialog dialog(this);
+ dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
+ Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
+ dialog.setWindowModality(Qt::WindowModal);
+ dialog.exec();
+
+ if (dialog.GetStatus()) {
+ Settings::values.current_user = static_cast<s32>(dialog.GetIndex());
+ }
+}
+
void GMainWindow::BootGame(const QString& filename) {
LOG_INFO(Frontend, "yuzu starting...");
StoreRecentFile(filename); // Put the filename on top of the list
+ if (UISettings::values.select_user_on_boot) {
+ SelectAndSetCurrentUser();
+ }
+
if (!LoadROM(filename))
return;
@@ -689,8 +910,8 @@ void GMainWindow::BootGame(const QString& filename) {
.arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
QString::fromStdString(title_name)));
- render_window->show();
- render_window->setFocus();
+ loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
+ loading_screen->show();
emulation_running = true;
if (ui.action_Fullscreen->isChecked()) {
@@ -722,7 +943,10 @@ void GMainWindow::ShutdownGame() {
ui.action_Restart->setEnabled(false);
ui.action_Report_Compatibility->setEnabled(false);
ui.action_Load_Amiibo->setEnabled(false);
+ ui.action_Capture_Screenshot->setEnabled(false);
render_window->hide();
+ loading_screen->hide();
+ loading_screen->Clear();
game_list->show();
game_list->setFilterFocus();
setWindowTitle(QString("yuzu %1| %2-%3")
@@ -784,31 +1008,25 @@ void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target
const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
ASSERT(program_id != 0);
- Service::Account::ProfileManager manager{};
- const auto user_ids = manager.GetAllUsers();
- QStringList list;
- for (const auto& user_id : user_ids) {
- if (user_id == Service::Account::UUID{})
- continue;
- Service::Account::ProfileBase base;
- if (!manager.GetProfileBase(user_id, base))
- continue;
-
- list.push_back(QString::fromStdString(Common::StringFromFixedZeroTerminatedBuffer(
- reinterpret_cast<const char*>(base.username.data()), base.username.size())));
- }
+ const auto select_profile = [this]() -> s32 {
+ QtProfileSelectionDialog dialog(this);
+ dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
+ Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
+ dialog.setWindowModality(Qt::WindowModal);
+ dialog.exec();
- bool ok = false;
- const auto index_string =
- QInputDialog::getItem(this, tr("Select User"),
- tr("Please select the user's save data you would like to open."),
- list, Settings::values.current_user, false, &ok);
- if (!ok)
- return;
+ if (!dialog.GetStatus()) {
+ return -1;
+ }
+
+ return dialog.GetIndex();
+ };
- const auto index = list.indexOf(index_string);
- ASSERT(index != -1 && index < 8);
+ const auto index = select_profile();
+ if (index == -1)
+ return;
+ Service::Account::ProfileManager manager;
const auto user_id = manager.GetUser(index);
ASSERT(user_id);
path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
@@ -905,7 +1123,7 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
}
const auto installed = Service::FileSystem::GetUnionContents();
- auto romfs_title_id = SelectRomFSDumpTarget(*installed, program_id);
+ const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
if (!romfs_title_id) {
failed();
@@ -920,7 +1138,7 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
if (*romfs_title_id == program_id) {
romfs = file;
} else {
- romfs = installed->GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
+ romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
}
const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
@@ -986,6 +1204,32 @@ void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
}
+void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
+ u64 title_id{};
+ const auto v_file = Core::GetGameFileFromPath(vfs, file);
+ const auto loader = Loader::GetLoader(v_file);
+ if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
+ QMessageBox::information(this, tr("Properties"),
+ tr("The game properties could not be loaded."));
+ return;
+ }
+
+ ConfigurePerGameGeneral dialog(this, title_id);
+ dialog.loadFromFile(v_file);
+ auto result = dialog.exec();
+ if (result == QDialog::Accepted) {
+ dialog.applyConfiguration();
+
+ const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
+ if (reload) {
+ game_list->PopulateAsync(UISettings::values.gamedir,
+ UISettings::values.gamedir_deepscan);
+ }
+
+ config->Save();
+ }
+}
+
void GMainWindow::OnMenuLoadFile() {
const QString extensions =
QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
@@ -1246,6 +1490,7 @@ void GMainWindow::OnStartGame() {
qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
qRegisterMetaType<std::string>("std::string");
qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
+ qRegisterMetaType<std::string_view>("std::string_view");
connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
@@ -1259,6 +1504,7 @@ void GMainWindow::OnStartGame() {
discord_rpc->Update();
ui.action_Load_Amiibo->setEnabled(true);
+ ui.action_Capture_Screenshot->setEnabled(true);
}
void GMainWindow::OnPauseGame() {
@@ -1267,12 +1513,17 @@ void GMainWindow::OnPauseGame() {
ui.action_Start->setEnabled(true);
ui.action_Pause->setEnabled(false);
ui.action_Stop->setEnabled(true);
+ ui.action_Capture_Screenshot->setEnabled(false);
}
void GMainWindow::OnStopGame() {
ShutdownGame();
}
+void GMainWindow::OnLoadComplete() {
+ loading_screen->OnLoadComplete();
+}
+
void GMainWindow::OnMenuReportCompatibility() {
if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
CompatDB compatdb{this};
@@ -1429,6 +1680,18 @@ void GMainWindow::OnToggleFilterBar() {
}
}
+void GMainWindow::OnCaptureScreenshot() {
+ OnPauseGame();
+ const QString path =
+ QFileDialog::getSaveFileName(this, tr("Capture Screenshot"),
+ UISettings::values.screenshot_path, tr("PNG Image (*.png)"));
+ if (!path.isEmpty()) {
+ UISettings::values.screenshot_path = QFileInfo(path).path();
+ render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
+ }
+ OnStartGame();
+}
+
void GMainWindow::UpdateStatusBar() {
if (emu_thread == nullptr) {
status_bar_update_timer.stop();
@@ -1527,9 +1790,8 @@ void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
this, tr("Confirm Key Rederivation"),
tr("You are about to force rederive all of your keys. \nIf you do not know what this "
"means or what you are doing, \nthis is a potentially destructive action. \nPlease "
- "make "
- "sure this is what you want \nand optionally make backups.\n\nThis will delete your "
- "autogenerated key files and re-run the key derivation module."),
+ "make sure this is what you want \nand optionally make backups.\n\nThis will delete "
+ "your autogenerated key files and re-run the key derivation module."),
QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
if (res == QMessageBox::Cancel)
@@ -1574,7 +1836,7 @@ void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
errors +
tr("<br><br>You can get all of these and dump all of your games easily by "
"following <a href='https://yuzu-emu.org/help/quickstart/'>the "
- "quickstart guide</a>. Alternatively, you can use another method of dumping "
+ "quickstart guide</a>. Alternatively, you can use another method of dumping"
"to obtain all of your keys."));
}
@@ -1781,6 +2043,9 @@ int main(int argc, char* argv[]) {
GMainWindow main_window;
// After settings have been loaded by GMainWindow, apply the filter
main_window.show();
+
+ Settings::LogSettings();
+
int result = app.exec();
detached_tasks.WaitForAllTasks();
return result;
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index 674e73412..e07c892cf 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -13,6 +13,7 @@
#include "common/common_types.h"
#include "core/core.h"
+#include "core/hle/service/acc/profile_manager.h"
#include "ui_main.h"
#include "yuzu/compatibility_list.h"
#include "yuzu/hotkeys.h"
@@ -24,8 +25,10 @@ class GImageInfo;
class GraphicsBreakPointsWidget;
class GraphicsSurfaceWidget;
class GRenderWindow;
+class LoadingScreen;
class MicroProfileDialog;
class ProfilerWidget;
+class QLabel;
class WaitTreeWidget;
enum class GameListOpenTarget;
@@ -99,12 +102,19 @@ signals:
// Signal that tells widgets to update icons to use the current theme
void UpdateThemedIcons();
+ void ProfileSelectorFinishedSelection(std::optional<Service::Account::UUID> uuid);
void SoftwareKeyboardFinishedText(std::optional<std::u16string> text);
void SoftwareKeyboardFinishedCheckDialog();
+ void WebBrowserUnpackRomFS();
+ void WebBrowserFinishedBrowsing();
+
public slots:
+ void OnLoadComplete();
+ void ProfileSelectorSelectProfile();
void SoftwareKeyboardGetText(const Core::Frontend::SoftwareKeyboardParameters& parameters);
void SoftwareKeyboardInvokeCheckDialog(std::u16string error_message);
+ void WebBrowserOpenPage(std::string_view filename, std::string_view arguments);
private:
void InitializeWidgets();
@@ -126,6 +136,8 @@ private:
void ShowTelemetryCallout();
void SetDiscordEnabled(bool state);
+ void SelectAndSetCurrentUser();
+
/**
* Stores the filename in the recently loaded files list.
* The new filename is stored at the beginning of the recently loaded files list.
@@ -168,6 +180,7 @@ private slots:
void OnGameListCopyTID(u64 program_id);
void OnGameListNavigateToGamedbEntry(u64 program_id,
const CompatibilityList& compatibility_list);
+ void OnGameListOpenPerGameProperties(const std::string& file);
void OnMenuLoadFile();
void OnMenuLoadFolder();
void OnMenuInstallToNAND();
@@ -186,6 +199,7 @@ private slots:
void ShowFullscreen();
void HideFullscreen();
void ToggleWindowMode();
+ void OnCaptureScreenshot();
void OnCoreError(Core::System::ResultStatus, std::string);
void OnReinitializeKeys(ReinitializeKeyBehavior behavior);
@@ -199,6 +213,7 @@ private:
GRenderWindow* render_window;
GameList* game_list;
+ LoadingScreen* loading_screen;
// Status bar elements
QLabel* message_label = nullptr;
diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui
index 75e96387f..ffcabb495 100644
--- a/src/yuzu/main.ui
+++ b/src/yuzu/main.ui
@@ -101,11 +101,13 @@
<addaction name="action_Show_Status_Bar"/>
<addaction name="menu_View_Debugging"/>
</widget>
- <widget class ="QMenu" name="menu_Tools">
+ <widget class="QMenu" name="menu_Tools">
<property name="title">
<string>Tools</string>
</property>
- <addaction name="action_Rederive" />
+ <addaction name="action_Rederive"/>
+ <addaction name="separator"/>
+ <addaction name="action_Capture_Screenshot"/>
</widget>
<widget class="QMenu" name="menu_Help">
<property name="title">
@@ -118,7 +120,7 @@
<addaction name="menu_File"/>
<addaction name="menu_Emulation"/>
<addaction name="menu_View"/>
- <addaction name="menu_Tools" />
+ <addaction name="menu_Tools"/>
<addaction name="menu_Help"/>
</widget>
<action name="action_Install_File_NAND">
@@ -173,11 +175,11 @@
<string>&amp;Stop</string>
</property>
</action>
- <action name="action_Rederive">
- <property name="text">
- <string>Reinitialize keys...</string>
- </property>
- </action>
+ <action name="action_Rederive">
+ <property name="text">
+ <string>Reinitialize keys...</string>
+ </property>
+ </action>
<action name="action_About">
<property name="text">
<string>About yuzu</string>
@@ -252,39 +254,47 @@
<string>Fullscreen</string>
</property>
</action>
- <action name="action_Restart">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Restart</string>
- </property>
- </action>
+ <action name="action_Restart">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Restart</string>
+ </property>
+ </action>
<action name="action_Load_Amiibo">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Load Amiibo...</string>
- </property>
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Load Amiibo...</string>
+ </property>
</action>
- <action name="action_Report_Compatibility">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Report Compatibility</string>
- </property>
- <property name="visible">
- <bool>false</bool>
- </property>
- </action>
- <action name="action_Open_yuzu_Folder">
- <property name="text">
- <string>Open yuzu Folder</string>
- </property>
- </action>
- </widget>
+ <action name="action_Report_Compatibility">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Report Compatibility</string>
+ </property>
+ <property name="visible">
+ <bool>false</bool>
+ </property>
+ </action>
+ <action name="action_Open_yuzu_Folder">
+ <property name="text">
+ <string>Open yuzu Folder</string>
+ </property>
+ </action>
+ <action name="action_Capture_Screenshot">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Capture Screenshot</string>
+ </property>
+ </action>
+ </widget>
<resources/>
<connections/>
</ui>
diff --git a/src/yuzu/ui_settings.h b/src/yuzu/ui_settings.h
index e80aebc0a..82aaeedb0 100644
--- a/src/yuzu/ui_settings.h
+++ b/src/yuzu/ui_settings.h
@@ -10,6 +10,7 @@
#include <QByteArray>
#include <QString>
#include <QStringList>
+#include "common/common_types.h"
namespace UISettings {
@@ -39,11 +40,16 @@ struct Values {
bool confirm_before_closing;
bool first_start;
+ bool select_user_on_boot;
+
// Discord RPC
bool enable_discord_presence;
+ u16 screenshot_resolution_factor;
+
QString roms_path;
QString symbols_path;
+ QString screenshot_path;
QString gamedir;
bool gamedir_deepscan;
QStringList recent_files;
@@ -58,6 +64,9 @@ struct Values {
// logging
bool show_console;
+ // Controllers
+ int profile_index;
+
// Game List
bool show_unknown;
bool show_add_ons;
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index 097c1fbe3..7a77f76e8 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -3,6 +3,7 @@
// Refer to the license.txt file included.
#include <memory>
+#include <sstream>
#include <SDL.h>
#include <inih/cpp/INIReader.h>
#include "common/file_util.h"
@@ -324,13 +325,21 @@ void Config::ReadValues() {
Settings::values.current_user = std::clamp<int>(
sdl2_config->GetInteger("System", "current_user", 0), 0, Service::Account::MAX_USERS - 1);
- const auto enabled = sdl2_config->GetBoolean("System", "rng_seed_enabled", false);
- if (enabled) {
+ const auto rng_seed_enabled = sdl2_config->GetBoolean("System", "rng_seed_enabled", false);
+ if (rng_seed_enabled) {
Settings::values.rng_seed = sdl2_config->GetInteger("System", "rng_seed", 0);
} else {
Settings::values.rng_seed = std::nullopt;
}
+ const auto custom_rtc_enabled = sdl2_config->GetBoolean("System", "custom_rtc_enabled", false);
+ if (custom_rtc_enabled) {
+ Settings::values.custom_rtc =
+ std::chrono::seconds(sdl2_config->GetInteger("System", "custom_rtc", 0));
+ } else {
+ Settings::values.custom_rtc = std::nullopt;
+ }
+
// Core
Settings::values.use_cpu_jit = sdl2_config->GetBoolean("Core", "use_cpu_jit", true);
Settings::values.use_multi_core = sdl2_config->GetBoolean("Core", "use_multi_core", false);
@@ -369,6 +378,23 @@ void Config::ReadValues() {
Settings::values.dump_exefs = sdl2_config->GetBoolean("Debugging", "dump_exefs", false);
Settings::values.dump_nso = sdl2_config->GetBoolean("Debugging", "dump_nso", false);
+ const auto title_list = sdl2_config->Get("AddOns", "title_ids", "");
+ std::stringstream ss(title_list);
+ std::string line;
+ while (std::getline(ss, line, '|')) {
+ const auto title_id = std::stoul(line, nullptr, 16);
+ const auto disabled_list = sdl2_config->Get("AddOns", "disabled_" + line, "");
+
+ std::stringstream inner_ss(disabled_list);
+ std::string inner_line;
+ std::vector<std::string> out;
+ while (std::getline(inner_ss, inner_line, '|')) {
+ out.push_back(inner_line);
+ }
+
+ Settings::values.disabled_addons.insert_or_assign(title_id, out);
+ }
+
// Web Service
Settings::values.enable_telemetry =
sdl2_config->GetBoolean("WebService", "enable_telemetry", true);
diff --git a/src/yuzu_cmd/default_ini.h b/src/yuzu_cmd/default_ini.h
index d73669f36..ba51a4a51 100644
--- a/src/yuzu_cmd/default_ini.h
+++ b/src/yuzu_cmd/default_ini.h
@@ -183,6 +183,12 @@ enable_nfc =
rng_seed_enabled =
rng_seed =
+# Sets the current time (in seconds since 12:00 AM Jan 1, 1970) that will be used by the time service
+# This will auto-increment, with the time set being the time the game is started
+# This override will only occur if custom_rtc_enabled is true, otherwise the current time is used
+custom_rtc_enabled =
+custom_rtc =
+
# Sets the account username, max length is 32 characters
# yuzu (default)
username = yuzu
@@ -221,5 +227,12 @@ web_api_url = https://api.yuzu-emu.org
# See https://profile.yuzu-emu.org/ for more info
yuzu_username =
yuzu_token =
+
+[AddOns]
+# Used to disable add-ons
+# List of title IDs of games that will have add-ons disabled (separated by '|'):
+title_ids =
+# For each title ID, have a key/value pair called `disabled_<title_id>` equal to the names of the add-ons to disable (sep. by '|')
+# e.x. disabled_0100000000010000 = Update|DLC <- disables Updates and DLC on Super Mario Odyssey
)";
}
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
index 2d6f8cced..7df8eff53 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
@@ -111,6 +111,8 @@ void EmuWindow_SDL2::Fullscreen() {
bool EmuWindow_SDL2::SupportsRequiredGLExtensions() {
std::vector<std::string> unsupported_ext;
+ if (!GLAD_GL_ARB_direct_state_access)
+ unsupported_ext.push_back("ARB_direct_state_access");
if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
unsupported_ext.push_back("ARB_vertex_type_10f_11f_11f_rev");
if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
@@ -193,6 +195,7 @@ EmuWindow_SDL2::EmuWindow_SDL2(bool fullscreen) {
SDL_GL_SetSwapInterval(false);
LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch,
Common::g_scm_desc);
+ Settings::LogSettings();
DoneCurrent();
}