Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ResourceManagerBindings.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3
5#include "BoundarySpan.hpp"
8#include "../core/Types.hpp"
9#include "../core/Log.hpp"
10
11// Not under the emscripten guard below: this TU compiles for native too, and the
12// device is what `rm_supportsCompressedFormat` asks — a forward declaration
13// reaches its members on neither target.
15
16#ifdef __EMSCRIPTEN__
17#include <emscripten/val.h>
18#endif
19
20namespace esengine {
21
22namespace {
23
30TextureFormat boundaryTextureFormat(i32 format) {
31 if (format == 0) return TextureFormat::RGB8;
32 return format == 2 ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8;
33}
34
37void applySamplingCodes(TextureSpecification& spec, i32 filterMode, i32 wrapMode) {
38 const bool coded = filterMode >= 0;
39 spec.generateMips = coded && (filterMode & 2) != 0;
40 spec.minFilter = (coded && (filterMode & 1) == 0) ? TextureFilter::Nearest : TextureFilter::Linear;
41 spec.magFilter = spec.minFilter;
42
43 switch (wrapMode) {
44 case 0: spec.wrapS = TextureWrap::Repeat; spec.wrapT = TextureWrap::Repeat; break;
45 case 1: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
46 case 2: spec.wrapS = TextureWrap::MirroredRepeat; spec.wrapT = TextureWrap::MirroredRepeat; break;
47 default: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
48 }
49}
50
51} // namespace
52
54 uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY, u32 content) {
55 const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTexture");
56 if (!pixels) return 0;
57 ConstSpan<u8> pixelSpan(pixels, pixelsLen);
58
59 auto handle = rm.createTexture(static_cast<resource::ResourceContent>(content), width, height,
60 pixelSpan, boundaryTextureFormat(format), flipY);
61 return handle.id();
62}
63
65 uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY,
66 i32 filterMode, i32 wrapMode, u32 content) {
67 const u8* pixels = pixelsPtr ? boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTextureEx") : nullptr;
68 if (pixelsPtr && !pixels) return 0;
69
70 const TextureFormat texFormat = boundaryTextureFormat(format);
71
73 spec.width = width;
74 spec.height = height;
75 spec.format = texFormat;
76 applySamplingCodes(spec, filterMode, wrapMode);
77
78 auto handle = rm.createTexture(static_cast<resource::ResourceContent>(content), spec);
79 if (!handle.isValid()) {
80 return 0;
81 }
82
83 auto* texture = rm.getTexture(handle);
84 if (texture && pixels) {
85 const u64 required = static_cast<u64>(width) * height * (texFormat == TextureFormat::RGB8 ? 3 : 4);
86 if (pixelsLen < required) {
87 ES_LOG_ERROR("rm_createTextureEx: pixel buffer {} < required {}; upload skipped",
88 pixelsLen, required);
89 } else {
90 texture->setDataRaw(pixels, static_cast<u32>(required), flipY);
91 }
92 }
93
94 return handle.id();
95}
96
98 uintptr_t pixelsPtr, u32 pixelsLen, i32 format,
99 i32 filterMode, i32 wrapMode, u32 content) {
100 const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTextureArray");
101 if (!pixels) return 0;
103 spec.width = width;
104 spec.height = height;
105 spec.layers = layers;
107 applySamplingCodes(spec, filterMode, wrapMode);
108 auto handle = rm.createTextureArray(static_cast<resource::ResourceContent>(content), spec,
109 ConstSpan<u8>(pixels, pixelsLen));
110 return handle.id();
111}
112
119 auto* device = rm.device();
120 if (!device) return false;
121 if (format < 0 || format > static_cast<i32>(GfxCompressedFormat::S3TC_DXT5_SRGB)) return false;
122 return device->supportsCompressedFormat(static_cast<GfxCompressedFormat>(format));
123}
124
127 i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels, u32 content) {
128 if (format < 0 || format > static_cast<i32>(GfxCompressedFormat::S3TC_DXT5_SRGB)) return 0;
129 const u8* data = boundarySpan<u8>(dataPtr, dataLen, "rm_createCompressedTexture");
130 if (!data) return 0;
131 auto handle = rm.createCompressedTexture(static_cast<resource::ResourceContent>(content), width, height,
132 static_cast<GfxCompressedFormat>(format),
133 ConstSpan<u8>(data, dataLen),
134 mipLevels ? mipLevels : 1);
135 return handle.id();
136}
137
139 const std::string& vertSrc, const std::string& fragSrc) {
140 auto handle = rm.createShader(vertSrc, fragSrc);
141 return handle.id();
142}
143
145 u32 width, u32 height, u32 content) {
146 auto handle = rm.registerExternalTexture(static_cast<resource::ResourceContent>(content),
147 glTextureId, width, height);
148 return handle.id();
149}
150
152 return rm.wrapDeviceTexture(TextureHandle{textureId}, width, height).id();
153}
154
158
162
166
170
172 // One crossing: a loss owes every sourced texture at once, so a call per
173 // handle is a call per texture.
174 std::string out;
175 for (const auto& owed : rm.texturesAwaitingReupload()) {
176 if (!out.empty()) out += '\n';
177 out += std::to_string(owed.handle.id());
178 out += '|';
179 out += std::to_string(static_cast<u32>(owed.content));
180 out += '|';
181 out += rm.getTexturePath(owed.handle);
182 }
183 return out;
184}
185
187 std::string out;
189 if (!out.empty()) out += ',';
190 out += std::to_string(handle.id());
191 }
192 return out;
193}
194
196 std::string out;
197 for (const auto& row : rm.meshRealizations()) {
198 if (!out.empty()) out += ',';
199 out += std::to_string(row.handle);
200 out += ':';
201 out += row.realized ? '1' : '0';
202 }
203 return out;
204}
205
207 u32 width, u32 height, u32 bytes, u32 content) {
208 auto handle = rm.registerExternalTexture(static_cast<resource::ResourceContent>(content),
209 glTextureId, width, height, static_cast<usize>(bytes));
210 return handle.id();
211}
212
216
220
221void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, const std::string& path) {
223}
224
226 rm.setTextureBudget(static_cast<usize>(bytes));
227}
228
230 rm.setRetainedBudget(static_cast<usize>(bytes));
231}
232
234 return rm.acquireTextureByPath(path).id();
235}
236
237bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string& path) {
238 return rm.invalidateTexturePath(path);
239}
240
242 return static_cast<u32>(rm.trimTextureCache());
243}
244
245#ifdef __EMSCRIPTEN__
246emscripten::val rm_getResourceStats(resource::ResourceManager& rm) {
247 const auto st = rm.getStats();
248 auto result = emscripten::val::object();
249 result.set("shaderCount", static_cast<f64>(st.shaderCount));
250 result.set("textureCount", static_cast<f64>(st.textureCount));
251 result.set("vertexBufferCount", static_cast<f64>(st.vertexBufferCount));
252 result.set("indexBufferCount", static_cast<f64>(st.indexBufferCount));
253 result.set("cacheHits", static_cast<f64>(st.cacheHits));
254 result.set("cacheMisses", static_cast<f64>(st.cacheMisses));
255 result.set("textureBytes", static_cast<f64>(st.textureBytes));
256 result.set("textureBudget", static_cast<f64>(st.textureBudget));
257 result.set("textureEvictableCount", static_cast<f64>(st.textureEvictableCount));
258 result.set("retainedBytes", static_cast<f64>(st.retainedBytes));
259 return result;
260}
261#endif // __EMSCRIPTEN__
262
266
270
272 auto* tex = rm.getTexture(resource::TextureHandle(handleId));
273 return tex ? tex->getId() : 0;
274}
275
276#ifdef __EMSCRIPTEN__
277emscripten::val rm_getTextureDimensions(resource::ResourceManager& rm, u32 handleId) {
278 auto* tex = rm.getTexture(resource::TextureHandle(handleId));
279 if (!tex) {
280 return emscripten::val::null();
281 }
282 auto result = emscripten::val::object();
283 result.set("width", tex->getWidth());
284 result.set("height", tex->getHeight());
285 return result;
286}
287#endif // __EMSCRIPTEN__
288
289#ifdef ES_ENABLE_BITMAP_TEXT
290u32 rm_loadBitmapFont(resource::ResourceManager& rm, const std::string& fntContent,
291 u32 textureHandle, u32 texWidth, u32 texHeight) {
292 auto handle = rm.createBitmapFont(fntContent,
293 resource::TextureHandle(textureHandle), texWidth, texHeight);
294 return handle.id();
295}
296
297u32 rm_createLabelAtlasFont(resource::ResourceManager& rm, u32 textureHandle,
298 u32 texWidth, u32 texHeight, const std::string& chars,
299 u32 charWidth, u32 charHeight) {
300 auto handle = rm.createLabelAtlasFont(
301 resource::TextureHandle(textureHandle), texWidth, texHeight,
302 chars, charWidth, charHeight);
303 return handle.id();
304}
305
306void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId) {
307 rm.releaseBitmapFont(resource::BitmapFontHandle(handleId));
308}
309
310u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId) {
311 return rm.getBitmapFontRefCount(resource::BitmapFontHandle(handleId));
312}
313
314#ifdef __EMSCRIPTEN__
315emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,
316 const std::string& text, f32 fontSize, f32 spacing) {
317 auto* font = rm.getBitmapFont(resource::BitmapFontHandle(fontHandle));
318 if (!font) {
319 auto result = emscripten::val::object();
320 result.set("width", 0);
321 result.set("height", 0);
322 return result;
323 }
324 auto metrics = font->measureText(text, fontSize, spacing);
325 auto result = emscripten::val::object();
326 result.set("width", metrics.width);
327 result.set("height", metrics.height);
328 return result;
329}
330#endif // __EMSCRIPTEN__
331#endif // ES_ENABLE_BITMAP_TEXT
332
334 u32 x, u32 y, u32 width, u32 height,
335 uintptr_t pixelsPtr, u32 pixelsLen) {
336 auto* tex = rm.getTexture(resource::TextureHandle(handleId));
337 if (!tex) return;
338 // Sub-region pixels must already match the texture's format (RGBA8 atlas);
339 // updateSubRegion bounds-checks the rect + buffer size internally.
340 const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_updateTextureSubregion");
341 if (!pixels) return;
342 tex->updateSubRegion(x, y, width, height, pixels, pixelsLen, /*flipY=*/false);
343}
344
346 f32 left, f32 right, f32 top, f32 bottom) {
348 metadata.sliceBorder.left = left;
349 metadata.sliceBorder.right = right;
350 metadata.sliceBorder.top = top;
351 metadata.sliceBorder.bottom = bottom;
352 rm.setTextureMetadata(resource::TextureHandle(handleId), metadata);
353}
354
355} // namespace esengine
356
Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Texture metadata structures for nine-slice and other settings.
Core type definitions and utilities for ESEngine.
virtual bool supportsCompressedFormat(GfxCompressedFormat format)=0
Reports whether the backend can sample the given compressed format.
u32 getId() const
Gets the texture handle's raw value, for command payloads and the WASM boundary.
Definition Texture.hpp:236
IdType id() const
Gets the packed identifier (index + generation).
Definition Handle.hpp:85
Central manager for GPU resources.
Texture * getTexture(TextureHandle handle)
Gets a texture by handle.
u32 getTextureRefCount(TextureHandle handle) const
Gets the current reference count for a texture.
u32 textureNativeId(TextureHandle handle) const
The backend's own name for a texture's object, for a host that writes its pixels itself; 0 when there...
void forgoTextureContent(TextureHandle handle)
Gives up on an owed texture's content: it keeps blank storage.
const std::string & getTexturePath(TextureHandle handle) const
Gets the cached path for a texture.
void registerTextureWithPath(TextureHandle handle, const std::string &path)
Registers a texture with a path for cache lookup.
std::vector< OwedTexture > texturesAwaitingReupload() const
std::vector< MeshHandle > meshesAwaitingRematerialization() const
Replayable meshes whose geometry the device is still waiting for.
TextureHandle createTextureArray(ResourceContent content, const TextureSpecification &spec, ConstSpan< u8 > pixels)
Creates a 2D texture array from spec.layers same-size RGBA8 (or SRGB8A8) layers.
TextureHandle wrapDeviceTexture(::esengine::TextureHandle texture, u32 width, u32 height)
Names a texture the device holds for another owner (a render target's colour plane) by a resource han...
void releaseShader(ShaderHandle handle)
Releases a shader (decrements ref count).
TextureHandle createCompressedTexture(ResourceContent content, u32 width, u32 height, GfxCompressedFormat format, ConstSpan< u8 > data, u32 mipLevels=1)
Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading the pre-compressed blocks for mip...
ShaderHandle createShader(const std::string &vertSrc, const std::string &fragSrc, bool rewriteLoose=true, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
u32 getShaderRefCount(ShaderHandle handle) const
Gets the current reference count for a shader.
std::vector< MeshRealization > meshRealizations()
Every live mesh, for a recovery criterion to read.
void restoreTextureContent(TextureHandle handle)
Settles an owed texture whose provider wrote the pixels itself.
bool adoptTextureContent(TextureHandle target, TextureHandle source)
Moves a freshly loaded texture's pixels behind an owed handle.
bool invalidateTexturePath(const std::string &path)
Severs a path's texture-cache identity (hot reload). The next acquireTextureByPath for it misses,...
TextureHandle createTexture(ResourceContent content, const TextureSpecification &spec)
Creates a texture from specification.
void setTextureMetadata(TextureHandle handle, const TextureMetadata &metadata)
Sets metadata for a texture.
void setRetainedBudget(usize bytes)
See GfxDevice::setRetainedBudget.
void releaseTexture(TextureHandle handle)
Releases a texture (decrements ref count).
TextureHandle registerExternalTexture(ResourceContent content, u32 glTextureId, u32 width, u32 height, usize bytes=0)
Registers an externally-created GL texture.
usize trimTextureCache()
Frees every evictable cached texture now (memory pressure). Held textures and the budget are untouche...
void setTextureBudget(usize bytes)
Sets the texture pool's resident-byte budget (0 = no eviction). Over budget, refCount==0 textures are...
TextureHandle acquireTextureByPath(const std::string &path)
Reuses a cached texture by its build path: returns its handle with an added reference (reviving an ev...
ResourceContent
Who refills a resource's GPU content after a device loss.
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::text::BitmapFont > BitmapFontHandle
Handle to a bitmap font resource.
Definition Handle.hpp:238
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
Definition Handle.hpp:226
u32 rm_createTexture(resource::ResourceManager &rm, u32 width, u32 height, uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY, u32 content)
u32 rm_registerExternalTextureSized(resource::ResourceManager &rm, u32 glTextureId, u32 width, u32 height, u32 bytes, u32 content)
std::string rm_texturesAwaitingReupload(resource::ResourceManager &rm)
The textures the device is waiting for content for, as handle|content|path lines.
u32 rm_createTextureArray(resource::ResourceManager &rm, u32 width, u32 height, u32 layers, uintptr_t pixelsPtr, u32 pixelsLen, i32 format, i32 filterMode, i32 wrapMode, u32 content)
const T * boundarySpan(uintptr_t ptr, u64 count, const char *what)
Validates a JS-supplied pointer to count elements of T and returns it typed.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
@ MirroredRepeat
Tile with mirroring.
Definition GfxEnums.hpp:65
@ Repeat
Tile the texture.
Definition GfxEnums.hpp:63
@ ClampToEdge
Clamp to edge pixels.
Definition GfxEnums.hpp:64
std::string rm_meshesAwaitingRemat(resource::ResourceManager &rm)
Replayable meshes still owed their geometry, as comma-separated handle ids. No path: the engine never...
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
void rm_setTextureBudget(resource::ResourceManager &rm, u32 bytes)
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
bool rm_invalidateTexturePath(resource::ResourceManager &rm, const std::string &path)
void rm_releaseTexture(resource::ResourceManager &rm, u32 handleId)
u32 rm_getShaderRefCount(resource::ResourceManager &rm, u32 handleId)
void rm_setRetainedBudget(resource::ResourceManager &rm, u32 bytes)
u32 rm_registerExternalTexture(resource::ResourceManager &rm, u32 glTextureId, u32 width, u32 height, u32 content)
void rm_restoreTextureContent(resource::ResourceManager &rm, u32 handle)
@ Linear
Bilinear interpolation (smooth).
Definition GfxEnums.hpp:59
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
void rm_releaseShader(resource::ResourceManager &rm, u32 handleId)
TextureFormat
Texture pixel format.
Definition Texture.hpp:45
@ RGB8
3 channels, 8 bits each (24 bpp)
Definition Texture.hpp:47
@ SRGB8A8
sRGB-encoded RGBA8: hardware-linearized on sample (32 bpp)
Definition Texture.hpp:49
@ RGBA8
4 channels, 8 bits each (32 bpp)
Definition Texture.hpp:48
bool rm_supportsCompressedFormat(resource::ResourceManager &rm, i32 format)
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
@ S3TC_DXT5_SRGB
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT (extension).
Definition GfxEnums.hpp:335
u32 rm_getTextureRefCount(resource::ResourceManager &rm, u32 handleId)
u32 rm_getTextureGLId(resource::ResourceManager &rm, u32 handleId)
void rm_setTextureMetadata(resource::ResourceManager &rm, u32 handleId, f32 left, f32 right, f32 top, f32 bottom)
u32 rm_trimTextureCache(resource::ResourceManager &rm)
u32 rm_getTextureNativeId(resource::ResourceManager &rm, u32 handle)
void rm_registerTextureWithPath(resource::ResourceManager &rm, u32 handleId, const std::string &path)
std::span< const T > ConstSpan
Definition Types.hpp:242
void rm_forgoTextureContent(resource::ResourceManager &rm, u32 handle)
Gives up on an owed texture's content; it keeps blank storage.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
u32 rm_acquireTextureByPath(resource::ResourceManager &rm, const std::string &path)
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
bool rm_adoptTextureContent(resource::ResourceManager &rm, u32 target, u32 source)
Moves a freshly loaded texture's pixels behind an owed handle.
u32 rm_createCompressedTexture(resource::ResourceManager &rm, u32 width, u32 height, i32 format, uintptr_t dataPtr, u32 dataLen, u32 mipLevels, u32 content)
u32 rm_createShader(resource::ResourceManager &rm, const std::string &vertSrc, const std::string &fragSrc)
double f64
64-bit floating point
Definition Types.hpp:61
void rm_updateTextureSubregion(resource::ResourceManager &rm, u32 handleId, u32 x, u32 y, u32 width, u32 height, uintptr_t pixelsPtr, u32 pixelsLen)
std::string rm_meshRealizations(resource::ResourceManager &rm)
Every live mesh as handle:realized.
u32 rm_createTextureEx(resource::ResourceManager &rm, u32 width, u32 height, uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY, i32 filterMode, i32 wrapMode, u32 content)
float f32
32-bit floating point
Definition Types.hpp:59
u32 rm_wrapDeviceTexture(resource::ResourceManager &rm, u32 textureId, u32 width, u32 height)
A resource handle for a device texture another owner keeps (a render target's colour).
Texture creation parameters.
Definition Texture.hpp:74
u32 height
Texture height in pixels.
Definition Texture.hpp:78
TextureFormat format
Pixel format.
Definition Texture.hpp:80
u32 width
Texture width in pixels.
Definition Texture.hpp:76
u32 layers
Above 1, a 2D texture array of this many layers (see TextureDesc::layers).
Definition Texture.hpp:92
f32 left
Left border width in pixels.
f32 top
Top border height in pixels.
f32 bottom
Bottom border height in pixels.
f32 right
Right border width in pixels.
Metadata associated with a texture resource.
SliceBorder sliceBorder
Nine-slice border configuration.