Invalidate the right goal list when changing goals
[openttd/fttd.git] / src / heightmap.cpp
blob0fb4cc2e9dbf0604937b4f3305096b6f851433a6
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file heightmap.cpp Creating of maps from heightmaps. */
12 #include "stdafx.h"
13 #include "map/ground.h"
14 #include "heightmap.h"
15 #include "error.h"
16 #include "saveload/saveload.h"
17 #include "bmp.h"
18 #include "gfx_func.h"
19 #include "fios.h"
20 #include "fileio_func.h"
22 #include "table/strings.h"
24 /**
25 * Convert RGB colours to Grayscale using 29.9% Red, 58.7% Green, 11.4% Blue
26 * (average luminosity formula, NTSC Colour Space)
28 static inline byte RGBToGrayscale(byte red, byte green, byte blue)
30 /* To avoid doubles and stuff, multiply it with a total of 65536 (16bits), then
31 * divide by it to normalize the value to a byte again. */
32 return ((red * 19595) + (green * 38470) + (blue * 7471)) / 65536;
36 #ifdef WITH_PNG
38 #include <png.h>
40 /**
41 * The PNG Heightmap loader.
43 static void ReadHeightmapPNGImageData(byte *map, png_structp png_ptr, png_infop info_ptr)
45 uint x, y;
46 byte gray_palette[256];
47 png_bytep *row_pointers = NULL;
48 bool has_palette = png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_PALETTE;
49 uint channels = png_get_channels(png_ptr, info_ptr);
51 /* Get palette and convert it to grayscale */
52 if (has_palette) {
53 int i;
54 int palette_size;
55 png_color *palette;
56 bool all_gray = true;
58 png_get_PLTE(png_ptr, info_ptr, &palette, &palette_size);
59 for (i = 0; i < palette_size && (palette_size != 16 || all_gray); i++) {
60 all_gray &= palette[i].red == palette[i].green && palette[i].red == palette[i].blue;
61 gray_palette[i] = RGBToGrayscale(palette[i].red, palette[i].green, palette[i].blue);
64 /**
65 * For a non-gray palette of size 16 we assume that
66 * the order of the palette determines the height;
67 * the first entry is the sea (level 0), the second one
68 * level 1, etc.
70 if (palette_size == 16 && !all_gray) {
71 for (i = 0; i < palette_size; i++) {
72 gray_palette[i] = 256 * i / palette_size;
77 row_pointers = png_get_rows(png_ptr, info_ptr);
79 /* Read the raw image data and convert in 8-bit grayscale */
80 for (x = 0; x < png_get_image_width(png_ptr, info_ptr); x++) {
81 for (y = 0; y < png_get_image_height(png_ptr, info_ptr); y++) {
82 byte *pixel = &map[y * png_get_image_width(png_ptr, info_ptr) + x];
83 uint x_offset = x * channels;
85 if (has_palette) {
86 *pixel = gray_palette[row_pointers[y][x_offset]];
87 } else if (channels == 3) {
88 *pixel = RGBToGrayscale(row_pointers[y][x_offset + 0],
89 row_pointers[y][x_offset + 1], row_pointers[y][x_offset + 2]);
90 } else {
91 *pixel = row_pointers[y][x_offset];
97 /**
98 * Reads the heightmap and/or size of the heightmap from a PNG file.
99 * If map == NULL only the size of the PNG is read, otherwise a map
100 * with grayscale pixels is allocated and assigned to *map.
102 static bool ReadHeightmapPNG(char *filename, uint *x, uint *y, byte **map)
104 FILE *fp;
105 png_structp png_ptr = NULL;
106 png_infop info_ptr = NULL;
108 fp = FioFOpenFile(filename, "rb", HEIGHTMAP_DIR);
109 if (fp == NULL) {
110 ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_FILE_NOT_FOUND, WL_ERROR);
111 return false;
114 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
115 if (png_ptr == NULL) {
116 ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_MISC, WL_ERROR);
117 fclose(fp);
118 return false;
121 info_ptr = png_create_info_struct(png_ptr);
122 if (info_ptr == NULL || setjmp(png_jmpbuf(png_ptr))) {
123 ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_MISC, WL_ERROR);
124 fclose(fp);
125 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
126 return false;
129 png_init_io(png_ptr, fp);
131 /* Allocate memory and read image, without alpha or 16-bit samples
132 * (result is either 8-bit indexed/grayscale or 24-bit RGB) */
133 png_set_packing(png_ptr);
134 png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_PACKING | PNG_TRANSFORM_STRIP_ALPHA | PNG_TRANSFORM_STRIP_16, NULL);
136 /* Maps of wrong colour-depth are not used.
137 * (this should have been taken care of by stripping alpha and 16-bit samples on load) */
138 if ((png_get_channels(png_ptr, info_ptr) != 1) && (png_get_channels(png_ptr, info_ptr) != 3) && (png_get_bit_depth(png_ptr, info_ptr) != 8)) {
139 ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_IMAGE_TYPE, WL_ERROR);
140 fclose(fp);
141 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
142 return false;
145 uint width = png_get_image_width(png_ptr, info_ptr);
146 uint height = png_get_image_height(png_ptr, info_ptr);
148 /* Check if image dimensions don't overflow a size_t to avoid memory corruption. */
149 if ((uint64)width * height >= (size_t)-1) {
150 ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_HEIGHTMAP_TOO_LARGE, WL_ERROR);
151 fclose(fp);
152 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
153 return false;
156 if (map != NULL) {
157 *map = MallocT<byte>(width * height);
158 ReadHeightmapPNGImageData(*map, png_ptr, info_ptr);
161 *x = width;
162 *y = height;
164 fclose(fp);
165 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
166 return true;
169 #endif /* WITH_PNG */
173 * The BMP Heightmap loader.
175 static void ReadHeightmapBMPImageData(byte *map, BmpInfo *info, BmpData *data)
177 uint x, y;
178 byte gray_palette[256];
180 if (data->palette != NULL) {
181 uint i;
182 bool all_gray = true;
184 if (info->palette_size != 2) {
185 for (i = 0; i < info->palette_size && (info->palette_size != 16 || all_gray); i++) {
186 all_gray &= data->palette[i].r == data->palette[i].g && data->palette[i].r == data->palette[i].b;
187 gray_palette[i] = RGBToGrayscale(data->palette[i].r, data->palette[i].g, data->palette[i].b);
191 * For a non-gray palette of size 16 we assume that
192 * the order of the palette determines the height;
193 * the first entry is the sea (level 0), the second one
194 * level 1, etc.
196 if (info->palette_size == 16 && !all_gray) {
197 for (i = 0; i < info->palette_size; i++) {
198 gray_palette[i] = 256 * i / info->palette_size;
201 } else {
203 * For a palette of size 2 we assume that the order of the palette determines the height;
204 * the first entry is the sea (level 0), the second one is the land (level 1)
206 gray_palette[0] = 0;
207 gray_palette[1] = 16;
211 /* Read the raw image data and convert in 8-bit grayscale */
212 for (y = 0; y < info->height; y++) {
213 byte *pixel = &map[y * info->width];
214 byte *bitmap = &data->bitmap[y * info->width * (info->bpp == 24 ? 3 : 1)];
216 for (x = 0; x < info->width; x++) {
217 if (info->bpp != 24) {
218 *pixel++ = gray_palette[*bitmap++];
219 } else {
220 *pixel++ = RGBToGrayscale(*bitmap, *(bitmap + 1), *(bitmap + 2));
221 bitmap += 3;
228 * Reads the heightmap and/or size of the heightmap from a BMP file.
229 * If map == NULL only the size of the BMP is read, otherwise a map
230 * with grayscale pixels is allocated and assigned to *map.
232 static bool ReadHeightmapBMP(char *filename, uint *x, uint *y, byte **map)
234 FILE *f;
235 BmpInfo info;
236 BmpData data;
237 BmpBuffer buffer;
239 /* Init BmpData */
240 memset(&data, 0, sizeof(data));
242 f = FioFOpenFile(filename, "rb", HEIGHTMAP_DIR);
243 if (f == NULL) {
244 ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_PNGMAP_FILE_NOT_FOUND, WL_ERROR);
245 return false;
248 BmpInitializeBuffer(&buffer, f);
250 if (!BmpReadHeader(&buffer, &info, &data)) {
251 ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_BMPMAP_IMAGE_TYPE, WL_ERROR);
252 fclose(f);
253 BmpDestroyData(&data);
254 return false;
257 /* Check if image dimensions don't overflow a size_t to avoid memory corruption. */
258 if ((uint64)info.width * info.height >= (size_t)-1 / (info.bpp == 24 ? 3 : 1)) {
259 ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_HEIGHTMAP_TOO_LARGE, WL_ERROR);
260 fclose(f);
261 BmpDestroyData(&data);
262 return false;
265 if (map != NULL) {
266 if (!BmpReadBitmap(&buffer, &info, &data)) {
267 ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_BMPMAP_IMAGE_TYPE, WL_ERROR);
268 fclose(f);
269 BmpDestroyData(&data);
270 return false;
273 *map = MallocT<byte>(info.width * info.height);
274 ReadHeightmapBMPImageData(*map, &info, &data);
277 BmpDestroyData(&data);
279 *x = info.width;
280 *y = info.height;
282 fclose(f);
283 return true;
287 * Converts a given grayscale map to something that fits in OTTD map system
288 * and create a map of that data.
289 * @param img_width the with of the image in pixels/tiles
290 * @param img_height the height of the image in pixels/tiles
291 * @param map the input map
293 static void GrayscaleToMapHeights(uint img_width, uint img_height, byte *map)
295 /* Defines the detail of the aspect ratio (to avoid doubles) */
296 const uint num_div = 16384;
298 uint width, height;
299 uint row, col;
300 uint row_pad = 0, col_pad = 0;
301 uint img_scale;
302 uint img_row, img_col;
303 TileIndex tile;
305 /* Get map size and calculate scale and padding values */
306 switch (_settings_game.game_creation.heightmap_rotation) {
307 default: NOT_REACHED();
308 case HM_COUNTER_CLOCKWISE:
309 width = MapSizeX();
310 height = MapSizeY();
311 break;
312 case HM_CLOCKWISE:
313 width = MapSizeY();
314 height = MapSizeX();
315 break;
318 if ((img_width * num_div) / img_height > ((width * num_div) / height)) {
319 /* Image is wider than map - center vertically */
320 img_scale = (width * num_div) / img_width;
321 row_pad = (1 + height - ((img_height * img_scale) / num_div)) / 2;
322 } else {
323 /* Image is taller than map - center horizontally */
324 img_scale = (height * num_div) / img_height;
325 col_pad = (1 + width - ((img_width * img_scale) / num_div)) / 2;
328 if (_settings_game.construction.freeform_edges) {
329 for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
330 for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
333 /* Form the landscape */
334 for (row = 0; row < height; row++) {
335 for (col = 0; col < width; col++) {
336 switch (_settings_game.game_creation.heightmap_rotation) {
337 default: NOT_REACHED();
338 case HM_COUNTER_CLOCKWISE: tile = TileXY(col, row); break;
339 case HM_CLOCKWISE: tile = TileXY(row, col); break;
342 /* Check if current tile is within the 1-pixel map edge or padding regions */
343 if ((!_settings_game.construction.freeform_edges && DistanceFromEdge(tile) <= 1) ||
344 (row < row_pad) || (row >= (height - row_pad - (_settings_game.construction.freeform_edges ? 0 : 1))) ||
345 (col < col_pad) || (col >= (width - col_pad - (_settings_game.construction.freeform_edges ? 0 : 1)))) {
346 SetTileHeight(tile, 0);
347 } else {
348 /* Use nearest neighbour resizing to scale map data.
349 * We rotate the map 45 degrees (counter)clockwise */
350 img_row = (((row - row_pad) * num_div) / img_scale);
351 switch (_settings_game.game_creation.heightmap_rotation) {
352 default: NOT_REACHED();
353 case HM_COUNTER_CLOCKWISE:
354 img_col = (((width - 1 - col - col_pad) * num_div) / img_scale);
355 break;
356 case HM_CLOCKWISE:
357 img_col = (((col - col_pad) * num_div) / img_scale);
358 break;
361 assert(img_row < img_height);
362 assert(img_col < img_width);
364 /* Colour scales from 0 to 255, OpenTTD height scales from 0 to 15 */
365 SetTileHeight(tile, map[img_row * img_width + img_col] / 16);
367 /* Only clear the tiles within the map area. */
368 if (IsInnerTile(tile)) {
369 MakeClear(tile, GROUND_GRASS, 3);
376 * This function takes care of the fact that land in OpenTTD can never differ
377 * more than 1 in height
379 void FixSlopes()
381 uint width, height;
382 int row, col;
383 byte current_tile;
385 /* Adjust height difference to maximum one horizontal/vertical change. */
386 width = MapSizeX();
387 height = MapSizeY();
389 /* Top and left edge */
390 for (row = 0; (uint)row < height; row++) {
391 for (col = 0; (uint)col < width; col++) {
392 current_tile = MAX_TILE_HEIGHT;
393 if (col != 0) {
394 /* Find lowest tile; either the top or left one */
395 current_tile = TileHeight(TileXY(col - 1, row)); // top edge
397 if (row != 0) {
398 if (TileHeight(TileXY(col, row - 1)) < current_tile) {
399 current_tile = TileHeight(TileXY(col, row - 1)); // left edge
403 /* Does the height differ more than one? */
404 if (TileHeight(TileXY(col, row)) >= (uint)current_tile + 2) {
405 /* Then change the height to be no more than one */
406 SetTileHeight(TileXY(col, row), current_tile + 1);
411 /* Bottom and right edge */
412 for (row = height - 1; row >= 0; row--) {
413 for (col = width - 1; col >= 0; col--) {
414 current_tile = MAX_TILE_HEIGHT;
415 if ((uint)col != width - 1) {
416 /* Find lowest tile; either the bottom and right one */
417 current_tile = TileHeight(TileXY(col + 1, row)); // bottom edge
420 if ((uint)row != height - 1) {
421 if (TileHeight(TileXY(col, row + 1)) < current_tile) {
422 current_tile = TileHeight(TileXY(col, row + 1)); // right edge
426 /* Does the height differ more than one? */
427 if (TileHeight(TileXY(col, row)) >= (uint)current_tile + 2) {
428 /* Then change the height to be no more than one */
429 SetTileHeight(TileXY(col, row), current_tile + 1);
436 * Reads the heightmap with the correct file reader
438 static bool ReadHeightMap(char *filename, uint *x, uint *y, byte **map)
440 switch (_file_to_saveload.mode) {
441 default: NOT_REACHED();
442 #ifdef WITH_PNG
443 case SL_PNG:
444 return ReadHeightmapPNG(filename, x, y, map);
445 #endif /* WITH_PNG */
446 case SL_BMP:
447 return ReadHeightmapBMP(filename, x, y, map);
452 * Get the dimensions of a heightmap.
453 * @param filename to query
454 * @param x dimension x
455 * @param y dimension y
456 * @return Returns false if loading of the image failed.
458 bool GetHeightmapDimensions(char *filename, uint *x, uint *y)
460 return ReadHeightMap(filename, x, y, NULL);
464 * Load a heightmap from file and change the map in his current dimensions
465 * to a landscape representing the heightmap.
466 * It converts pixels to height. The brighter, the higher.
467 * @param filename of the heightmap file to be imported
469 void LoadHeightmap(char *filename)
471 uint x, y;
472 byte *map = NULL;
474 if (!ReadHeightMap(filename, &x, &y, &map)) {
475 free(map);
476 return;
479 GrayscaleToMapHeights(x, y, map);
480 free(map);
482 FixSlopes();
483 MarkWholeScreenDirty();
487 * Make an empty world where all tiles are of height 'tile_height'.
488 * @param tile_height of the desired new empty world
490 void FlatEmptyWorld(byte tile_height)
492 int edge_distance = _settings_game.construction.freeform_edges ? 0 : 2;
493 for (uint row = edge_distance; row < MapSizeY() - edge_distance; row++) {
494 for (uint col = edge_distance; col < MapSizeX() - edge_distance; col++) {
495 SetTileHeight(TileXY(col, row), tile_height);
499 FixSlopes();
500 MarkWholeScreenDirty();