| 97 | } |
| 98 | |
| 99 | void AsyncTextureLoader::runWorker() |
| 100 | { |
| 101 | // This function is the entry point for worker threads. |
| 102 | // The workers wait on the load request queue and load a texture when woken up. |
| 103 | // To avoid the upload heap growing too large, we synchronize the threads and |
| 104 | // issue a global GPU flush at regular intervals. |
| 105 | |
| 106 | while (true) |
| 107 | { |
| 108 | // Wait on condition until more work is ready. |
| 109 | std::unique_lock<std::mutex> lock(mMutex); |
| 110 | mCondition.wait(lock, [&]() { return mTerminate || !mLoadRequestQueue.empty() || mFlushPending; }); |
| 111 | |
| 112 | // Sync thread if a flush is pending. |
| 113 | if (mFlushPending) |
| 114 | { |
| 115 | lock.unlock(); |
| 116 | mFlushBarrier->wait(); |
| 117 | mCondition.notify_one(); |
| 118 | continue; |
| 119 | } |
| 120 | |
| 121 | // Terminate thread unless there is more work to do. |
| 122 | if (mTerminate && mLoadRequestQueue.empty() && !mFlushPending) |
| 123 | break; |
| 124 | |
| 125 | // Go back waiting if queue is currently empty. |
| 126 | if (mLoadRequestQueue.empty()) |
| 127 | continue; |
| 128 | |
| 129 | // Pop next load request from queue. |
| 130 | auto request = std::move(mLoadRequestQueue.front()); |
| 131 | mLoadRequestQueue.pop(); |
| 132 | |
| 133 | lock.unlock(); |
| 134 | |
| 135 | // Load the textures (this part is running in parallel). |
| 136 | ref<Texture> pTexture; |
| 137 | if (request.paths.size() == 1) |
| 138 | { |
| 139 | pTexture = Texture::createFromFile( |
| 140 | mpDevice, request.paths[0], request.generateMipLevels, request.loadAsSRGB, request.bindFlags, request.importFlags |
| 141 | ); |
| 142 | } |
| 143 | else |
| 144 | { |
| 145 | pTexture = Texture::createMippedFromFiles(mpDevice, request.paths, request.loadAsSRGB, request.bindFlags, request.importFlags); |
| 146 | } |
| 147 | |
| 148 | request.promise.set_value(pTexture); |
| 149 | |
| 150 | if (request.callback) |
| 151 | { |
| 152 | request.callback(pTexture); |
| 153 | } |
| 154 | |
| 155 | lock.lock(); |
| 156 | |