Add tileset loading
This commit is contained in:
@@ -113,6 +113,69 @@ uint64_t Window::load_image(const char *path, bool pixel_art) {
|
||||
return id;
|
||||
}
|
||||
|
||||
std::vector<uint64_t> Window::load_image_set(const char *path, Vec2<float> tile_size, Vec2<float> padding, Vec2<float> offset, bool pixel_art) {
|
||||
SDL_Surface *surface = IMG_Load(path);
|
||||
|
||||
if (!surface) {
|
||||
fprintf(stderr, "Failed to load image set: %s\n", SDL_GetError());
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<uint64_t> image_ids;
|
||||
|
||||
int columns = (int)((surface->w - offset.x + padding.x) / (tile_size.x + padding.x));
|
||||
int rows = (int)((surface->h - offset.y + padding.y) / (tile_size.y + padding.y));
|
||||
|
||||
for (int y = 0; y < rows; y++) {
|
||||
for (int x = 0; x < columns; x++) {
|
||||
SDL_Rect src_rect = {
|
||||
(int)(offset.x + x * (tile_size.x + padding.x)),
|
||||
(int)(offset.y + y * (tile_size.y + padding.y)),
|
||||
(int)tile_size.x,
|
||||
(int)tile_size.y
|
||||
};
|
||||
|
||||
SDL_Surface *tile_surface = SDL_CreateSurface(src_rect.w, src_rect.h, SDL_PIXELFORMAT_RGBA8888);
|
||||
SDL_BlitSurface(surface, &src_rect, tile_surface, nullptr);
|
||||
|
||||
SDL_Texture *texture = SDL_CreateTexture(
|
||||
renderer,
|
||||
SDL_PIXELFORMAT_RGBA8888,
|
||||
SDL_TEXTUREACCESS_STREAMING,
|
||||
tile_surface->w,
|
||||
tile_surface->h
|
||||
);
|
||||
|
||||
if (!texture) {
|
||||
fprintf(stderr, "Failed to create texture for tile: %s\n", SDL_GetError());
|
||||
SDL_DestroySurface(tile_surface);
|
||||
continue;
|
||||
}
|
||||
|
||||
SDL_UpdateTexture(
|
||||
texture,
|
||||
nullptr,
|
||||
tile_surface->pixels,
|
||||
tile_surface->pitch
|
||||
);
|
||||
|
||||
if (pixel_art) {
|
||||
SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_NEAREST);
|
||||
}
|
||||
|
||||
Image *img = new Image{texture, {(float)tile_surface->w, (float)tile_surface->h}};
|
||||
uint64_t id = image_pool.acquire(img);
|
||||
image_pool.use(id);
|
||||
image_ids.push_back(id);
|
||||
|
||||
SDL_DestroySurface(tile_surface);
|
||||
}
|
||||
}
|
||||
|
||||
SDL_DestroySurface(surface);
|
||||
return image_ids;
|
||||
}
|
||||
|
||||
uint64_t Window::create_image(Vec2<float> size, bool pixel_art) {
|
||||
SDL_Texture *texture = SDL_CreateTexture(
|
||||
renderer,
|
||||
|
||||
Reference in New Issue
Block a user