ysfx_gmem.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #pragma once
  2. #include "ysfx_gmem.hpp"
  3. #include "WDL/eel2/ns-eel.h"
  4. #include <unordered_map>
  5. #include <mutex>
  6. namespace
  7. {
  8. struct gmem_context
  9. {
  10. ~gmem_context()
  11. {
  12. NSEEL_VM_FreeGRAM(&ctx);
  13. }
  14. std::size_t refcount = 1;
  15. void* ctx = nullptr;
  16. };
  17. std::unordered_map<std::string, std::unique_ptr<gmem_context>> gmem_registry;
  18. std::mutex gmem_registry_mutex;
  19. }
  20. static void** acquire_gmem(std::string_view name)
  21. {
  22. std::lock_guard lock(gmem_registry_mutex);
  23. std::string key(name);
  24. auto it = gmem_registry.find(key);
  25. if (it == gmem_registry.end())
  26. {
  27. auto [new_it, _] = gmem_registry.emplace(key, std::make_unique<gmem_context>());
  28. return &new_it->second->ctx;
  29. }
  30. ++it->second->refcount;
  31. return &it->second->ctx;
  32. }
  33. static void release_gmem(std::string_view name)
  34. {
  35. std::lock_guard lock(gmem_registry_mutex);
  36. auto it = gmem_registry.find(std::string(name));
  37. if (it == gmem_registry.end())
  38. {
  39. // Double detach somehow? Should probably log this.
  40. return;
  41. }
  42. if (--it->second->refcount == 0)
  43. gmem_registry.erase(it);
  44. }
  45. void ysfx_gmem_detach(ysfx_t* fx)
  46. {
  47. if (fx->gmem_name.empty())
  48. return;
  49. NSEEL_VM_SetGRAM(fx->vm.get(), nullptr);
  50. release_gmem(fx->gmem_name);
  51. fx->gmem_name.clear();
  52. }
  53. void ysfx_gmem_attach(ysfx_t* fx, std::string_view name)
  54. {
  55. if (fx->gmem_name == name)
  56. return;
  57. ysfx_gmem_detach(fx);
  58. if (name.empty())
  59. {
  60. NSEEL_VM_SetGRAM(fx->vm.get(), nullptr);
  61. return;
  62. }
  63. void** ctx = acquire_gmem(name);
  64. NSEEL_VM_SetGRAM(fx->vm.get(), ctx);
  65. fx->gmem_name = name;
  66. }
  67. std::string get_gmem_identifier(ysfx_t* fx)
  68. {
  69. return fx->gmem_name;
  70. }
  71. void** get_gmem_address(ysfx_t* fx)
  72. {
  73. std::lock_guard lock(gmem_registry_mutex);
  74. std::string name = fx->gmem_name;
  75. if (name.empty())
  76. return nullptr;
  77. auto it = gmem_registry.find(std::string(name));
  78. if (it == gmem_registry.end())
  79. return nullptr;
  80. else
  81. return &it->second->ctx;
  82. }