Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Texture.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16
17#include "./Texture.hpp"
18#include "./GfxDevice.hpp"
19#include "../../core/Log.hpp"
20
21#include <span>
22
23namespace esengine {
24
25namespace {
26
27GfxPixelFormat toGfxPixelFormat(TextureFormat format) {
28 switch (format) {
35 default: return GfxPixelFormat::RGBA8;
36 }
37}
38
39u32 bytesPerPixel(TextureFormat format) {
40 return gfxBytesPerPixel(toGfxPixelFormat(format));
41}
42
43} // namespace
44
46 if (handle_ != TextureHandle::Invalid && device_ && owns_) {
47 device_->deleteTexture(handle_);
48 }
49}
50
51Texture::Texture(Texture&& other) noexcept
52 : device_(other.device_)
53 , handle_(other.handle_)
54 , width_(other.width_)
55 , height_(other.height_)
56 , format_(other.format_)
57 , owns_(other.owns_) {
58 other.handle_ = TextureHandle::Invalid;
59 other.width_ = 0;
60 other.height_ = 0;
61 other.format_ = TextureFormat::None;
62}
63
65 if (this != &other) {
66 if (handle_ != TextureHandle::Invalid && device_ && owns_) {
67 device_->deleteTexture(handle_);
68 }
69 device_ = other.device_;
70 handle_ = other.handle_;
71 width_ = other.width_;
72 height_ = other.height_;
73 format_ = other.format_;
74 owns_ = other.owns_;
75 other.handle_ = TextureHandle::Invalid;
76 other.width_ = 0;
77 other.height_ = 0;
78 other.format_ = TextureFormat::None;
79 }
80 return *this;
81}
82
84 auto texture = makeUnique<Texture>();
85 texture->device_ = &device;
86 if (!texture->initialize(spec, content, nullptr, false)) {
87 return nullptr;
88 }
89 return texture;
90}
91
93 const void* pixels) {
94 auto texture = makeUnique<Texture>();
95 texture->device_ = &device;
96 if (!texture->initialize(spec, content, pixels, false)) {
97 return nullptr;
98 }
99 return texture;
100}
101
103 std::span<const u8> pixels, TextureFormat format, bool flipY) {
104 [[maybe_unused]] u32 expectedSize = width * height * bytesPerPixel(format);
105 ES_ASSERT(pixels.size() == expectedSize, "Pixel data size mismatch");
106 return createRaw(device, content, width, height, pixels.data(), format, flipY);
107}
108
110 const std::vector<u8>& pixels, TextureFormat format, bool flipY) {
111 return create(device, content, width, height, std::span<const u8>(pixels), format, flipY);
112}
113
115 const void* data, TextureFormat format, bool flipY) {
117 spec.width = width;
118 spec.height = height;
119 spec.format = format;
122 spec.generateMips = false;
123
124 auto texture = makeUnique<Texture>();
125 texture->device_ = &device;
126 if (!texture->initialize(spec, content, data, flipY)) {
127 return nullptr;
128 }
129 return texture;
130}
131
132Unique<Texture> Texture::createVolume(GfxDevice& device, GfxContent content, u32 width, u32 height, u32 depth,
133 const void* data, TextureFormat format) {
135 spec.width = width;
136 spec.height = height;
137 spec.format = format;
140 spec.generateMips = false;
141 spec.layers = depth;
142 spec.volume = true;
143
144 auto texture = makeUnique<Texture>();
145 texture->device_ = &device;
146 if (!texture->initialize(spec, content, data, false)) {
147 return nullptr;
148 }
149 return texture;
150}
151
153 GfxCompressedFormat format, std::span<const u8> data,
154 u32 mipLevels) {
155 auto texture = makeUnique<Texture>();
156 texture->device_ = &device;
157 texture->width_ = width;
158 texture->height_ = height;
159 texture->format_ = TextureFormat::RGBA8; // sampled as colour; the GPU format is the compressed one
160
161 TextureDesc desc;
162 desc.width = width;
163 desc.height = height;
168 desc.mipmaps = mipLevels > 1;
169
170 texture->handle_ = device.createCompressedTexture(desc, content, format, data.data(),
171 static_cast<u32>(data.size()), mipLevels);
172 if (texture->handle_ == TextureHandle::Invalid) {
173 ES_LOG_ERROR("Texture::createCompressed: failed for {}x{}", width, height);
174 return nullptr;
175 }
176 return texture;
177}
178
180 u32 width, u32 height, TextureFormat format) {
181 TextureDesc desc;
182 desc.width = width;
183 desc.height = height;
184 desc.format = toGfxPixelFormat(format);
185
186 auto texture = makeUnique<Texture>();
187 texture->device_ = &device;
188 texture->handle_ = device.importExternalTexture(glTextureId, desc, content);
189 texture->width_ = width;
190 texture->height_ = height;
191 texture->format_ = format;
192 return texture;
193}
194
196 if (!device.textureDesc(handle)) return nullptr;
197 auto texture = makeUnique<Texture>();
198 texture->device_ = &device;
199 texture->handle_ = handle;
200 texture->width_ = width;
201 texture->height_ = height;
202 texture->format_ = TextureFormat::RGBA8;
203 texture->owns_ = false;
204 return texture;
205}
206
208 if (!device_ || !owns_ || !from.owns_ || !device_->adoptTextureContent(handle_, from.handle_)) {
209 return false;
210 }
211 width_ = from.width_;
212 height_ = from.height_;
213 format_ = from.format_;
214 from.handle_ = TextureHandle::Invalid;
215 return true;
216}
217
218bool Texture::initialize(const TextureSpecification& spec, GfxContent content, const void* pixels, bool flipY) {
219 width_ = spec.width;
220 height_ = spec.height;
221 format_ = spec.format;
222
223 TextureDesc desc;
224 desc.width = spec.width;
225 desc.height = spec.height;
226 desc.format = toGfxPixelFormat(spec.format);
227 desc.minFilter = spec.minFilter;
228 desc.magFilter = spec.magFilter;
229 desc.wrapS = spec.wrapS;
230 desc.wrapT = spec.wrapT;
231 desc.mipmaps = spec.generateMips;
232 desc.flipY = flipY;
233 desc.layers = spec.layers ? spec.layers : 1;
234 desc.volume = spec.volume;
235
236 handle_ = device_->createTexture(desc, content, pixels);
237 if (handle_ == TextureHandle::Invalid) {
238 // Out of memory or a lost context: surface the failure instead of
239 // returning a "valid" texture wrapping the null handle (renders as black).
240 ES_LOG_ERROR("Texture::initialize: createTexture failed for {}x{}", width_, height_);
241 return false;
242 }
243
244 ES_LOG_DEBUG("Created texture {}x{} (handle: {})", width_, height_, static_cast<u32>(handle_));
245 return true;
246}
247
248void Texture::bind(u32 slot) const {
249 if (device_) device_->bindTexture(slot, handle_);
250}
251
252void Texture::unbind() const {
253 if (device_) device_->bindTexture(0, TextureHandle::Invalid);
254}
255
256void Texture::setData(std::span<const u8> pixels) {
257 [[maybe_unused]] u32 expectedSize = width_ * height_ * bytesPerPixel(format_);
258 ES_ASSERT(pixels.size() == expectedSize, "Pixel data size mismatch");
259 setDataRaw(pixels.data(), static_cast<u32>(pixels.size()));
260}
261
262void Texture::setData(const std::vector<u8>& pixels) {
263 setData(std::span<const u8>(pixels));
264}
265
266void Texture::setDataRaw(const void* data, u32 sizeBytes, bool flipY) {
267 // Always-on size guard (independent of ES_ASSERT, which is stripped in release).
268 // updateTexture below reads width_*height_*bpp bytes from `data`; a smaller
269 // buffer would cause an out-of-bounds read of WASM linear memory.
270 u32 expectedSize = width_ * height_ * bytesPerPixel(format_);
271 if (sizeBytes < expectedSize) {
272 ES_LOG_ERROR("Texture::setDataRaw: data size {} < required {} for {}x{}; skipping upload to avoid OOB read",
273 sizeBytes, expectedSize, width_, height_);
274 return;
275 }
276
277 device_->updateTexture(handle_, 0, 0, width_, height_, data, flipY);
278}
279
280void Texture::updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height,
281 const void* data, u32 sizeBytes, bool flipY) {
282 // The sub-rect must lie fully inside the texture; otherwise the upload
283 // writes outside the allocated texture storage (GL error / undefined).
284 if (width > width_ || xoffset > width_ - width ||
285 height > height_ || yoffset > height_ - height) {
286 ES_LOG_ERROR("Texture::updateSubRegion: rect {}x{} at ({},{}) exceeds texture {}x{}; skipping",
287 width, height, xoffset, yoffset, width_, height_);
288 return;
289 }
290 // Always-on size guard (ES_ASSERT is stripped in release): updateTexture
291 // reads width*height*bpp bytes from `data`; a smaller buffer would OOB-read
292 // WASM linear memory.
293 u32 expectedSize = width * height * bytesPerPixel(format_);
294 if (sizeBytes < expectedSize) {
295 ES_LOG_ERROR("Texture::updateSubRegion: data size {} < required {} for {}x{}; skipping to avoid OOB read",
296 sizeBytes, expectedSize, width, height);
297 return;
298 }
299
300 device_->updateTexture(handle_, static_cast<i32>(xoffset), static_cast<i32>(yoffset),
301 width, height, data, flipY);
302}
303
304} // namespace esengine
Abstract graphics device interface.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_ASSERT(condition, message)
Assert macro (debug builds only).
Definition Log.hpp:328
#define ES_LOG_DEBUG(...)
Definition Log.hpp:282
GPU texture abstraction for 2D images.
A content policy. provider names who refills a Sourced object and key what it refills; both are the p...
Abstract graphics device interface.
Definition GfxDevice.hpp:75
TextureHandle importExternalTexture(u32 nativeId, const TextureDesc &desc, GfxContent content)
Adopts a texture a host created with the device's own API (a JS-side WebGL upload).
TextureHandle createTexture(const TextureDesc &desc, GfxContent content, const void *pixels)
Creates a 2D texture; uploads pixels (tightly packed, desc-sized) when non-null.
TextureHandle createCompressedTexture(const TextureDesc &desc, GfxContent content, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)
Creates a texture from pre-compressed GPU block data.
const TextureDesc * textureDesc(TextureHandle texture) const
void updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height, const void *data, u32 sizeBytes, bool flipY=false)
Uploads pixel data to a sub-rectangle of the texture.
Definition Texture.cpp:280
void bind(u32 slot=0) const
Binds the texture to a texture unit.
Definition Texture.cpp:248
static Unique< Texture > createCompressed(GfxDevice &device, GfxContent content, u32 width, u32 height, GfxCompressedFormat format, std::span< const u8 > data, u32 mipLevels=1)
Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading the pre-compressed blocks in one ...
Definition Texture.cpp:152
static Unique< Texture > createFromExternalId(GfxDevice &device, GfxContent content, u32 glTextureId, u32 width, u32 height, TextureFormat format=TextureFormat::RGBA8)
Hands the device a texture the host made with its own API; the device owns it from here.
Definition Texture.cpp:179
void setDataRaw(const void *data, u32 sizeBytes, bool flipY=false)
Updates texture pixel data from raw pointer (internal use).
Definition Texture.cpp:266
void unbind() const
Unbinds the texture.
Definition Texture.cpp:252
static Unique< Texture > createArray(GfxDevice &device, GfxContent content, const TextureSpecification &spec, const void *pixels)
Creates a 2D texture array from spec.layers layers of spec.width x spec.height.
Definition Texture.cpp:92
virtual ~Texture()
Definition Texture.cpp:45
static Unique< Texture > createRaw(GfxDevice &device, GfxContent content, u32 width, u32 height, const void *data, TextureFormat format=TextureFormat::RGBA8, bool flipY=false)
Creates a texture from raw pixel pointer (internal use).
Definition Texture.cpp:114
static Unique< Texture > createVolume(GfxDevice &device, GfxContent content, u32 width, u32 height, u32 depth, const void *data, TextureFormat format)
A 3D texture, linearly filtered across all three axes and clamped at every edge.
Definition Texture.cpp:132
static Unique< Texture > create(GfxDevice &device, GfxContent content, const TextureSpecification &spec)
Creates an empty texture from specification.
Definition Texture.cpp:83
void setData(std::span< const u8 > pixels)
Updates texture pixel data from span.
Definition Texture.cpp:256
TextureHandle handle() const
Gets the device texture handle.
Definition Texture.hpp:233
Texture & operator=(const Texture &)=delete
static Unique< Texture > borrow(GfxDevice &device, TextureHandle texture, u32 width, u32 height)
Names a texture the device already holds for another owner (a render target's colour plane),...
Definition Texture.cpp:195
bool adoptContent(Texture &from)
Takes from's pixels behind this texture's handle; from is empty afterwards.
Definition Texture.cpp:207
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
Definition Types.hpp:99
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
@ ClampToEdge
Clamp to edge pixels.
Definition GfxEnums.hpp:64
@ Linear
Bilinear interpolation (smooth).
Definition GfxEnums.hpp:59
TextureFormat
Texture pixel format.
Definition Texture.hpp:45
@ RGB8
3 channels, 8 bits each (24 bpp)
Definition Texture.hpp:47
@ RGBA32F
Full-float storage (128 bpp); fetched by texel, never filtered.
Definition Texture.hpp:51
@ SRGB8A8
sRGB-encoded RGBA8: hardware-linearized on sample (32 bpp)
Definition Texture.hpp:49
@ RGBA16F
Half-float HDR (64 bpp); render use gated on supportsFloatTargets.
Definition Texture.hpp:50
@ RGBA8
4 channels, 8 bits each (32 bpp)
Definition Texture.hpp:48
@ Depth24
Depth buffer format (24 bits).
Definition Texture.hpp:52
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
std::unique_ptr< T > Unique
Unique ownership smart pointer.
Definition Types.hpp:75
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
u32 gfxBytesPerPixel(GfxPixelFormat fmt)
Bytes one pixel occupies in the CALLER's upload buffer — the single source both backends size a read ...
Definition GfxEnums.hpp:299
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
TextureFilter minFilter
Definition GfxEnums.hpp:422
TextureFilter magFilter
Definition GfxEnums.hpp:423
GfxPixelFormat format
Definition GfxEnums.hpp:421
Texture creation parameters.
Definition Texture.hpp:74
TextureFilter minFilter
Minification filter.
Definition Texture.hpp:82
bool volume
A 3D texture layers deep (see TextureDesc::volume).
Definition Texture.hpp:94
TextureWrap wrapS
Horizontal wrap mode.
Definition Texture.hpp:86
u32 height
Texture height in pixels.
Definition Texture.hpp:78
bool generateMips
Generate mipmaps automatically.
Definition Texture.hpp:90
TextureFormat format
Pixel format.
Definition Texture.hpp:80
u32 width
Texture width in pixels.
Definition Texture.hpp:76
TextureWrap wrapT
Vertical wrap mode.
Definition Texture.hpp:88
TextureFilter magFilter
Magnification filter.
Definition Texture.hpp:84
u32 layers
Above 1, a 2D texture array of this many layers (see TextureDesc::layers).
Definition Texture.hpp:92