Skip to content

Instantly share code, notes, and snippets.

@carloscm
Last active March 4, 2020 18:22
Show Gist options
  • Save carloscm/43779dda1b0b0f513b53471285982f07 to your computer and use it in GitHub Desktop.
Save carloscm/43779dda1b0b0f513b53471285982f07 to your computer and use it in GitHub Desktop.
#include <stb_image_resize.h>
static void build_mips(uint8_t* data, size_t base, uint32_t w, uint32_t h)
{
uint32_t mw = w;
uint32_t mh = h;
uint32_t pw = w;
uint32_t ph = h;
size_t prev_start = base;
size_t last_size = size_t(w) * size_t(h) * 4;
while (mw > 1 || mh > 1) {
mw = std::max(1u, mw >> 1);
mh = std::max(1u, mh >> 1);
stbir_resize_uint8(
&data[prev_start], pw, ph, 0,
&data[base + last_size], mw, mh, 0, 4
);
pw = mw;
ph = mh;
prev_start = base + last_size;
last_size += size_t(mw) * size_t(mh) * 4;
}
}
static size_t mips_required_memory(uint32_t w, uint32_t h)
{
size_t layer_bytes_0 = size_t(w) * size_t(h) * 4;
size_t layer_bytes = layer_bytes_0;
uint32_t mw = w;
uint32_t mh = h;
while (mw > 1 || mh > 1) {
mw = std::max(1u, mw >> 1);
mh = std::max(1u, mh >> 1);
layer_bytes += size_t(mw) * size_t(mh) * 4;
}
return layer_bytes;
}
void example(std::string const& path)
{
uint32_t w = 0;
uint32_t h = 0;
auto data = load_image(path, w, h); // last two are refs
size_t s = mips_required_memory(w, h);
const bgfx::Memory* mem = bgfx::alloc(uint32_t(s));
memcpy(&mem->data[0], data.data(), s);
build_mips(&mem->data[0], 0, w, h);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment