| 16 | namespace ktx |
| 17 | { |
| 18 | class texture |
| 19 | { |
| 20 | private: |
| 21 | texture(ktxTexture* ptr) |
| 22 | : m_ptr{ ptr, &destroy } |
| 23 | { |
| 24 | } |
| 25 | |
| 26 | texture() : m_ptr{ nullptr, &destroy } |
| 27 | { |
| 28 | } |
| 29 | |
| 30 | texture(ktxTexture2* ptr) |
| 31 | : m_ptr{ reinterpret_cast<ktxTexture*>(ptr), &destroy } |
| 32 | { |
| 33 | } |
| 34 | |
| 35 | static void destroy(ktxTexture* ptr) |
| 36 | { |
| 37 | ktxTexture_Destroy(ptr); |
| 38 | } |
| 39 | |
| 40 | std::unique_ptr<ktxTexture, decltype(&destroy)> m_ptr; |
| 41 | |
| 42 | public: |
| 43 | operator ktxTexture2*() const { |
| 44 | return reinterpret_cast<ktxTexture2*>(m_ptr.get()); |
| 45 | } |
| 46 | |
| 47 | bool isTexture2() const { |
| 48 | return (m_ptr->classId == ktxTexture2_c); |
| 49 | |
| 50 | } |
| 51 | |
| 52 | texture(texture&&) = default; |
| 53 | |
| 54 | texture(const val& data) : m_ptr{ nullptr, &destroy } |
| 55 | { |
| 56 | std::vector<uint8_t> bytes{}; |
| 57 | bytes.resize(data["byteLength"].as<size_t>()); |
| 58 | val memory = emscripten::val::module_property("HEAP8")["buffer"]; |
| 59 | val memoryView = data["constructor"].new_(memory, reinterpret_cast<uintptr_t>(bytes.data()), data["length"].as<uint32_t>()); |
| 60 | // Yes, this code IS copying the data. Sigh! According to Alon |
| 61 | // Zakai: |
| 62 | // "There isn't a way to let compiled code access a new |
| 63 | // ArrayBuffer. The compiled code has hardcoded access to the |
| 64 | // wasm Memory it was instantiated with - all the pointers it |
| 65 | // can understand are indexes into that Memory. It can't refer |
| 66 | // to anything else, I'm afraid." |
| 67 | // |
| 68 | // "In the future using different address spaces or techniques |
| 69 | // with reference types may open up some possibilities here." |
| 70 | memoryView.call<void>("set", data); |
| 71 | |
| 72 | // Load the image data now, otherwise we'd have to copy it from |
| 73 | // JS into a buffer only for it to be copied from that buffer into |
| 74 | // the texture later. |
| 75 | ktxTexture* ptr = nullptr; |