Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions agdk/agdktunnel/app/src/main/cpp/gfx_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -277,18 +277,14 @@ void GfxManager::CreateUniformBuffers() {
}

void GfxManager::DestroyRenderResources() {
Renderer& renderer = Renderer::GetInstance();
// Releasing the resources destroys them (deferred by the renderer); this doesn't need (or
// create) the renderer instance
for (int32_t i = kGfxType_BasicLines; i < kGfxType_Count; ++i) {
renderer.DestroyRenderState(mRenderStates[i]);
mRenderStates[i] = nullptr;
renderer.DestroyUniformBuffer(mUniformBuffers[i]);
mUniformBuffers[i] = nullptr;
}
renderer.DestroyShaderProgram(mTrivialShaderProgram);
mTrivialShaderProgram = nullptr;
renderer.DestroyShaderProgram(mOurShaderProgram);
mOurShaderProgram = nullptr;
renderer.DestroyRenderPass(mMainRenderPass);
mMainRenderPass = nullptr;
}

Expand Down
24 changes: 21 additions & 3 deletions agdk/agdktunnel/app/src/main/cpp/loader_scene.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class LoaderScene::TextureLoader {

LoadedTextureData _loadedTextures[MAX_ASSET_TEXTURES];

// The loader scene runs again on every return to the main menu: textures that are
// already loaded aren't read again
static bool IsTextureLoaded(const char *textureName) {
TextureManager *textureManager = TunnelEngine::GetInstance()->GetTextureManager();
return textureManager != NULL && textureManager->IsTextureLoaded(textureName);
}

public:
~TextureLoader() {
// Wait for any textures to finish loading so we don't accidentally call
Expand Down Expand Up @@ -114,9 +121,16 @@ class LoaderScene::TextureLoader {
const char **assetPackFiles = gameAssetManager->GetGameAssetPackFileList(assetPackName,
&assetPackFileCount);
if (assetPackFiles != NULL) {
_totalLoadCount += assetPackFileCount;
_remainingLoadCount += assetPackFileCount;
ALOGI("TextureLoader: found %d assets from pack %s", assetPackFileCount, assetPackName);
int toLoadCount = 0;
for (int i = 0; i < assetPackFileCount; ++i) {
if (!IsTextureLoaded(assetPackFiles[i])) {
++toLoadCount;
}
}
_totalLoadCount += toLoadCount;
_remainingLoadCount += toLoadCount;
ALOGI("TextureLoader: found %d assets from pack %s, %d to load", assetPackFileCount,
assetPackName, toLoadCount);
} else {
ALOGI("TextureLoader: could not retrieve the list from pack %s", assetPackName);
}
Expand All @@ -130,6 +144,10 @@ class LoaderScene::TextureLoader {
ALOGI("TextureLoader: loading textures from asset pack %s", assetPackName);
if (assetPackFiles != NULL) {
for (int i = 0; i < assetPackFileCount; ++i) {
if (IsTextureLoaded(assetPackFiles[i])) {
// Not counted by FindTexturesFromAssetPack
continue;
}
uint64_t fileSize = gameAssetManager->GetGameAssetSize(assetPackFiles[i]);
ALOGI("TextureLoader: the size of asset %s is %d",
assetPackFiles[i], (int)fileSize);
Expand Down
26 changes: 18 additions & 8 deletions agdk/agdktunnel/app/src/main/cpp/texture_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -257,10 +257,7 @@ TextureManager::TextureManager() {
}

TextureManager::~TextureManager() {
for (std::vector<TextureReference>::iterator iter = mTextures.begin(); iter != mTextures.end();
++iter) {
simple_renderer::Renderer::GetInstance().DestroyTexture(iter->mTextureReference);
}
// Releasing the textures destroys them (deferred by the renderer)
mTextures.clear();
}

Expand Down Expand Up @@ -295,6 +292,17 @@ bool TextureManager::LoadTexture(const char *textureName) {

bool TextureManager::CreateTexture(const char *textureName, const size_t textureSize,
const uint8_t *textureData) {
if (textureName == nullptr || textureData == nullptr) {
ALOGE("TextureManager: CreateTexture without a name or data");
free((void *) textureData);
return false;
}
if (IsTextureLoaded(textureName)) {
// Already loaded (e.g. the loader scene runs again when returning to the main menu):
// keep the existing texture instead of creating another copy
free((void *) textureData);
return true;
}
std::shared_ptr<simple_renderer::Texture> newTexture = nullptr;
const TextureFileFormat fileFormat = GetFileFormat(textureData, textureSize);

Expand Down Expand Up @@ -327,10 +335,12 @@ std::shared_ptr<simple_renderer::Texture> TextureManager::GetTexture(const char
}

TextureManager::TextureReference TextureManager::FindReferenceForName(const char *textureName) {
for (std::vector<TextureReference>::iterator iter = mTextures.begin();
iter != mTextures.end(); ++iter) {
if (strcmp(textureName, iter->mTextureName) == 0) {
return *iter;
if (textureName != nullptr) {
for (std::vector<TextureReference>::iterator iter = mTextures.begin();
iter != mTextures.end(); ++iter) {
if (iter->mTextureName == textureName) {
return *iter;
}
}
}
TextureManager::TextureReference emptyReference(0, NULL, nullptr);
Expand Down
7 changes: 5 additions & 2 deletions agdk/agdktunnel/app/src/main/cpp/texture_manager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "simple_renderer/renderer_texture.h"
#include "util.hpp"
Expand Down Expand Up @@ -65,10 +66,12 @@ class TextureManager {
const char *textureName,
std::shared_ptr<simple_renderer::Texture> textureReference) :
mTextureMipCount(textureMipCount),
mTextureName(textureName), mTextureReference(textureReference) {}
mTextureName(textureName != nullptr ? textureName : ""),
mTextureReference(textureReference) {}

uint32_t mTextureMipCount;
const char *mTextureName;
// A copy (the caller's name, e.g. an asset list entry, may not outlive the texture)
std::string mTextureName;
std::shared_ptr<simple_renderer::Texture> mTextureReference;
};

Expand Down
3 changes: 3 additions & 0 deletions agdk/common/base_game_framework/include/display_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,9 @@ class DisplayManager {
* @param frame_handle Handle to the specified swapchain
* @param frame_resources A reference to a `SwapchainFrameResourcesVk` structure to populate
* with swapchain frame resources related to rendering using Vulkan
* @param acquire_frame_image If true, wait for the frame's previous use to finish (its frame
* fence) and acquire its swapchain image. Fails if the image was already acquired and the frame
* not presented since (::PresentCurrentSwapchainFrame).
* @return True if resource information was successfully retrieved.
*/
bool GetSwapchainFrameResourcesVk(const SwapchainFrameHandle frame_handle,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,7 @@ DisplayManager::SwapchainFrameHandle GraphicsAPIGLES::PresentCurrentSwapchainFra

bool GraphicsAPIGLES::GetGraphicsAPIResourcesGLES(GraphicsAPIResourcesGLES& api_resources_gles) {
api_resources_gles.egl_context = egl_context_;
api_resources_gles.egl_display = egl_display_;
return (egl_context_ != EGL_NO_CONTEXT);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ namespace base_game_framework {

struct GraphicsAPIResourcesGLES {
EGLContext egl_context = EGL_NO_CONTEXT;
// The context's display (also valid while there is no surface, e.g. no window)
EGLDisplay egl_display = EGL_NO_DISPLAY;
};

struct SwapchainFrameResourcesGLES {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -757,8 +757,20 @@ bool GraphicsAPIVulkan::GetSwapchainFrameResourcesVk(
vk_device_ != VK_NULL_HANDLE && vk_swapchain_ != VK_NULL_HANDLE &&
swapchain_info_.swapchain_current_frame_index_ < in_flight_frame_fence_.size()) {

if (acquire_frame_image && swapchain_acquired_current_frame_image_) {
// This frame's image was already acquired (and maybe submitted) without being presented:
// acquiring again would skip the wait for the frame fence, so the caller could reuse the
// frame's resources while the GPU still uses them
DebugManager::Log(DebugManager::kLog_Channel_Default,
DebugManager::kLog_Level_Error,
BGM_CLASS_TAG,
"GetSwapchainFrameResourcesVk: the current frame's image was already "
"acquired, present it first");
return false;
}

// If we haven't acquired the image for this frame, do it now
if (!swapchain_acquired_current_frame_image_ && acquire_frame_image) {
if (acquire_frame_image) {
vkWaitForFences(vk_device_, 1,
&in_flight_frame_fence_[swapchain_info_.swapchain_current_frame_index_],
VK_TRUE, UINT64_MAX);
Expand Down Expand Up @@ -819,6 +831,7 @@ bool GraphicsAPIVulkan::GetSwapchainFrameResourcesVk(
frame_resources.swapchain_extent = swapchain_info_.swapchain_extent_;
frame_resources.swapchain_frame_index = swapchain_info_.swapchain_current_frame_index_;
frame_resources.swapchain_image_index = swapchain_info_.swapchain_current_image_index_;
frame_resources.swapchain_frame_count = swapchain_info_.swapchain_frame_count_;
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ struct SwapchainFrameResourcesVk {
VkFormat swapchain_depth_stencil_format = VK_FORMAT_UNDEFINED;
uint32_t swapchain_frame_index = 0;
uint32_t swapchain_image_index = 0;
// Frames in flight (frame indices are below it), fixed for the swapchain's lifetime
uint32_t swapchain_frame_count = 0;
};

} // namespace base_game_framework
Expand Down
37 changes: 20 additions & 17 deletions agdk/common/simple_renderer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ required by the Android Baseline Profile for Vulkan.

### Resources

Each render resource in SimpleRenderer has an associated class. Creation and destruction of resource
objects is done through the Renderer interface instead of calling resource constructors or
destructors directly. The resource classes are:
Each render resource in SimpleRenderer has an associated class. Resource objects are created
through the Renderer interface instead of calling resource constructors directly, and destroyed
when the last shared pointer to them is released. The resource classes are:

* IndexBuffer
* UniformBuffer
Expand Down Expand Up @@ -100,25 +100,28 @@ parameter to a creation parameters structure specific to each resource type:
const VertexBuffer::VertexBufferCreationParams& params) = 0;
```

With one exception, data pointers in a `...CreationParams` struct are not referenced post-creation
and are not required to persist after return from the `Create...` call.

The exception is the pointer specified by the `element_array` field in the
`UniformBufferCreationParams` structure. The data associated with that pointer will be referenced
and must persist until after destruction of the `UniformBuffer` object.
Data pointers in a `...CreationParams` struct are not referenced post-creation and are not
required to persist after return from the `Create...` call (a `UniformBuffer` copies its
`element_array`).

#### Resource destruction

The renderer has `Destroy...` calls for each resource type. The destroy calls take the shared
pointer to the resource object as a parameter. The caller should not retain any additional
references to the shared pointer after calling the destroy function.
A resource is destroyed when the last shared pointer to it is released (the `Create...` calls
return a shared pointer with a custom deleter). Destruction is deferred until it is safe:

* Vulkan: until every frame that was in flight when the resource was released has finished
executing on the GPU, so a resource can be released right after its last draw call.
* OpenGL ES: until the next render frame (Renderer::BeginFrame), when the context is current.

Remaining deferred destructions happen when the swapchain is recreated (Vulkan) and when the
renderer instance is shut down. Release all pointers to a renderer's resources before shutting it
down: a resource released after shutdown can't be destroyed (its device or context is gone), and is
leaked with an error. Resources still referenced at shutdown are logged.

Resources are not immediately deleted, but placed in a pending deletion queue. The queue is emptied
at the beginning of each render frame (during the call to Renderer::BeginFrame) or when the
renderer instance is shutdown.
The `Destroy...` calls are optional and do nothing; they are kept for compatibility.

In debug mode, the renderer will assert if there are additional references being held to the
shared pointer when destructing the resources.
Resources hold references to the resources they use (e.g. a `RenderState` to its
`ShaderProgram` and `UniformBuffer`), so those live at least as long.

#### Resource dependencies

Expand Down
72 changes: 39 additions & 33 deletions agdk/common/simple_renderer/renderer_gles.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ namespace simple_renderer {
static const char *kAstcExtensionString = "GL_OES_texture_compression_astc";

RendererGLES::RendererGLES() :
// GL keeps objects used by queued commands alive until they are done, so released
// resources are deleted at the next frame (with the context current) without frame tracking
resources_(0),
swapchain_handle_(Renderer::GetSwapchainHandle()),
frame_active_(false),
egl_context_(EGL_NO_CONTEXT),
Expand All @@ -51,26 +54,57 @@ void RendererGLES::RefreshEGLResources() {
// context with the swapchain), so don't keep using handles from an earlier frame
DisplayManager& display_manager = DisplayManager::GetInstance();
GraphicsAPIResourcesGLES graphics_api_resources_gles;
egl_context_ = display_manager.GetGraphicsAPIResourcesGLES(graphics_api_resources_gles) ?
graphics_api_resources_gles.egl_context : EGL_NO_CONTEXT;
if (display_manager.GetGraphicsAPIResourcesGLES(graphics_api_resources_gles)) {
egl_context_ = graphics_api_resources_gles.egl_context;
egl_display_ = graphics_api_resources_gles.egl_display;
} else {
egl_context_ = EGL_NO_CONTEXT;
egl_display_ = EGL_NO_DISPLAY;
}
SwapchainFrameResourcesGLES swapchain_frame_resources_gles;
const base_game_framework::DisplayManager::SwapchainFrameHandle frame_handle =
display_manager.GetCurrentSwapchainFrame(swapchain_handle_);
if (display_manager.GetSwapchainFrameResourcesGLES(frame_handle,
swapchain_frame_resources_gles)) {
egl_display_ = swapchain_frame_resources_gles.egl_display;
egl_surface_ = swapchain_frame_resources_gles.egl_surface;
} else {
// No valid swapchain (e.g. no window)
egl_display_ = EGL_NO_DISPLAY;
egl_surface_ = EGL_NO_SURFACE;
}
}

void RendererGLES::PrepareShutdown() {
render_pass_ = nullptr;
render_state_ = nullptr;
resources_.ProcessDeleteQueue();
// GL objects can only be deleted with their context current, and the window (with the
// surface) may already be gone, e.g. when the Activity finishes (APP_CMD_TERM_WINDOW comes
// before APP_CMD_DESTROY). Make the context current, without a surface then
// (EGL_KHR_surfaceless_context). Resources whose context isn't current skip their GL
// deletes (see IsGLESContextCurrent): they are deleted with their context.
const EGLDisplay previous_display = eglGetCurrentDisplay();
const EGLSurface previous_draw = eglGetCurrentSurface(EGL_DRAW);
const EGLSurface previous_read = eglGetCurrentSurface(EGL_READ);
const EGLContext previous_context = eglGetCurrentContext();
RefreshEGLResources();
bool made_current = false;
if (egl_context_ != EGL_NO_CONTEXT && egl_display_ != EGL_NO_DISPLAY) {
made_current = (eglMakeCurrent(egl_display_, egl_surface_, egl_surface_, egl_context_) ==
EGL_TRUE);
if (!made_current) {
RENDERER_ERROR("PrepareShutdown: eglMakeCurrent failed: 0x%x, GL objects are left to "
"the context", eglGetError());
}
}
resources_.Shutdown("Renderer shutdown");
// Leave the previously current context (or none) current
if (made_current && (previous_context != egl_context_ || previous_draw != egl_surface_ ||
previous_read != egl_surface_)) {
if (previous_context == EGL_NO_CONTEXT) {
eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
} else {
eglMakeCurrent(previous_display, previous_draw, previous_read, previous_context);
}
}
}

bool RendererGLES::GetFeatureAvailable(const RendererFeature feature) {
Expand Down Expand Up @@ -276,61 +310,33 @@ std::shared_ptr<IndexBuffer> RendererGLES::CreateIndexBuffer(
return resources_.AddIndexBuffer(new IndexBufferGLES(params));
}

void RendererGLES::DestroyIndexBuffer(std::shared_ptr<IndexBuffer> index_buffer) {
resources_.QueueDeleteIndexBuffer(index_buffer);
}

std::shared_ptr<RenderPass> RendererGLES::CreateRenderPass(
const RenderPass::RenderPassCreationParams& params) {
return resources_.AddRenderPass(new RenderPassGLES(params));
}

void RendererGLES::DestroyRenderPass(std::shared_ptr<RenderPass> render_pass) {
resources_.QueueDeleteRenderPass(render_pass);
}

std::shared_ptr<RenderState> RendererGLES::CreateRenderState(
const RenderState::RenderStateCreationParams& params) {
return resources_.AddRenderState(new RenderStateGLES(params));
}

void RendererGLES::DestroyRenderState(std::shared_ptr<RenderState> render_state) {
resources_.QueueDeleteRenderState(render_state);
}

std::shared_ptr<ShaderProgram> RendererGLES::CreateShaderProgram(
const ShaderProgram::ShaderProgramCreationParams& params) {
return resources_.AddShaderProgram(new ShaderProgramGLES(params));
}

void RendererGLES::DestroyShaderProgram(std::shared_ptr<ShaderProgram> shader_program) {
resources_.QueueDeleteShaderProgram(shader_program);
}

std::shared_ptr<Texture> RendererGLES::CreateTexture(const Texture::TextureCreationParams& params) {
return resources_.AddTexture(new TextureGLES(params));
}

void RendererGLES::DestroyTexture(std::shared_ptr<Texture> texture) {
resources_.QueueDeleteTexture(texture);
}

std::shared_ptr<UniformBuffer> RendererGLES::CreateUniformBuffer(
const UniformBuffer::UniformBufferCreationParams& params) {
return resources_.AddUniformBuffer(new UniformBufferGLES(params));
}

void RendererGLES::DestroyUniformBuffer(std::shared_ptr<UniformBuffer> uniform_buffer) {
resources_.QueueDeleteUniformBuffer(uniform_buffer);
}

std::shared_ptr<VertexBuffer> RendererGLES::CreateVertexBuffer(
const VertexBuffer::VertexBufferCreationParams& params) {
return resources_.AddVertexBuffer(new VertexBufferGLES(params));
}

void RendererGLES::DestroyVertexBuffer(std::shared_ptr<VertexBuffer> vertex_buffer) {
resources_.QueueDeleteVertexBuffer(vertex_buffer);
}

}
Loading