Created
December 28, 2015 22:32
-
-
Save bqqbarbhg/daf66755ba99e093f665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define STB_IMAGE_IMPLEMENTATION | |
#define STB_IMAGE_WRITE_IMPLEMENTATION | |
#define STB_RECT_PACK_IMPLEMENTATION | |
#include "stb_image.h" | |
#include "stb_image_write.h" | |
#include "stb_rect_pack.h" | |
#include "bitmap.h" | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
struct Image | |
{ | |
const char *name; | |
unsigned char *data; | |
int width, height; | |
}; | |
int main(int argc, char **argv) | |
{ | |
int capacity = argc - 1; | |
stbrp_rect *rects = (stbrp_rect*)calloc(capacity, sizeof(stbrp_rect)); | |
Image *images = (Image*)calloc(capacity, sizeof(Image)); | |
int success = 1; | |
int count = 0; | |
for (int i = 1; i < argc; i++) { | |
int width, height, channels; | |
unsigned char *data = stbi_load(argv[i], &width, &height, &channels, 4); | |
if (channels != 4) { | |
fprintf(stderr, "Wrong number of components in file '%s', skipping...\n", argv[i]); | |
success = 0; | |
continue; | |
} | |
rects[count].id = count; | |
rects[count].w = (stbrp_coord)width; | |
rects[count].h = (stbrp_coord)height; | |
images[count].name = argv[i]; | |
images[count].data = data; | |
images[count].width = width; | |
images[count].height = height; | |
count++; | |
} | |
int atlas_size = 1024; | |
stbrp_node *nodes = (stbrp_node*)malloc(sizeof(stbrp_node) * atlas_size); | |
stbrp_context rp_ctx; | |
stbrp_init_target(&rp_ctx, atlas_size, atlas_size, nodes, atlas_size); | |
stbrp_pack_rects(&rp_ctx, rects, count); | |
unsigned char *data = (unsigned char*)calloc(atlas_size * atlas_size, 4); | |
for (int i = 0; i < count; i++) { | |
Image *image = images + rects[i].id; | |
if (!rects[i].was_packed) { | |
fprintf(stderr, "Could not pack '%s', skipping...\n", image->name); | |
success = 0; | |
continue; | |
} | |
int bx = rects[i].x; | |
int by = rects[i].y; | |
int w = image->width; | |
int h = image->height; | |
unsigned char *src = images[i].data; | |
for (int y = 0; y < h; y++) { | |
for (int x = 0; x < w; x++) { | |
int si = (y * w + x) * 4; | |
int di = ((by + y) * atlas_size + x + bx) * 4; | |
data[di + 0] = src[si + 0]; | |
data[di + 1] = src[si + 1]; | |
data[di + 2] = src[si + 2]; | |
data[di + 3] = src[si + 3]; | |
} | |
} | |
} | |
free(nodes); | |
stbi_write_png("atlas.png", atlas_size, atlas_size, 4, data, atlas_size * 4); | |
return success ? 0 : 1; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment